- Java 94.5%
- Mermaid 5.3%
- Python 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| .github | ||
| ai-pentest | ||
| .gitignore | ||
| CLAUDE.md | ||
| LICENSE | ||
| README.md | ||
swiyu-ai-pentest 🛡️🤖
Multi-repository AI security scanning and triage engine for the swiyu Trust Infrastructure.
The swiyu AI Security Scanner supports the development teams of the swiyu E-ID Trust Infrastructure (issuer, verifier, shared libraries) in improving their code quality with the help of AI. It finds deviations from the specification and faulty implementations so that they can be fixed early. It checks the code against the Swiss E-ID profiles and the normative standards behind them (OID4VCI, OID4VP, RFC 9449 DPoP, RFC 9901 SD-JWT, W3C DID Core).
Important: this project does not replace penetration tests. It is in no way a substitute for pentests or security reviews by internal or external partners. It is an additional, automated aid for developers: it provides hints and hypotheses that are verified against the specification, not a security assessment or a proof that the code is free of vulnerabilities. A clean report does not mean the code is secure, and findings are LLM-based and must be reviewed and validated by people before they are acted upon.
Instead of sending the whole code base to one expensive LLM, the scanner works as a five-stage funnel: cheap deterministic and fast-LLM stages narrow the code down to a few hypotheses, a strong LLM verifies each hypothesis against the specifications, a judge removes duplicates, and only confirmed findings end up in the report.
- Java 25, Spring Boot 4, Spring AI (Anthropic or any OpenAI-compatible endpoint)
- Specification retrieval (RAG) through Context7
- Output as SARIF 2.1.0 (GitHub Code Scanning) and a Markdown summary
- Runs as a CLI, locally or as a scheduled GitHub Action
Table of contents
- How it works
- Stage 1: File filtering
- Stage 2: AI triage
- Stage 3: Deep scan
- Stage 4: Judge
- Stage 5: Reporting
- Suspect mode
- Getting started
- Configuration
- Output files
- Scheduled scan (GitHub Actions)
- Project structure and architecture rules
- Testing
- Design principles
How it works
flowchart TD
subgraph P1["Stage 1: File filtering and I/O (FileFilterService)"]
direction TD
A1["Traverse repository structure and paths"] --> A2["Drop build artifacts (target/), .git and binary files"] --> A3["Read relevant Java source files"]
end
subgraph P2["Stage 2: AI triage and pre-filtering (AiTriageService)"]
direction TD
B0{"claims-dir set?"}
B0 -- yes --> B0a["Stage 2a: derive hypotheses from suspected claims<br/>(SuspectClaimsService)"]
B0 -- no --> B1
B0a --> B1["Sort files by security keyword density"]
B1 --> B2["Call fast and cheap LLM (e.g. Claude 5.5 Haiku)"]
B2 --> B3["Create targeted security hypotheses (H001, H002, ...)<br/>reduces data volume by roughly 60-70 %"]
B3 --> B4["Bundle into TriageResult, write triage.json"]
end
subgraph P3["Stage 3: Deep scan and RAG verification (DeepScanService)"]
direction TD
C0{"Another hypothesis to check?"}
C0 -- yes --> C1["Query normative Swiss E-ID profiles and RFCs<br/>via Context7 REST API"]
C1 --> C2["Inject code context + RAG specifications into prompt"]
C2 --> C3["Call strong reasoning LLM (e.g. Claude 5.5 Sonnet)"]
C3 --> C4{"Verdict CONFIRMED?"}
C4 -- yes --> C5["Create verified Finding"]
C4 -- no --> C6["Discard as false positive / inconclusive<br/>(discarded.json)"]
C5 --> C0
C6 --> C0
end
subgraph P4["Stage 4: Judge and deduplication (JudgeService)"]
direction TD
D0["Receive confirmed findings from Stage 3"]
D0 --> D1{"Judge enabled, no dry run,<br/>2 ≤ findings ≤ max-findings?"}
D1 -- yes --> D2["Call strongest LLM (e.g. Claude 5.1 Fable)"]
D2 --> D3["Group findings of the same defect into clusters<br/>(code and specification tools available)"]
D3 --> D4["Validate clusters, build one finding per cluster<br/>from the originals (highest severity, mergedLocations)"]
D1 -- no --> D5["Pass findings on unchanged"]
end
subgraph P5["Stage 5: Reporting and export (SarifReportGenerator, SummaryReportGenerator)"]
direction TD
E1["Convert findings to GitHub SARIF v2.1.0"] --> E2["Create Markdown summary report"] --> E3["Write results.sarif and summary.md"]
end
P1 --> P2 --> P3 --> P4 --> P5
| Stage | Package | Uses | Input → Output |
|---|---|---|---|
| 1 Filtering | stage1_filtering |
file system only | repos → ScanContext |
| 2 Triage | stage2_triage |
fast, cheap LLM | ScanContext → hypotheses |
| 3 Deep scan | stage3_deepscan |
strong LLM + Context7 RAG | hypotheses → confirmed findings + audit |
| 4 Judge | stage4_judge |
strongest LLM (one call) | findings → consolidated findings |
| 5 Reporting | stage5_reporting |
file system only | findings → results.sarif, summary.md |
Which stage uses which resources
Cost and external dependencies grow from Stage 1 to Stage 4. Stage 1 and 5 run entirely locally. Stage 2 calls a low-cost model. Stage 3 uses a good model plus the Context7 RAG server and local tool callbacks (the LLM can request missing code or specification rules while it reasons). Stage 4 calls the strongest model once; it can use the same tool callbacks to verify its groupings.
flowchart LR
subgraph Local["Local machine / CI runner"]
direction LR
S1["<b>Stage 1</b> File filtering<br/>purely local, no AI, no network"]
S2["<b>Stage 2</b> AI triage"]
S3["<b>Stage 3</b> Deep scan"]
S4["<b>Stage 4</b> Judge"]
S5["<b>Stage 5</b> Reporting<br/>purely local, no AI, no network"]
FS[("Repos in workspace/<br/>ScanContext in memory")]
Tools["Local tool callbacks<br/>getMethodSource, getFieldSource<br/>(read from ScanContext)"]
Out[("results.sarif<br/>summary.md")]
end
subgraph Remote["External services"]
direction TB
LLMLow["Low-cost LLM<br/>fast model (e.g. Claude Haiku)"]
LLMMid["Good LLM<br/>strong reasoning model (e.g. Claude Sonnet)"]
LLMTop["Strongest LLM<br/>(e.g. Claude Fable)<br/>one call per run"]
RAG["Context7 RAG server<br/>Swiss E-ID profiles, OID4VCI, OID4VP, RFCs"]
end
FS --> S1 --> S2 --> S3 --> S4 --> S5 --> Out
S2 -- "one call per file" --> LLMLow
S3 -- "one call per hypothesis" --> LLMMid
S3 -. "tool call" .-> Tools
S3 -. "tool call searchSpecifications<br/>+ spec context before the call" .-> RAG
S4 -- "one call for all findings" --> LLMTop
S4 -. "tool calls (verification of groupings)" .-> Tools
S4 -. "tool call searchSpecifications" .-> RAG
style S1 fill:#dcfce7,stroke:#15803d
style S5 fill:#dcfce7,stroke:#15803d
style S2 fill:#fef9c3,stroke:#a16207
style S3 fill:#fed7aa,stroke:#c2410c
style S4 fill:#fecaca,stroke:#b91c1c
| Stage | LLM | Default model | RAG (Context7) | Tool callbacks | LLM calls |
|---|---|---|---|---|---|
| 1 Filtering | none | - | no | no | 0 |
| 2 Triage | low-cost | claude-haiku-5-5 |
no | no | one per file |
| 3 Deep scan | good | claude-sonnet-5-5 |
yes | getMethodSource, getFieldSource, searchSpecifications |
one per hypothesis |
| 4 Judge | strongest | claude-fable-5-1 |
only via tool, to settle unclear groupings | getMethodSource, getFieldSource, searchSpecifications |
one per run |
| 5 Reporting | none | - | no | no | 0 |
Data flows in one direction and stages exchange data only through immutable records from domain:
flowchart TD
CLI["CLI<br/>--repo=<name>=<path> (repeatable), --output=<dir>"]
CLI --> Init["PentestPipeline<br/>create output directory"]
Init --> S1["<b>Stage 1</b> File Filtering<br/>→ ScanContext"]
S1 --> S2["<b>Stage 2</b> AI Triage<br/>(optional Stage 2a: hypotheses from suspected claims)<br/>→ Hypotheses"]
S2 --> S3["<b>Stage 3</b> Deep Scan (RAG)<br/>→ Findings"]
S3 --> Aborted{"Stage 3 aborted?"}
Aborted -- yes --> LogErr["Log error<br/>(findings found so far are kept)"]
Aborted -- no --> S4
LogErr --> S4["<b>Stage 4</b> Judge (LLM)<br/>→ consolidated Findings (duplicates merged)"]
S4 --> S5["<b>Stage 5</b> Reporting<br/>→ results.sarif, summary.md"]
style LogErr fill:#fecaca,stroke:#b91c1c
Key ideas:
- Hypotheses are pointers, not findings. Stage 2 only says "this method deserves a closer look". It never decides whether something is a vulnerability.
- LLM output is untrusted. It is parsed leniently, validated, and never controls file paths or code execution. Source code in prompts is treated as untrusted data (prompt injection defense).
- Deterministic safety nets surround every LLM call: heuristic fallback in Stage 2,
VerdictPolicyin Stage 3, cluster normalization in Stage 4. The judge can neither invent nor drop a finding. - Fail loudly where it matters. If the specification source (Context7) is unreachable, Stage 3 aborts instead of guessing. Whether other LLM failures abort or degrade gracefully is controlled by
scanner.fail-on-llm-error. - Cross-repo call graphs. Files are keyed as
<repo>:<relative/path>, so Stage 3 can follow calls from the issuer/verifier intoswiyu-generic-java-lib.
Stage 1: File filtering
Deterministic I/O, no AI and no network (FileFilterService). It walks every repo, skips build and tooling directories (.git, .idea, target, build, .gradle, build-logic, .build, DerivedData, Pods, node_modules, ...) and, unless scanner.include-tests=true, test directories (test, tests, benches, androidTest, testFixtures, Tests, Mocks and every directory ending in Tests or Test, e.g. Xcode test targets and Kotlin Multiplatform source sets such as commonTest), plus the directories in scanner.exclude-dirs (a name or a repo-relative path, e.g. UI code of the Android or iOS wallet). Files must match scanner.file-extensions (default .java, .rs, Cargo.toml, .kt, .swift; suffix match), be at most scanner.max-file-size-kb large and be readable UTF-8. The result is the ScanContext: repo roots, the list of target files and all file contents.
flowchart TD
In["Input: repos (name → path)"] --> Walk["Walk file tree of repo"]
Walk --> Excl{"Excluded directory?<br/>.git, .idea, target, build, node_modules, tests*"}
Excl -- yes --> SkipDir["Skip subtree"]
Excl -- no --> Match{"Matching extension,<br/>size ≤ max-file-size-kb,<br/>readable UTF-8?"}
Match -- yes --> Read["Read content<br/>store under key <repo>:<relative/path>"]
Match -- no --> SkipFile["Skip file<br/>(warn if unreadable)"]
SkipDir --> More
Read --> More
SkipFile --> More
More{"More files and<br/>max-files not reached?"}
More -- yes --> Walk
More -- no --> Out["Output: ScanContext<br/>(roots, target files, file contents)"]
Note["* tests directories are only excluded if scanner.include-tests=false"]
Excl -.- Note
Stage 2: AI triage
A cheap pre-filter that turns files into hypotheses (AiTriageService). Per file (in parallel, on virtual threads) a fast LLM (triageChatClient, default claude-haiku-5-5) is asked which concrete locations implement critical protocol or identity logic worth verifying. To stay generic, the triage prompt forbids describing the suspected defect; Stage 3 reads the code itself.
Helpers, one job each: TriagePromptBuilder, HeuristicTriage (keyword-based fallback: at least two security keywords make a file suspicious), HypothesisPolicy (caps hypotheses per file by priority, scanner.max-hypotheses-per-file), TriageResultWriter.
Notable behaviour:
- Per language (
SourceLanguage, chosen by file extension: Java, Rust, Kotlin, Swift): the prompts inprompts/contain{{placeholders}}filled fromprompts/lang/<language>.properties, and an optionalprompts/lang/<language>-hint.txtadds language notes (Rust idioms, Android wallet threats for Kotlin, iOS wallet threats for Swift). The heuristic uses per-language keywords; Rust, Kotlin and Swift match them case-insensitively, soverify_signatureandverifyJwtSignaturecount. - Dry run (
scanner.dry-run=true, the default): only the heuristic runs, no LLM is called. - LLM failure: falls back to the heuristic, unless the file already has hypotheses (then it counts as covered) or
scanner.fail-on-llm-error=true(then the run aborts). - Stage 2a, suspected claims (
scanner.claims-dir): hypotheses are first derived from known suspicions (see Suspect mode) and handed to Stage 2 as already known, so triage only asks for new ones. - Partial scans (
scanner.full-scan=false): hypotheses discarded in earlier runs (scanner.discarded-dir, written by Stage 5) are loaded and not raised again.
flowchart TD
In["Input: ScanContext"] --> Claims{"scanner.claims-dir set?"}
Claims -- yes --> A2a["Stage 2a SuspectClaimsService<br/>load all *.json claims files<br/>keep entries without repo or with a scanned repo"]
A2a --> ClaimTriage["Per entry: claim triage<br/>suspectFile → one file,<br/>else keyword → all matching files"]
ClaimTriage --> Existing["Existing hypotheses<br/>(entry without match is skipped)"]
Claims -- no --> NoExisting["Existing hypotheses = none"]
Existing --> Select
NoExisting --> Select["Select files (scanner.triage-limit)"]
subgraph PerFile["Per file (parallel, virtual threads)"]
direction TD
Dry{"dry-run?"}
Dry -- yes --> Heur["HeuristicTriage<br/>≥ 2 security keywords = suspicious"]
Dry -- no --> Prompt["TriagePromptBuilder<br/>incl. known hypotheses of the file:<br/>DISCARDED (partial scan) and PENDING (only NEW ones wanted)"]
Prompt --> LLM["Fast LLM (triageChatClient)<br/>→ TriageResponse"]
LLM --> Failed{"LLM failed?"}
Failed -- no --> Map["Map response to Hypotheses<br/>(defaults + validation)"]
Failed -- yes --> FailFast{"fail-on-llm-error?"}
FailFast -- yes --> Abort["Abort with error"]
FailFast -- no --> HasExisting{"File has existing<br/>hypotheses?"}
HasExisting -- yes --> Covered["No hypotheses<br/>(already covered)"]
HasExisting -- no --> Fallback["Fallback: HeuristicTriage"]
Heur --> Cap
Map --> Cap
Covered --> Cap
Fallback --> Cap
Cap["HypothesisPolicy<br/>cap per file by priority"]
end
Select --> Dry
Cap --> Merge["Merge: existing hypotheses first, then new ones<br/>assign IDs (H001, H002, ...)"]
Merge --> Summary["Build TriageSummary<br/>(files, suspicious, reduction, hypotheses)"]
Summary --> Debug{"debug-output?"}
Debug -- yes --> Write["JsonFiles writes JSON"]
Debug -- no --> Out
Write --> Out["Output: TriageResult (hypotheses)"]
style Abort fill:#fecaca,stroke:#b91c1c
Stage 3: Deep scan
The core of the scanner (DeepScanService). Every hypothesis is verified with a strong LLM (deepScanChatClient, scanner.deep-scan-model-name, default claude-sonnet-5-5), again in parallel on virtual threads. Hypotheses on the same method share one code and specification context.
- Code context (
CodeContextService): the flagged method plus the call graph resolved from theScanContext, bounded byscanner.max-call-graph-*andscanner.max-lib-files. Java is parsed with JavaParser; Rust, Kotlin and Swift are analysed text-based. In Kotlin, use cases called through a property (verifyJwt(...)) are followed from the interface to the implementinginvoke; in Swift, injected use cases (@Injected(\.useCase)) are followed from theirFactory<Protocol>registration inextension Containerto the conforming type'scallAsFunction. - Specification context (
SpecContextAssembler,Context7RAGClient): normative rules are fetched from Context7, Swiss profile first, then base specifications. - LLM verification: the model gets hypothesis, specs and code, plus tools to fetch missing code (
getMethodSource,getFieldSource) and to search specifications (searchSpecifications). Answer: aVerdict(CONFIRMED,FALSE_POSITIVE,INCONCLUSIVE), confidence, CWE, severity, line number, remediation, spec references and, for confirmed findings, a one-line title of the defect (at most 100 characters; the hypothesis title is the fallback). - Verdict policy (
VerdictPolicy): aCONFIRMEDverdict that admits in its own justification that relevant code was not visible is downgraded toINCONCLUSIVE. Pure logic defects without a violated spec rule are capped at medium severity.
Every hypothesis gets an AuditEntry; only CONFIRMED ones become Findings. Stage 3 aborts if Context7 stays unreachable after scanner.context7-max-attempts attempts or the LLM repeatedly fails. Rate-limit errors are retried with backoff. With scanner.debug-output=true every LLM exchange is written to <hypothesisId>_deepScan.json.
flowchart TD
In["Input: ScanContext + Hypotheses"] --> Select["Select hypotheses<br/>(skip-low-priority, deep-scan-limit)"]
Select --> Dry{"dry-run?"}
Dry -- yes --> DryOut["Audit entries only ('not assessed'), no findings<br/>Output: DeepScanResult"]
Dry -- no --> Ctx
subgraph PerHyp["Per hypothesis (parallel, virtual threads)"]
direction TD
Ctx["CodeContextService<br/>flagged method and call graph from ScanContext"]
Ctx --> Spec["SpecContextAssembler<br/>query Context7 (Swiss Profile first, then base specs)"]
Spec --> C7{"Context7 unreachable<br/>after retries?"}
C7 -- yes --> AbortC7["Cancel remaining work<br/>Abort Stage 3 (abortReason)"]
C7 -- no --> Prompt["DeepScanPromptBuilder<br/>hypothesis + specs + code"]
Prompt --> LLM["Strong LLM (deepScanChatClient)<br/>tools: getMethodSource, getFieldSource, searchSpecifications<br/>→ VerificationResponse"]
LLM --> Failed{"LLM failed?"}
Failed -- yes --> FailFast{"fail-on-llm-error?"}
FailFast -- yes --> AbortLlm["Abort with error"]
FailFast -- no --> Inconclusive["Verdict INCONCLUSIVE"]
Failed -- no --> MapRes["Map to VerificationResult<br/>(lenient, validated)"]
MapRes --> Policy["VerdictPolicy<br/>downgrade speculative CONFIRMED"]
Inconclusive --> Audit
Policy --> Audit["Add AuditEntry"]
Audit --> Confirmed{"CONFIRMED?"}
Confirmed -- yes --> Finding["Create Finding"]
end
Confirmed -- no --> Out
Finding --> Out["Output: DeepScanResult<br/>(findings, audit, abortReason)"]
style AbortC7 fill:#fecaca,stroke:#b91c1c
style AbortLlm fill:#fecaca,stroke:#b91c1c
Stage 4: Judge
The same defect is often confirmed several times through different hypotheses: from different entry points, from callers of the faulty method, or under different CWE ids. JudgeService makes one call to the strongest model (judgeChatClient, default claude-fable-5-1, scanner.judge.*) that groups findings describing the same defect into clusters. The judge may check the code and the specifications with the Stage 3 tools.
The judge only groups:
- The reported finding is always built from the original findings: the primary finding (where the defect lives and is fixed) with the highest member severity, the union of spec references, and
mergedLocationsplusmergeRationalefor traceability. - The only text the judge writes is an optional title for clusters of more than one finding, describing the shared defect; it is normalized to one line, ignored for clusters of one, and without it the primary finding keeps its Stage 3 title.
- The grouping is untrusted and normalized: unknown or repeated ids are dropped, an invalid primary is replaced, and findings the judge did not assign become clusters of their own. No finding can get lost.
- The judge is fail-safe: if it is disabled, in dry-run mode, has fewer than two findings, more than
scanner.judge.max-findings, non-unique ids, or the LLM fails, the findings are passed on unchanged (unlessfail-on-llm-erroris set). - When in doubt the judge keeps findings separate: a wrong merge hides a real finding, a missing merge only costs a duplicate line.
flowchart TD
In["Input: ScanContext + Findings from Stage 3"] --> Skip1{"judge disabled, dry-run<br/>or fewer than 2 findings?"}
Skip1 -- yes --> Unchanged["Findings unchanged<br/>(one cluster per finding)"]
Skip1 -- no --> Skip2{"findings > scanner.judge.max-findings?"}
Skip2 -- yes --> Unchanged
Skip2 -- no --> Skip3{"hypothesis ids unique and not null?"}
Skip3 -- no --> Unchanged
Skip3 -- yes --> Prompt["JudgePromptBuilder<br/>findings are untrusted data"]
Prompt --> LLM["Strongest LLM (judgeChatClient, one call)<br/>tools: getMethodSource, getFieldSource, searchSpecifications<br/>→ JudgeResponse (clusters)"]
LLM --> Retry{"LLM failed and<br/>attempts < 2?"}
Retry -- yes --> LLM
Retry -- no --> Failed{"LLM failed or no answer?"}
Failed -- yes --> FailFast{"fail-on-llm-error?"}
FailFast -- yes --> Abort["Abort with error"]
FailFast -- no --> Unchanged
Failed -- no --> Normalize["Normalize clusters<br/>drop unknown / repeated ids, replace invalid primary,<br/>unassigned findings become their own cluster,<br/>cluster title only for merges"]
Normalize --> Merge["Per cluster: build finding from the originals<br/>primary finding, highest member severity,<br/>union of spec references, mergedLocations + mergeRationale"]
Merge --> Out["Output: JudgeResult<br/>(consolidated findings, clusters)"]
Unchanged --> Out
Out --> Debug{"debug-output?"}
Debug -- yes --> Write["Write judge.json"]
Note["The judge only groups. It can neither invent nor drop a finding;<br/>the result is always built from the original findings."]
Normalize -.- Note
style Abort fill:#fecaca,stroke:#b91c1c
Stage 5: Reporting
Output formats only, no analysis. SarifReportGenerator writes SARIF 2.1.0 for GitHub Security integration, SummaryReportGenerator writes a Markdown report with funnel metrics (ReportStats), severity distribution, per-repo counts and finding details. Only CONFIRMED findings are exported.
- SARIF
level: critical/high →error, medium →warning, low →note - Alert title: GitHub shows the rule's
shortDescription, so every finding gets its own rule whose title is the LLM-written one-line summary of the defect (Stage 3, or the judge for merged findings); without a title the classificationCWE-<n> / <category>is used. The Markdown summary uses the same title as heading and lists the classification below it. - SARIF
ruleId:CWE-<n> / <category> / <hash>, where the hash covers repo, file and function. It never depends on the LLM-written title, so a defect keeps its alert across runs; the CWE stays filterable as tagexternal/cwe/cwe-<n> - Merged findings carry
relatedLocations(SARIF) and "Also reported at" (Markdown) - A stable
partialFingerprintsvalue (swiyuFinding/v1) lets GitHub track findings across runs - False positives and inconclusive hypotheses are never reported; with
debug-outputthey are archived indiscarded.json
flowchart TD
In["Input: consolidated findings from Stage 4 (Judge)"] --> Sarif & Summary
subgraph Parallel["Report generation"]
direction TD
Sarif["SarifReportGenerator<br/>map findings to SARIF 2.1.0<br/>(rules, results, locations,<br/>relatedLocations of merged findings)"]
Sarif --> WriteSarif["Write results.sarif<br/>(GitHub Security integration)"]
Summary["SummaryReportGenerator<br/>aggregate findings by severity / repo<br/>(ReportStats, 'Also reported at' for merged findings)"]
Summary --> WriteMd["Write summary.md"]
end
WriteSarif --> Out
WriteMd --> Out["Output directory contains results.sarif and summary.md"]
Out --> Debug{"debug-output?"}
Debug -- yes --> Disc["DiscardedFindingsLogger writes discarded.json<br/>(FALSE_POSITIVE / INCONCLUSIVE of the Stage 3 audit)"]
Note["Only CONFIRMED findings are exported.<br/>level: critical/high = error, medium = warning, low = note<br/>one rule per finding, alert title = finding title<br/>ruleId: CWE-<n> / <category> / <location hash><br/>Duplicates were already merged in Stage 4"]
Out -.- Note
Suspect mode
Besides the full scan there is a second pipeline (SuspectPipeline) for existing suspicions, for example from a security review or a Jira issue. Stage 1, 3, 4 and 5 are the same as in the full scan (VerificationStages); Stage 2 derives hypotheses from the statement instead of scanning every file.
# one file + one suspicion
--suspect-file=swiyu-issuer:src/main/java/.../DpopService.java --suspect-claim="DPoP key is not bound to the attested key"
# a topic: all files mentioning the keyword (any spelling) are checked
--suspect-keyword=sd-jwt --suspect-claim-file=claim.txt
Suspicions can also be kept in a claims directory (scanner.claims-dir), as a JSON array per file:
[
{
"repo": "swiyu-issuer",
"suspectKey": "sd-jwt",
"suspectClaim": "SD-JWT disclosure digests are not re-hashed against the signed _sd values.",
"suspectFile": "optional: restricts the claim to one file"
}
]
Entries with a repo apply only if that repo is scanned. src/main/resources/suspectedClaims/ contains the claims derived from known high-risk EIDSEC issues (missing key/identity binding, incomplete cryptographic verification, race conditions, insecure defaults, ...). Suspect mode additionally writes hypotheses.json and suspect-verdicts.json (the verdicts of all hypotheses).
Getting started
Prerequisites
- Java 25 and Maven (
mvn) - Local clones of the repos to scan, e.g. in
workspace/(git-ignored):swiyu-issuer,swiyu-verifier,libs/swiyu-generic-java-lib,didresolver,didtoolbox-java,eidch-android-wallet,eidch-ios-wallet,libs/swiyu-wallet-shared-kmp,swiyu-core-business-service,swiyu-registry-trust-data-service,swiyu-registry-identifier-data-service,swiyu-registry-status-data-service - An LLM API key (Anthropic, or an OpenAI-compatible endpoint) and optionally a Context7 API key
Build
mvn -DskipTests clean package -f ai-pentest/pom.xml
Use the locally installed mvn (there is no Maven Wrapper). Behind a corporate proxy add -Pbit-proxy.
Run
export ANTHROPIC_API_KEY=sk-...
export CONTEXT7_API_KEY=... # optional
java -jar ai-pentest/target/ai-pentest-1.0-SNAPSHOT.jar \
--spring.profiles.active=hub-smoke \
--repo=swiyu-issuer=workspace/swiyu-issuer \
--repo=swiyu-generic-java-lib=workspace/libs/swiyu-generic-java-lib \
--output=workspace/output/swiyu-issuer
| Argument | Meaning |
|---|---|
--repo=<name>=<path> |
repo to scan, repeatable; the name defaults to the directory name |
--output=<dir> |
output directory (default workspace/output) |
--suspect-file, --suspect-keyword, --suspect-claim, --suspect-claim-file |
suspect mode |
--spring.profiles.active=<profile> |
configuration profile |
Note:
scanner.dry-runistrueby default. Without a profile that setsdry-run: false, no LLM is called and only the keyword heuristic runs. This is intended for fast, free smoke runs.
Profiles
| Profile | Purpose |
|---|---|
| (default) | dry run, heuristics only, no LLM |
hub-smoke |
real LLM run with debug output, fail-on-llm-error=true, claims from suspectedClaims/ |
hyp-smoke |
real LLM run with a stronger Stage 3 model |
suspect-smoke |
suspect-mode runs with the strongest Stage 3 model |
scheduled-scan |
profile of the weekly GitHub Action |
Configuration
All settings are type-safe (ScannerProperties, JudgeProperties) and live under scanner.* in application.yml.
| Property | Default | Description |
|---|---|---|
scanner.dry-run |
true |
heuristics only, no LLM call |
scanner.fail-on-llm-error |
false |
abort on LLM failures instead of falling back |
scanner.debug-output |
false |
write intermediate files (see Output files) |
scanner.triage-model-name |
claude-haiku-5-5 |
Stage 2 model (TRIAGE_MODEL) |
scanner.deep-scan-model-name |
claude-sonnet-5-5 |
Stage 3 model (DEEP_SCAN_MODEL) |
scanner.judge.enabled |
true |
enable Stage 4 (JUDGE_ENABLED) |
scanner.judge.model-name |
claude-fable-5-1 |
Stage 4 model (JUDGE_MODEL) |
scanner.judge.max-findings |
300 |
judge is skipped above this number of findings |
scanner.max-workers |
4 |
parallel LLM calls |
scanner.include-tests |
false |
scan test directories |
scanner.exclude-dirs |
(empty) | extra directories skipped in Stage 1: a name (presentation) or a repo-relative path (app/src/main/res) |
scanner.max-files / scanner.triage-limit / scanner.deep-scan-limit |
0 (unlimited) |
limits per stage, useful for cheap trial runs |
scanner.max-hypotheses-per-file |
3 |
cap per file in Stage 2 |
scanner.skip-low-priority |
false |
do not verify low-priority hypotheses |
scanner.full-scan |
true |
false: skip hypotheses already discarded in earlier runs |
scanner.discarded-dir |
src/main/resources/discarded |
archive of discarded hypotheses |
scanner.claims-dir |
(blank) | enables Stage 2a with suspected claims |
scanner.context7-* |
Context7 API key, library, timeout (10 s), attempts (3) | |
scanner.max-call-graph-*, scanner.max-lib-files |
size limits of the Stage 3 code context |
Environment variables: ANTHROPIC_API_KEY, AI_HUB_API_KEY (falls back to OPENAI_API_KEY), AI_HUB_BASE_URL, AI_CHAT_PROVIDER (anthropic by default), CONTEXT7_API_KEY, TRIAGE_MODEL, DEEP_SCAN_MODEL, JUDGE_MODEL, JUDGE_ENABLED.
New switches belong into ScannerProperties (with @DefaultValue), application.yml and, if relevant, the smoke profiles.
Output files
Always written to --output:
| File | Content |
|---|---|
results.sarif |
confirmed, consolidated findings in SARIF 2.1.0 |
summary.md |
funnel metrics, severity distribution, finding details |
With scanner.debug-output=true additionally:
| File | Content |
|---|---|
triage.json, hypotheses.json |
Stage 2 result and the plain hypothesis list |
deepScan.json, <id>_deepScan.json |
Stage 3 result and the LLM exchange per hypothesis |
judge.json |
Stage 4 clusters |
discarded.json |
false-positive and inconclusive hypotheses (reusable via scanner.discarded-dir) |
In suspect mode hypotheses.json, discarded.json and suspect-verdicts.json (all verdicts) are always written.
Scheduled scan (GitHub Actions)
.github/workflows/scheduled-scan.yml runs the scanner every Monday at 02:00 UTC or manually (workflow_dispatch, target all, swiyu-issuer, swiyu-verifier, didresolver (Rust), didtoolbox-java, eidch-android-wallet (Kotlin), eidch-ios-wallet (Swift), swiyu-core-business-service or the registry data services swiyu-registry-trust-data-service, swiyu-registry-identifier-data-service and swiyu-registry-status-data-service (all Java)). For each target it
- checks out this repo, the target repo and its shared library:
swiyu-generic-java-libforswiyu-issuerandswiyu-verifier,swiyu-wallet-shared-kmp(Kotlin Multiplatform: SD-JWT consistency, DCQL, backup encryption, proximity) for the two wallets;didresolver,didtoolbox-java, the core business service and the registry data services are scanned on their own. Stage 3 follows calls from the Android wallet into the library; the iOS wallet calls it through theBITSwiyuSharedKMPframework, so there the model reaches the Kotlin code through the code lookup tool, - builds the scanner with Java 25 and runs it with the
scheduled-scanprofile (foreidch-android-walletwith--scanner.exclude-dirs=presentation,theme,composables, so the Compose UI is skipped; foreidch-ios-walletwith--scanner.exclude-dirs=Presentation,Views,View,BITL10n,BITTheming, so SwiftUI and the generated strings and assets are skipped), - publishes
summary.mdto the job summary, uploads all outputs as an artifact (no issue is created, issues are disabled for security reasons) and uploads the SARIF file to the GitHub Security tab (optional,continue-on-error).
Required secrets: ANTHROPIC_API_KEY, CONTEXT7_API_KEY.
Project structure and architecture rules
.
├── ai-pentest/ the Java application (single Maven module)
│ ├── docs/diagrams/ Mermaid (.mmd) diagrams, sync-readme.py embeds them into this README
│ └── src/main/java/ch/admin/swiyu/aipentest/
│ ├── AiPentestApplication.java CLI runner, parses arguments only
│ ├── config/ ScannerProperties, JudgeProperties, AiConfig (ChatClients, RestClient), LlmResponses, LlmErrors
│ ├── domain/ immutable records shared between stages, plus Severity
│ ├── io/ JsonFiles (the one JSON writer for reports and debug files)
│ ├── tools/ LLM tools shared by Stage 3 and 4: Context7RAGClient, MissingCodeTool, SpecificationRagTool, JavaSources
│ ├── pipeline/ PentestPipeline, SuspectPipeline, VerificationStages (the only classes knowing the stage order)
│ ├── stage1_filtering/ ... stage5_reporting/
│ ├── class.mmd class diagram (Mermaid), kept in sync with the code
│ └── ...
│ └── src/main/resources/prompts/ system prompts as files, not as Java constants
├── workspace/ scan targets, read-only input (git-ignored)
├── examples/ fixtures, e.g. SAST results in SARIF format
└── .github/ scheduled-scan workflow, Copilot instructions
- Allowed dependencies:
AiPentestApplication → pipeline → stage packages → tools / io / domain / config. Stage packages must not depend on each other or onpipeline; code shared by several stages goes totools(LLM tools, Context7, parsing),io(file output) ordomain.domain,config,ioandtoolsdepend on no stage package. No cycles. - Spring beans are stateless, with constructor injection and
finalfields (no field injection, no Lombok). ChatClientis only used byAiTriageService,DeepScanServiceandJudgeService; onlyContext7RAGClienttalks to Context7.- LLM response DTOs stay in their stage package and are mapped explicitly to domain records. The LLM never sets
repoorfilePath. - Every public class and method has JavaDoc, all code comments are in English.
The full guidelines are in .github/copilot-instructions.md.
Testing
The project follows the test pyramid. Tests live in ai-pentest/src/test/java and mirror the stage packages.
# unit tests incl. architecture rules, no network, no LLM
mvn test -Dtest='!*SmokeTest,!*LlmTest' -f ai-pentest/pom.xml
# a single test class, e.g. behind the corporate proxy
mvn -Pbit-proxy test -Dtest=JudgeServiceTest -f ai-pentest/pom.xml
- Unit tests isolate components (mocked
ChatClient, Context7 and file system) and cover business logic such as file filtering,HeuristicTriage,HypothesisPolicy,VerdictPolicy, judge clustering and SARIF/Markdown generation. - Architecture tests (
ArchitectureTest, ArchUnit) enforce the architecture rules: layering, independent stage packages, no package cycles,domainfree of Spring,ChatClient/RestClient/JavaParser only where allowed, no field injection. - Integration and smoke tests against real resources are opt-in: LLM tests (
AiTriageServiceLlmTest,PentestPipelineLlmTest) are skipped unlessAI_HUB_API_KEYorOPENAI_API_KEYis set, workspace tests (FileFilterServiceWorkspaceTest,PentestPipelineSmokeTest) are skipped ifworkspace/is missing. - Naming: unit tests
methodName_stateUnderTest_expectedBehavior, integration and application testsgiven_when_then.
Design principles
- Precision over volume: a finding is only reported after a strong model confirmed it against the specification, and speculative confirmations are downgraded.
- Cost-aware funnel: the cheapest tool does the broadest work, the most expensive model sees the least data.
- Traceability: every hypothesis has an audit entry, merged findings keep their origin, and debug output allows reproducing each LLM exchange.
- No silent failures: unreachable specification source or (optionally) LLM errors abort the run instead of producing a misleading clean report.
License
See LICENSE.