infigraph-core 1.5.5

AST-powered code analysis framework — parser, graph, diff, and analysis engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use anyhow::Result;
use serde::Serialize;

use crate::graph::GraphStore;

#[derive(Debug, Clone, Serialize)]
pub struct ConcernMatch {
    pub symbol_id: String,
    pub kind: &'static str,
    pub detail: String,
}

struct ConcernPattern {
    kind: &'static str,
    patterns: &'static [&'static str],
}

static CONCERN_PATTERNS: &[ConcernPattern] = &[
    // Authorization
    ConcernPattern {
        kind: "Authorization",
        patterns: &[
            // Java/Kotlin
            "@PreAuthorize(",
            "@PostAuthorize(",
            "@Secured(",
            "@RolesAllowed(",
            "@PermitAll",
            "@DenyAll",
            // Python
            "@login_required",
            "@permission_required(",
            "@requires_auth",
            // TS/JS (NestJS)
            "@UseGuards(",
            "@Roles(",
            "@SetMetadata('roles'",
            // C#
            "[Authorize(",
            "[Authorize]",
            "[AllowAnonymous]",
            // Rust
            "#[guard(",
            "#[authorize(",
        ],
    },
    // Validation
    ConcernPattern {
        kind: "Validation",
        patterns: &[
            // Java/Kotlin
            "@Valid",
            "@Validated",
            "@NotNull",
            "@NotBlank",
            "@NotEmpty",
            "@Size(",
            "@Pattern(",
            "@Min(",
            "@Max(",
            // Python
            "@validator(",
            "@pydantic.validator(",
            "@field_validator(",
            // TS/JS (NestJS)
            "@UsePipes(",
            "ValidationPipe",
            // C#
            "[ValidateAntiForgeryToken]",
            "[Required]",
            "[Range(",
            "[StringLength(",
            // Rust
            "#[validate(",
        ],
    },
    // Caching
    ConcernPattern {
        kind: "Caching",
        patterns: &[
            // Java/Kotlin
            "@Cacheable(",
            "@CacheEvict(",
            "@CachePut(",
            "@Caching(",
            // Python
            "@cache",
            "@lru_cache(",
            "@cached_property",
            "@memoize",
            // TS/JS (NestJS)
            "@CacheKey(",
            "@CacheTTL(",
            "CacheInterceptor",
            // C#
            "[OutputCache(",
            "[ResponseCache(",
            // Ruby
            "caches_action",
            "caches_page",
            // Rust
            "#[cached(",
        ],
    },
    // Transaction
    ConcernPattern {
        kind: "Transaction",
        patterns: &[
            // Java/Kotlin
            "@Transactional(",
            "@Transactional\n",
            // Python
            "@atomic",
            "@transaction.atomic",
            "@commit_on_success",
            // TS/JS
            "@Transactional()",
            // C#
            "[Transaction]",
            // Rust
            "#[transactional]",
        ],
    },
    // RateLimiting
    ConcernPattern {
        kind: "RateLimiting",
        patterns: &[
            // Java
            "@RateLimiter(",
            "@RateLimit(",
            "@Bulkhead(",
            // Python
            "@rate_limit(",
            "@throttle(",
            "@ratelimit(",
            // TS/JS (NestJS)
            "@Throttle(",
            "@SkipThrottle(",
            // C#
            "[EnableRateLimiting(",
            "[DisableRateLimiting(",
            // Rust
            "#[rate_limit(",
        ],
    },
    // AuditLogging
    ConcernPattern {
        kind: "AuditLogging",
        patterns: &[
            "@Auditable(",
            "@Audit(",
            "@Logged",
            "@audit_log(",
            "@log_action(",
            "LoggingInterceptor",
            "[Audit]",
            "#[instrument(",
        ],
    },
    // FeatureFlag
    ConcernPattern {
        kind: "FeatureFlag",
        patterns: &[
            "@FeatureFlag(",
            "@Toggle(",
            "@Feature(",
            "@feature_flag(",
            "@feature_enabled(",
            "[FeatureGate(",
            "#[feature(",
        ],
    },
    // Cors
    ConcernPattern {
        kind: "Cors",
        patterns: &[
            "@CrossOrigin(",
            "@CrossOrigin\n",
            "[EnableCors(",
            "[DisableCors(",
            "#[cors(",
        ],
    },
    // Async
    ConcernPattern {
        kind: "Async",
        patterns: &[
            // Java
            "@Async",
            "@Scheduled(",
            "@EventListener(",
            // Python
            "@celery.task",
            "@background_task(",
            "@periodic_task(",
            // TS/JS (NestJS)
            "@Cron(",
            "@Interval(",
            "@EventPattern(",
            // C#
            "[BackgroundService]",
            // Rust
            "#[tokio::main]",
        ],
    },
    // Retry / Resilience
    ConcernPattern {
        kind: "Retry",
        patterns: &[
            "@Retry(",
            "@Retryable(",
            "@CircuitBreaker(",
            "@retry(",
            "@backoff(",
            "@circuit_breaker(",
            "RetryInterceptor",
            "[Retry(",
            "[CircuitBreaker(",
            "#[retry(",
        ],
    },
];

