From 46d3ff27a63c5a9fe752f8e67d02d6ccffe30761 Mon Sep 17 00:00:00 2001 From: kidkender Date: Fri, 13 Nov 2026 11:46:42 +0700 Subject: [PATCH 1/2] docs: update the roadmap after v0.10.0 Express (framework #5), Go tenant isolation and Spring Boot guards moved to shipped; #9 closed now that graph-augmenter's pass-level catches report; Gin path join and CLI detection noted under #11. New #12: measure Go tenant isolation on apps the rules were not written against, and a way to mark global-by-design queries. Summary table re-ranked. --- docs/next-version-ideas.md | 46 +++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/docs/next-version-ideas.md b/docs/next-version-ideas.md index fa55f74..7ea735e 100644 --- a/docs/next-version-ideas.md +++ b/docs/next-version-ideas.md @@ -3,6 +3,7 @@ > Generated: 2026-06-30 > Updated: 2026-07-03 — after v0.5.0 shipped (Spring Boot parser, AQL, Architecture Constraints, AI Context API, `archmind visualize`) > Updated: 2026-11-10 — statuses checked against the code at v0.9.1 +> Updated: 2026-11-13 — after v0.10.0 shipped (Express parser, Go tenant isolation, Spring Boot `guards`) --- @@ -13,11 +14,14 @@ - ✅ **Architecture Constraints** (`@kidkender/archmind-constraints`) — define/enforce structural rules - ✅ **AI Context API** (`@kidkender/archmind-context`) — `buildSemanticContext()`, exposed via `archmind_get_context` MCP tool - ✅ **`archmind visualize`** — Execution Timeline HTML report -- ✅ **Framework #4: Go/Gin** (`@kidkender/archmind-go-parser`, v0.8.x) — route, auth-gate (including runtime skip-lists), authz-check, validation-gate, and GORM transaction-boundary detection for Gin projects. Isolation/tenant scoping is not implemented yet. +- ✅ **Framework #4: Go/Gin** (`@kidkender/archmind-go-parser`, v0.8.x) — route, auth-gate (including runtime skip-lists), authz-check, validation-gate, and GORM transaction-boundary detection for Gin projects. Tenant isolation since v0.10.0 (see below). - ✅ **`@kidkender/archmind-lens`** (v0.9.0–0.9.1) — Go symbol-to-entry-point call graph, exposed as MCP `archmind_symbol_context`. - ✅ **Benchmark CLI (#2)** — `archmind benchmark` (`apps/cli/src/commands/benchmark.ts`) reads the pain specs and scores node/edge recall. - ✅ **Graph Diff for PR review (#1)** — `archmind diff --format markdown` plus the sticky-comment workflow in `docs/ci-templates/topology-guard.yml`. -- ✅ **CI** — `.github/workflows/ci.yml` builds and tests on every push and PR to `main`. +- ✅ **CI** — `.github/workflows/ci.yml` builds and tests on every push and PR to `main`. Since v0.10.0 a clean checkout builds (workspaces in dependency order), so CI is green on a fresh clone. +- ✅ **Framework #5: Express.js** (`@kidkender/archmind-express-parser` 0.1.0, v0.10.0) — routers across files, middleware chain classified into auth / authz / validation, handlers through controllers and wrappers, service calls, transactions (Sequelize, TypeORM, Prisma, Mongoose, Knex). Wired into analysis, the CLI and the MCP server. +- ✅ **Go tenant isolation** (`go-parser` 0.4.0, v0.10.0) — `ir:tenant_context` and scoped / unscoped queries on routes that resolve a tenant, followed through registries, typed locals, DAO and model wrappers; `archmind.json` `isolation`. On two real multi-tenant apps: 129 and 40 routes with a tenant, 15 and 8 distinct unscoped sites, none tenant-filtered in fact (rules were written against those two apps). +- ✅ **Spring Boot `archmind.json` `guards`** (#10, v0.10.0) and Laravel parsing each file once per run (invoiceninja: out of memory → 22 s). These shipped features open up new follow-on ideas below (#5, #7) that weren't possible before. @@ -76,6 +80,7 @@ archmind benchmark run --all --output=results/baseline.json **Priority:** Medium — mở rộng reach **Effort:** High (nhưng thấp hơn trước — đã có 3 parser để rút pattern chung) +**Status:** Express.js ✅ Done (v0.10.0, `@kidkender/archmind-express-parser` 0.1.0). Still open: FastAPI/Django, and the adapter kit (shared interface + conformance suite) — Express was built the old way, with its own conformance cases in `research/cross-framework`. Express limits: decorator routing (routing-controllers, tsoa) yields no routes; no tenant isolation, side effects or response shaping; not yet through the LLM accuracy benchmark. Đã có Laravel + NestJS + Spring Boot. Với 3 parser, giờ là lúc tách phần chung (route extraction, auth gate detection, transaction boundary detection) thành spec/interface tái sử dụng được trước khi thêm framework thứ 4 — tránh mỗi parser tự implement lại từ đầu. @@ -198,7 +203,7 @@ Benchmarked against akaunting (642 routes) as a fresh, previously-unseen repo **Priority:** High — undermines trust in the whole test suite and any CI built on top of it **Effort:** Medium -**Status:** ✅ Done (2026-11-10) for laravel-parser and springboot-parser — read+parse sites go through `php-source.ts` / `java-source.ts`: an unreadable file yields nothing, a parse failure is printed on stderr with the file path and the file is skipped. This also fixed files over 32 KiB (tree-sitter 0.21 throws "Invalid argument" past its default buffer; only `route-parser.ts` passed `bufferSize`, so every other parser silently returned nothing for large controllers and services). Still open: the broad `catch { /* skip */ }` around whole passes in `graph-augmenter.ts`. +**Status:** ✅ Done (2026-11-10) for laravel-parser and springboot-parser — read+parse sites go through `php-source.ts` / `java-source.ts`: an unreadable file yields nothing, a parse failure is printed on stderr with the file path and the file is skipped. This also fixed files over 32 KiB (tree-sitter 0.21 throws "Invalid argument" past its default buffer; only `route-parser.ts` passed `bufferSize`, so every other parser silently returned nothing for large controllers and services). The pass-level catches in `laravel-parser/src/graph-augmenter.ts` now report on stderr (`reportSkipped`, v0.10.0) instead of swallowing the error. Initial hypothesis (below, kept for record) was a `tree-sitter@^0.21.0` / `tree-sitter-php@^0.23.12` ABI skew. **That was wrong** — disproved empirically: a plain-Node script reusing the same `Parser` singleton for 500 heavy parses in a row had zero failures. The real cause: Jest reuses one worker *process* across multiple test files in the same package; each file re-imports that package's module-level `new Parser()` singleton, and repeatedly re-loading the native tree-sitter addon into the same process is what makes `_parser.parse(source)` intermittently throw — not the grammar/core version pairing itself. Confirmed by setting `maxWorkers` high enough (in `laravel-parser`'s and `springboot-parser`'s `jest.config.js`) that every test file always gets its own process: 5/5 and then 3/3 repeated full-suite runs came back completely clean, both isolated and via `npm test`. @@ -231,21 +236,40 @@ Count at v0.9.1 of bare `catch {` in parser sources (tests excluded): laravel 36 After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from the 0.8.2 spot-check still not handled: engine held in a struct field and mutated by a receiver method, engine wrapped in a custom type with its own `.GET()`/`.POST()`, functional-options chains, Wire-style DI. Lens limits: embedded interfaces, two types with the same name in different packages. +Fixed in v0.10.0: group prefixes joined like Gin (`Group("api").Group("v1")` was `apiv1…`; 233 of 267 routes malformed on one project), and the CLI detects a `go.mod` one directory down. + +--- + +## 12. Go tenant isolation: measure blind and cut by-design noise + +**Priority:** Medium +**Effort:** Low-Medium +**Status:** Open + +The v0.10.0 rules were written against the two apps they were measured on (thingspanel, ginfast), so precision on an unseen app is unknown. Of 23 distinct unscoped sites there, about 10 are worth reporting (lookups by id or full loads without a tenant filter) and about 13 are global by design (login, username / email uniqueness, super-admin setup, a user's own record by token id). + +- Measure on one or two multi-tenant Gin apps not used to write the rules, and review each unscoped site by hand. +- A way to mark a query or function as global by design (an `archmind.json` list, or recognising login / uniqueness checks), since `ignoreFindings` drops every `missing_tenant_scope`. +- Types are matched by bare name across packages: two DAOs or models with the same name in different packages can be confused. +- Not seen: GORM plugins, global scopes outside a registered callback, scopes whose name and arguments carry no tenant signal. + --- ## Summary Table | Idea | Impact | Effort | Recommended Order | |------|--------|--------|-------------------| -| Go tenant scoping | Medium | Medium | **3rd** | -| Remaining Gin layouts + lens limits (#11) | Medium | Medium | **4th** | -| Modular Laravel support (#8, partial) | Medium | Medium | **5th** | -| Auto-fix Suggestions (#4) | Medium | Medium | **6th** | -| Framework #5 + adapter kit (#3) | High | High | **7th** | -| Web UI Visualizer (#6) | Medium | High | **8th** | -| OTel Runtime Expansion (#7) | High | High | **9th** | +| Go tenant isolation: blind measurement + by-design noise (#12) | Medium | Low-Medium | **1st** | +| Remaining Gin layouts + lens limits (#11) | Medium | Medium | **2nd** | +| Modular Laravel support (#8, partial) | Medium | Medium | **3rd** | +| Auto-fix Suggestions (#4) | Medium | Medium | **4th** | +| Adapter kit + Framework #6 (FastAPI/Django) (#3) | High | High | **5th** | +| Web UI Visualizer (#6) | Medium | High | **6th** | +| OTel Runtime Expansion (#7) | High | High | **7th** | +| ~~Go tenant scoping~~ | | | Done (v0.10.0) — `go-parser` 0.4.0 | +| ~~Framework #5: Express.js (#3)~~ | | | Done (v0.10.0) — `express-parser` 0.1.0 | | ~~AQL/Constraints in CI (#5)~~ | | | Done | | ~~Benchmark CLI (#2)~~ | | | Done | | ~~Graph Diff PR Comment (#1)~~ | | | Done | | ~~Spring Boot reads `archmind.json` (#10)~~ | | | Done | -| ~~Narrow swallow-catch in parsers (#9)~~ | | | Done (graph-augmenter pass-level catches remain) | +| ~~Narrow swallow-catch in parsers (#9)~~ | | | Done (graph-augmenter pass-level catches report since v0.10.0) | From ee94a6c9120ce4e65b68b85a5badf12abb997234 Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 24 Nov 2026 08:04:14 +0700 Subject: [PATCH 2/2] fix(laravel): cut false-positive authorization findings on real apps Across five open-source Laravel apps scanned with no config, HIGH/CRITICAL findings drop from 951 to 63 (-93%). Sixteen root causes are fixed, each with its own test. The main ones: - Laravel 11+ apps have no Kernel.php, so can:/role:/auth middleware aliases were not recognised - unknown middleware (including RedirectIfAuthenticated) was treated as an authentication step - authorization done outside $this->authorize() (controller helpers, FormRequests, services, scoped queries) was not detected - public paths and resource/route mismatches are now handled explicitly Also adds a GitHub Action (action.yml), a wrong-finding issue template, the scan methodology and a sample report under research/laravel-scan, and refreshes README, CHANGELOG and package metadata. Co-Authored-By: Claude Opus 5.5 --- .github/ISSUE_TEMPLATE/wrong-finding.yml | 43 ++ CHANGELOG.md | 24 + README.md | 162 ++++-- action.yml | 75 +++ apps/cli/package.json | 22 +- apps/cli/src/commands/findings.ts | 25 +- apps/cli/src/utils/parse-project.ts | 27 + .../resource-unprotected-precision.test.ts | 157 ++++++ packages/explainer/src/index.ts | 2 + .../pattern-detectors/delegated-validation.ts | 6 +- .../exposed-read-endpoint.ts | 4 +- .../missing-authorization.ts | 8 + .../src/pattern-detectors/public-paths.ts | 13 + .../pattern-detectors/resource-mismatch.ts | 28 +- .../__tests__/authorization-precision.test.ts | 518 ++++++++++++++++++ .../fixtures/routes-namespace-alias.php | 6 + .../src/__tests__/kernel-parser.test.ts | 7 +- .../src/__tests__/middleware-mapper.test.ts | 6 +- .../src/__tests__/route-parser.test.ts | 23 +- .../laravel-parser/src/controller-parser.ts | 315 +++++++++-- .../laravel-parser/src/graph-augmenter.ts | 282 +++++++++- .../laravel-parser/src/middleware-mapper.ts | 47 +- .../laravel-parser/src/resource-parser.ts | 11 +- packages/laravel-parser/src/route-parser.ts | 25 +- packages/mcp-server/package.json | 25 +- research/laravel-scan/README.md | 78 +++ research/laravel-scan/sample.json | 442 +++++++++++++++ 27 files changed, 2256 insertions(+), 125 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/wrong-finding.yml create mode 100644 action.yml create mode 100644 packages/explainer/src/__tests__/resource-unprotected-precision.test.ts create mode 100644 packages/explainer/src/pattern-detectors/public-paths.ts create mode 100644 packages/laravel-parser/src/__tests__/authorization-precision.test.ts create mode 100644 packages/laravel-parser/src/__tests__/fixtures/routes-namespace-alias.php create mode 100644 research/laravel-scan/README.md create mode 100644 research/laravel-scan/sample.json diff --git a/.github/ISSUE_TEMPLATE/wrong-finding.yml b/.github/ISSUE_TEMPLATE/wrong-finding.yml new file mode 100644 index 0000000..ceb892a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/wrong-finding.yml @@ -0,0 +1,43 @@ +name: Wrong finding or missed route +description: ArchMind reported something that isn't a problem, missed a route, or found nothing on your project. +labels: [accuracy] +body: + - type: dropdown + id: framework + attributes: + label: Framework + options: [Laravel, NestJS, Express, Spring Boot, Go/Gin, Other / not detected] + validations: + required: true + - type: dropdown + id: kind + attributes: + label: What went wrong + options: + - False positive (finding is not a real problem) + - Missed problem (a real issue was not reported) + - Route missing or wrong (path, middleware, handler) + - Nothing analyzed (0 entrypoints) + validations: + required: true + - type: input + id: route + attributes: + label: Route + placeholder: "DELETE /api/vaults/{id}" + - type: textarea + id: got + attributes: + label: What ArchMind output + description: Paste the relevant part of `archmind findings` or `archmind trace` output. + render: text + - type: textarea + id: expected + attributes: + label: What you expected, and why + description: e.g. "authorization happens in a custom middleware `EnsureTeamOwner`" — a small code snippet helps most. + - type: input + id: version + attributes: + label: ArchMind version + placeholder: "0.10.0" diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d651a8..1ee53bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## [Unreleased] + +### Fixed — false positives on real Laravel apps +Measured on invoiceninja, monica, akaunting, koel and BookStack with no config: HIGH/CRITICAL findings 951 → 63, default output 92 lines across the five apps. Of the remaining HIGH/CRITICAL findings read by hand, 30 of 42 are worth a look and 12 are false positives; none is a confirmed vulnerability. Details and every remaining false positive: `research/laravel-scan/README.md`. +- `laravel-parser`: unresolved class middleware is classified by name instead of defaulting to `ir:auth_gate` (invoiceninja `SessionDomains` made public routes read as authenticated); `RedirectIfAuthenticated` / `guest` are never auth gates; `ValidateSignature` / `signed` / `signed:relative` are signature checks. +- `laravel-parser`: Laravel's built-in aliases are recognised without a `Kernel.php` (Laravel 11+): `auth`, `auth.basic`, `can:…`, `role:…`, `ability:…`, `abilities:…`, `guest`. +- `laravel-parser`: authorization in the controller is read beyond `$this->authorize()` / `Gate::allows()`: permission helpers (`$this->checkPermission()`, `checkOwnablePermission()`, `ensure…`), `$user->can()` / `hasRole()` / `hasPermissionTo()`, global `userCan()`, `Gate::denies/any/none/inspect`, `authorizeForUser()`, `authorizeResource()` in the constructor (with `except`/`only`), and constructor `$this->middleware([...])` arrays, enum entries and chained `->only()` / `->except()`. +- `laravel-parser`: authorization outside the controller: `FormRequest::authorize()` with a real check (not `true` or a login test, including per-item `return false` loops), service classes with a `permissions()` rule list or a Gate/can/403 check in the called method, inline `(new Service)->method()` calls, repository queries scoped to the caller (`accessible()`, `withUserContext()`, `whereBelongsTo(auth()…)`), controller queries filtered on the caller's key (`whereClientId()`, `where('user_id', auth()->id())`) and writes through the caller's own relations (`$request->user()->tokens()->delete()`). Filters on shared keys (`company_id`, `account_id`, `team_id`…) do not count. +- `laravel-parser`: `missing_policy` names the policy after the model passed to `authorize()` (Laravel's rule), not the controller; it looks in policy sub-folders and `$policies` / `Gate::policy()` / `#[UsePolicy]` registrations, and is not raised for interface-typed params or calls without a model. +- `laravel-parser`: only Eloquent models the handler actually uses become `ir:resource` nodes (helpers like `SearchResultsFormatter` were reported as unprotected resources). +- `laravel-parser`: route files using `use Foo\Controllers as Alias;` + `Alias\XController` resolve to the controller file (BookStack's API had no controller analysis at all); `apiResource('artists.songs')` is `/artists/{artist}/songs`; routes to methods a controller can't have get a `handler_not_found` annotation and no findings. +- `laravel-parser`: API resource fields sent only to the caller (`$this->when($isCurrentUser, …)`) and boolean flags (`is_…`, `has_…`) are not sensitive fields. +- `explainer`: `resource_unprotected` is only raised when the route has no authorization and no signed URL, is HIGH behind a login and CRITICAL only on public routes, and no longer duplicates `missing_authorization` on authenticated mutations. +- `explainer`: `missing_authorization` skips self-service routes that load no other record (`/me`, `/profile`, `/preferences`, `/my-account`, logout, two-factor, `broadcasting/auth`); `exposed_read_endpoint` and `delegated_validation` are INFO on public-by-design paths (login, register, password, verify, SSO/SAML/OIDC callbacks, invitations, webhooks, health). +- CLI: `findings` shows CRITICAL/HIGH/MEDIUM by default (`--all` for LOW and INFO) and only CRITICAL/HIGH set exit code 1, in text and `--json`. When no framework is detected or 0 entrypoints are found it says so on stderr and exits 2 instead of printing "No findings." +- CLI: the npm package now depends on `tree-sitter-java`; without it every Spring Boot project silently produced no routes. + +### Added +- `action.yml`: GitHub Action (`uses: Kidkender/archMind@`) running `verify`, `findings` or `diff`. +- `.github/ISSUE_TEMPLATE/wrong-finding.yml` for false positives, missed problems and unparsed projects. + +### Changed +- README leads with what ArchMind finds and how noisy it is; npm descriptions/keywords updated (the MCP server lists the frameworks it supports — not Spring Boot). + ## [0.10.0] - 2026-11-13 ### Added diff --git a/README.md b/README.md index 0fc78cb..fe3c6c1 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,56 @@ # ArchMind -**Semantic execution graph engine for Laravel, NestJS, Spring Boot, Go/Gin and Express — built for AI assistants and CI.** +**Find the routes that forgot to check something — and stop the next refactor from forgetting it again.** -ArchMind parses your app into a structured execution graph and gives AI assistants (Claude, Cursor, Copilot) the minimal relevant subgraph for a query — achieving comparable or better answer quality at a fraction of the tokens that naive file-dump RAG uses. +ArchMind reads your Laravel, NestJS, Express, Spring Boot or Go/Gin app and builds, for every route, a graph of what it actually checks: authentication, authorization (policy / role / gate), validation, transaction boundaries, tenant scoping. It reports what is **missing**, fails CI when a check **disappears**, and gives AI assistants the same evidence over MCP. ---- - -## Why execution graphs beat naive RAG - -Naive RAG dumps raw source files into the LLM context. ArchMind retrieves only the nodes relevant to the question — authentication gates, policy checks, transaction boundaries, tenant isolation — and nothing else. - -### Benchmark results (real repos, hand-verified ground truth, real GPT-4o calls — not simulated) - -| Benchmark | Sample | archMind | Baseline (raw file dump) | -|---|---|---|---| -| Guest-access / authorization accuracy — 5 real Laravel apps (invoiceninja, monica, akaunting, koel, BookStack) | 50 hand-verified entrypoints | 66% correct, 98% correct+partial | 68% correct, 100% correct+partial | -| Token cost, same benchmark | 50 entrypoints | **5.08× fewer prompt tokens** (14,517 vs 73,712) | baseline | -| Guest-access / authorization accuracy — 5 fresh, previously-unseen repos across Laravel/Spring Boot/NestJS (panel, attendize, spring-petclinic, SpringBlade, nestjs-boilerplate) | 20 entrypoints | **90% correct** (18/20), 0 incorrect | 65% correct (13/20), 5 confidently incorrect | -| Token cost, same cross-framework set | 24 calls | **73.4% fewer prompt tokens** (7,116 vs 26,764) | baseline | - -**Read the accuracy numbers honestly:** on Laravel alone, raw accuracy is statistically tied with a naive file dump — the win there is almost entirely token efficiency (same answer quality, 1/5th the context). The larger accuracy edge shows up on the cross-framework sample, and traces to a specific mechanism, not "the LLM likes archMind more": ArchMind's evidence package marks facts as explicitly **present or ABSENT** (e.g. `✗ auth_middleware`), which lets the model correctly infer "no auth required" instead of reading silence as ambiguity — a raw file dump gives the model no equivalent signal to reason from, so it hedges to `UNCLEAR` far more often (5 of the baseline's misses were exactly this). - -ArchMind's accuracy pass has also surfaced real, previously undocumented security issues in the repos it was tested against — including an unauthenticated multi-tenant data exposure and a path-traversal-adjacent unguarded file endpoint — precisely because the graph's explicit absence-marking caught missing auth that a raw-file read past over. +Offline. No LLM, no API key, no account. -**Where it doesn't win:** deeper reasoning benchmarks (cross-file causality, multi-turn sessions) show archMind edging ahead but with concrete, documented gaps — transaction-scope flattening (the graph knows *a* transaction exists but not precisely which downstream calls are inside it) and an accessor-vs-terminal-mutation gap (a relationship accessor is captured as touched, without confirming the chained `.delete()` on it actually ran). These are IR-granularity ceilings, not retrieval-reach problems, and are being worked on incrementally rather than glossed over. +```bash +npx @kidkender/archmind findings --project . +``` -The difference compounds on large codebases where a single route touches dozens of files. +``` +DELETE /api/vaults/{id} + ! HIGH missing_authorization + DELETE /api/vaults/{id} is authenticated but not authorized — any logged-in user can perform this mutation -**Go/Gin support is newer and not yet held to the same bar.** The numbers above are Laravel/NestJS/Spring Boot only, from hand-verified ground truth compared against real LLM calls. Go/Gin has been validated structurally — full-project parsing against 3 real Gin+GORM codebases with zero crashes and spot-checked node accuracy — but not yet run through the same hand-verified accuracy benchmark. Treat it as functional but less battle-tested until that benchmark exists. +GET /api/invoices/{id} + ! HIGH missing_tenant_scope + Invoice::find fetches by raw ID with no tenant constraint — any authenticated user can access another tenant's Invoice by guessing the ID +``` -**Express support is the newest, measured structurally only.** On six projects it had not seen it found every real route (101 of 101) and every transaction-opening route of a production app, and classified 9 of 15 security middleware correctly before fixes made on that same set (15 of 15 after) — see [`research/express-corpus`](research/express-corpus/README.md). It has not been through the LLM accuracy benchmark either. +On real open-source apps it has surfaced previously undocumented issues, including an **unauthenticated multi-tenant data exposure** and an **unguarded file endpoint** — found because ArchMind records a missing check as an explicit fact (`✗ auth_middleware`), not as silence. ---- +### What it checks -## MCP Server (Claude Code / AI assistants) +| Problem | Finding / guard | +|---|---| +| Logged-in user can change data they shouldn't (no policy, gate or role check) | `missing_authorization` | +| Policy referenced but the class doesn't exist | `missing_policy` | +| Record fetched by ID in a multi-tenant route without the tenant filter | `missing_tenant_scope` | +| Public route that returns business data or sensitive fields | `exposed_read_endpoint`, `api_resource_unprotected`, `sensitive_field_exposed` | +| Event or job dispatched inside a transaction that may roll back | `event_before_commit` | +| A refactor drops auth middleware, a `DB::transaction()` or a tenant scope | `archmind verify` fails the build | -ArchMind ships an MCP server that gives AI assistants structured execution graph access. +Detector coverage differs per framework — see [Supported frameworks](#supported-frameworks). -```bash -npm install -g @kidkender/archmind-mcp -``` +### Who it's for -Add to your MCP settings: +- **Teams running multi-tenant SaaS** who need every route tenant-scoped and authorized. +- **Reviewers** who want a PR comment saying "this PR removed the transaction from `POST /orders`" instead of reading the diff. +- **AI-assisted development** (Claude Code, Cursor, Copilot): the assistant asks ArchMind what a route checks instead of guessing from raw files. -```json -{ - "archmind": { - "command": "archmind-mcp" - } -} -``` +### How noisy is it? -Ask Claude: *"Why is authorization checked twice on POST /orders?"* — it calls `archmind_get_execution_graph` and reasons over the actual execution path, not a raw file dump. +Measured on five real Laravel apps (invoiceninja, monica, akaunting, koel, BookStack), no config: +**92 findings shown** by default across all five, **63 HIGH/CRITICAL** (down from 951 in 0.10.0). +Of the HIGH/CRITICAL ones we checked by reading the code, 71% were worth a reviewer's attention and +29% were false positives; none was a confirmed vulnerability. Every number, and each false positive, +is in [`research/laravel-scan`](research/laravel-scan/README.md). -### MCP tools +> Coming from **Enlightn** (archived in January 2026)? ArchMind covers a different, complementary area — route-level authorization, tenant isolation and transactions, with a CI regression guard — and runs on Windows, macOS and Linux. -| Tool | What it does | -|------|-------------| -| `archmind_list_entrypoints` | All routes in the project | -| `archmind_get_execution_graph` | Execution graph for a specific route (with optional focus pruning) | -| `archmind_get_findings` | Static detectors — auth gaps, transaction anomalies, isolation issues | -| `archmind_get_dependents` | Cross-route impact: what breaks if I change `OrderService`? | -| `archmind_invalidate_cache` | Force re-parse after source changes | --- @@ -105,6 +94,21 @@ If this is intentional, run: archmind verify --project . --update ### CI Integration +With the GitHub Action: + +```yaml +# .github/workflows/archmind.yml +on: pull_request +jobs: + archmind: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: Kidkender/archMind@main # command: verify (default) | findings | diff +``` + +Or with plain npm: + ```yaml # .github/workflows/topology-guard.yml - uses: actions/setup-node@v4 @@ -129,14 +133,48 @@ git commit -m "chore: add topology baseline" --- +## MCP Server (Claude Code / AI assistants) + +ArchMind ships an MCP server that gives AI assistants structured execution graph access. It supports Laravel, NestJS, Express and Go/Gin; Spring Boot is available in the CLI only for now. + +```bash +npm install -g @kidkender/archmind-mcp +``` + +Add to your MCP settings: + +```json +{ + "archmind": { + "command": "archmind-mcp" + } +} +``` + +Ask Claude: *"Why is authorization checked twice on POST /orders?"* — it calls `archmind_get_execution_graph` and reasons over the actual execution path, not a raw file dump. + +### MCP tools + +| Tool | What it does | +|------|-------------| +| `archmind_list_entrypoints` | All routes in the project | +| `archmind_get_execution_graph` | Execution graph for a specific route (with optional focus pruning) | +| `archmind_get_findings` | Static detectors — auth gaps, transaction anomalies, isolation issues | +| `archmind_get_dependents` | Cross-route impact: what breaks if I change `OrderService`? | +| `archmind_invalidate_cache` | Force re-parse after source changes | + +--- + ## CLI commands ```bash # Trace the execution graph of any route archmind trace --project . "POST /orders" -# Find security gaps across all routes +# Find security gaps across all routes (CRITICAL / HIGH / MEDIUM; exit 1 on CRITICAL or HIGH) archmind findings --project . +archmind findings --project . --all # also LOW (code quality) and INFO notes +archmind findings --project . --json # machine-readable, all severities # Save baseline, then verify on every PR archmind verify --project . --update # save @@ -174,6 +212,34 @@ DELETE /api/vaults/{id} 4 finding(s) across 4 route(s) ``` +--- + +## Benchmarks: does it help AI assistants? + +Naive RAG dumps raw source files into the LLM context. ArchMind retrieves only the nodes relevant to the question — authentication gates, policy checks, transaction boundaries, tenant isolation — and nothing else. + +### Benchmark results (real repos, hand-verified ground truth, real GPT-4o calls — not simulated) + +| Benchmark | Sample | archMind | Baseline (raw file dump) | +|---|---|---|---| +| Guest-access / authorization accuracy — 5 real Laravel apps (invoiceninja, monica, akaunting, koel, BookStack) | 50 hand-verified entrypoints | 66% correct, 98% correct+partial | 68% correct, 100% correct+partial | +| Token cost, same benchmark | 50 entrypoints | **5.08× fewer prompt tokens** (14,517 vs 73,712) | baseline | +| Guest-access / authorization accuracy — 5 fresh, previously-unseen repos across Laravel/Spring Boot/NestJS (panel, attendize, spring-petclinic, SpringBlade, nestjs-boilerplate) | 20 entrypoints | **90% correct** (18/20), 0 incorrect | 65% correct (13/20), 5 confidently incorrect | +| Token cost, same cross-framework set | 24 calls | **73.4% fewer prompt tokens** (7,116 vs 26,764) | baseline | + +**Read the accuracy numbers honestly:** on Laravel alone, raw accuracy is statistically tied with a naive file dump — the win there is almost entirely token efficiency (same answer quality, 1/5th the context). The larger accuracy edge shows up on the cross-framework sample, and traces to a specific mechanism, not "the LLM likes archMind more": ArchMind's evidence package marks facts as explicitly **present or ABSENT** (e.g. `✗ auth_middleware`), which lets the model correctly infer "no auth required" instead of reading silence as ambiguity — a raw file dump gives the model no equivalent signal to reason from, so it hedges to `UNCLEAR` far more often (5 of the baseline's misses were exactly this). + +ArchMind's accuracy pass has also surfaced real, previously undocumented security issues in the repos it was tested against — including an unauthenticated multi-tenant data exposure and a path-traversal-adjacent unguarded file endpoint — precisely because the graph's explicit absence-marking caught missing auth that a raw-file read past over. + +**Where it doesn't win:** deeper reasoning benchmarks (cross-file causality, multi-turn sessions) show archMind edging ahead but with concrete, documented gaps — transaction-scope flattening (the graph knows *a* transaction exists but not precisely which downstream calls are inside it) and an accessor-vs-terminal-mutation gap (a relationship accessor is captured as touched, without confirming the chained `.delete()` on it actually ran). These are IR-granularity ceilings, not retrieval-reach problems, and are being worked on incrementally rather than glossed over. + +The difference compounds on large codebases where a single route touches dozens of files. + +**Go/Gin support is newer and not yet held to the same bar.** The numbers above are Laravel/NestJS/Spring Boot only, from hand-verified ground truth compared against real LLM calls. Go/Gin has been validated structurally — full-project parsing against 3 real Gin+GORM codebases with zero crashes and spot-checked node accuracy — but not yet run through the same hand-verified accuracy benchmark. Treat it as functional but less battle-tested until that benchmark exists. + +**Express support is the newest, measured structurally only.** On six projects it had not seen it found every real route (101 of 101) and every transaction-opening route of a production app, and classified 9 of 15 security middleware correctly before fixes made on that same set (15 of 15 after) — see [`research/express-corpus`](research/express-corpus/README.md). It has not been through the LLM accuracy benchmark either. + + --- ## Supported frameworks diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..3988a85 --- /dev/null +++ b/action.yml @@ -0,0 +1,75 @@ +name: ArchMind Route Guard +description: Fail the PR when a route loses its auth, authorization, transaction or tenant scope; report routes missing authorization. +author: kidkender +branding: + icon: shield + color: blue + +inputs: + command: + description: > + What to run. "verify" fails when a route loses a check compared to the committed baseline + (.archmind/baselines/). "findings" fails when any finding is reported. "diff" prints a + Markdown topology diff (exit 1 on regression). + required: false + default: verify + project: + description: Path to the app (Laravel, NestJS, Express, Spring Boot, Go/Gin). + required: false + default: . + version: + description: "@kidkender/archmind version to run (npm version or tag)." + required: false + default: latest + node-version: + description: Node.js version used to run ArchMind. + required: false + default: "20" + fail: + description: Set to "false" to report without failing the job. + required: false + default: "true" + +outputs: + exit-code: + description: Exit code of the ArchMind command (0 clean, 1 regression/findings, 2 nothing analyzed). + value: ${{ steps.run.outputs.exit_code }} + report: + description: Command output (Markdown for "diff"). + value: ${{ steps.run.outputs.report }} + +runs: + using: composite + steps: + - uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node-version }} + + - id: run + shell: bash + env: + AM_COMMAND: ${{ inputs.command }} + AM_PROJECT: ${{ inputs.project }} + AM_VERSION: ${{ inputs.version }} + run: | + set +e + case "$AM_COMMAND" in + verify) ARGS=(verify --project "$AM_PROJECT") ;; + findings) ARGS=(findings --project "$AM_PROJECT") ;; + diff) ARGS=(diff --project "$AM_PROJECT" --format markdown) ;; + *) echo "::error::Unknown command '$AM_COMMAND' (use verify, findings or diff)"; exit 2 ;; + esac + OUTPUT=$(npx --yes "@kidkender/archmind@${AM_VERSION}" "${ARGS[@]}" 2>&1) + CODE=$? + echo "$OUTPUT" + echo "exit_code=$CODE" >> "$GITHUB_OUTPUT" + DELIM="ARCHMIND_$(date +%s%N)" + { echo "report<<$DELIM"; echo "$OUTPUT"; echo "$DELIM"; } >> "$GITHUB_OUTPUT" + if [ "$AM_COMMAND" = "diff" ]; then echo "$OUTPUT" >> "$GITHUB_STEP_SUMMARY"; fi + exit 0 + + - if: ${{ inputs.fail == 'true' && steps.run.outputs.exit_code != '0' }} + shell: bash + run: | + echo "::error::ArchMind ${{ inputs.command }} exited with ${{ steps.run.outputs.exit_code }} — see the log above." + exit 1 diff --git a/apps/cli/package.json b/apps/cli/package.json index fa10d3d..46d3d44 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@kidkender/archmind", "version": "0.10.0", - "description": "Execution topology intelligence for Laravel, NestJS, and Go/Gin — trace routes, detect regressions, find security gaps. No LLM required.", + "description": "Find routes with missing authorization, lost transactions and unscoped tenant queries in Laravel, NestJS, Express, Spring Boot and Go/Gin apps — and fail CI when a refactor drops them. Offline, no LLM.", "type": "module", "bin": { "archmind": "./dist/index.cjs" @@ -14,6 +14,7 @@ "dependencies": { "tree-sitter": "^0.21.0", "tree-sitter-php": "^0.22.0", + "tree-sitter-java": "^0.23.5", "@kidkender/archmind-explainer": "*", "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-llm-client": "*", @@ -32,15 +33,24 @@ }, "keywords": [ "laravel", - "static-analysis", + "nestjs", + "express", + "spring-boot", + "gin", "security", + "authorization", + "multi-tenant", + "static-analysis", + "sast", + "ci", "cli", + "github-actions", "execution-graph" ], "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/kidkender/archmind" + "url": "git+https://github.com/Kidkender/archMind.git" }, "engines": { "node": ">=18" @@ -52,5 +62,9 @@ "dist/index.cjs", "CHANGELOG.md", "README.md" - ] + ], + "homepage": "https://github.com/Kidkender/archMind#readme", + "bugs": { + "url": "https://github.com/Kidkender/archMind/issues" + } } diff --git a/apps/cli/src/commands/findings.ts b/apps/cli/src/commands/findings.ts index 3a163b5..24dd63d 100644 --- a/apps/cli/src/commands/findings.ts +++ b/apps/cli/src/commands/findings.ts @@ -17,6 +17,7 @@ export function runFindings(flags: Record, positional: string[]) const projectRoot = requireProject(flags) const routeFilter = positional[0] const isJson = "json" in flags + const showAll = "all" in flags const { graphs } = parseProject(projectRoot) const ignore = loadUserConfig(projectRoot)?.ignoreFindings @@ -37,15 +38,30 @@ export function runFindings(flags: Record, positional: string[]) } } + // Shown by default: CRITICAL / HIGH / MEDIUM. LOW findings are code-quality + // notes (fat_controller…) and INFO ones describe the graph ("authorization is + // delegated to middleware") — both hidden unless --all. Only CRITICAL/HIGH fail CI. + const isProblem = (f: Finding): boolean => ["critical", "high", "medium"].includes(f.severity.toLowerCase()) + const failsBuild = allFindings.some(({ finding: f }) => ["critical", "high"].includes(f.severity.toLowerCase())) + if (isJson) { // Use exitCode + return so stdout flushes before the process ends - process.exitCode = allFindings.length > 0 ? 1 : 0 + process.exitCode = graphs.length === 0 ? 2 : failsBuild ? 1 : 0 process.stdout.write(JSON.stringify(allFindings, null, 2) + "\n") return } + if (graphs.length === 0) { + // parseProject already explained why on stderr; don't claim a clean result + console.log("No entrypoints analyzed — no findings can be reported.") + process.exit(2) + } + + const hiddenInfo = showAll ? 0 : allFindings.filter(({ finding }) => !isProblem(finding)).length + if (!showAll) allFindings = allFindings.filter(({ finding }) => isProblem(finding)) + if (allFindings.length === 0) { - console.log("No findings.") + console.log(hiddenInfo > 0 ? `No findings (${hiddenInfo} low/informational hidden — use --all).` : "No findings.") process.exit(0) } @@ -76,7 +92,10 @@ export function runFindings(flags: Record, positional: string[]) } } - console.log(`\n${total} finding(s) across ${byRoute.size} route(s)`) + console.log( + `\n${total} finding(s) across ${byRoute.size} route(s)` + + (hiddenInfo > 0 ? ` — ${hiddenInfo} low/informational hidden, use --all` : ""), + ) const hasHighPlus = allFindings.some(({ finding: f }) => ["critical", "high"].includes(f.severity.toLowerCase()) diff --git a/apps/cli/src/utils/parse-project.ts b/apps/cli/src/utils/parse-project.ts index 15f802d..0944121 100644 --- a/apps/cli/src/utils/parse-project.ts +++ b/apps/cli/src/utils/parse-project.ts @@ -111,8 +111,35 @@ export function detectFramework(projectRoot: string): Framework { return "unknown" } +const SUPPORTED_FRAMEWORKS = "Laravel, NestJS, Spring Boot, Go/Gin, Express" + +/** + * Warn on stderr (stdout stays clean for --json) when nothing was analyzed, + * so an unsupported project never reads as "no findings" — a false all-clear. + */ +function warnIfNothingParsed(parsed: ParsedProject, detected: Framework): ParsedProject { + if (detected === "unknown") { + process.stderr.write( + `archmind: could not detect a supported framework in ${parsed.projectRoot}\n` + + ` (supported: ${SUPPORTED_FRAMEWORKS}). Falling back to Laravel parsing.\n`, + ) + } + if (parsed.routeCount === 0) { + process.stderr.write( + `archmind: found 0 entrypoints in ${parsed.projectRoot} (parsed as ${parsed.framework}).\n` + + ` Nothing was analyzed. If this project uses a supported framework, please open an issue:\n` + + ` https://github.com/kidkender/archmind/issues\n`, + ) + } + return parsed +} + export function parseProject(projectRoot: string): ParsedProject { const framework = detectFramework(projectRoot) + return warnIfNothingParsed(parseDetectedProject(projectRoot, framework), framework) +} + +function parseDetectedProject(projectRoot: string, framework: Framework): ParsedProject { if (framework === "nestjs") { const graphs = parseNestJSProject(projectRoot) diff --git a/packages/explainer/src/__tests__/resource-unprotected-precision.test.ts b/packages/explainer/src/__tests__/resource-unprotected-precision.test.ts new file mode 100644 index 0000000..c12e34a --- /dev/null +++ b/packages/explainer/src/__tests__/resource-unprotected-precision.test.ts @@ -0,0 +1,157 @@ +import { describe, test, expect } from "@jest/globals" +import { detectResourceMismatch } from "../pattern-detectors/resource-mismatch.js" +import { detectDelegatedValidation } from "../pattern-detectors/delegated-validation.js" +import { extractValidationGateFacts } from "../fact-extraction/validation.js" +import { FINDING_TYPES } from "../findings/types.js" +import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge } from "@kidkender/archmind-protocol" + +const ctrl: ExecutionNode = { id: "ctrl", type: "ir:business_handler", symbol: "VaultController::show", role: "handler" } +const res: ExecutionNode = { id: "res_vault", type: "ir:resource", symbol: "Vault", role: "accessed_resource" } +const auth: ExecutionNode = { id: "mw_auth", type: "ir:auth_gate", symbol: "auth:sanctum", role: "authentication" } +const accesses: ExecutionEdge = { from: "ctrl", to: "res_vault", relation: "ir:accesses", traceability: "static" } + +function graph(method: string, extra: ExecutionNode[] = [], extraEdges: ExecutionEdge[] = []): IntermediateExecutionGraph { + return { + entrypoint: `${method} /vaults/{vault}`, + method, + path: "/vaults/{vault}", + nodes: [ctrl, res, ...extra], + edges: [accesses, ...extraEdges], + annotations: [], + } +} + +const unprotected = (g: IntermediateExecutionGraph) => + detectResourceMismatch(g).filter((f) => f.type === FINDING_TYPES.RESOURCE_UNPROTECTED) + +describe("resource_unprotected precision", () => { + test("public route reading a model by ID → CRITICAL", () => { + const f = unprotected(graph("GET")) + expect(f).toHaveLength(1) + expect(f[0]!.severity).toBe("CRITICAL") + }) + + test("authenticated read with no authorization → HIGH (IDOR among users), not CRITICAL", () => { + const f = unprotected(graph("GET", [auth])) + expect(f).toHaveLength(1) + expect(f[0]!.severity).toBe("HIGH") + expect(f[0]!.summary).toContain("any logged-in user") + }) + + test("any authorization on the route (helper, service rule, FormRequest) → no claim", () => { + const helper: ExecutionNode = { id: "authz", type: "ir:authz_check", symbol: "checkPermission(vault-view)", role: "authorization" } + expect(unprotected(graph("GET", [auth, helper]))).toHaveLength(0) + }) + + test("authenticated mutation without authorization is left to missing_authorization (no duplicate)", () => { + expect(unprotected(graph("DELETE", [auth]))).toHaveLength(0) + }) + + test("provable mismatch is still reported", () => { + const other: ExecutionNode = { id: "res_post", type: "ir:resource", symbol: "Post", role: "accessed_resource" } + const pol: ExecutionNode = { id: "pol", type: "ir:authz_check", symbol: "PostPolicy::view", role: "authorization" } + const g = graph("GET", [auth, other, pol], [{ from: "pol", to: "res_post", relation: "ir:authorizes", traceability: "semantic" }]) + expect(detectResourceMismatch(g).some((f) => f.type === FINDING_TYPES.RESOURCE_MISMATCH)).toBe(true) + }) +}) + +describe("delegated_validation on public-by-design routes", () => { + function frGraph(path: string): IntermediateExecutionGraph { + return { + entrypoint: `POST ${path}`, + method: "POST", + path, + nodes: [{ id: "fr", type: "ir:validation_gate", symbol: "SignupRequest::authorize", role: "validation_only" }], + edges: [], + annotations: [], + } + } + const run = (g: IntermediateExecutionGraph) => detectDelegatedValidation(extractValidationGateFacts(g), [], g) + + test.each(["/api/v1/signup", "/client/password/email", "/api/v1/login/precheck", "/webhooks/stripe"])( + "%s → INFO", + (path) => { + expect(run(frGraph(path))[0]!.severity).toBe("INFO") + }, + ) + + test("an ordinary public mutation stays MEDIUM", () => { + expect(run(frGraph("/api/v1/invoices"))[0]!.severity).toBe("MEDIUM") + }) +}) + +import { explain } from "../index.js" + +describe("missing_authorization on self-service routes", () => { + function mutation(path: string, extra: ExecutionNode[] = []): IntermediateExecutionGraph { + return { + entrypoint: `PATCH ${path}`, + method: "PATCH", + path, + nodes: [auth, { id: "ctrl", type: "ir:business_handler", symbol: "PreferencesController::update", role: "handler" }, ...extra], + edges: [{ from: "mw_auth", to: "ctrl", relation: "ir:precedes", traceability: "static" }], + annotations: [], + } + } + const types = (g: IntermediateExecutionGraph) => explain(g).map((f) => f.type) + + test.each(["/preferences/toggle-dark-mode", "/my-account/shortcuts", "/api/me/password", "/user/profile"])( + "%s → not reported (acting on the caller's own record)", + (path) => { + expect(types(mutation(path))).not.toContain(FINDING_TYPES.MISSING_AUTHORIZATION) + }, + ) + + test("a self-service path that loads another record by ID is still reported", () => { + const g = mutation("/profile/{user}", [{ id: "res_user", type: "ir:resource", symbol: "User", role: "accessed_resource" }]) + g.edges.push({ from: "ctrl", to: "res_user", relation: "ir:accesses", traceability: "static" }) + expect(types(g)).toContain(FINDING_TYPES.MISSING_AUTHORIZATION) + }) + + test("an ordinary mutation is still reported", () => { + expect(types(mutation("/settings/webhooks/create"))).toContain(FINDING_TYPES.MISSING_AUTHORIZATION) + }) + + test("a route whose handler method doesn't exist reports nothing", () => { + const g = mutation("/artists/{artist}/songs/{id}") + g.annotations.push({ type: "handler_not_found", description: "no method", nodes: ["ctrl"] }) + expect(explain(g)).toEqual([]) + }) +}) + +describe("signed URLs and more self-service paths", () => { + test("a signed URL protects a public record read", () => { + const signed: ExecutionNode = { id: "mw_signed", type: "signature_check", symbol: "signed", role: "authentication" } + expect(unprotected(graph("GET", [signed]))).toHaveLength(0) + }) + test.each(["/api/v1/settings/enable_two_factor", "/api/broadcasting/auth"])("%s → self-service", (path) => { + const g: IntermediateExecutionGraph = { + entrypoint: `POST ${path}`, method: "POST", path, + nodes: [auth, { id: "ctrl", type: "ir:business_handler", symbol: "X::y", role: "handler" }], + edges: [], annotations: [], + } + expect(explain(g).map((f) => f.type)).not.toContain(FINDING_TYPES.MISSING_AUTHORIZATION) + }) +}) + +import { detectExposedReadEndpoint } from "../pattern-detectors/exposed-read-endpoint.js" + +describe("exposed_read_endpoint on public-by-design routes", () => { + function publicRead(path: string): IntermediateExecutionGraph { + return { + entrypoint: `GET ${path}`, method: "GET", path, + nodes: [ + { id: "ctrl", type: "ir:business_handler", symbol: "SsoController::acs", role: "handler" }, + { id: "svc", type: "ir:service_call", symbol: "Saml2Service::processAcs", role: "service" }, + ], + edges: [{ from: "ctrl", to: "svc", relation: "calls", traceability: "semantic" }], + annotations: [], + } + } + test.each(["/saml2/acs", "/auth/oidc/callback", "/register/invite/{token}"])("%s → INFO", (path) => { + expect(detectExposedReadEndpoint(publicRead(path))[0]?.severity).toBe("INFO") + }) + test("an ordinary public read stays MEDIUM", () => { + expect(detectExposedReadEndpoint(publicRead("/api/invoices"))[0]?.severity).toBe("MEDIUM") + }) +}) diff --git a/packages/explainer/src/index.ts b/packages/explainer/src/index.ts index 576532d..0018d86 100644 --- a/packages/explainer/src/index.ts +++ b/packages/explainer/src/index.ts @@ -14,6 +14,8 @@ export interface ExplainOptions { } export function explain(graph: IntermediateExecutionGraph, query?: string, options: ExplainOptions = {}): Finding[] { + // A route whose handler method doesn't exist can't be reached — nothing to report. + if (graph.annotations?.some((a) => a.type === "handler_not_found")) return [] const facts = extractFacts(graph) const ignored = new Set(options.ignore ?? []) const ranked = rankFindings(detect(facts, graph).filter((f) => !ignored.has(f.type))) diff --git a/packages/explainer/src/pattern-detectors/delegated-validation.ts b/packages/explainer/src/pattern-detectors/delegated-validation.ts index af3d198..7cd4341 100644 --- a/packages/explainer/src/pattern-detectors/delegated-validation.ts +++ b/packages/explainer/src/pattern-detectors/delegated-validation.ts @@ -5,6 +5,7 @@ import { FINDING_TYPES } from "../findings/types.js" import { stableHash } from "../findings/stable-hash.js" import { checkMissingNodes } from "../findings/uncertainty.js" import { validationCanAuthorize } from "./framework.js" +import { isPublicByDesign } from "./public-paths.js" function edgesAmong(graph: IntermediateExecutionGraph, nodeIds: string[]): string[] { const idSet = new Set(nodeIds) @@ -82,7 +83,10 @@ export function detectDelegatedValidation( }) } - const severity = authNodeIds.length > 0 ? "INFO" as const : "MEDIUM" as const + // Login, signup, password reset, webhooks… are public by design: a FormRequest + // that returns true there is expected, not a gap. + const publicByDesign = isPublicByDesign(graph.path) + const severity = authNodeIds.length > 0 || publicByDesign ? "INFO" as const : "MEDIUM" as const const confidence = gate.confidence findings.push({ diff --git a/packages/explainer/src/pattern-detectors/exposed-read-endpoint.ts b/packages/explainer/src/pattern-detectors/exposed-read-endpoint.ts index 29625a3..3143395 100644 --- a/packages/explainer/src/pattern-detectors/exposed-read-endpoint.ts +++ b/packages/explainer/src/pattern-detectors/exposed-read-endpoint.ts @@ -4,6 +4,7 @@ import { query } from "@kidkender/archmind-graph-query" import type { Finding } from "../findings/types.js" import { FINDING_TYPES } from "../findings/types.js" import { stableHash } from "../findings/stable-hash.js" +import { isPublicByDesign } from "./public-paths.js" const READ_METHODS = new Set(["GET", "HEAD"]) @@ -41,7 +42,8 @@ export function detectExposedReadEndpoint( { id: `${FINDING_TYPES.EXPOSED_READ_ENDPOINT}-${stableHash([ctrlNode.id, method])}`, type: FINDING_TYPES.EXPOSED_READ_ENDPOINT, - severity: "MEDIUM", + // SSO callbacks, invitation links, password reset… are public by design + severity: isPublicByDesign(graph.path) ? "INFO" : "MEDIUM", confidence: "MEDIUM", provenance: { detector: FINDING_TYPES.EXPOSED_READ_ENDPOINT, diff --git a/packages/explainer/src/pattern-detectors/missing-authorization.ts b/packages/explainer/src/pattern-detectors/missing-authorization.ts index f81c7c8..3248ec5 100644 --- a/packages/explainer/src/pattern-detectors/missing-authorization.ts +++ b/packages/explainer/src/pattern-detectors/missing-authorization.ts @@ -6,6 +6,9 @@ import type { Finding, Evidence } from "../findings/types.js" import { FINDING_TYPES } from "../findings/types.js" import { stableHash } from "../findings/stable-hash.js" +const SELF_SERVICE_PATH = + /(^|\/)(me|my|my-account|myaccount|profile|preferences|logout|sign-?out|\w*two[-_]?factor\w*|2fa|mfa|password_timeout|broadcasting\/auth|user\/(profile|password|preferences|settings)|settings\/(profile|account|personal|password|security|appearance|language|preferences|cancel))(\/|$)/i + /** * Detects mutation routes (POST/PUT/PATCH/DELETE) that have an authentication * gate but no authorization layer (policy or authorization_check node). @@ -38,6 +41,11 @@ export function detectMissingAuthorization( // Guard: authz node directly on graph (covers cases fact-layer misses) if (q.security().hasAuthorization()) return [] + // Self-service routes (/me, /profile, /preferences, /my-account, logout…) act + // on the caller's own record: being logged in IS the authorization. Only when + // the route doesn't load some other record by ID (no route-bound resource). + if (SELF_SERVICE_PATH.test(graph.path ?? "") && !q.data().resources().exists()) return [] + const gateFact = authFacts.find((f) => f.layer === "middleware")! const evidence: Evidence[] = [ { diff --git a/packages/explainer/src/pattern-detectors/public-paths.ts b/packages/explainer/src/pattern-detectors/public-paths.ts new file mode 100644 index 0000000..6941c89 --- /dev/null +++ b/packages/explainer/src/pattern-detectors/public-paths.ts @@ -0,0 +1,13 @@ +/** + * Paths that are public by design: authentication flows (login, signup, + * password reset, email verification, SSO/SAML/OIDC callbacks), links that + * carry their own token (invitations, unsubscribe), webhooks and health checks. + * A route here having no auth is expected — detectors report it as INFO, not + * as a gap. + */ +export const PUBLIC_BY_DESIGN_PATH = + /(^|\/)(login|logout|signin|sign-in|signup|sign-up|register|registration|password|passwords|forgot|reset|verify|verification|confirm|otp|2fa|two-factor|mfa|oauth|sso|saml2?|oidc|acs|sls|callback|webhooks?|hooks?|precheck|invitations?|invite|unsubscribe|health|healthz|ping|status|manifest(\.json)?|robots\.txt|sitemap(\.xml)?)(\/|$|[-_.])/i + +export function isPublicByDesign(path: string | undefined): boolean { + return PUBLIC_BY_DESIGN_PATH.test(path ?? "") +} diff --git a/packages/explainer/src/pattern-detectors/resource-mismatch.ts b/packages/explainer/src/pattern-detectors/resource-mismatch.ts index de40641..45ae98a 100644 --- a/packages/explainer/src/pattern-detectors/resource-mismatch.ts +++ b/packages/explainer/src/pattern-detectors/resource-mismatch.ts @@ -51,8 +51,24 @@ export function detectResourceMismatch( const ctrlNode = query(graph).nodes().ofType(IR_NODE_TYPES.BUSINESS_HANDLER).first() - // RESOURCE_UNPROTECTED: accessed resource has no matching authorizes edge - for (const acc of accessed) { + // RESOURCE_UNPROTECTED: accessed resource has no matching authorizes edge. + // + // Only claimed when the route has no authorization of any kind. An authz + // check that isn't wired to this resource (a permission helper, a service + // rule, FormRequest::authorize(), a role middleware) may well cover it — we + // can't prove it doesn't, and RESOURCE_MISMATCH below handles the provable case. + const q = query(graph) + const anyAuthorization = q.security().hasAuthorization() + const authenticated = q.security().authenticationGates().exists() + // An authenticated mutation with no authorization is already reported, with + // the same evidence, by missing_authorization — don't report it twice. + const coveredByMissingAuthorization = authenticated && q.isMutation() + // A signed URL (Laravel `signed` middleware) is a capability: only someone + // holding the link the app generated can load the record. + const signedUrl = graph.nodes.some((n) => n.type === "signature_check") + const unprotectedCandidates = anyAuthorization || coveredByMissingAuthorization || signedUrl ? [] : accessed + + for (const acc of unprotectedCandidates) { if (authorizedClasses.has(acc.className)) continue const evidence = [ @@ -71,7 +87,9 @@ export function detectResourceMismatch( findings.push({ id: `${FINDING_TYPES.RESOURCE_UNPROTECTED}-${stableHash([acc.nodeId, graph.entrypoint ?? ""])}`, type: FINDING_TYPES.RESOURCE_UNPROTECTED, - severity: "CRITICAL", + // CRITICAL only when anyone, not logged in, can reach the record by ID; + // behind a login it is an IDOR risk among authenticated users. + severity: authenticated ? "HIGH" : "CRITICAL", confidence: "HIGH", provenance: { detector: FINDING_TYPES.RESOURCE_UNPROTECTED, @@ -81,7 +99,9 @@ export function detectResourceMismatch( .filter((e) => e.to === acc.nodeId || e.from === acc.nodeId) .map((e) => `${e.from}:${e.relation}:${e.to}`), }, - summary: `${acc.className} is accessed without authorization — no policy or Gate check covers this resource`, + summary: authenticated + ? `${acc.className} is loaded by ID with no authorization check — any logged-in user can reach any ${acc.className}` + : `${acc.className} is loaded by ID on a public route with no authentication or authorization`, reasoning: [ { type: "resource_accessed", diff --git a/packages/laravel-parser/src/__tests__/authorization-precision.test.ts b/packages/laravel-parser/src/__tests__/authorization-precision.test.ts new file mode 100644 index 0000000..9e17d35 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/authorization-precision.test.ts @@ -0,0 +1,518 @@ +/** + * Authorization precision on real-app patterns (research/laravel-scan): + * each case here was a false positive on BookStack, monica, invoiceninja or koel + * before 0.11. The graph must carry an authorization fact for each of them — + * and must not invent resources or missing policies. + */ +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join, dirname } from "path" +import { augmentGraph, isRealAuthorizeBody } from "../graph-augmenter.js" +import { middlewareToNode } from "../middleware-mapper.js" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" + +let root: string + +function put(rel: string, body: string): void { + const p = join(root, rel) + mkdirSync(dirname(p), { recursive: true }) + writeFileSync(p, body) +} + +function graphFor(method: string, path: string, controller: string, action: string): IntermediateExecutionGraph { + return { + entrypoint: `${method} ${path}`, + method, + path, + nodes: [ + { id: "mw_auth", type: "ir:auth_gate", symbol: "auth:sanctum", role: "authentication" }, + { + id: `ctrl_${controller.toLowerCase()}_${action}`, + type: "ir:business_handler", + symbol: `${controller}::${action}`, + role: "handler", + file: `app/Http/Controllers/${controller}.php`, + }, + ], + edges: [{ from: "mw_auth", to: `ctrl_${controller.toLowerCase()}_${action}`, relation: "ir:precedes", traceability: "static" }], + annotations: [], + } +} + +const authz = (g: IntermediateExecutionGraph) => g.nodes.filter((n) => n.type === "ir:authz_check") + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "archmind-authz-")) + + put("app/Models/Page.php", `checkOwnablePermission('page-update', $page); + $page->save(); + } + public function delete(string $id) { + if (!userCan('page-delete')) { abort(403); } + } + public function search(SearchResultsFormatter $formatter) { + return $formatter; + } + public function publish(Page $page) { + abort_unless(request()->user()->can('publish', $page), 403); + } +} +`) + + // koel: Laravel resolves the policy from the model, not the controller name + put("app/Http/Controllers/ScrobbleController.php", `authorize('access', $song); + } + public function missing(Page $page) { + $this->authorize('view', $page); + } +} +`) + + // authorizeResource() in the constructor + put("app/Http/Controllers/SongController.php", `authorizeResource(Song::class, 'song', ['except' => ['index']]); } + public function update(Song $song) { $song->save(); } + public function index() { return Song::all(); } +} +`) + + // monica: (new UpdateVault)->execute() with permissions() rules in the service + put("app/Services/UpdateVault.php", `validateRules($data); } +} +`) + put("app/Http/Controllers/VaultController.php", `execute(['vault_id' => $vaultId]); + return $vault; + } +} +`) + + // invoiceninja: authorization in FormRequest::authorize() + put("app/Http/Requests/UpdateClientRequest.php", `user()->can('edit', $this->client); } + public function rules() { return []; } +} +`) + put("app/Http/Requests/StoreNoteRequest.php", `check(); } +} +`) + put("app/Http/Controllers/ClientController.php", `only() + put("app/Http/Controllers/WebhookController.php", `middleware([Permission::SettingsManage->middleware()]); + $this->middleware('can:export')->only(['export']); + } + public function update(Request $request, string $id) { return 1; } + public function export() { return 1; } +} +`) + + // koel: apiResource on a controller that only implements index() + put("app/Http/Controllers/ArtistSongController.php", ` { + rmSync(root, { recursive: true, force: true }) +}) + +describe("controller-level permission helpers (BookStack)", () => { + test("$this->checkOwnablePermission() is an authorization fact", () => { + const g = augmentGraph(graphFor("PUT", "/api/pages/{page}", "PageApiController", "update"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("checkOwnablePermission(page-update)") + // wired to the bound model, so resource_unprotected has nothing to report + const res = g.nodes.find((n) => n.type === "ir:resource") + expect(res?.symbol).toBe("Page") + expect(g.edges.some((e) => e.relation === "ir:authorizes" && e.to === res!.id)).toBe(true) + expect(g.annotations.some((a) => a.type === "missing_policy")).toBe(false) + }) + + test("global userCan() helper is an authorization fact", () => { + const g = augmentGraph(graphFor("DELETE", "/api/pages/{id}", "PageApiController", "delete"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("userCan(page-delete)") + }) + + test("$user->can() inside abort_unless is an authorization fact", () => { + const g = augmentGraph(graphFor("POST", "/api/pages/{page}/publish", "PageApiController", "publish"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("can(publish)") + }) + + test("a typed helper param that is not an Eloquent model is not a resource", () => { + const g = augmentGraph(graphFor("GET", "/search", "PageApiController", "search"), { projectRoot: root }) + expect(g.nodes.some((n) => n.type === "ir:resource")).toBe(false) + }) +}) + +describe("policy resolution by model (koel)", () => { + test("authorize('access', $song) resolves SongPolicy, found in a sub-folder — no missing_policy", () => { + const g = augmentGraph(graphFor("POST", "/api/songs/{song}/scrobble", "ScrobbleController", "__invoke"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("SongPolicy::access") + expect(g.annotations.some((a) => a.type === "missing_policy")).toBe(false) + }) + + test("authorize() on a model whose policy really doesn't exist still raises missing_policy", () => { + const g = augmentGraph(graphFor("GET", "/pages/{page}", "ScrobbleController", "missing"), { projectRoot: root }) + const missing = g.annotations.filter((a) => a.type === "missing_policy") + expect(missing).toHaveLength(1) + expect(missing[0]!.description).toContain("PagePolicy") + }) + + test("authorizeResource() in the constructor authorizes resource methods, honouring except", () => { + const upd = augmentGraph(graphFor("PUT", "/songs/{song}", "SongController", "update"), { projectRoot: root }) + expect(authz(upd).map((n) => n.symbol)).toContain("SongPolicy::update") + const idx = augmentGraph(graphFor("GET", "/songs", "SongController", "index"), { projectRoot: root }) + expect(authz(idx)).toHaveLength(0) + }) +}) + +describe("service-layer authorization (monica)", () => { + test("(new UpdateVault)->execute() is a service call whose permissions() rules are an authz fact", () => { + const g = augmentGraph(graphFor("PUT", "/api/vaults/{id}", "VaultController", "update"), { projectRoot: root }) + expect(g.nodes.some((n) => n.type === "ir:service_call" && n.symbol === "UpdateVault::execute")).toBe(true) + const check = authz(g).find((n) => n.symbol === "UpdateVault::permissions") + expect(check?.args).toEqual(["author_must_belong_to_account", "author_must_be_vault_manager"]) + }) +}) + +describe("FormRequest::authorize() (invoiceninja)", () => { + test("a real check in authorize() is an authorization fact", () => { + const g = augmentGraph(graphFor("PUT", "/api/v1/clients/{id}", "ClientController", "update"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("UpdateClientRequest::authorize") + }) + + test("authorize() that only checks login is not", () => { + const g = augmentGraph(graphFor("POST", "/api/v1/notes", "ClientController", "note"), { projectRoot: root }) + expect(authz(g)).toHaveLength(0) + }) + + test.each([ + ["true", false], + ["false", false], + ["auth()->check()", false], + ["$this->user() !== null", false], + ["auth()->user()->can('edit', $this->client)", true], + ["$this->user()->isAdmin()", true], + ["if ($this->user()->cannot('x')) { return false; } return true;", true], + ])("isRealAuthorizeBody(%s) = %s", (body, expected) => { + expect(isRealAuthorizeBody(body)).toBe(expected) + }) +}) + +describe("middleware classification", () => { + test.each([ + ["SessionDomains", "ir:unknown_middleware"], + ["App\\Http\\Middleware\\SetLocale", "ir:unknown_middleware"], + ["TokenAuth", "ir:auth_gate"], + ["App\\Http\\Middleware\\Authenticate", "ir:auth_gate"], + ["AuthorizeAdmin", "ir:authz_check"], + ["CheckRole", "ir:authz_check"], + ])("%s → %s", (raw, type) => { + expect(middlewareToNode(raw, 0).type).toBe(type) + }) +}) + +describe("constructor middleware (BookStack WebhookController)", () => { + test("enum ->middleware() in a middleware array is an authorization check", () => { + const g = augmentGraph(graphFor("PUT", "/settings/webhooks/{id}", "WebhookController", "update"), { projectRoot: root }) + expect(authz(g).length).toBeGreaterThan(0) + }) + test("->only([...]) chained on $this->middleware() limits it to those methods", () => { + const upd = augmentGraph(graphFor("PUT", "/settings/webhooks/{id}", "WebhookController", "update"), { projectRoot: root }) + expect(upd.nodes.some((n) => n.symbol === "can:export")).toBe(false) + const exp = augmentGraph(graphFor("GET", "/settings/webhooks/export", "WebhookController", "export"), { projectRoot: root }) + expect(exp.nodes.some((n) => n.symbol === "can:export" && n.type === "ir:authz_check")).toBe(true) + }) +}) + +describe("routes to actions the controller doesn't define", () => { + test("flagged when the controller can't inherit the method", () => { + const g = augmentGraph(graphFor("PUT", "/artists/{artist}/songs/{id}", "ArtistSongController", "update"), { projectRoot: root }) + expect(g.annotations.some((a) => a.type === "handler_not_found")).toBe(true) + }) + test("not flagged when a base class may provide it", () => { + const g = augmentGraph(graphFor("PUT", "/things/{id}", "CrudController", "update"), { projectRoot: root }) + expect(g.annotations.some((a) => a.type === "handler_not_found")).toBe(false) + }) +}) + +describe("same-namespace typed params", () => { + test("a class next to the controller that isn't a model is not a resource", () => { + const g: IntermediateExecutionGraph = { + ...graphFor("GET", "/search", "SearchController", "search"), + } + g.nodes[1] = { ...g.nodes[1]!, file: "app/Search/SearchController.php" } + const out = augmentGraph(g, { projectRoot: root }) + expect(out.nodes.some((n) => n.type === "ir:resource")).toBe(false) + }) +}) + +describe("built-in middleware aliases without a Kernel (Laravel 11+)", () => { + test.each([ + ["auth", "ir:auth_gate"], + ["can:update,post", "ir:authz_check"], + ["role:admin", "ir:authz_check"], + ["guest", "ir:unknown_middleware"], + ["App\Http\Middleware\RedirectIfAuthenticated", "ir:unknown_middleware"], + ])("%s → %s", (raw, type) => { + expect(middlewareToNode(raw, 0).type).toBe(type) + }) +}) + +describe("signed URLs", () => { + test.each([ + ["signed", "signature_check"], + ["signed:relative", "signature_check"], + ["App\Http\Middleware\ValidateSignature", "signature_check"], + ])("%s → %s", (raw, type) => { + expect(middlewareToNode(raw, 0).type).toBe(type) + }) +}) + +import { parseApiResource } from "../resource-parser.js" + +describe("sensitive fields in API resources (koel UserResource)", () => { + test("conditional ($this->when) fields and boolean flags are not sensitive; plain secrets are", () => { + put("app/Http/Resources/UserResource.php", ` $this->name, + 'subsonic_api_key' => $this->when($isCurrentUser, fn () => $this->subsonic_api_key), + 'has_password' => (bool) $this->password, + 'is_admin' => $this->is_admin, + 'api_token' => $this->api_token, + ]; + } +} +`) + const info = parseApiResource(join(root, "app/Http/Resources/UserResource.php"))! + const sensitive = info.fields.filter((f) => f.isSensitive).map((f) => f.key) + expect(sensitive).toEqual(["api_token"]) + }) +}) + +describe("writes and reads scoped to the caller", () => { + beforeAll(() => { + put("app/Repositories/AlbumRepository.php", `withUserContext(user: $this->auth->user())->findOrFail($id); + } + public function getRaw($id) { return Album::query()->findOrFail($id); } +} +`) + put("app/Http/Controllers/AlbumController.php", `repository->getOne($song->id); } + public function raw(Song $song) { return $this->repository->getRaw($song->id); } +} +`) + put("app/Http/Controllers/UserTokenController.php", `user()->userTokens()->where('driver', $driver)->delete(); + } + public function company(Request $request) { + $request->user()->company()->update(['name' => 'x']); + } +} +`) + }) + + test("repository re-fetch through accessible()/withUserContext() is an authorization fact (koel)", () => { + const g = augmentGraph(graphFor("GET", "/api/albums/{song}", "AlbumController", "show"), { projectRoot: root }) + expect(authz(g).map((n) => n.symbol)).toContain("AlbumRepository::getOne (query scoped to caller)") + const raw = augmentGraph(graphFor("GET", "/api/albums/{song}/raw", "AlbumController", "raw"), { projectRoot: root }) + expect(authz(raw)).toHaveLength(0) + }) + + test("deleting through the caller's own relation is scoped; through company() is not (monica)", () => { + const own = augmentGraph(graphFor("DELETE", "/auth/{driver}", "UserTokenController", "destroy"), { projectRoot: root }) + expect(authz(own).map((n) => n.symbol)).toContain("scoped to caller(userTokens()->delete)") + const shared = augmentGraph(graphFor("POST", "/company", "UserTokenController", "company"), { projectRoot: root }) + expect(authz(shared)).toHaveLength(0) + }) +}) + + +describe("route-bound model the handler never uses (invoiceninja ProfileController::edit)", () => { + test("is not a resource the route exposes", () => { + put("app/Http/Controllers/ProfileController.php", [ + " n.type === "ir:resource")).toBe(false) + }) +}) + +describe("policy on an interface-typed param (koel Authenticatable $invitor)", () => { + test("no missing_policy — Laravel resolves the policy from the runtime class", () => { + put("app/Http/Controllers/InviteController.php", [ + "authorize('manage', $invitor); }", + "}", + ].join("\n")) + const g = augmentGraph(graphFor("POST", "/api/invitations", "InviteController", "invite"), { projectRoot: root }) + expect(g.annotations.some((a) => a.type === "missing_policy")).toBe(false) + }) +}) + +describe("queries filtered on the caller (invoiceninja client portal)", () => { + test("whereClientId() scopes the route; where('company_id', ) does not", () => { + put("app/Http/Controllers/PortalController.php", [ + "pdf($request->ids); }", + " private function pdf($ids) {", + " return Invoice::query()->whereIn('id', $ids)->whereClientId(auth()->guard('contact')->user()->client_id)->get();", + " }", + " public function multiple(Request $request) {", + " return Document::query()->whereIn('id', $request->ids)->where('company_id', auth()->guard('contact')->user()->company_id)->get();", + " }", + "}", + ].join("\n")) + const own = augmentGraph(graphFor("POST", "/client/invoices/download", "PortalController", "download"), { projectRoot: root }) + expect(authz(own).map((n) => n.symbol)).toContain("query scoped to caller(client_id)") + const shared = augmentGraph(graphFor("POST", "/client/documents/download_multiple", "PortalController", "multiple"), { projectRoot: root }) + expect(authz(shared)).toHaveLength(0) + }) +}) + +describe("FormRequest authorize() with a conditional deny (invoiceninja DownloadMultipleDocumentsRequest)", () => { + test("a loop that returns false per item is a real check; `if (!auth()->check()) return false; return true;` is not", () => { + put("app/Http/Requests/DownloadRequest.php", [ + "contactCanAccessDocument($c, $d)) { return false; } }", + " return true;", + " }", + "}", + ].join("\n")) + put("app/Http/Requests/LoggedInRequest.php", [ + "check()) { return false; }", + " return true;", + " }", + "}", + ].join("\n")) + put("app/Http/Controllers/DocController.php", [ + " n.symbol)).toContain("DownloadRequest::authorize") + const mine = augmentGraph(graphFor("POST", "/docs/mine", "DocController", "mine"), { projectRoot: root }) + expect(authz(mine)).toHaveLength(0) + }) +}) diff --git a/packages/laravel-parser/src/__tests__/fixtures/routes-namespace-alias.php b/packages/laravel-parser/src/__tests__/fixtures/routes-namespace-alias.php new file mode 100644 index 0000000..58584b8 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/fixtures/routes-namespace-alias.php @@ -0,0 +1,6 @@ + { describe("parseRouteFile — alias resolution", () => { const KERNEL = join(FIXTURES, "app/Http/Kernel.php") - test("without aliasMap: role:admin emits honest unknown_middleware node", () => { + test("without aliasMap: role:admin is still an authorization check (like permission:)", () => { + // Laravel 11+ apps have no Kernel.php to resolve aliases; `role:` (spatie's + // conventional alias) is classified by its shape, the same way `permission:` + // always was — reading it as unknown made role-gated routes look unauthorized. const graphs = parseRouteFile(join(FIXTURES, "routes-alias.php")) const g = graphs.find((g) => g.path === "/reports")! const roleNode = g.nodes.find((n) => n.symbol === "role:admin") expect(roleNode).toBeDefined() - expect(roleNode!.type).toBe("ir:unknown_middleware") + expect(roleNode!.type).toBe("ir:authz_check") }) test("with aliasMap: role:admin resolves to authorization_check", () => { diff --git a/packages/laravel-parser/src/__tests__/middleware-mapper.test.ts b/packages/laravel-parser/src/__tests__/middleware-mapper.test.ts index bc4a027..09b9655 100644 --- a/packages/laravel-parser/src/__tests__/middleware-mapper.test.ts +++ b/packages/laravel-parser/src/__tests__/middleware-mapper.test.ts @@ -44,9 +44,11 @@ describe("middlewareToNode", () => { expect(node.type).toBe("email_verification") }) - test("class-based: ResolveTenant → middleware with class name", () => { + test("class-based: ResolveTenant → unknown middleware, not an auth gate", () => { + // Resolving a tenant is not authentication — defaulting class middleware to + // auth_gate made public routes read as "authenticated" (invoiceninja SessionDomains). const node = middlewareToNode("ResolveTenant", 1) - expect(node.type).toBe("ir:auth_gate") + expect(node.type).toBe("ir:unknown_middleware") expect(node.symbol).toBe("ResolveTenant") expect(node.args).toContain("ResolveTenant") }) diff --git a/packages/laravel-parser/src/__tests__/route-parser.test.ts b/packages/laravel-parser/src/__tests__/route-parser.test.ts index b5803fa..d062024 100644 --- a/packages/laravel-parser/src/__tests__/route-parser.test.ts +++ b/packages/laravel-parser/src/__tests__/route-parser.test.ts @@ -1,4 +1,6 @@ import { join, dirname } from "path" +import { writeFileSync, mkdtempSync } from "fs" +import { tmpdir } from "os" import { fileURLToPath } from "url" import { parseRouteFile } from "../route-parser.js" import { parseConstantClass } from "../constant-resolver.js" @@ -58,7 +60,7 @@ describe("parseRouteFile — nested middleware groups", () => { const types = g.nodes.map((n) => n.type) expect(types).toEqual([ "ir:auth_gate", - "ir:auth_gate", + "ir:unknown_middleware", // ResolveTenant — tenant context, not authentication "ir:authz_check", "ir:business_handler", ]) @@ -177,3 +179,22 @@ describe("parseConstantClass", () => { expect(map["Permissions"]["TASK_DELETE"]).toBe("task.delete") }) }) + +describe("parseRouteFile — namespace alias import (BookStack routes/api.php)", () => { + test("EntityControllers\PageApiController resolves through `use … as EntityControllers`", () => { + const graphs = parseRouteFile(fixture("routes-namespace-alias.php"), { namespaces: { "BookStack\\": "app/" } }) + const ctrl = graphs[0]!.nodes.find((n) => n.type === "ir:business_handler") + expect(ctrl?.file).toBe("app/Entities/Controllers/PageApiController.php") + }) +}) + +describe("parseRouteFile — nested resource", () => { + test("apiResource('artists.songs') → /artists/{artist}/songs", () => { + const dir = mkdtempSync(join(tmpdir(), "am-nested-")) + const file = join(dir, "api.php") + writeFileSync(file, " g.entrypoint) + expect(paths).toContain("GET /artists/{artist}/songs") + expect(paths).toContain("PUT /artists/{artist}/songs/{id}") + }) +}) diff --git a/packages/laravel-parser/src/controller-parser.ts b/packages/laravel-parser/src/controller-parser.ts index 625d234..b309b78 100644 --- a/packages/laravel-parser/src/controller-parser.ts +++ b/packages/laravel-parser/src/controller-parser.ts @@ -21,12 +21,29 @@ export interface AuthorizeCall { ability: string // first string arg, e.g. "update" mechanism: string // full call text, e.g. "$this->authorize('update', $task)" modelVar?: string // second arg variable name, e.g. "$task" + /** + * "policy" (default): resolved through a Laravel policy — $this->authorize(), + * Gate::allows(), authorizeResource(). "helper": an authorization check that + * isn't a policy lookup — $this->checkPermission(), $user->can(), userCan() — + * so no policy class is inferred (and no missing_policy can be raised). + */ + kind?: "policy" | "helper" + /** Model class the policy is resolved from (Laravel picks the policy by model, not by controller). */ + modelClass?: string + /** Helper name for kind "helper", e.g. "checkOwnablePermission". */ + helper?: string } export interface ModelParam { className: string // e.g. "Product" classFqcn: string // e.g. "App\Models\Product" paramName: string // e.g. "$product" + /** + * Whether the handler body references the param. A bound model the handler + * never touches (invoiceninja's ProfileController::edit renders the logged-in + * contact, not `$client_contact`) can't expose another user's record. + */ + usedInBody?: boolean } export interface ServiceCall { @@ -150,8 +167,11 @@ export function parseControllerMethod( const formRequests = extractFormRequests(methodNode, useMap) const modelParams = extractModelParams(methodNode, useMap) - const authorizeCalls = extractAuthorizeCalls(methodNode, modelParams) - const serviceCalls = extractServiceCalls(methodNode, allInjections, useMap, requestParamVars) + const authorizeCalls = [ + ...extractAuthorizeCalls(methodNode, modelParams), + ...extractAuthorizeResource(root, methodName, modelParams), + ] + const serviceCalls = extractServiceCalls(methodNode, allInjections, useMap, requestParamVars) const returnedResources = extractReturnedResources(methodNode, useMap) const standaloneDispatches = extractStandaloneDispatches(methodNode, useMap) const standaloneNotifications = extractNotificationDispatches(methodNode, useMap) @@ -245,15 +265,30 @@ export function parseFormRequestAuthorize(filePath: string): string | undefined const body = methodNode.childForFieldName("body") if (!body) return undefined + let topReturn: string | undefined for (const child of body.children) { if (child.type === "return_statement") { const expr = child.children.find( (c) => c.type !== "return" && c.type !== ";" && c.text.trim() !== "" ) - if (expr) return expr.text.trim() + if (expr) { topReturn = expr.text.trim(); break } } } - return undefined + + // `if ($this->user()->cannot('edit', $this->client)) { return false; } return true;` + // — the final `return true` hides a real check made earlier in the body. + // Report the (compacted) body so the check is not read as a passthrough. + const bodyText = body.text + // A conditional `return false` is a deny branch — e.g. invoiceninja's + // DownloadMultipleDocumentsRequest loops `if (! $this->contactCanAccessDocument(...)) return false;` + // — unless the only condition is "is someone logged in". + const authOnlyBody = /^\{\s*(if\s*\(\s*!\s*(auth\(\)->check\(\)|Auth::check\(\)|\$this->user\(\)|auth\(\)->user\(\))\s*\)\s*\{?\s*return\s+false;\s*\}?\s*)?return\s+true;\s*\}$/ + const conditionalDeny = /return\s+false/.test(bodyText) && !authOnlyBody.test(bodyText.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, "").trim()) + const checksEarlier = conditionalDeny || /->(can|cannot|cant|hasPermissionTo|hasPermission|hasRole|hasAnyRole|isAdmin|isOwner)\s*\(|Gate::|authorize\s*\(|abort(_if|_unless)?\s*\(/.test(bodyText) + if ((topReturn === undefined || /^true$/i.test(topReturn)) && checksEarlier) { + return bodyText.replace(/^\{|\}$/g, "").replace(/\s+/g, " ").trim().slice(0, 240) + } + return topReturn } // ---- Use-statement extraction ----------------------------------------- @@ -394,7 +429,9 @@ function extractModelParams( const classFqcn = useMap.get(typeName) ?? typeName if (SKIP_FQCN.has(classFqcn)) continue - results.push({ className: typeName, classFqcn, paramName: varNode.text }) + const bodyText = methodNode.childForFieldName("body")?.text ?? "" + const usedInBody = new RegExp(`\\${varNode.text}\\b`).test(bodyText) + results.push({ className: typeName, classFqcn, paramName: varNode.text, usedInBody }) } return results @@ -410,23 +447,101 @@ function extractAuthorizeCalls(methodNode: Parser.SyntaxNode, modelParams: Model return results } +// Gate facade methods that resolve an ability (policy or Gate::define) +const GATE_METHODS = new Set(["authorize", "allows", "check", "denies", "any", "none", "inspect"]) + +// $this->helper(...) names that perform an authorization check, e.g. +// BookStack's checkOwnablePermission() / checkPermission(), ensureCanEdit(), +// authorizeOwner(). Plain "authorize" is the policy call handled above. +const SELF_HELPER_RE = + /^(authorize\w+|check\w*(permission|access|abilit|role|owner|admin|can)\w*|ensure\w*(permission|access|can|owner|role|admin|allowed|authori)\w*|require\w*(permission|role|admin|owner|access)\w*|deny\w*|abortUnless\w*|abortIf(Not|Cannot)\w*)$/i + +// ->method(...) on any object: $request->user()->can('x'), Gate::forUser($u)->allows(...), +// spatie/laravel-permission's hasPermissionTo / hasRole. +const MEMBER_CHECK_METHODS = new Set([ + "can", "cannot", "cant", "allows", "denies", + "hasPermissionTo", "hasPermission", "hasAnyPermission", "hasAllPermissions", "checkPermissionTo", + "hasRole", "hasAnyRole", "hasAllRoles", "isAdmin", "isSuperAdmin", "isOwner", "isOwnerOf", +]) + +const SELF_WRITE_METHODS = new Set(["delete", "update", "save", "create", "updateOrCreate", "forceDelete", "attach", "detach", "sync", "toggle"]) +// current user, optionally followed by ONE relation call: group 2 = relation name +const CALLER_CHAIN_RE = /^(\$request->user\(\)|auth\(\)->user\(\)|Auth::user\(\)|\$this->user\(\)|request\(\)->user\(\))(?:\s*->\s*(\w+)\s*\(\))?/ +const SHARED_PARENT_RE = /^(company|companies|account|team|teams|organi[sz]ation|tenant|workspace|vault|vaults|group|project|currentTeam)$/i +// An expression that yields the caller: auth()->user(), auth()->guard('x')->user(), $request->user(), Auth::id()… +const CALLER_EXPR_RE = /auth\(\)(->guard\([^)]*\))?->(user|id)\(\)|Auth::(user|id)\(\)|\$request->user\(\)|request\(\)->user\(\)|\$this->user\(\)/ +const SHARED_KEY_RE = /^(company|account|team|tenant|organi[sz]ation|workspace|group|project)_id$/ + +// Global helper functions that check permissions (BookStack's userCan()). +const FUNCTION_HELPER_RE = /^(userCan\w*|user_can|authorize\w*|check\w*Permission\w*)$/ + function gatherAuthorizeCalls(node: Parser.SyntaxNode, results: AuthorizeCall[], modelParams: ModelParam[]): void { - // $this->authorize('ability', $model) if (node.type === "member_call_expression") { const obj = node.childForFieldName("object") - const name = node.childForFieldName("name") - if (obj?.text === "$this" && name?.text === "authorize") { - pushAuthorizeCall(node, results, modelParams) + const name = node.childForFieldName("name")?.text + if (obj?.text === "$this" && (name === "authorize" || name === "authorizeForUser")) { + // $this->authorize('ability', $model) — a policy lookup + pushAuthorizeCall(node, results, modelParams, "policy", name === "authorizeForUser" ? 1 : 0) + } else if (obj?.text === "$this" && name && SELF_HELPER_RE.test(name) && name !== "authorizeResource") { + pushAuthorizeCall(node, results, modelParams, "helper", 0, name) + } else if (obj?.text !== "$this" && name && MEMBER_CHECK_METHODS.has(name)) { + pushAuthorizeCall(node, results, modelParams, "helper", 0, name) } } - // Gate::authorize('ability', $model) or Gate::allows('ability', $model) + // Gate::authorize('ability', $model), Gate::allows / denies / check / any / none / inspect // tree-sitter-php uses "scoped_call_expression" with field "scope" for the class if (node.type === "scoped_call_expression") { const cls = node.childForFieldName("scope") const method = node.childForFieldName("name") - if (cls?.text === "Gate" && (method?.text === "authorize" || method?.text === "allows" || method?.text === "check")) { - pushAuthorizeCall(node, results, modelParams) + if (cls?.text === "Gate" && method && GATE_METHODS.has(method.text)) { + pushAuthorizeCall(node, results, modelParams, "policy", 0) + } + } + + if (node.type === "function_call_expression") { + const fn = node.childForFieldName("function")?.text + if (fn && FUNCTION_HELPER_RE.test(fn)) { + pushAuthorizeCall(node, results, modelParams, "helper", 0, fn) + } + } + + // A query filtered on the caller's own key — `->whereClientId(auth()->guard('contact') + // ->user()->client_id)` (invoiceninja client portal), `->where('user_id', auth()->id())` + // — returns only the caller's rows. Filtering on a SHARED key (company_id, account_id, + // team_id…) does not: other users/clients of the same company still match. + if (node.type === "member_call_expression") { + const name = node.childForFieldName("name")?.text ?? "" + const args = node.childForFieldName("arguments")?.text ?? "" + const col = /^where[A-Z]\w*Id$/.test(name) + ? name.slice(5).replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase() // whereClientId → client_id + : name === "where" ? (args.match(/^\(\s*['"]([\w.]+)['"]/)?.[1]?.split(".").pop() ?? "") : "" + if (col && /_id$/.test(col) && CALLER_EXPR_RE.test(args) && !SHARED_KEY_RE.test(col)) { + results.push({ + ability: col, + mechanism: node.text.slice(0, 160), + kind: "helper", + helper: "query scoped to caller", + }) + } + } + + // A write that goes through the caller's own record can only touch that + // caller's data: `$request->user()->userTokens()->where(...)->delete()` + // (monica), `auth()->user()->update([...])`. Shared parents — the caller's + // company / account / team — are excluded: writing there still needs a role check. + if (node.type === "member_call_expression") { + const name = node.childForFieldName("name")?.text + if (name && SELF_WRITE_METHODS.has(name)) { + const m = node.text.match(CALLER_CHAIN_RE) + if (m && !SHARED_PARENT_RE.test(m[2] ?? "")) { + results.push({ + ability: m[2] ? `${m[2]}()->${name}` : name, + mechanism: node.text.slice(0, 160), + kind: "helper", + helper: "scoped to caller", + }) + } } } @@ -435,26 +550,102 @@ function gatherAuthorizeCalls(node: Parser.SyntaxNode, results: AuthorizeCall[], } } -function pushAuthorizeCall(node: Parser.SyntaxNode, results: AuthorizeCall[], modelParams: ModelParam[]): void { +function pushAuthorizeCall( + node: Parser.SyntaxNode, + results: AuthorizeCall[], + modelParams: ModelParam[], + kind: "policy" | "helper", + abilityIndex: number, + helper?: string, +): void { const argsNode = node.childForFieldName("arguments") - if (!argsNode) return - const argValues = (argsNode.children as Parser.SyntaxNode[]) - .filter((c) => c.type === "argument") - .map((c) => c.firstNamedChild) - .filter((c): c is Parser.SyntaxNode => c !== null) - const ability = argValues[0] ? resolveStringNode(argValues[0]) : "unknown" - - // Extract the model variable from the second arg (e.g. "$task" from authorize('update', $task)) - let modelVar: string | undefined - if (argValues[1]?.type === "variable_name") { - const varText = argValues[1].text // e.g. "$task" - // Only set modelVar if we have a matching typed model param - if (modelParams.some((mp) => mp.paramName === varText)) { - modelVar = varText + const argValues = argsNode + ? (argsNode.children as Parser.SyntaxNode[]) + .filter((c) => c.type === "argument") + .map((c) => c.firstNamedChild) + .filter((c): c is Parser.SyntaxNode => c !== null) + : [] + const abilityNode = argValues[abilityIndex] + // Helpers like isAdmin() take no ability argument — name the check by the helper itself + const ability = abilityNode ? resolveStringNode(abilityNode) : (helper ?? "unknown") + + // The model the check targets: a typed route-model param passed as any later + // argument ($this->authorize('update', $task)), or Model::class. + let modelVar: string | undefined + let modelClass: string | undefined + for (const arg of argValues.slice(abilityIndex + 1)) { + if (arg.type === "variable_name") { + const mp = modelParams.find((p) => p.paramName === arg.text) + if (mp) { modelVar = mp.paramName; modelClass = mp.className; break } + } + if (arg.type === "class_constant_access_expression" && /::class$/.test(arg.text)) { + modelClass = arg.text.replace(/::class$/, "").split("\\").pop() + break } } - results.push({ ability, mechanism: node.text, modelVar }) + results.push({ + ability, + mechanism: node.text, + modelVar, + kind, + ...(modelClass ? { modelClass } : {}), + ...(helper ? { helper } : {}), + }) +} + +// ---- authorizeResource() in the constructor ---------------------------- + +// Controller method → ability, as Laravel's AuthorizesRequests::resourceAbilityMap() +const RESOURCE_ABILITY_MAP: Record = { + index: "viewAny", show: "view", create: "create", store: "create", + edit: "update", update: "update", destroy: "delete", +} + +/** + * `$this->authorizeResource(Post::class, 'post')` in __construct() authorizes + * every resource method through PostPolicy (unless excluded via `['except' => …]`). + */ +function extractAuthorizeResource( + root: Parser.SyntaxNode, + methodName: string, + modelParams: ModelParam[], +): AuthorizeCall[] { + const ability = RESOURCE_ABILITY_MAP[methodName] + if (!ability) return [] + const ctor = findMethod(root, "__construct") + const body = ctor?.childForFieldName("body") + if (!body) return [] + + const found: AuthorizeCall[] = [] + const walk = (node: Parser.SyntaxNode): void => { + if (node.type === "member_call_expression") { + const obj = node.childForFieldName("object") + const name = node.childForFieldName("name") + if (obj?.text === "$this" && name?.text === "authorizeResource") { + const text = node.text + const except = text.match(/['"]except['"]\s*=>\s*\[([^\]]*)\]/) + const only = text.match(/['"]only['"]\s*=>\s*\[([^\]]*)\]/) + const listed = (m: RegExpMatchArray | null) => (m?.[1] ?? "").includes(`'${methodName}'`) || (m?.[1] ?? "").includes(`"${methodName}"`) + if (except && listed(except)) return + if (only && !listed(only)) return + const classArg = text.match(/authorizeResource\(\s*([\w\\]+)::class/) + const modelClass = classArg?.[1]?.split("\\").pop() + const mp = modelParams.find((p) => p.className === modelClass) + found.push({ + ability, + mechanism: text, + kind: "policy", + ...(modelClass ? { modelClass } : {}), + ...(mp ? { modelVar: mp.paramName } : {}), + }) + return + } + } + for (const child of node.children as Parser.SyntaxNode[]) walk(child) + } + walk(body) + return found } // ---- Private method call extraction ---------------------------------- @@ -553,7 +744,32 @@ function collectMiddlewareCalls(node: Parser.SyntaxNode, results: ConstructorMid } } - results.push({ raw, except, only }) + // $this->middleware('auth')->only(['edit']) / ->except('index') + const parent = node.parent + if (parent?.type === "member_call_expression") { + const chained = parent.childForFieldName("name")?.text + const chainArgs = parent.childForFieldName("arguments") + if ((chained === "only" || chained === "except") && chainArgs) { + const vals = [...chainArgs.text.matchAll(/['"]([\w-]+)['"]/g)].map((m) => m[1]!) + if (chained === "only") only = vals + else except = vals + } + } + + // An array of middleware: one entry each. Non-literal entries such as + // BookStack's `Permission::SettingsManage->middleware()` (an enum that + // returns 'can:settings-manage') are kept as a `can:` check rather than + // dropped — they are authorization middleware by construction. + const raws = firstVal.type === "array_creation_expression" + ? (firstVal.namedChildren as Parser.SyntaxNode[]) + .filter((e) => e.type === "array_element_initializer") + .map((e) => e.firstNamedChild) + .filter((v): v is Parser.SyntaxNode => v !== null) + .map((v) => (v.type === "string" || v.type === "encapsed_string") + ? resolveStringNode(v) + : /->middleware\(\)|Permission|Role|Ability/.test(v.text) ? `can:${v.text}` : v.text) + : [raw] + for (const r of raws) if (r) results.push({ raw: r, except, only }) } } } @@ -775,7 +991,7 @@ function extractServiceCalls( const results: ServiceCall[] = [] const body = methodNode.childForFieldName("body") if (!body) return results - gatherServiceCalls(body, injections, results, requestParamVars) + gatherServiceCalls(body, injections, results, requestParamVars, _useMap) return results } @@ -811,7 +1027,8 @@ function findRequestParamArg( function tryExtractBaseServiceCall( callNode: Parser.SyntaxNode, injections: Map, - requestParamVars: Map = new Map() + requestParamVars: Map = new Map(), + useMap: Map = new Map() ): ServiceCall | null { const objNode = callNode.childForFieldName("object") const nameNode = callNode.childForFieldName("name") @@ -866,6 +1083,31 @@ function tryExtractBaseServiceCall( } } + // Pattern 3: (new UpdateVault)->execute($data) — a service built inline + // (monica's action/service classes). Only project classes imported via `use` + // count, so (new Carbon)->… and the like stay out. + const created = objNode?.type === "parenthesized_expression" ? objNode.firstNamedChild : objNode + if (created?.type === "object_creation_expression") { + const clsNode = (created.namedChildren as Parser.SyntaxNode[]).find( + (c) => c.type === "name" || c.type === "qualified_name" + ) + const short = clsNode?.text.replace(/^\\/, "").split("\\").pop() + const fqcn = short ? useMap.get(short) : undefined + if (short && fqcn && !/^(Illuminate|Carbon|Symfony|GuzzleHttp)\\/.test(fqcn)) { + const argsNode = callNode.childForFieldName("arguments") + const stringArgs = argsNode ? extractStringCallArgs(argsNode) : [] + const requestParamArg = findRequestParamArg(argsNode, requestParamVars) + return { + propertyName: `new ${short}`, + serviceClass: short, + serviceFqcn: fqcn, + method: nameNode.text, + args: stringArgs, + ...(requestParamArg ? { requestParamArg } : {}), + } + } + } + return null } @@ -878,7 +1120,8 @@ function gatherServiceCalls( node: Parser.SyntaxNode, injections: Map, results: ServiceCall[], - requestParamVars: Map = new Map() + requestParamVars: Map = new Map(), + useMap: Map = new Map() ): void { if (node.type === "member_call_expression") { const objNode = node.childForFieldName("object") @@ -889,7 +1132,7 @@ function gatherServiceCalls( // $user->apiTokens()->delete() — fold into one node instead of dropping // the mutation or double-emitting the base accessor separately. if (objNode?.type === "member_call_expression" && MUTATING_METHODS.has(nameNode.text)) { - const base = tryExtractBaseServiceCall(objNode, injections, requestParamVars) + const base = tryExtractBaseServiceCall(objNode, injections, requestParamVars, useMap) if (base) { results.push({ ...base, @@ -902,19 +1145,19 @@ function gatherServiceCalls( // one JS object per node (it depends on its node cache and on GC), // so identity made the base accessor show up again in some runs. for (const child of node.children as Parser.SyntaxNode[]) { - if (!sameNode(child, objNode)) gatherServiceCalls(child, injections, results, requestParamVars) + if (!sameNode(child, objNode)) gatherServiceCalls(child, injections, results, requestParamVars, useMap) } return } } - const base = tryExtractBaseServiceCall(node, injections, requestParamVars) + const base = tryExtractBaseServiceCall(node, injections, requestParamVars, useMap) if (base) results.push(base) } } for (const child of node.children as Parser.SyntaxNode[]) { - gatherServiceCalls(child, injections, results, requestParamVars) + gatherServiceCalls(child, injections, results, requestParamVars, useMap) } } diff --git a/packages/laravel-parser/src/graph-augmenter.ts b/packages/laravel-parser/src/graph-augmenter.ts index c1d064b..fd89d6d 100644 --- a/packages/laravel-parser/src/graph-augmenter.ts +++ b/packages/laravel-parser/src/graph-augmenter.ts @@ -1,5 +1,5 @@ import { join } from "path" -import { existsSync, readFileSync } from "fs" +import { existsSync, readFileSync, readdirSync } from "fs" import type { IntermediateExecutionGraph, ExecutionNode, @@ -154,6 +154,19 @@ export function augmentGraph( if (methodName) { const filePath = join(opts.projectRoot, ctrlNode.file) const l1 = ctrlL1(cache, filePath, methodName) + // Route::resource()/apiResource() registers every action, but a controller + // that only implements index() (koel's ArtistSongController) has no store/ + // update/destroy — those routes fail with BadMethodCall, they can't be a + // security gap. Flag them so detectors skip them. + if (l1 && l1.methodLine === undefined && handlerCannotBeInherited(filePath)) { + newAnnotations.push({ + type: "handler_not_found", + nodes: [ctrlNode.id], + description: `${ctrlNode.symbol} is routed but the method is not defined in ${ctrlNode.file}`, + severity: "info", + confidence: "HIGH", + }) + } if (l1) { // Backfill line number onto the business_handler node for editor CodeLens anchoring if (l1.methodLine) { @@ -181,14 +194,75 @@ export function augmentGraph( relation: "form_request", traceability: "static", }) + + // FormRequest::authorize() that checks more than "is someone logged in" + // (e.g. `auth()->user()->can('edit', $this->client)`) is Laravel's + // standard place for authorization — record it as an authz fact. + if (authzBody && isRealAuthorizeBody(authzBody)) { + const authzId = `${id}_authz` + if (!newNodes.some((n) => n.id === authzId)) { + newNodes.push({ + id: authzId, + type: IR_NODE_TYPES.AUTHZ_CHECK, + symbol: `${fr.shortName}::authorize`, + role: "authorization", + file: frFile, + detail: authzBody, + }) + newEdges.push({ + from: id, + to: authzId, + relation: "policy_check", + traceability: "static", + mechanism: authzBody, + }) + } + } } // Policy nodes — include inferred file so they can be augmented below const addedPolicyNodes: ExecutionNode[] = [] for (const auth of l1.authorizeCalls) { - const policyClass = inferPolicyClass(ctrlClass ?? "") + const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, "_") + + // Non-policy authorization ($this->checkPermission(), $user->can(), userCan()): + // an authorization fact, but there is no policy class to infer or to miss. + if (auth.kind === "helper") { + const helper = auth.helper ?? "check" + const id = `authz_${slug(ctrlNode.id)}_${slug(helper)}_${slug(auth.ability)}` + if (newNodes.some((n) => n.id === id)) continue + const helperNode: ExecutionNode = { + id, + type: IR_NODE_TYPES.AUTHZ_CHECK, + symbol: auth.ability === helper ? helper : `${helper}(${auth.ability})`, + role: "authorization", + } + newNodes.push(helperNode) + addedPolicyNodes.push(helperNode) + newEdges.push({ + from: ctrlNode.id, + to: id, + relation: IR_EDGE_RELATIONS.CHECKS_PERMISSION, + traceability: "static", + mechanism: auth.mechanism, + }) + continue + } + + // Laravel resolves the policy from the model passed to authorize(), not + // from the controller name: authorize('access', $song) → SongPolicy. + // Without a known model (authorize('admin') / Gate::define abilities) + // the policy can't be named, so no missing_policy can be claimed. + const policyClass = auth.modelClass ? `${auth.modelClass}Policy` : inferPolicyClass(ctrlClass ?? "") + // A param typed as an interface (koel's `Authenticatable $invitor`) is + // resolved to its runtime class by Laravel (User → UserPolicy): only a + // concrete Eloquent model names its policy statically. + const boundParam = l1.modelParams.find((p) => p.className === auth.modelClass) + const policyKnown = auth.modelClass !== undefined && + (!boundParam || isEloquentModel(boundParam.classFqcn, opts.projectRoot, config.namespaces, ctrlNode.file)) const policyFile = resolvePolicyFile(opts.projectRoot, policyClass, config.policyPaths) - const id = `policy_${policyClass.toLowerCase().replace(/[^a-z0-9]/g, "_")}_${auth.ability}` + const id = `policy_${slug(policyClass)}_${auth.ability}` + if (newNodes.some((n) => n.id === id)) continue const policyNode: ExecutionNode = { id, type: IR_NODE_TYPES.AUTHZ_CHECK, @@ -200,7 +274,7 @@ export function augmentGraph( addedPolicyNodes.push(policyNode) // Annotate when the policy class file doesn't exist — structural fact, deterministic - if (!existsSync(join(opts.projectRoot, policyFile))) { + if (policyKnown && !policyExists(opts.projectRoot, policyClass, policyFile)) { newAnnotations.push({ type: "missing_policy", nodes: [id], @@ -219,7 +293,7 @@ export function augmentGraph( } // RESOURCE nodes — route-model-binding params (IR v1.1) - emitResourceNodes(newNodes, newEdges, ctrlNode, l1.modelParams, addedPolicyNodes, l1.authorizeCalls) + emitResourceNodes(newNodes, newEdges, ctrlNode, l1.modelParams, addedPolicyNodes, l1.authorizeCalls, opts.projectRoot, config.namespaces) // API_RESOURCE nodes — JsonResource returns (IR v1.2) emitApiResourceNodes(newNodes, newEdges, ctrlNode, l1.returnedResources, opts.projectRoot, config, cache) @@ -502,6 +576,129 @@ export function fqcnToRelativePath(fqcn: string): string { // ---- Helpers ---------------------------------------------------------- +/** + * True when a controller can't get a missing action from elsewhere: it extends + * nothing or Laravel's bare base `Controller`, uses no traits and has no __call. + * Anything else (a CRUD base class, a trait) might provide the method. + */ +function handlerCannotBeInherited(absFile: string): boolean { + let src: string + try { src = readFileSync(absFile, "utf-8") } catch { return false } + const decl = src.match(/\bclass\s+\w+(?:\s+extends\s+([\w\\]+))?/) + if (!decl) return false + const parent = decl[1]?.split("\\").pop() + if (parent && parent !== "Controller") return false + const body = src.slice(decl.index! + decl[0].length) + // `use SomeTrait;` inside the class body (imports precede the class keyword) + if (/^\s*use\s+[\w\\]+(\s*,\s*[\w\\]+)*\s*[;{]/m.test(body)) return false + if (/function\s+__call\s*\(/.test(body)) return false + return true +} + +/** + * Whether a FormRequest authorize() return expression is a real authorization + * check, as opposed to `true`, `false` or a bare "is authenticated" test. + */ +export function isRealAuthorizeBody(body: string): boolean { + const b = body.trim().replace(/;$/, "").trim() + if (/^(true|false)$/i.test(b)) return false + const authOnly = + /^!?\s*(auth\(\)(->guard\([^)]*\))?->(check|guest)\(\)|Auth::(check|guest)\(\)|\$this->user\(\)|auth\(\)->user\(\)|\(bool\)\s*\$this->user\(\)|!?\s*is_null\(\s*(\$this->user\(\)|auth\(\)->user\(\))\s*\)|(\$this->user\(\)|auth\(\)->user\(\))\s*(!==|!=|===|==)\s*null|auth\(\)->id\(\)|Auth::id\(\))$/i + return !authOnly.test(b) +} + +const serviceAuthzCache = new Map() + +/** + * Authorization performed by a service class, read from its source: + * - a `permissions()` method returning a non-empty list of rule names + * (monica's BaseService pattern, enforced by validateRules()), or + * - a Gate / authorize / can / AuthorizationException / abort(403) check in + * the body of the called method. + */ +function detectServiceAuthorization( + absFile: string, + method: string, +): { symbol: string; rules: string[]; mechanism: string } | null { + const key = `${absFile}#${method}` + if (serviceAuthzCache.has(key)) return serviceAuthzCache.get(key)! + let result: { symbol: string; rules: string[]; mechanism: string } | null = null + let src = "" + try { src = readFileSync(absFile, "utf-8") } catch { /* unreadable */ } + + const perms = src.match(/function\s+permissions\s*\([^)]*\)[^{]*\{([\s\S]*?)\n\s*\}/) + if (perms) { + const rules = [...perms[1].matchAll(/['"]([\w.:-]+)['"]/g)].map((m) => m[1]!) + if (rules.length > 0) result = { symbol: "permissions", rules, mechanism: `permissions(): [${rules.join(", ")}]` } + } + + if (!result) { + const start = src.search(new RegExp(`function\\s+${method}\\s*\\(`)) + if (start >= 0) { + const next = src.slice(start + 8).search(/\n\s*(public|protected|private)?\s*(static\s+)?function\s+\w+\s*\(/) + const body = next >= 0 ? src.slice(start, start + 8 + next) : src.slice(start) + const m = body.match(/Gate::(authorize|allows|denies|check|inspect)\s*\([^;]*|\$this->authorize\s*\([^;]*|->(can|cannot|hasPermissionTo|hasRole)\s*\([^;]*|throw\s+new\s+\\?[\w\\]*AuthorizationException[^;]*|abort(_if|_unless)?\s*\([^;]*\b403\b[^;]*/) + // Or the record is re-fetched through a query scoped to the caller, so + // another user's record 404s (koel: getOne() → withUserContext() → + // accessible(); whereBelongsTo(auth()->user()); where('user_id', auth()->id())). + const scoped = m ? null : body.match(/->(accessible|withUserContext|forUser|visibleTo|ownedBy|accessibleBy)\s*\([^;]*|whereBelongsTo\s*\(\s*(auth\(\)|\$user|\$this->user|Auth::)[^;]*|where\(\s*['"](user_id|owner_id|author_id|created_by)['"]\s*,\s*(auth\(\)|\$user|\$this->user|Auth::|\$request->user\(\))[^;]*/) + if (m) result = { symbol: method, rules: [], mechanism: m[0].trim().slice(0, 160) } + else if (scoped) result = { symbol: `${method} (query scoped to caller)`, rules: [], mechanism: scoped[0].trim().slice(0, 160) } + } + } + + serviceAuthzCache.set(key, result) + return result +} + +// Per project root: every *Policy.php basename under app/ (any depth), plus the +// text of providers that register policies explicitly. +const policyIndexCache = new Map; registrations: string }>() + +function policyIndex(projectRoot: string): { files: Set; registrations: string } { + const cached = policyIndexCache.get(projectRoot) + if (cached) return cached + const files = new Set() + let registrations = "" + const walk = (dir: string, depth: number): void => { + if (depth > 8) return + let entries: import("fs").Dirent[] + try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return } + for (const e of entries) { + if (e.isDirectory()) { + if (e.name === "node_modules" || e.name === "vendor" || e.name.startsWith(".")) continue + walk(join(dir, e.name), depth + 1) + } else if (e.name.endsWith(".php")) { + if (e.name.endsWith("Policy.php")) files.add(e.name.slice(0, -4)) + // Policy registrations live in providers ($policies, Gate::policy) or on + // the model itself (#[UsePolicy(...)]) — keep the text of files that mention one + if (/Provider\.php$|\/Models\//.test(join(dir, e.name).replace(/\\/g, "/"))) { + try { + const text = readFileSync(join(dir, e.name), "utf-8") + if (/\$policies|Gate::policy|UsePolicy/.test(text)) registrations += "\n" + text + } catch { /* unreadable file */ } + } + } + } + } + walk(join(projectRoot, "app"), 0) + const index = { files, registrations } + policyIndexCache.set(projectRoot, index) + return index +} + +/** + * Whether a policy class exists anywhere Laravel could find it: the configured + * policy path, any *Policy.php under app/ (domain folders), or an explicit + * registration ($policies map, Gate::policy(), #[UsePolicy]). + */ +function policyExists(projectRoot: string, policyClass: string, policyFile: string): boolean { + if (existsSync(join(projectRoot, policyFile))) return true + const { files, registrations } = policyIndex(projectRoot) + if (files.has(policyClass)) return true + return new RegExp(`\\b${policyClass}\\b`).test(registrations) +} + function inferPolicyClass(controllerClass: string): string { const m = controllerClass.match(/^(.+)Controller$/) return m ? `${m[1]}Policy` : `${controllerClass}Policy` @@ -576,6 +773,31 @@ function addServiceCallNodes( traceability: "semantic", }) + // Authorization enforced inside the service (monica's + // `permissions(): ['author_must_be_vault_manager']`, or a Gate/authorize/can + // check in the called method) — make it an explicit authz fact. + const serviceAuthz = file ? detectServiceAuthorization(join(projectRoot, file), sc.method) : null + if (serviceAuthz) { + const authzId = `${id}_authz` + if (!nodes.some((n) => n.id === authzId)) { + nodes.push({ + id: authzId, + type: IR_NODE_TYPES.AUTHZ_CHECK, + symbol: `${sc.serviceClass}::${serviceAuthz.symbol}`, + role: "authorization", + ...(file ? { file } : {}), + ...(serviceAuthz.rules.length > 0 ? { args: serviceAuthz.rules } : {}), + }) + edges.push({ + from: id, + to: authzId, + relation: IR_EDGE_RELATIONS.CHECKS_PERMISSION, + traceability: "static", + mechanism: serviceAuthz.mechanism, + }) + } + } + // Cross-method extension of Phase 6 (narrow cut): this call received a // request-derived value as one of its arguments — check whether the // callee itself branches on the corresponding parameter (BookStack's @@ -1102,15 +1324,57 @@ import type { AuthorizeCall } from "./controller-parser.js" * - Find the AUTHZ_CHECK node added for that call * - Emit ir:authorizes edge: AUTHZ_CHECK → RESOURCE */ +const eloquentCache = new Map() + +/** Whether a route-bound param class is an Eloquent model (by namespace, else by its class declaration). */ +function isEloquentModel(fqcn: string, projectRoot: string, namespaces: Record, callerFile?: string): boolean { + if (/\\Models?\\/.test(fqcn)) return true + const key = `${projectRoot}|${fqcn}|${fqcn.includes("\\") ? "" : (callerFile ?? "")}` + const hit = eloquentCache.get(key) + if (hit !== undefined) return hit + // Short name with no `use` import: same-namespace class we can't place — try the + // conventional model folders, else keep the previous behaviour (treat as a model). + const candidates = fqcn.includes("\\") + ? [fqcnToPath(fqcn, namespaces)].filter((p): p is string => p !== null) + : [ + // same namespace as the caller → same directory under PSR-4 + ...(callerFile ? [`${callerFile.replace(/[\\/][^\\/]+$/, "")}/${fqcn}.php`] : []), + `app/Models/${fqcn}.php`, + `app/${fqcn}.php`, + ] + const file = candidates.find((rel) => existsSync(join(projectRoot, rel))) + let result: boolean + if (file) { + try { + const src = readFileSync(join(projectRoot, file), "utf-8") + result = /class\s+\w+\s+extends\s+\\?[\w\\]*(Model|Authenticatable|Pivot|User)\b/.test(src) + } catch { + result = false + } + } else { + result = !fqcn.includes("\\") + } + eloquentCache.set(key, result) + return result +} + function emitResourceNodes( nodes: ExecutionNode[], edges: ExecutionEdge[], ctrlNode: ExecutionNode, modelParams: ModelParam[], policyNodes: ExecutionNode[], - authorizeCalls: AuthorizeCall[] + authorizeCalls: AuthorizeCall[], + projectRoot?: string, + namespaces?: Record ): void { for (const mp of modelParams) { + // Only Eloquent models are resources a caller can reach by ID. Typed params + // such as SearchResultsFormatter or BankIntegrationFilters are injected + // helpers, not data, and must not raise resource_unprotected. + if (projectRoot && namespaces && !isEloquentModel(mp.classFqcn, projectRoot, namespaces, ctrlNode.file)) continue + if (mp.usedInBody === false) continue + const resourceId = `resource_${mp.className.toLowerCase()}_${ctrlNode.id}` if (!nodes.some((n) => n.id === resourceId)) { @@ -1134,8 +1398,10 @@ function emitResourceNodes( for (const auth of authorizeCalls) { if (auth.modelVar !== mp.paramName) continue // Find the policy node that corresponds to this authorize call (matched by ability) - const policyNode = policyNodes.find( - (p) => p.symbol.endsWith(`::${auth.ability}`) + const policyNode = policyNodes.find((p) => + auth.kind === "helper" + ? p.symbol === auth.helper || p.symbol === `${auth.helper}(${auth.ability})` + : p.symbol.endsWith(`::${auth.ability}`) ) if (!policyNode) continue edges.push({ diff --git a/packages/laravel-parser/src/middleware-mapper.ts b/packages/laravel-parser/src/middleware-mapper.ts index 59fa28d..00b6226 100644 --- a/packages/laravel-parser/src/middleware-mapper.ts +++ b/packages/laravel-parser/src/middleware-mapper.ts @@ -19,10 +19,24 @@ interface MiddlewareMapping { */ function classifyFqcn(fqcn: string): MiddlewareMapping { const short = fqcn.split("\\").pop() ?? fqcn - if (/Authenticate|Guard/.test(short)) { + // Guest-only middleware (RedirectIfAuthenticated, the `guest` alias) is the + // opposite of authentication — the route is for logged-OUT users (login, + // register, password reset). It must never read as an auth gate. + if (/RedirectIfAuthenticated|Guest/.test(short)) { + return { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "guest" } + } + // Signed-URL validation (Illuminate ValidateSignature, app subclasses) + if (/ValidateSignature|SignedUrl|ValidateSigned/.test(short)) { + return { type: "signature_check", role: "authentication" } + } + // "Authorize…" contains "Auth" — check it before the authentication patterns + if (/Authoriz/.test(short)) { + return { type: IR_NODE_TYPES.AUTHZ_CHECK, role: "authorization" } + } + if (/Authenticat|Guard|^Auth|Auth(Middleware)?$|Jwt|JWT|TokenAuth|CheckLogin|RequireLogin|LoggedIn/.test(short)) { return { type: IR_NODE_TYPES.AUTH_GATE, role: "authentication" } } - if (/Permission|Role|Authorize|CheckAccess|HasRole|EnsureRole|EnsureUser/.test(short)) { + if (/Permission|Role|CheckAccess|HasRole|EnsureRole|EnsureUser|Admin|Owner/.test(short)) { return { type: IR_NODE_TYPES.AUTHZ_CHECK, role: "authorization" } } if (/Throttle|RateLimit/.test(short)) { @@ -77,13 +91,30 @@ function mapMiddleware(raw: string): MiddlewareMapping { } } + // Laravel's built-in aliases, recognised even without a Kernel.php to resolve + // them (Laravel 11+ registers them in the framework, not in the app): + // auth / auth.basic → Authenticate + // can:update,post → Authorize (policy / Gate ability) + // role:, ability:, abilities: (spatie, sanctum token abilities) + // guest → RedirectIfAuthenticated (logged-out only) + if (raw === "auth" || raw === "auth.basic") { + return { type: IR_NODE_TYPES.AUTH_GATE, role: "authentication" } + } + const abilityMatch = raw.match(/^(can|role|roles|ability|abilities|role_or_permission):(.+)$/) + if (abilityMatch) { + return { type: IR_NODE_TYPES.AUTHZ_CHECK, role: "authorization", args: abilityMatch[2]!.split(/[|,]/) } + } + if (raw === "guest") { + return { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "guest" } + } + // throttle:60,1 if (/^throttle:/.test(raw)) { return { type: "rate_limiter", role: "rate_limiting" } } - // signed - if (raw === "signed") { + // signed, signed:relative — a signed URL: only holders of the link get in + if (raw === "signed" || /^signed:/.test(raw)) { return { type: "signature_check", role: "authentication" } } @@ -92,9 +123,13 @@ function mapMiddleware(raw: string): MiddlewareMapping { return { type: "email_verification", role: "authentication" } } - // Class-based middleware — use short class name as symbol + // Class-based middleware — classify by class name, the same heuristics as an + // alias resolved to its FQCN. Defaulting every class to auth_gate made + // session/locale/domain middleware (invoiceninja's SessionDomains) read as + // "authenticated" on public routes such as password reset. if (raw.includes("\\") || /^[A-Z]/.test(raw)) { - return { type: IR_NODE_TYPES.AUTH_GATE, role: "middleware", args: [raw] } + const fqcn = raw.replace(/::class$/, "") + return { ...classifyFqcn(fqcn), args: [raw] } } // Bare, unresolved string with no class/keyword signal (e.g. a group name like diff --git a/packages/laravel-parser/src/resource-parser.ts b/packages/laravel-parser/src/resource-parser.ts index 6be1c9d..8811e47 100644 --- a/packages/laravel-parser/src/resource-parser.ts +++ b/packages/laravel-parser/src/resource-parser.ts @@ -145,8 +145,15 @@ function extractArrayFields(arrayNode: Parser.SyntaxNode, fields: ResourceField[ if (keyNode.type === "string") { const key = resolveString(keyNode) const valueExpr = valNode.text.trim() - // Skip $this->when(...) — captured separately as conditional - const isSensitive = SENSITIVE_PATTERNS.test(key) + // A field returned through $this->when(, …) is only + // sent to that caller (koel: subsonic_api_key `when($isCurrentUser)`), and + // is_/has_/can_ keys are boolean flags (has_password says a password exists, + // not what it is) — neither leaks the secret. A condition on the serialized + // record itself (`when($this->isAdmin(), $this->api_token)`) still does. + const cond = valueExpr.match(/^\$this->(?:when|mergeWhen)\s*\(([^,]*),/)?.[1] ?? "" + const conditional = /isCurrentUser|currentUser|\bauth\(\)|Auth::|\$request->user\(\)|->can\(|->is\(|isOwner|isSelf/i.test(cond) + const booleanFlag = /^(is|has|can)_/i.test(key) + const isSensitive = SENSITIVE_PATTERNS.test(key) && !conditional && !booleanFlag fields.push({ key, valueExpr, isSensitive }) } } diff --git a/packages/laravel-parser/src/route-parser.ts b/packages/laravel-parser/src/route-parser.ts index e1e75b4..1157c95 100644 --- a/packages/laravel-parser/src/route-parser.ts +++ b/packages/laravel-parser/src/route-parser.ts @@ -211,7 +211,12 @@ function handleRouteExpression( .flatMap((m) => resolveMiddlewareArgs(m.args, opts.constants)) const allMiddleware = [...ctx.middleware, ...inlineMiddleware] - const rawPath = resolveString(resourceVerb.args[0], opts.constants) ?? "/" + const rawName = resolveString(resourceVerb.args[0], opts.constants) ?? "/" + // Nested resource: 'artists.songs' → artists/{artist}/songs (Laravel names the + // parent parameter after the singular segment). + const rawPath = rawName.includes(".") + ? rawName.split(".").map((seg, i, all) => (i < all.length - 1 ? `${seg}/{${singularize(seg)}}` : seg)).join("/") + : rawName const fullPath = joinPath(ctx.prefix, rawPath) // Controller arg: [VaultController::class] or ['App\...\VaultController'] const ctrlArg = resourceVerb.args[1] @@ -325,7 +330,16 @@ function buildGraph( // backslash as "already complete" silently dropped the group namespace for this pattern // (found via real-repo blind test on Akaunting's classic RouteServiceProvider-namespaced // routes). + // A qualified name whose first segment is a `use … as Alias` import resolves + // through that import (PHP name resolution): with + // `use BookStack\Entities\Controllers as EntityControllers;`, + // `EntityControllers\PageApiController` is BookStack\Entities\Controllers\PageApiController. + // Missing this left every BookStack API controller unresolved — no file, so + // none of its authorization checks were read. + const firstSegment = !controller.startsWith("\\") && controller.includes("\\") ? controller.split("\\")[0]! : "" + const aliasedNamespace = firstSegment ? useMap.get(firstSegment) : undefined const fqcnFromMap = useMap.get(controller) + ?? (aliasedNamespace ? `${aliasedNamespace}\\${controller.slice(firstSegment.length + 1)}` : undefined) const fqcn = fqcnFromMap ?? (controller.startsWith("\\") ? controller.slice(1) @@ -610,6 +624,15 @@ function unquote(s: string): string { return s } +/** English singular of a resource segment, the way Laravel names nested params (artists → artist, categories → category). */ +function singularize(word: string): string { + if (/ies$/i.test(word)) return word.slice(0, -3) + "y" + if (/(ss|us)$/i.test(word)) return word + if (/(xes|ches|shes|sses)$/i.test(word)) return word.slice(0, -2) + if (/s$/i.test(word)) return word.slice(0, -1) + return word +} + function joinPath(base: string, segment: string): string { const b = base.endsWith("/") ? base.slice(0, -1) : base const s = segment.startsWith("/") ? segment : "/" + segment diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index e929cdf..4774f83 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,7 +1,7 @@ { "name": "@kidkender/archmind-mcp", "version": "0.8.0", - "description": "ArchMind MCP server — semantic execution graph intelligence for Laravel, NestJS, and Go/Gin projects, wired into Claude Code and any MCP-compatible AI client.", + "description": "MCP server that tells Claude Code, Cursor and other AI assistants what each route of your Laravel, NestJS, Express or Go/Gin app checks — and what it is missing (auth, policy, transaction, tenant scope).", "type": "module", "bin": { "archmind-mcp": "dist/index.cjs" @@ -36,16 +36,25 @@ "keywords": [ "laravel", "nestjs", - "mcp", - "static-analysis", + "express", + "gin", "security", - "execution-graph", - "claude-code" + "authorization", + "multi-tenant", + "static-analysis", + "sast", + "ci", + "mcp", + "mcp-server", + "claude-code", + "cursor", + "ai", + "execution-graph" ], "license": "MIT", "repository": { "type": "git", - "url": "git+https://github.com/Architecture-Mind/archMind.git" + "url": "git+https://github.com/Kidkender/archMind.git" }, "engines": { "node": ">=18" @@ -55,5 +64,9 @@ ], "publishConfig": { "access": "public" + }, + "homepage": "https://github.com/Kidkender/archMind#readme", + "bugs": { + "url": "https://github.com/Kidkender/archMind/issues" } } diff --git a/research/laravel-scan/README.md b/research/laravel-scan/README.md new file mode 100644 index 0000000..717657b --- /dev/null +++ b/research/laravel-scan/README.md @@ -0,0 +1,78 @@ +# Laravel scan: false-positive cleanup (2026-11-23) + +Goal: make `archmind findings` trustworthy on real Laravel apps before any public post. + +- **Before**: `@kidkender/archmind` 0.10.0 from npm (Test-Project/_archmind-tools) → `raw/.json` +- **After**: this branch (`fix/laravel-precision`), local build → `after/.json` +- Repos: the 5 Laravel apps in Test-Project/laravel (commits listed in Test-Project/CLONED.md). +- Command: `archmind findings --project --json` (all severities). + +## Result + +| Repo | Before: total | Before: HIGH+CRITICAL | After: total | After: shown by default (≥ MEDIUM) | After: HIGH+CRITICAL | +|---|---|---|---|---|---| +| invoiceninja | 946 | 329 | 596 | 77 | 60 | +| monica | 243 | 243 | 0 | 0 | 0 | +| akaunting | 152 | 95 | 57 | 7 | 0 | +| koel | 358 | 168 | 212 | 7 | 3 | +| BookStack | 122 | 116 | 73 | 1 | 0 | +| **Total** | **1,821** | **951** | **938** | **92** | **63** | + +HIGH+CRITICAL findings: **951 → 63 (−93%)**. Default output (what a new user sees): 92 lines across 5 apps. + +## Triage of the 63 remaining HIGH/CRITICAL (code read at the cloned commit) + +| Verdict | Count | Findings | +|---|---|---| +| **Worth a look** (verified) | 30 | invoiceninja `POST /api/v1/reports/*` ×28 — `GenericReportRequest::authorize()` returns `true`; a non-admin without `view_reports` is not rejected, their input is blanked in `prepareForValidation()` and the report job still runs. invoiceninja `POST /quickbooks/action` — `authorize()` returns `true`, any company user can force-push/pull an invoice to QuickBooks. koel `GET /api/youtube/search/song/{song}` — no `SongPolicy::access` check (only matters for private songs in Plus). | +| **False positive** (verified) | 12 | invoiceninja `system_logs` store/update/destroy ×4 (handlers always return 400, no write); `quickbooks/settings` and client `payment_methods` PUT/PATCH ×2 (routed methods don't exist; controllers use traits so ArchMind can't prove it); `client/subscriptions/{subscription}/purchase` ×3 (public checkout page by design). koel `itunes/song/{album}` (redirects to iTunes, no private data); koel collaboration-invite token (returned to the inviter by design). | +| **Not verified** | 21 | invoiceninja app-level actions: check_subdomain, reactivate_email, feedback, filters, connected_account ×2, companies/current, emails/entityHistory, one_time_token, preview ×2, quickbooks/reconnect_url, support/messages/send, self-update/check_version, tasks/sort, verify ×2, subscriptions/steps/check, client credit_response, client payment_methods POST, client quotes/download. | +| **Confirmed vulnerability** | 0 | Two candidates (invoiceninja client/vendor `documents/download_multiple`, company-only query) were withdrawn: `DownloadMultipleDocumentsRequest::authorize()` checks every document with `contactCanAccessDocument()`. | + +Verified precision: **30 of 42 (71%)** are worth a reviewer's attention; 12 of 42 are false positives. +None is a confirmed vulnerability — do not market this as "found N vulnerabilities". + +## What was wrong, and the fix (each with a test in laravel-parser / explainer) + +| Root cause | Example | Fix | +|---|---|---| +| Unresolved class middleware defaulted to **auth gate** | invoiceninja `SessionDomains` made password reset look "authenticated" | classify by name; unknown stays unknown (`middleware-mapper.ts`) | +| `RedirectIfAuthenticated` / `guest` read as auth gate | akaunting `/auth/login` "authenticated but not authorized" | guest-only middleware is never an auth gate | +| Laravel 11+ has no Kernel: `can:`, `role:`, `auth`, `signed:relative` unrecognised | monica `can:vault-viewer,vault` on every vault route (224 findings) | built-in aliases mapped without a Kernel | +| Controller permission helpers not seen | BookStack `checkOwnablePermission()`, `userCan()`, `$user->can()` | helper calls are authz facts (no policy inferred) | +| Constructor middleware arrays / enums / `->only()` | BookStack `Permission::SettingsManage->middleware()` | parsed per entry; non-literal permission entries kept as `can:` | +| `authorizeResource()` in constructor ignored | resource controllers | maps methods → abilities, honours `except`/`only` | +| Policy name inferred from the **controller** | koel `ScrobbleController` → `ScrobblePolicy` (49 missing_policy) | from the model (`$song` → `SongPolicy`), searched in sub-folders and registrations; interfaces skipped | +| Route alias imports not resolved | BookStack `use … as EntityControllers` — no controller file read at all | PHP name resolution of the first segment | +| Any typed param treated as a resource | `SearchResultsFormatter`, `BankIntegrationFilters` (486 CRITICAL) | only Eloquent models, only if the handler uses the param | +| resource_unprotected despite other authz, always CRITICAL, duplicated | — | only when no authz/signed URL at all; HIGH behind login, CRITICAL when public; not duplicated with missing_authorization | +| Service-layer authorization invisible | monica `(new UpdateVault)->execute()` + `permissions()` | inline `new` service calls; `permissions()` rules and Gate/can/403 in the called method | +| Queries scoped to the caller not seen | koel `getOne()` → `withUserContext()` → `accessible()`; invoiceninja `whereClientId()`; monica `$request->user()->userTokens()->delete()` | caller-scoped queries/writes are authz facts — shared keys (`company_id`, `account_id`, `team_id`) excluded | +| FormRequest `authorize()` checks ignored | invoiceninja `auth()->user()->can('edit', $this->client)`; per-item `return false` loops | real checks become authz facts; `true` / login-only bodies do not | +| Routes to actions that don't exist | koel `apiResource('artists.songs')` with only `index()` | `handler_not_found` → no findings; nested resource paths fixed | +| Public-by-design routes as gaps | SSO callbacks, invitations, login/password, broadcasting/auth, logout, `/me`, `/preferences` | INFO or not reported | +| Sensitive-field noise | koel `when($isCurrentUser, …)` fields, `has_password` flag | caller-conditional fields and boolean flags are not secrets | +| Output flooded with LOW/INFO | BookStack 62 × fat_controller | default output ≥ MEDIUM, `--all` for the rest; only CRITICAL/HIGH fail CI | + +## Also found on the way + +- **Published CLI 0.10.0 can't parse Spring Boot**: it bundles the Spring parser but not its native + `tree-sitter-java` dependency, so every Spring project silently printed "No findings." Fixed by adding + the dependency; the CLI now also warns (stderr, exit 2) whenever 0 entrypoints are found. +- The MCP server does not support Spring Boot (CLI only) — README and npm description now say so. +- Non-Laravel regression check (0.10.0 vs this branch, same repos): NestJS, Express, Go, RuoYi unchanged except + ginfast `POST /api/users/logout` (logout, correctly dropped); SpringBlade 0 → 94 (now actually parsed). + +## Known limits (not fixed) + +- Any `ir:service_call` still counts as an authorization layer in `missing_authorization` (explainer + fact extraction) — a source of false negatives, not false positives. Changing it affects every framework. +- MEDIUM/LOW findings were not triaged. +- 21 HIGH findings above are unverified. + +## Exit bar status + +Set in the first version of this file: "≥ 70% real or worth a look, and no app > ~30 HIGH/CRITICAL without config". +- Precision bar: met on the verified set (71%), with zero confirmed vulnerabilities. +- Volume bar: met for 4 of 5 apps; invoiceninja has 60 (28 are one report pattern). An `archmind.json` + `ignoreFindings` or a per-route ignore would bring it under; not added. diff --git a/research/laravel-scan/sample.json b/research/laravel-scan/sample.json new file mode 100644 index 0000000..71644e8 --- /dev/null +++ b/research/laravel-scan/sample.json @@ -0,0 +1,442 @@ +[ + { + "repo": "invoiceninja", + "route": "POST /client/documents/download_multiple", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /client/documents/download_multiple is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_8_auth_contact", + "ctrl_app_http_controllers_clientportal_documentcontroller_downloadMultiple" + ] + }, + { + "repo": "invoiceninja", + "route": "PATCH /api/v1/system_logs/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PATCH /api/v1/system_logs/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_systemlogcontroller_update" + ] + }, + { + "repo": "invoiceninja", + "route": "POST /api/v1/reports/contacts", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/v1/reports/contacts is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_clientcontactreportcontroller___invoke" + ] + }, + { + "repo": "invoiceninja", + "route": "POST /api/v1/reports/invoice_items", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/v1/reports/invoice_items is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_invoiceitemreportcontroller___invoke" + ] + }, + { + "repo": "invoiceninja", + "route": "POST /api/v1/password_timeout", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/v1/password_timeout is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_passwordtimeoutcontroller___invoke" + ] + }, + { + "repo": "invoiceninja", + "route": "GET /client/subscriptions/{subscription}/purchase/v2", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Subscription is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_subscription_ctrl_app_http_controllers_clientportal_subscriptionpurchasecontroller_upgrade", + "ctrl_app_http_controllers_clientportal_subscriptionpurchasecontroller_upgrade" + ] + }, + { + "repo": "invoiceninja", + "route": "POST /api/v1/emails/entityHistory", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/v1/emails/entityHistory is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_emailhistorycontroller_entityHistory" + ] + }, + { + "repo": "invoiceninja", + "route": "POST /api/v1/one_time_token", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/v1/one_time_token is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_3_token_auth", + "ctrl_onetimetokencontroller_create" + ] + }, + { + "repo": "monica", + "route": "GET /vaults/{vault}/calendar/years/{year}/months/{month}/days/{day}", + "type": "resource_unprotected", + "sev": "HIGH", + "summary": "Vault is loaded by ID with no authorization check — any logged-in user can reach any Vault", + "ev": [ + "resource_vault_ctrl_vaultcalendarcontroller_day", + "ctrl_vaultcalendarcontroller_day" + ] + }, + { + "repo": "monica", + "route": "POST /vaults/{vault}/contacts/{contact}/vcard", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /vaults/{vault}/contacts/{contact}/vcard is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_contactvcardcontroller_download" + ] + }, + { + "repo": "monica", + "route": "DELETE /vaults/{vault}/contacts/{contact}/", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "DELETE /vaults/{vault}/contacts/{contact}/ is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_contactcontroller_destroy" + ] + }, + { + "repo": "monica", + "route": "POST /vaults/{vault}/search", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /vaults/{vault}/search is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_vaultsearchcontroller_show" + ] + }, + { + "repo": "monica", + "route": "PUT /settings/cancel", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PUT /settings/cancel is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_cancelaccountcontroller_destroy" + ] + }, + { + "repo": "monica", + "route": "POST /settings/personalize/modules", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /settings/personalize/modules is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_personalizemodulescontroller_store" + ] + }, + { + "repo": "monica", + "route": "GET /vaults/{vault}/contacts/", + "type": "resource_unprotected", + "sev": "HIGH", + "summary": "Vault is loaded by ID with no authorization check — any logged-in user can reach any Vault", + "ev": [ + "resource_vault_ctrl_contactcontroller_index", + "ctrl_contactcontroller_index" + ] + }, + { + "repo": "monica", + "route": "DELETE /settings/personalize/modules/{module}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "DELETE /settings/personalize/modules/{module} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_0_auth_sanctum", + "ctrl_personalizemodulescontroller_destroy" + ] + }, + { + "repo": "akaunting", + "route": "GET /{company_id}/signed/invoices/{invoice}/pdf", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Document is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_document_ctrl_portal_invoices_pdfInvoice", + "ctrl_portal_invoices_pdfInvoice" + ] + }, + { + "repo": "akaunting", + "route": "POST /auth/login", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /auth/login is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth_redirect", + "ctrl_auth_login_store" + ] + }, + { + "repo": "akaunting", + "route": "GET /{company_id}/signed/invoices/{invoice}/finish", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Document is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_document_ctrl_portal_invoices_finish", + "ctrl_portal_invoices_finish" + ] + }, + { + "repo": "akaunting", + "route": "POST /auth/forgot", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /auth/forgot is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth_redirect", + "ctrl_auth_forgot_store" + ] + }, + { + "repo": "akaunting", + "route": "POST /auth/reset", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /auth/reset is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth_redirect", + "ctrl_auth_reset_store" + ] + }, + { + "repo": "akaunting", + "route": "GET /{company_id}/signed/invoices/{invoice}/print", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Document is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_document_ctrl_portal_invoices_printInvoice", + "ctrl_portal_invoices_printInvoice" + ] + }, + { + "repo": "akaunting", + "route": "GET /{company_id}/signed/payments/{payment}/print", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Transaction is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_transaction_ctrl_portal_payments_printPayment", + "ctrl_portal_payments_printPayment" + ] + }, + { + "repo": "akaunting", + "route": "POST /auth/register", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /auth/register is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth_redirect", + "ctrl_auth_register_store" + ] + }, + { + "repo": "koel", + "route": "PUT /api/artists.songs/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PUT /api/artists.songs/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth", + "ctrl_artistsongcontroller_update" + ] + }, + { + "repo": "koel", + "route": "POST /api/artists.songs", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /api/artists.songs is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth", + "ctrl_artistsongcontroller_store" + ] + }, + { + "repo": "koel", + "route": "GET /api/youtube/search/song/{song}", + "type": "resource_unprotected", + "sev": "HIGH", + "summary": "Song is loaded by ID with no authorization check — any logged-in user can reach any Song", + "ev": [ + "resource_song_ctrl_searchyoutubecontroller___invoke", + "ctrl_searchyoutubecontroller___invoke" + ] + }, + { + "repo": "koel", + "route": "POST /api/me/subsonic-api-key/regenerate", + "type": "sensitive_field_exposed", + "sev": "HIGH", + "summary": "UserResource::toArray serializes 3 sensitive field(s): is_admin, subsonic_api_key, has_password", + "ev": [ + "api_res_userresource_ctrl_regeneratesubsonicapikeycontroller___invoke", + "ctrl_regeneratesubsonicapikeycontroller___invoke" + ] + }, + { + "repo": "koel", + "route": "PATCH /api/artists.songs/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PATCH /api/artists.songs/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth", + "ctrl_artistsongcontroller_update" + ] + }, + { + "repo": "koel", + "route": "GET /embeds/{embed}/stream/{song}/{options}", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "Song is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_song_ctrl_streamembedcontroller___invoke", + "ctrl_streamembedcontroller___invoke" + ] + }, + { + "repo": "koel", + "route": "GET /api/albums/{id}", + "type": "resource_unprotected", + "sev": "HIGH", + "summary": "Album is loaded by ID with no authorization check — any logged-in user can reach any Album", + "ev": [ + "resource_album_ctrl_albumcontroller_show", + "ctrl_albumcontroller_show" + ] + }, + { + "repo": "koel", + "route": "DELETE /api/artists.songs/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "DELETE /api/artists.songs/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_1_auth", + "ctrl_artistsongcontroller_destroy" + ] + }, + { + "repo": "BookStack", + "route": "GET /search", + "type": "resource_unprotected", + "sev": "HIGH", + "summary": "SearchResultsFormatter is loaded by ID with no authorization check — any logged-in user can reach any SearchResultsFormatter", + "ev": [ + "resource_searchresultsformatter_ctrl_searchcontroller_search", + "ctrl_searchcontroller_search" + ] + }, + { + "repo": "BookStack", + "route": "PUT /settings/webhooks/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PUT /settings/webhooks/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_activitycontrollers_webhookcontroller_update" + ] + }, + { + "repo": "BookStack", + "route": "PUT /my-account/shortcuts", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PUT /my-account/shortcuts is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_usercontrollers_useraccountcontroller_updateShortcuts" + ] + }, + { + "repo": "BookStack", + "route": "DELETE /ajax/page/{id}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "DELETE /ajax/page/{id} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_entitycontrollers_pagecontroller_ajaxDestroy" + ] + }, + { + "repo": "BookStack", + "route": "PATCH /preferences/change-view/{type}", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PATCH /preferences/change-view/{type} is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_usercontrollers_userpreferencescontroller_changeView" + ] + }, + { + "repo": "BookStack", + "route": "POST /settings/webhooks/create", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "POST /settings/webhooks/create is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_activitycontrollers_webhookcontroller_store" + ] + }, + { + "repo": "BookStack", + "route": "PATCH /preferences/toggle-dark-mode", + "type": "missing_authorization", + "sev": "HIGH", + "summary": "PATCH /preferences/toggle-dark-mode is authenticated but not authorized — any logged-in user can perform this mutation", + "ev": [ + "mw_10_auth", + "ctrl_usercontrollers_userpreferencescontroller_toggleDarkMode" + ] + }, + { + "repo": "BookStack", + "route": "GET /manifest.json", + "type": "resource_unprotected", + "sev": "CRITICAL", + "summary": "PwaManifestBuilder is loaded by ID on a public route with no authentication or authorization", + "ev": [ + "resource_pwamanifestbuilder_ctrl_metacontroller_pwaManifest", + "ctrl_metacontroller_pwaManifest" + ] + } +] \ No newline at end of file