diff --git a/CHANGELOG.md b/CHANGELOG.md index b23f1f7..64eed4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [Unreleased] + +### Fixed +- **`@kidkender/archmind-explainer`: input validation outside Laravel is no longer counted as an authorization layer.** `over_authorized_route` counted every `ir:validation_gate` as a third authorization layer ("FormRequest::authorize") and `delegated_validation` reported validators as delegating authorization. Both describe Laravel's `FormRequest::authorize()`; a NestJS `ValidationPipe`, Spring `@Valid`, Gin binding or Express celebrate / express-validator only checks the input, so ordinary authenticated, role-checked, validated routes on those frameworks got these findings. The FormRequest meaning now applies when the graph's framework is `laravel` or unset. Outside Laravel a route has at most two authorization layers, so `over_authorized_route` does not fire there. +- `@kidkender/archmind-nestjs-parser`: writes inside a transaction were linked to it by `within_transaction`, which is not an IR relation, so `validateGraph` reported it as unknown. They are now linked by `ir:wraps`, as in Laravel graphs. New conformance suite on a transaction fixture. +- `@kidkender/archmind-laravel-parser`: the transaction, isolation, audit-log and nested service-call passes inside a service method, and a queued job's `handle()`, swallowed any error silently. The parsers already turn unreadable files into empty results, so what reached these catches was a bug that read as "nothing found". It is now reported on stderr (`[archmind] laravel-parser: skipped for : `) and the pass is skipped as before. +- Flaky tests in `retrieval`, `nestjs-parser` and `mcp-server`: their tests load the tree-sitter parsers, whose module-level parser fails intermittently when Jest reuses one worker process across test files. Each test file now gets its own process (`maxWorkers`), as `laravel-parser` already did. Measured: `retrieval` with every file in one process failed 5 of 5 runs; with the fix it passed 10 of 10, as did `nestjs-parser`. +- `npm run trace` at the repository root pointed at `apps/cli/dist/index.js`; the CLI builds to `index.cjs`. + ## [0.9.1] - 2026-10-28 ### Added diff --git a/package.json b/package.json index 32891ad..8eced82 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "build": "npm run build --workspaces --if-present", "test": "npm run test --workspaces --if-present", - "trace": "node apps/cli/dist/index.js trace" + "trace": "node apps/cli/dist/index.cjs trace" }, "overrides": { "js-yaml": "^4.2.0" diff --git a/packages/explainer/src/__tests__/nestjs-detectors.test.ts b/packages/explainer/src/__tests__/nestjs-detectors.test.ts index cda0d02..eaa4a9e 100644 --- a/packages/explainer/src/__tests__/nestjs-detectors.test.ts +++ b/packages/explainer/src/__tests__/nestjs-detectors.test.ts @@ -198,11 +198,10 @@ describe("NestJS: detectSynchronousMail", () => { // ── over_authorized_route ───────────────────────────────────────────────────── describe("NestJS: detectOverAuthorizedRoute", () => { - it("fires when all 3 distinct layer types present (auth_gate + authz_check + validation_gate)", () => { - // Detector counts distinct LAYER TYPES, not node count: - // 1. ir:auth_gate → "auth middleware" - // 2. ir:authz_check → "policy/Gate check" - // 3. ir:validation_gate → "FormRequest::authorize" (DTO validation in NestJS) + it("does not count DTO validation as an authorization layer (auth_gate + authz_check + validation_gate)", () => { + // Only a Laravel FormRequest can authorize (FormRequest::authorize). A NestJS + // DTO / ValidationPipe checks the input, so this route has two authorization + // layers (guard + roles), below the detector's threshold of three. const graph = nestjsGraph({ method: "DELETE", path: "/admin/resources/:id", @@ -218,9 +217,7 @@ describe("NestJS: detectOverAuthorizedRoute", () => { { from: "ctrl", to: "mw_2", relation: "validates", traceability: "static" }, ], }) - const findings = detectOverAuthorizedRoute(graph) - expect(findings).toHaveLength(1) - expect(findings[0].type).toBe("over_authorized_route") + expect(detectOverAuthorizedRoute(graph)).toEqual([]) }) }) diff --git a/packages/explainer/src/__tests__/validation-framework.test.ts b/packages/explainer/src/__tests__/validation-framework.test.ts new file mode 100644 index 0000000..0e95da6 --- /dev/null +++ b/packages/explainer/src/__tests__/validation-framework.test.ts @@ -0,0 +1,47 @@ +import { describe, test, expect } from "@jest/globals" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { explain } from "../index.js" +import { FINDING_TYPES } from "../findings/types.js" + +// A validation gate carries authorization only in Laravel (FormRequest::authorize). +// The same route — authenticated, role-checked, input-validated — must not be +// reported as over-authorized, or as delegating authorization from its +// validator, when the validator is a NestJS pipe, a Spring @Valid, a Gin +// binding or an Express celebrate / express-validator. + +function route(framework: string | undefined): IntermediateExecutionGraph { + return { + entrypoint: "POST /orders", + method: "POST", + path: "/orders", + annotations: [], + ...(framework ? { framework } : {}), + nodes: [ + { id: "auth", type: "ir:auth_gate", symbol: "auth:sanctum" }, + { id: "authz", type: "ir:authz_check", symbol: "OrderPolicy::create", args: ["create"] }, + { id: "valid", type: "ir:validation_gate", symbol: "StoreOrderRequest" }, + { id: "handler", type: "ir:business_handler", symbol: "OrderController::store" }, + ], + edges: [ + { from: "auth", to: "authz", relation: "ir:precedes", traceability: "static" }, + { from: "authz", to: "valid", relation: "ir:precedes", traceability: "static" }, + { from: "valid", to: "handler", relation: "ir:precedes", traceability: "static" }, + ], + } +} + +const types = (g: IntermediateExecutionGraph) => explain(g).map((f) => f.type) + +describe("validation gates as authorization layers", () => { + test.each([["laravel"], [undefined]])("framework %s: a FormRequest counts as an authorization layer", (framework) => { + const found = types(route(framework)) + expect(found).toContain(FINDING_TYPES.OVER_AUTHORIZED_ROUTE) + expect(found).toContain(FINDING_TYPES.DELEGATED_VALIDATION) + }) + + test.each([["express"], ["nestjs"], ["springboot"], ["gin"]])("framework %s: input validation is not an authorization layer", (framework) => { + const found = types(route(framework)) + expect(found).not.toContain(FINDING_TYPES.OVER_AUTHORIZED_ROUTE) + expect(found).not.toContain(FINDING_TYPES.DELEGATED_VALIDATION) + }) +}) diff --git a/packages/explainer/src/pattern-detectors/delegated-validation.ts b/packages/explainer/src/pattern-detectors/delegated-validation.ts index 7fd587d..af3d198 100644 --- a/packages/explainer/src/pattern-detectors/delegated-validation.ts +++ b/packages/explainer/src/pattern-detectors/delegated-validation.ts @@ -4,6 +4,7 @@ import type { Finding, ReasoningStep, Evidence, UncertaintyReason } from "../fin 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" function edgesAmong(graph: IntermediateExecutionGraph, nodeIds: string[]): string[] { const idSet = new Set(nodeIds) @@ -17,6 +18,10 @@ export function detectDelegatedValidation( authNodeIds: string[], graph: IntermediateExecutionGraph ): Finding[] { + // "delegates authorization" is about FormRequest::authorize() returning true; + // a validation gate that cannot authorize has nothing to delegate + if (!validationCanAuthorize(graph)) return [] + const gateFacts = facts.filter( (f): f is ValidationGateFact => f.kind === "validation_gate" && f.delegatesAuthorization diff --git a/packages/explainer/src/pattern-detectors/framework.ts b/packages/explainer/src/pattern-detectors/framework.ts new file mode 100644 index 0000000..1a2b11e --- /dev/null +++ b/packages/explainer/src/pattern-detectors/framework.ts @@ -0,0 +1,12 @@ +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" + +/** + * Whether a validation gate can carry authorization, as Laravel's + * FormRequest::authorize() does. Elsewhere — NestJS ValidationPipe, Spring + * @Valid, Gin binding tags, Express celebrate / express-validator — a + * validation gate only checks the input. A graph without a framework tag is a + * legacy or hand-built Laravel graph and keeps the Laravel meaning. + */ +export function validationCanAuthorize(graph: IntermediateExecutionGraph): boolean { + return !graph.framework || graph.framework === "laravel" +} diff --git a/packages/explainer/src/pattern-detectors/over-authorized-route.ts b/packages/explainer/src/pattern-detectors/over-authorized-route.ts index 4d55947..4d45f87 100644 --- a/packages/explainer/src/pattern-detectors/over-authorized-route.ts +++ b/packages/explainer/src/pattern-detectors/over-authorized-route.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 { validationCanAuthorize } from "./framework.js" // 3+ separate auth enforcement points signals over-engineering or // authorization logic spread across too many layers. @@ -26,7 +27,8 @@ export function detectOverAuthorizedRoute( const authGates = q.security().authenticationGates().toArray() const authzChecks = q.security().authorizationChecks().toArray() - const validationGates = q.nodes().ofType(IR_NODE_TYPES.VALIDATION_GATE).toArray() + // a validation gate is an authorization layer only where it can authorize (FormRequest::authorize) + const validationGates = validationCanAuthorize(graph) ? q.nodes().ofType(IR_NODE_TYPES.VALIDATION_GATE).toArray() : [] // Count distinct auth layers const layers: Array<{ label: string; nodes: typeof authGates }> = [] diff --git a/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts b/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts new file mode 100644 index 0000000..3393594 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts @@ -0,0 +1,60 @@ +import { describe, test, expect, jest, beforeAll, afterAll } from "@jest/globals" +import { join, dirname } from "path" +import { fileURLToPath } from "url" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" + +// A graph pass inside a service method that throws is skipped and reported on +// stderr; the rest of the route's graph — earlier passes, later passes of the +// same service — still comes out. The isolation parser is made to throw for the +// service file only, so the controller-level passes run normally. + +jest.unstable_mockModule("../isolation-parser.js", () => ({ + parseIsolation: (filePath: string) => { + if (filePath.replace(/\\/g, "/").includes("app/Services/UserRepo.php")) throw new Error("boom in isolation") + return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } + }, +})) + +const { augmentGraph } = await import("../graph-augmenter.js") + +const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), "fixtures") + +const SKELETON: IntermediateExecutionGraph = { + entrypoint: "DELETE /users/{user}", + method: "DELETE", path: "/users/{user}", + nodes: [{ + id: "ctrl_usercontroller_destroy", type: "ir:business_handler", + symbol: "UserController::destroy", role: "handler", + file: "app/Http/Controllers/UserController.php", + }], + edges: [], + annotations: [], +} + +describe("augmentGraph — a pass that throws inside a service", () => { + let warn: ReturnType + let graph: IntermediateExecutionGraph + + beforeAll(() => { + warn = jest.spyOn(console, "warn").mockImplementation(() => {}) + graph = augmentGraph(SKELETON, { projectRoot: FIXTURES }) + }) + + afterAll(() => warn.mockRestore()) + + test("is reported with the pass, the file and the error", () => { + const messages = warn.mock.calls.map((c: unknown[]) => String(c[0])) + expect(messages).toContainEqual( + "[archmind] laravel-parser: isolation pass skipped for app/Services/UserRepo.php: boom in isolation", + ) + }) + + test("does not stop the rest of the graph: the service's calls and the transaction are still there", () => { + expect(graph.nodes.some((n) => n.type === "ir:service_call" && n.symbol === "User::apiTokens()->delete")).toBe(true) + expect(graph.nodes.some((n) => n.type === "ir:txn_boundary" && n.symbol === "DB::transaction")).toBe(true) + }) + + test("does not stop the later passes of the same service: its guard clause is still found", () => { + expect(graph.nodes.find((n) => n.symbol === "UserRepo::ensureDeletable")?.type).toBe("ir:guard_clause") + }) +}) diff --git a/packages/laravel-parser/src/graph-augmenter.ts b/packages/laravel-parser/src/graph-augmenter.ts index 40e9501..c1d064b 100644 --- a/packages/laravel-parser/src/graph-augmenter.ts +++ b/packages/laravel-parser/src/graph-augmenter.ts @@ -11,6 +11,17 @@ import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmin const ADAPTER_VERSION = "0.1.0" +/** + * A graph pass that threw is skipped so the rest of the route's graph still + * comes out, but it is reported: the parsers already turn unreadable files into + * empty results, so what reaches these catches is a bug, and a silent catch made + * it read as "nothing found here". + */ +function reportSkipped(pass: string, file: string | undefined, err: unknown): void { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] laravel-parser: ${pass} skipped for ${file ?? ""}: ${reason}`) +} + // ---- Cached parse-op wrappers -------------------------------------------- type CtrlL1 = ReturnType @@ -818,14 +829,14 @@ function expandServiceCalls( addTransactionNodes(nodes, edges, scNode.id, txnResult.blocks, l1?.serviceCalls ?? []) budget.remaining -= txnResult.blocks.length * 3 } - } catch { /* file unreadable or parse error — skip gracefully */ } + } catch (err) { reportSkipped("transaction pass", scNode.file, err) } // Isolation/query pass inside service method try { const isoResult = isoRes(cache, filePath, isoConv, methodName) addIsolationNodes(nodes, edges, scNode.id, isoResult) budget.remaining -= isoResult.modelQueries.length - } catch { /* skip */ } + } catch (err) { reportSkipped("isolation pass", scNode.file, err) } // Audit-log pass inside service method (IR v1.5 Phase 5) try { @@ -836,7 +847,7 @@ function expandServiceCalls( budget.remaining -= auditCalls.length } } - } catch { /* skip */ } + } catch (err) { reportSkipped("audit-log pass", scNode.file, err) } // Deeper service calls from this service method try { @@ -862,7 +873,7 @@ function expandServiceCalls( const guardNodes = addSelfGuardClauseNodes(nodes, edges, scNode.id, scNode.file, scClass ?? "", l1.selfGuardCalls, newSvcNodes) budget.remaining -= guardNodes.length } - } catch { /* skip */ } + } catch (err) { reportSkipped("nested service-call pass", scNode.file, err) } } expandServiceCalls(nodes, edges, nextServiceNodes, projectRoot, config, depth - 1, visited, budget, focus, cache) @@ -1254,7 +1265,8 @@ function expandJobBody( let l1: ReturnType try { l1 = parseControllerMethod(filePath, "handle") - } catch { + } catch (err) { + reportSkipped("queued job handle()", jobNode.file, err) return } if (!l1) return diff --git a/packages/mcp-server/jest.config.js b/packages/mcp-server/jest.config.js index c158c8b..cfeae98 100644 --- a/packages/mcp-server/jest.config.js +++ b/packages/mcp-server/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The server's caches load the Laravel and Go parsers, whose module-level + // tree-sitter Parser intermittently fails when Jest reuses one worker process + // across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: { diff --git a/packages/nestjs-parser/jest.config.js b/packages/nestjs-parser/jest.config.js index 29918b5..ae35050 100644 --- a/packages/nestjs-parser/jest.config.js +++ b/packages/nestjs-parser/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The cross-framework tests load the Laravel and Spring Boot parsers, whose + // module-level tree-sitter Parser intermittently fails when Jest reuses one + // worker process across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/", "/fixtures/"], moduleNameMapper: { diff --git a/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts b/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts index 72318ce..94b1676 100644 --- a/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts +++ b/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts @@ -121,3 +121,36 @@ describe("IR conformance — NestJS global-guard fixture", () => { expect(unknown).toHaveLength(0) }) }) + +// --------------------------------------------------------------------------- +// Suite 4: Transaction fixture (txn boundary + writes) +// None of the fixtures above opens a transaction, which is how a non-IR edge +// relation between a transaction and its writes went unnoticed. +// --------------------------------------------------------------------------- + +describe("IR conformance — NestJS transaction fixture", () => { + let graphs: IntermediateExecutionGraph[] + + beforeAll(() => { + graphs = parseNestJSProject(join(process.cwd(), "../../research/cross-framework/auth-transaction/nestjs")) + }) + + test("the fixture opens a transaction with writes", () => { + const types = graphs.flatMap((g) => g.nodes.map((n) => n.type)) + expect(types).toContain("ir:txn_boundary") + expect(types).toContain("ir:txn_write") + }) + + test("no unknown node types or edge relations", () => { + expect(unknownOnly(allGraphViolations(graphs))).toEqual([]) + }) + + test("writes hang off the transaction by ir:wraps", () => { + const [g] = graphs + const txn = g.nodes.find((n) => n.type === "ir:txn_boundary")! + const writes = g.nodes.filter((n) => n.type === "ir:txn_write") + for (const w of writes) { + expect(g.edges).toContainEqual(expect.objectContaining({ from: txn.id, to: w.id, relation: "ir:wraps" })) + } + }) +}) diff --git a/packages/nestjs-parser/src/emitters/ir-emitter.ts b/packages/nestjs-parser/src/emitters/ir-emitter.ts index 0ba9f7b..f036e27 100644 --- a/packages/nestjs-parser/src/emitters/ir-emitter.ts +++ b/packages/nestjs-parser/src/emitters/ir-emitter.ts @@ -1,5 +1,5 @@ import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge, DTOSchema, EntrypointDescriptor } from "@kidkender/archmind-protocol" -import { IR_VERSION, IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { IR_VERSION, IR_NODE_TYPES, IR_EDGE_RELATIONS } from "@kidkender/archmind-protocol" import type { NestJSSemanticRoute } from "../types.js" const ADAPTER_VERSION = "0.2.0" @@ -156,10 +156,11 @@ function emitGraph( symbol: `${w.entity}::${w.operation}`, role: "persistence", }) + // ir:wraps, as Laravel and Express emit it ("within_transaction" is not an IR relation) edges.push({ from: txnId, to: writeId, - relation: "within_transaction", + relation: IR_EDGE_RELATIONS.WRAPS, traceability: "static", }) } diff --git a/packages/retrieval/jest.config.js b/packages/retrieval/jest.config.js index c158c8b..04eb59f 100644 --- a/packages/retrieval/jest.config.js +++ b/packages/retrieval/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // These tests load the Laravel / NestJS parsers, whose module-level tree-sitter + // Parser intermittently fails when Jest reuses one worker process across test + // files (see packages/laravel-parser/jest.config.js). One process per file. + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: {