attackmap-analyzer-rust 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of attackmap-analyzer-rust might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from .analyzer import RustAnalyzer
2
+
3
+ __all__ = ["RustAnalyzer"]
@@ -0,0 +1,543 @@
1
+ """Rust ecosystem analyzer for AttackMap.
2
+
3
+ Coverage (v0.1):
4
+ - Web frameworks: axum, actix-web, rocket (route + entrypoint extraction)
5
+ - Databases: sqlx, diesel, sea-orm, mongodb, redis, rusqlite, tokio-postgres
6
+ - Auth crates: jsonwebtoken, argon2/bcrypt/scrypt, oauth2, tower-http auth, axum-login,
7
+ actix-identity, tower-sessions
8
+ - HTTP clients (external calls): reqwest, hyper-client, isahc, surf, ureq
9
+ - Secrets: std::env::var, dotenv/dotenvy, secrecy crate
10
+ - Entrypoints: axum::serve, HttpServer::new(...).run, rocket::build, tide::new
11
+ - Workspace/crate names from Cargo.toml for service-name hints
12
+
13
+ Emits Signal v2 fields (line numbers + evidence snippets + confidence) so
14
+ downstream insights can cite `path/to/file.rs:NN`.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from pathlib import Path
21
+ from urllib.parse import urlparse
22
+
23
+ from .contracts import (
24
+ AnalyzerMetadata,
25
+ AuthHint,
26
+ DatabaseHint,
27
+ EntrypointHint,
28
+ ExternalCall,
29
+ FrameworkHint,
30
+ Route,
31
+ ScanResult,
32
+ SecretHint,
33
+ ServiceHint,
34
+ )
35
+
36
+ CODE_SUFFIXES = {".rs"}
37
+ SKIP_DIRS = {"target", ".git", "node_modules", ".cargo", "vendor"}
38
+ _SNIPPET_MAX_CHARS = 160
39
+
40
+
41
+ # ---------- Patterns ----------
42
+
43
+ # Axum: Router::new().route("/path", get(h).post(h2))
44
+ # We capture the path then walk a restricted method-chain that follows.
45
+ AXUM_ROUTE_PATTERN = re.compile(
46
+ r'\.route\(\s*"([^"]+)"\s*,\s*([a-zA-Z_][a-zA-Z0-9_:]*)\s*\(',
47
+ re.MULTILINE,
48
+ )
49
+ # Method-chain on the routing function, e.g. get(h).post(h2)
50
+ AXUM_METHOD_CHAIN_PATTERN = re.compile(
51
+ r"\.(get|post|put|delete|patch|head|options|trace|connect)\s*\(",
52
+ re.IGNORECASE,
53
+ )
54
+
55
+ # Actix-web attribute macros: #[get("/path")] / #[post("/path")] etc.
56
+ ACTIX_ATTRIBUTE_ROUTE_PATTERN = re.compile(
57
+ r'#\[\s*(get|post|put|delete|patch|head|options)\s*\(\s*"([^"]+)"',
58
+ re.IGNORECASE,
59
+ )
60
+ # Actix-web .route(): .route("/path", web::get().to(h))
61
+ ACTIX_WEB_ROUTE_PATTERN = re.compile(
62
+ r'\.route\(\s*"([^"]+)"\s*,\s*web::(get|post|put|delete|patch|head|options)\s*\(\s*\)',
63
+ re.IGNORECASE,
64
+ )
65
+ # Actix-web service routes: web::resource("/path").route(web::get().to(...))
66
+ ACTIX_RESOURCE_PATTERN = re.compile(
67
+ r'web::(?:resource|scope)\(\s*"([^"]+)"',
68
+ re.IGNORECASE,
69
+ )
70
+
71
+ # Rocket attribute macros: #[get("/path")], also with format/data: #[post("/users", data = "...")]
72
+ ROCKET_ATTRIBUTE_ROUTE_PATTERN = re.compile(
73
+ r'#\[\s*(get|post|put|delete|patch|head|options)\s*\(\s*"([^"]+)"',
74
+ re.IGNORECASE,
75
+ )
76
+
77
+ # External HTTP calls
78
+ OUTBOUND_PATTERNS: list[re.Pattern[str]] = [
79
+ re.compile(
80
+ r'\breqwest::(?:get|Client::new\(\)\.[a-z]+|blocking::get)\s*\(\s*["]([^"]+)["]',
81
+ re.IGNORECASE,
82
+ ),
83
+ re.compile(r'\.(?:get|post|put|delete|patch)\s*\(\s*["](https?://[^"]+)["]', re.IGNORECASE),
84
+ re.compile(r'\bisahc::(?:get|post|put|delete|patch)\s*\(\s*["]([^"]+)["]', re.IGNORECASE),
85
+ re.compile(r'\bsurf::(?:get|post|put|delete|patch)\s*\(\s*["]([^"]+)["]', re.IGNORECASE),
86
+ re.compile(r'\bureq::(?:get|post|put|delete|patch)\s*\(\s*["]([^"]+)["]', re.IGNORECASE),
87
+ ]
88
+
89
+ # Database libs (regex anchored on common entry points)
90
+ DB_PATTERNS: list[tuple[re.Pattern[str], str]] = [
91
+ (re.compile(r"\bsqlx::(?:postgres|Postgres)", re.IGNORECASE), "postgresql"),
92
+ (re.compile(r"\bsqlx::(?:mysql|MySql)", re.IGNORECASE), "mysql"),
93
+ (re.compile(r"\bsqlx::(?:sqlite|Sqlite)", re.IGNORECASE), "sqlite"),
94
+ (re.compile(r"\bsqlx::(?:Pool|Connection|query|query_as|query!)", re.IGNORECASE), "sql"),
95
+ (re.compile(r"\bdiesel::", re.IGNORECASE), "sql"),
96
+ (re.compile(r"\bsea_orm::|\bSeaOrm\b", re.IGNORECASE), "sql"),
97
+ (re.compile(r"\btokio_postgres::|\bpostgres::Client::", re.IGNORECASE), "postgresql"),
98
+ (re.compile(r"\brusqlite::", re.IGNORECASE), "sqlite"),
99
+ (re.compile(r"\bmongodb::Client", re.IGNORECASE), "mongodb"),
100
+ (re.compile(r"\bredis::(?:Client::open|aio::|Connection|cmd)", re.IGNORECASE), "redis"),
101
+ (re.compile(r"\bdeadpool_postgres", re.IGNORECASE), "postgresql"),
102
+ (re.compile(r"\bdeadpool_redis", re.IGNORECASE), "redis"),
103
+ (re.compile(r"\baws_sdk_s3::|\bS3Client\b", re.IGNORECASE), "object_storage"),
104
+ (re.compile(r"\baws_sdk_dynamodb::", re.IGNORECASE), "dynamodb"),
105
+ ]
106
+
107
+ # Auth-related signals (pattern, hint label)
108
+ AUTH_PATTERNS: list[tuple[re.Pattern[str], str, float]] = [
109
+ (re.compile(r"\bjsonwebtoken::", re.IGNORECASE), "jwt", 0.85),
110
+ (re.compile(r"\bargon2::", re.IGNORECASE), "argon2", 0.9),
111
+ (re.compile(r"\bbcrypt::", re.IGNORECASE), "bcrypt", 0.9),
112
+ (re.compile(r"\bscrypt::", re.IGNORECASE), "scrypt", 0.9),
113
+ (re.compile(r"\bpassword_hash::", re.IGNORECASE), "password_hash", 0.85),
114
+ (re.compile(r"\boauth2::", re.IGNORECASE), "oauth", 0.85),
115
+ (re.compile(r"\baxum_login::", re.IGNORECASE), "axum_login", 0.85),
116
+ (re.compile(r"\bactix_identity::", re.IGNORECASE), "actix_identity", 0.85),
117
+ (re.compile(r"\btower_sessions::", re.IGNORECASE), "tower_sessions", 0.85),
118
+ (re.compile(r"\btower_http::auth::", re.IGNORECASE), "tower_http_auth", 0.85),
119
+ (re.compile(r"\bAuthorization\b", re.IGNORECASE), "authorization_header", 0.6),
120
+ (re.compile(r"\bBearer\b", re.IGNORECASE), "bearer_token", 0.6),
121
+ (re.compile(r"\bapi[_-]?key\b", re.IGNORECASE), "api_key", 0.6),
122
+ ]
123
+
124
+ # Web framework presence. Confidence high — these markers are unambiguous.
125
+ FRAMEWORK_PATTERNS: list[tuple[re.Pattern[str], str]] = [
126
+ (re.compile(r"\baxum::", re.IGNORECASE), "axum"),
127
+ (re.compile(r"\bactix_web::", re.IGNORECASE), "actix-web"),
128
+ (re.compile(r"#\[\s*launch\s*\]|\brocket::build\s*\(", re.IGNORECASE), "rocket"),
129
+ (re.compile(r"\btide::", re.IGNORECASE), "tide"),
130
+ (re.compile(r"\bwarp::", re.IGNORECASE), "warp"),
131
+ (re.compile(r"\bpoem::", re.IGNORECASE), "poem"),
132
+ (re.compile(r"\bsalvo::", re.IGNORECASE), "salvo"),
133
+ (re.compile(r"\btower::Service\b", re.IGNORECASE), "tower"),
134
+ (re.compile(r"\bhyper::", re.IGNORECASE), "hyper"),
135
+ (re.compile(r"\btokio::", re.IGNORECASE), "tokio"),
136
+ ]
137
+
138
+ # Entrypoint markers — server bind / listen / startup
139
+ ENTRYPOINT_PATTERNS: list[tuple[re.Pattern[str], str]] = [
140
+ (re.compile(r"\baxum::serve\s*\(", re.IGNORECASE), "axum_serve"),
141
+ (re.compile(r"\baxum::Server::bind\s*\(", re.IGNORECASE), "axum_server_bind"),
142
+ (re.compile(r"\bHttpServer::new\s*\(", re.IGNORECASE), "actix_http_server"),
143
+ (re.compile(r"\brocket::build\s*\(", re.IGNORECASE), "rocket_build"),
144
+ (re.compile(r"#\[\s*launch\s*\]", re.IGNORECASE), "rocket_launch_attr"),
145
+ (re.compile(r"\btide::new\s*\(", re.IGNORECASE), "tide_new"),
146
+ (re.compile(r"#\[\s*tokio::main\s*\]", re.IGNORECASE), "tokio_main"),
147
+ (re.compile(r"#\[\s*actix_web::main\s*\]", re.IGNORECASE), "actix_main"),
148
+ ]
149
+
150
+ # Secrets — env var names containing SECRET/TOKEN/KEY/PASSWORD/PASS/PWD
151
+ SECRET_PATTERNS: list[re.Pattern[str]] = [
152
+ re.compile(
153
+ r'(?:std::)?env::var\s*\(\s*["]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)["]',
154
+ re.IGNORECASE,
155
+ ),
156
+ re.compile(
157
+ r'\bdotenv(?:y)?::var\s*\(\s*["]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)["]',
158
+ re.IGNORECASE,
159
+ ),
160
+ re.compile(
161
+ r'\benv!\s*\(\s*["]([A-Z0-9_]*(SECRET|TOKEN|KEY|PASSWORD|PASS|PWD)[A-Z0-9_]*)["]',
162
+ re.IGNORECASE,
163
+ ),
164
+ re.compile(r'\bsecrecy::SecretString::new\s*\(', re.IGNORECASE),
165
+ ]
166
+
167
+
168
+ def _line_of(content: str, offset: int) -> int:
169
+ """1-indexed line for an offset in content."""
170
+ if offset <= 0:
171
+ return 1
172
+ return content.count("\n", 0, offset) + 1
173
+
174
+
175
+ def _line_snippet(content: str, offset: int, *, max_chars: int = _SNIPPET_MAX_CHARS) -> str:
176
+ line_start = content.rfind("\n", 0, offset) + 1
177
+ line_end = content.find("\n", offset)
178
+ if line_end == -1:
179
+ line_end = len(content)
180
+ line = content[line_start:line_end].strip()
181
+ if len(line) > max_chars:
182
+ line = line[: max_chars - 1] + "…"
183
+ return line
184
+
185
+
186
+ def _crate_name_from_cargo(cargo_path: Path) -> str | None:
187
+ if not cargo_path.exists():
188
+ return None
189
+ try:
190
+ text = cargo_path.read_text(encoding="utf-8")
191
+ except UnicodeDecodeError:
192
+ return None
193
+ match = re.search(r'^\s*\[package\]\s*\n.*?^\s*name\s*=\s*"([^"]+)"', text, re.MULTILINE | re.DOTALL)
194
+ if match:
195
+ return match.group(1)
196
+ return None
197
+
198
+
199
+ def _workspace_members(cargo_path: Path) -> list[str]:
200
+ if not cargo_path.exists():
201
+ return []
202
+ try:
203
+ text = cargo_path.read_text(encoding="utf-8")
204
+ except UnicodeDecodeError:
205
+ return []
206
+ block = re.search(r"\[workspace\][^\[]*?members\s*=\s*\[([^\]]*)\]", text, re.DOTALL)
207
+ if not block:
208
+ return []
209
+ return re.findall(r'"([^"]+)"', block.group(1))
210
+
211
+
212
+ class RustAnalyzer:
213
+ metadata = AnalyzerMetadata(
214
+ name="rust",
215
+ display_name="Rust Analyzer",
216
+ version="0.1.0",
217
+ description="Rust ecosystem analyzer covering axum, actix-web, rocket, common DB/auth crates, and reqwest.",
218
+ scope="Rust crates and workspaces. Cargo-bearing repos are auto-detected; pure .rs trees also work.",
219
+ targets=["rust", "axum", "actix-web", "rocket"],
220
+ languages=["rust"],
221
+ priority=20,
222
+ experimental=False,
223
+ enabled_by_default=True,
224
+ )
225
+
226
+ @property
227
+ def name(self) -> str:
228
+ return self.metadata.name
229
+
230
+ # ---------- Public entry points ----------
231
+
232
+ def detect(self, repo_path: str | Path) -> bool:
233
+ root = Path(repo_path).resolve()
234
+ if not root.exists() or not root.is_dir():
235
+ return False
236
+ if (root / "Cargo.toml").exists() or (root / "Cargo.lock").exists():
237
+ return True
238
+ for path in root.rglob("Cargo.toml"):
239
+ if any(part in SKIP_DIRS for part in path.parts):
240
+ continue
241
+ return True
242
+ for path in root.rglob("*.rs"):
243
+ if any(part in SKIP_DIRS for part in path.parts):
244
+ continue
245
+ return True
246
+ return False
247
+
248
+ def analyze(self, repo_path: str | Path) -> ScanResult:
249
+ root = Path(repo_path).resolve()
250
+ result = ScanResult(root=str(root))
251
+ if not root.exists() or not root.is_dir():
252
+ return result
253
+
254
+ crate_name = _crate_name_from_cargo(root / "Cargo.toml")
255
+ workspace_members = _workspace_members(root / "Cargo.toml")
256
+ if crate_name:
257
+ self._append_unique_service(result, f"crate:{crate_name}", "Cargo.toml")
258
+ for member in workspace_members:
259
+ self._append_unique_service(result, f"workspace_member:{member}", "Cargo.toml")
260
+
261
+ for file_path in root.rglob("*.rs"):
262
+ if not file_path.is_file():
263
+ continue
264
+ if any(part in SKIP_DIRS for part in file_path.parts):
265
+ continue
266
+
267
+ result.files_scanned += 1
268
+ if "rust" not in result.languages:
269
+ result.languages.append("rust")
270
+
271
+ try:
272
+ content = file_path.read_text(encoding="utf-8")
273
+ except UnicodeDecodeError:
274
+ continue
275
+
276
+ relative = str(file_path.relative_to(root))
277
+ self._extract_routes(content, relative, result)
278
+ self._extract_databases(content, relative, result)
279
+ self._extract_auth(content, relative, result)
280
+ self._extract_secrets(content, relative, result)
281
+ self._extract_external_calls(content, relative, result)
282
+ self._extract_frameworks(content, relative, result)
283
+ self._extract_entrypoints(content, relative, result)
284
+ self._infer_service_role(content, relative, result)
285
+
286
+ result.languages.sort()
287
+ return result
288
+
289
+ # ---------- Extractors ----------
290
+
291
+ def _extract_routes(self, content: str, relative: str, result: ScanResult) -> None:
292
+ # axum: .route("/x", get(h).post(h2)) — pull every method in the routing chain.
293
+ # The capture-group regex sits on the *first* method call (e.g. `get(`); after the opening
294
+ # paren we walk forward looking for additional `.method(` chain links.
295
+ _http_verbs = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE", "CONNECT"}
296
+ for match in AXUM_ROUTE_PATTERN.finditer(content):
297
+ path = match.group(1)
298
+ line = _line_of(content, match.start())
299
+ methods: set[str] = set()
300
+ # First method is the one captured in group 2 (when it's an HTTP verb).
301
+ first_call = match.group(2).split("::")[-1].upper()
302
+ if first_call in _http_verbs:
303
+ methods.add(first_call)
304
+ # Walk a bounded window for chained `.post(...)` / `.delete(...)` etc., stopping at
305
+ # the next .route( or Router::new boundary so we don't pull from the next entry.
306
+ chain_window = content[match.end(): match.end() + 300]
307
+ stop = chain_window.find(".route(")
308
+ stop_alt = chain_window.find("Router::new")
309
+ if stop_alt != -1 and (stop == -1 or stop_alt < stop):
310
+ stop = stop_alt
311
+ if stop != -1:
312
+ chain_window = chain_window[:stop]
313
+ for chain_match in AXUM_METHOD_CHAIN_PATTERN.finditer(chain_window):
314
+ methods.add(chain_match.group(1).upper())
315
+ if not methods:
316
+ methods = {"ANY"}
317
+ for method in sorted(methods):
318
+ self._append_unique_route(result, path, method, relative, line)
319
+
320
+ # actix attribute routes: #[get("/path")] just above an fn
321
+ for match in ACTIX_ATTRIBUTE_ROUTE_PATTERN.finditer(content):
322
+ method, path = match.group(1).upper(), match.group(2)
323
+ self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
324
+
325
+ # actix .route(...): only fires when web:: namespace appears (so it doesn't double-count axum)
326
+ for match in ACTIX_WEB_ROUTE_PATTERN.finditer(content):
327
+ path, method = match.group(1), match.group(2).upper()
328
+ self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
329
+
330
+ # rocket attribute routes — same shape as actix attribute regex; emit only if rocket markers present.
331
+ if "rocket" in content.lower():
332
+ for match in ROCKET_ATTRIBUTE_ROUTE_PATTERN.finditer(content):
333
+ method, path = match.group(1).upper(), match.group(2)
334
+ self._append_unique_route(result, path, method, relative, _line_of(content, match.start()))
335
+
336
+ def _extract_databases(self, content: str, relative: str, result: ScanResult) -> None:
337
+ for pattern, kind in DB_PATTERNS:
338
+ match = pattern.search(content)
339
+ if match is None:
340
+ continue
341
+ self._append_unique_database(
342
+ result,
343
+ kind,
344
+ relative,
345
+ _line_of(content, match.start()),
346
+ _line_snippet(content, match.start()),
347
+ )
348
+
349
+ def _extract_auth(self, content: str, relative: str, result: ScanResult) -> None:
350
+ for pattern, hint, confidence in AUTH_PATTERNS:
351
+ match = pattern.search(content)
352
+ if match is None:
353
+ continue
354
+ self._append_unique_auth(
355
+ result,
356
+ hint,
357
+ relative,
358
+ _line_of(content, match.start()),
359
+ _line_snippet(content, match.start()),
360
+ confidence,
361
+ )
362
+
363
+ def _extract_secrets(self, content: str, relative: str, result: ScanResult) -> None:
364
+ for pattern in SECRET_PATTERNS:
365
+ for match in pattern.finditer(content):
366
+ groups = match.groups()
367
+ name = groups[0] if groups and groups[0] else "secrecy::SecretString"
368
+ self._append_unique_secret(
369
+ result,
370
+ name,
371
+ relative,
372
+ _line_of(content, match.start()),
373
+ _line_snippet(content, match.start()),
374
+ )
375
+
376
+ def _extract_external_calls(self, content: str, relative: str, result: ScanResult) -> None:
377
+ for pattern in OUTBOUND_PATTERNS:
378
+ for match in pattern.finditer(content):
379
+ target = match.group(1)
380
+ # Skip path-only matches (no URL scheme); they're often intra-crate paths.
381
+ if not (target.startswith("http://") or target.startswith("https://") or target.startswith("env://")):
382
+ continue
383
+ self._append_unique_external(
384
+ result,
385
+ target,
386
+ relative,
387
+ _line_of(content, match.start()),
388
+ _line_snippet(content, match.start()),
389
+ )
390
+
391
+ def _extract_frameworks(self, content: str, relative: str, result: ScanResult) -> None:
392
+ for pattern, name in FRAMEWORK_PATTERNS:
393
+ match = pattern.search(content)
394
+ if match is None:
395
+ continue
396
+ self._append_unique_framework(
397
+ result,
398
+ name,
399
+ relative,
400
+ _line_of(content, match.start()),
401
+ _line_snippet(content, match.start()),
402
+ )
403
+
404
+ def _extract_entrypoints(self, content: str, relative: str, result: ScanResult) -> None:
405
+ for pattern, hint in ENTRYPOINT_PATTERNS:
406
+ match = pattern.search(content)
407
+ if match is None:
408
+ continue
409
+ self._append_unique_entrypoint(
410
+ result,
411
+ hint,
412
+ relative,
413
+ _line_of(content, match.start()),
414
+ _line_snippet(content, match.start()),
415
+ )
416
+
417
+ def _infer_service_role(self, content: str, relative: str, result: ScanResult) -> None:
418
+ haystack = (relative + " " + content[:500]).lower()
419
+ role: str | None = None
420
+ if any(token in haystack for token in ("worker", "consumer", "queue", "background")):
421
+ role = "worker"
422
+ elif any(token in haystack for token in ("api", "server", "handler", "routes")):
423
+ role = "api"
424
+ elif any(token in haystack for token in ("client", "sdk")):
425
+ role = "client"
426
+ if role:
427
+ self._append_unique_service(result, f"service_role:{role}", relative)
428
+
429
+ # ---------- Append helpers (dedup-aware) ----------
430
+
431
+ @staticmethod
432
+ def _append_unique_route(
433
+ result: ScanResult,
434
+ path: str,
435
+ method: str,
436
+ file: str,
437
+ line: int | None,
438
+ ) -> None:
439
+ key = (path, method, file)
440
+ if any((item.path, item.method, item.file) == key for item in result.routes):
441
+ return
442
+ result.routes.append(Route(path=path, method=method, file=file, line=line))
443
+
444
+ @staticmethod
445
+ def _append_unique_database(
446
+ result: ScanResult,
447
+ kind: str,
448
+ file: str,
449
+ line: int | None,
450
+ evidence: str | None,
451
+ ) -> None:
452
+ key = (kind, file)
453
+ if any((item.kind, item.file) == key for item in result.databases):
454
+ return
455
+ result.databases.append(
456
+ DatabaseHint(kind=kind, file=file, line=line, evidence_text=evidence)
457
+ )
458
+
459
+ @staticmethod
460
+ def _append_unique_auth(
461
+ result: ScanResult,
462
+ hint: str,
463
+ file: str,
464
+ line: int | None,
465
+ evidence: str | None,
466
+ confidence: float,
467
+ ) -> None:
468
+ key = (hint, file)
469
+ if any((item.hint, item.file) == key for item in result.auth_hints):
470
+ return
471
+ result.auth_hints.append(
472
+ AuthHint(hint=hint, file=file, line=line, evidence_text=evidence, confidence=confidence)
473
+ )
474
+
475
+ @staticmethod
476
+ def _append_unique_secret(
477
+ result: ScanResult,
478
+ name: str,
479
+ file: str,
480
+ line: int | None,
481
+ evidence: str | None,
482
+ ) -> None:
483
+ key = (name, file)
484
+ if any((item.name, item.file) == key for item in result.secret_hints):
485
+ return
486
+ result.secret_hints.append(
487
+ SecretHint(name=name, file=file, line=line, evidence_text=evidence, confidence=0.85)
488
+ )
489
+
490
+ @staticmethod
491
+ def _append_unique_external(
492
+ result: ScanResult,
493
+ target: str,
494
+ file: str,
495
+ line: int | None,
496
+ evidence: str | None,
497
+ ) -> None:
498
+ key = (target, file)
499
+ if any((item.target, item.file) == key for item in result.external_calls):
500
+ return
501
+ result.external_calls.append(
502
+ ExternalCall(target=target, file=file, line=line, evidence_text=evidence)
503
+ )
504
+
505
+ @staticmethod
506
+ def _append_unique_framework(
507
+ result: ScanResult,
508
+ hint: str,
509
+ file: str,
510
+ line: int | None,
511
+ evidence: str | None,
512
+ ) -> None:
513
+ key = (hint, file)
514
+ if any((item.hint, item.file) == key for item in result.framework_hints):
515
+ return
516
+ result.framework_hints.append(
517
+ FrameworkHint(hint=hint, file=file, line=line, evidence_text=evidence)
518
+ )
519
+
520
+ @staticmethod
521
+ def _append_unique_entrypoint(
522
+ result: ScanResult,
523
+ hint: str,
524
+ file: str,
525
+ line: int | None,
526
+ evidence: str | None,
527
+ ) -> None:
528
+ key = (hint, file)
529
+ if any((item.hint, item.file) == key for item in result.entrypoint_hints):
530
+ return
531
+ result.entrypoint_hints.append(
532
+ EntrypointHint(hint=hint, file=file, line=line, evidence_text=evidence)
533
+ )
534
+
535
+ @staticmethod
536
+ def _append_unique_service(result: ScanResult, hint: str, file: str) -> None:
537
+ key = (hint, file)
538
+ if any((item.hint, item.file) == key for item in result.service_hints):
539
+ return
540
+ result.service_hints.append(ServiceHint(hint=hint, file=file))
541
+
542
+
543
+ __all__ = ["RustAnalyzer"]
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from attackmap.sdk.contracts import AnalyzerMetadata, AnalyzerProtocol
4
+ from attackmap.sdk.models import (
5
+ AuthHint,
6
+ DatabaseHint,
7
+ EntrypointHint,
8
+ ExternalCall,
9
+ FrameworkHint,
10
+ Route,
11
+ ScanResult,
12
+ SecretHint,
13
+ ServiceHint,
14
+ )
15
+
16
+ # Compatibility alias used by existing analyzer implementations.
17
+ AttackMapAnalyzerProtocol = AnalyzerProtocol
18
+
19
+ __all__ = [
20
+ "AnalyzerMetadata",
21
+ "AttackMapAnalyzerProtocol",
22
+ "Route",
23
+ "ExternalCall",
24
+ "DatabaseHint",
25
+ "AuthHint",
26
+ "EntrypointHint",
27
+ "FrameworkHint",
28
+ "ServiceHint",
29
+ "SecretHint",
30
+ "ScanResult",
31
+ ]
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: attackmap-analyzer-rust
3
+ Version: 0.1.0
4
+ Summary: Rust ecosystem analyzer plugin for AttackMap (axum, actix-web, rocket; sqlx/diesel/sea-orm; jsonwebtoken/argon2; reqwest).
5
+ Author: AttackMap Contributors
6
+ Author-email: Matthew Davis <matthewd@matthewd.xyz>
7
+ Maintainer-email: Matthew Davis <matthewd@matthewd.xyz>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/mlaify/attackmap-analyzer-rust
10
+ Project-URL: Repository, https://github.com/mlaify/attackmap-analyzer-rust
11
+ Project-URL: Issues, https://github.com/mlaify/attackmap-analyzer-rust/issues
12
+ Project-URL: Changelog, https://github.com/mlaify/attackmap-analyzer-rust/blob/main/CHANGELOG.md
13
+ Project-URL: AttackMap core, https://github.com/mlaify/AttackMap
14
+ Keywords: security,static-analysis,appsec,defensive-security,attackmap,attackmap-plugin
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Information Technology
18
+ Classifier: Intended Audience :: System Administrators
19
+ Classifier: License :: OSI Approved :: MIT License
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3 :: Only
26
+ Classifier: Topic :: Security
27
+ Classifier: Topic :: Software Development :: Quality Assurance
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.11
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: pydantic>=2.7.0
33
+ Provides-Extra: core
34
+ Requires-Dist: attackmap>=0.1.0; extra == "core"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
37
+ Requires-Dist: build>=1.2.0; extra == "dev"
38
+ Requires-Dist: attackmap>=0.1.0; extra == "dev"
39
+ Dynamic: license-file
40
+
41
+ # attackmap-analyzer-rust
42
+
43
+ Rust ecosystem analyzer for [AttackMap](https://github.com/mlaify/AttackMap).
44
+
45
+ This analyzer extracts structured signals from Rust crates and Cargo workspaces:
46
+
47
+ - **Web frameworks** — axum, actix-web, rocket (route + entrypoint extraction)
48
+ - **Databases** — sqlx (Postgres / MySQL / SQLite), diesel, sea-orm, tokio-postgres, rusqlite, mongodb, redis, deadpool, AWS SDK (S3 / DynamoDB)
49
+ - **Auth crates** — jsonwebtoken, argon2 / bcrypt / scrypt / password-hash, oauth2, axum-login, actix-identity, tower-sessions, tower-http auth
50
+ - **HTTP clients (external calls)** — reqwest, isahc, surf, ureq
51
+ - **Secrets** — `std::env::var`, `dotenv` / `dotenvy`, `env!` macro, `secrecy::SecretString`
52
+ - **Service hints** — Cargo `[package].name` and `[workspace].members`
53
+
54
+ All emissions populate AttackMap's Signal v2 fields (line numbers, evidence snippets, confidence scores) so downstream insights can cite `path/to/file.rs:NN`.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install git+https://github.com/mlaify/attackmap-analyzer-rust.git
60
+ ```
61
+
62
+ The analyzer is auto-discovered by AttackMap via the `attackmap.analyzers` entry-point group.
63
+
64
+ ## Usage with AttackMap
65
+
66
+ ```bash
67
+ # Auto-discovered when installed:
68
+ attackmap analyze /path/to/rust/repo
69
+
70
+ # Or invoke explicitly:
71
+ attackmap analyze /path/to/rust/repo --module rust
72
+ ```
73
+
74
+ ## Detection
75
+
76
+ `detect()` returns true when any of the following are present, ignoring `target/`, `.git/`, `node_modules/`, `.cargo/`, and `vendor/`:
77
+
78
+ - A `Cargo.toml` or `Cargo.lock` at the repository root, or anywhere in the tree
79
+ - One or more `.rs` files in the tree
80
+
81
+ ## Coverage notes
82
+
83
+ - **Warp** is intentionally not covered yet — its filter-based routing makes path extraction unreliable from regex alone.
84
+ - **Tide** framework presence is detected via `tide::` imports; route extraction for tide's `app.at("/x").get(...)` chain is on the roadmap.
85
+ - Multi-method axum chains like `.route("/x", get(h).post(h2))` produce one `Route` per HTTP verb in the chain, all sharing the same `line`.
86
+ - The actix-web attribute regex (`#[get(...)]`) and rocket attribute regex are intentionally identical; rocket emissions only fire when the file also mentions `rocket` somewhere, to avoid double-counting actix routes.
87
+
88
+ ## License
89
+
90
+ MIT
@@ -0,0 +1,9 @@
1
+ attackmap_analyzer_rust/__init__.py,sha256=jNIsqi2upFZUf6RkoyVp3WVD-fvvEbj9NwwRkiFpy-E,63
2
+ attackmap_analyzer_rust/analyzer.py,sha256=kEDGjkMbrMQarqCp_7l3E11pcFS8QWKV1jazs1CzXBY,21818
3
+ attackmap_analyzer_rust/contracts.py,sha256=6Kd8AZYMCQiR0JJpiAptlHYyuzr7ngWEwwXK-uUrWPM,643
4
+ attackmap_analyzer_rust-0.1.0.dist-info/licenses/LICENSE,sha256=vtPQVGUyxq359j0JmD3_eJaXyHmaHyjzaMOtaLwJc88,1097
5
+ attackmap_analyzer_rust-0.1.0.dist-info/METADATA,sha256=VsXOd9VfQOnAWBdaShviTaVhFyqEzu4B9t_MVdVkVTw,4131
6
+ attackmap_analyzer_rust-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ attackmap_analyzer_rust-0.1.0.dist-info/entry_points.txt,sha256=QCFC6xBuNBgFX_DBilz_B2ZJP1jMMeoqy_3jXKCHx0c,66
8
+ attackmap_analyzer_rust-0.1.0.dist-info/top_level.txt,sha256=VTNwgVcQmqxAjpCDx35w9CbzaQZR9Mmohxt7Z6PtJuM,24
9
+ attackmap_analyzer_rust-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [attackmap.analyzers]
2
+ rust = attackmap_analyzer_rust:RustAnalyzer
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthew Davis and AttackMap Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ attackmap_analyzer_rust