pub fn detect_cross_cutting(store: &GraphStore) -> Result<Vec<ConcernMatch>> {
    let _lock = store.write_lock()?;
    let conn = store.connection()?;

    let result = conn
        .query("MATCH (s:Symbol) WHERE s.docstring IS NOT NULL AND s.docstring <> '' RETURN s.id, s.docstring")
        .map_err(|e| anyhow::anyhow!("query failed: {e}"))?;

    let mut matches = Vec::new();

    for row in result {
        if row.len() < 2 {
            continue;
        }
        let symbol_id = row[0].to_string();
        let docstring = row[1].to_string();

        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    let detail = extract_matched_line(&docstring, pattern);
                    matches.push(ConcernMatch {
                        symbol_id: symbol_id.clone(),
                        kind: cp.kind,
                        detail,
                    });
                    break;
                }
            }
        }
    }

    if !matches.is_empty() {
        write_concerns(store, &matches)?;
    }

    Ok(matches)
}

fn extract_matched_line(docstring: &str, pattern: &str) -> String {
    for line in docstring.lines() {
        if line.contains(pattern) {
            return line.trim().to_string();
        }
    }
    pattern.to_string()
}

fn write_concerns(store: &GraphStore, matches: &[ConcernMatch]) -> Result<()> {
    let conn = store.connection()?;

    conn.query("BEGIN TRANSACTION")
        .map_err(|e| anyhow::anyhow!("begin txn: {e}"))?;

    // Clear old concern data
    let _ = conn.query("MATCH (c:Concern) DETACH DELETE c");

    for m in matches {
        let sym_esc = crate::escape_str(&m.symbol_id);
        let kind_esc = crate::escape_str(m.kind);
        let detail_esc = crate::escape_str(&m.detail);
        let concern_id = format!("{}::{}", m.symbol_id, m.kind);
        let id_esc = crate::escape_str(&concern_id);

        let _ = conn.query(&format!(
            "CREATE (c:Concern {{id: '{id_esc}', kind: '{kind_esc}', detail: '{detail_esc}'}})"
        ));
        let _ = conn.query(&format!(
            "MATCH (s:Symbol), (c:Concern) WHERE s.id = '{sym_esc}' AND c.id = '{id_esc}' CREATE (s)-[:HAS_CONCERN]->(c)"
        ));
    }

    conn.query("COMMIT")
        .map_err(|e| anyhow::anyhow!("commit txn: {e}"))?;

    Ok(())
}

pub fn format_concerns(matches: &[ConcernMatch]) -> String {
    if matches.is_empty() {
        return "No cross-cutting concerns detected.".to_string();
    }

    let mut by_kind: std::collections::BTreeMap<&str, Vec<&ConcernMatch>> =
        std::collections::BTreeMap::new();
    for m in matches {
        by_kind.entry(m.kind).or_default().push(m);
    }

    let mut out = format!("Cross-cutting concerns: {} total\n\n", matches.len());
    for (kind, items) in &by_kind {
        out.push_str(&format!("## {} ({} symbols)\n", kind, items.len()));
        for item in items {
            out.push_str(&format!("  {}{}\n", item.symbol_id, item.detail));
        }
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_detect_java_authorization() {
        let docstring = "@PreAuthorize(\"hasRole('ADMIN')\")\npublic void deleteUser() {}";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.contains(&"Authorization"),
            "should detect @PreAuthorize"
        );
    }

    #[test]
    fn test_detect_python_caching() {
        let docstring = "@lru_cache(maxsize=128)\ndef get_user(user_id):";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(found.contains(&"Caching"), "should detect @lru_cache");
    }

    #[test]
    fn test_detect_nestjs_throttle() {
        let docstring = "@Throttle(10, 60)\n@Roles('admin')\nasync getUsers() {}";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(found.contains(&"RateLimiting"), "should detect @Throttle");
        assert!(found.contains(&"Authorization"), "should detect @Roles");
    }

    #[test]
    fn test_detect_csharp_authorize() {
        let docstring = "[Authorize(Roles=\"Admin\")]\n[ValidateAntiForgeryToken]\npublic IActionResult Delete()";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.contains(&"Authorization"),
            "should detect [Authorize]"
        );
        assert!(
            found.contains(&"Validation"),
            "should detect [ValidateAntiForgeryToken]"
        );
    }

    #[test]
    fn test_detect_rust_instrument() {
        let docstring = "#[instrument(skip(db))]\nasync fn handle_request()";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.contains(&"AuditLogging"),
            "should detect #[instrument]"
        );
    }

    #[test]
    fn test_detect_spring_transactional() {
        let docstring = "@Transactional(readOnly = true)\npublic List<User> findAll()";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.contains(&"Transaction"),
            "should detect @Transactional"
        );
    }

    #[test]
    fn test_no_false_positive_on_plain_text() {
        let docstring = "This function validates cacheable behavior for users";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.is_empty(),
            "should not match plain text without annotation syntax: {:?}",
            found
        );
    }

    #[test]
    fn test_extract_matched_line() {
        let doc = "@PreAuthorize(\"hasRole('ADMIN')\")\npublic void delete()";
        let line = extract_matched_line(doc, "@PreAuthorize(");
        assert_eq!(line, "@PreAuthorize(\"hasRole('ADMIN')\")");
    }

    #[test]
    fn test_detect_python_login_required() {
        let docstring = "@login_required\ndef dashboard(request):";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        assert!(
            found.contains(&"Authorization"),
            "should detect @login_required"
        );
    }

    #[test]
    fn test_detect_ruby_before_action() {
        let docstring = "before_action :authenticate_user!\ndef index";
        let mut found = Vec::new();
        for cp in CONCERN_PATTERNS {
            for &pattern in cp.patterns {
                if docstring.contains(pattern) {
                    found.push(cp.kind);
                    break;
                }
            }
        }
        // Ruby patterns don't start with @ or [, they're bare method calls
        // "before_action :authenticate" is not in our patterns — let me check
        assert!(
            found.is_empty() || found.contains(&"Authorization"),
            "Ruby before_action pattern check: {:?}",
            found
        );
    }
}