@plune-ai/cairn 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -8
- package/dist/agent/check-docs.d.ts +25 -0
- package/dist/agent/check-docs.d.ts.map +1 -0
- package/dist/agent/check-docs.js +57 -0
- package/dist/agent/check-docs.js.map +1 -0
- package/dist/agent/collect-docs.d.ts +94 -0
- package/dist/agent/collect-docs.d.ts.map +1 -0
- package/dist/agent/collect-docs.js +326 -0
- package/dist/agent/collect-docs.js.map +1 -0
- package/dist/agent/graph.d.ts +39 -2
- package/dist/agent/graph.d.ts.map +1 -1
- package/dist/agent/graph.js +113 -4
- package/dist/agent/graph.js.map +1 -1
- package/dist/agent/index.d.ts +14 -0
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +114 -10
- package/dist/agent/index.js.map +1 -1
- package/dist/agent/overlays.d.ts +88 -0
- package/dist/agent/overlays.d.ts.map +1 -0
- package/dist/agent/overlays.js +447 -0
- package/dist/agent/overlays.js.map +1 -0
- package/dist/agent/repair-loop.d.ts +8 -1
- package/dist/agent/repair-loop.d.ts.map +1 -1
- package/dist/agent/repair-loop.js +18 -3
- package/dist/agent/repair-loop.js.map +1 -1
- package/dist/analyze/index.d.ts +1 -1
- package/dist/analyze/index.d.ts.map +1 -1
- package/dist/analyze/index.js +3 -2
- package/dist/analyze/index.js.map +1 -1
- package/dist/api/adversarial.d.ts +1 -1
- package/dist/api/adversarial.js +1 -1
- package/dist/api/collection.d.ts +20 -0
- package/dist/api/collection.d.ts.map +1 -0
- package/dist/api/collection.js +357 -0
- package/dist/api/collection.js.map +1 -0
- package/dist/api/derived.d.ts +179 -0
- package/dist/api/derived.d.ts.map +1 -0
- package/dist/api/derived.js +852 -0
- package/dist/api/derived.js.map +1 -0
- package/dist/api/discover.d.ts +66 -0
- package/dist/api/discover.d.ts.map +1 -0
- package/dist/api/discover.js +125 -0
- package/dist/api/discover.js.map +1 -0
- package/dist/api/flows.d.ts +194 -0
- package/dist/api/flows.d.ts.map +1 -0
- package/dist/api/flows.js +663 -0
- package/dist/api/flows.js.map +1 -0
- package/dist/api/guard.d.ts +19 -0
- package/dist/api/guard.d.ts.map +1 -1
- package/dist/api/guard.js +18 -4
- package/dist/api/guard.js.map +1 -1
- package/dist/api/openapi.d.ts +17 -1
- package/dist/api/openapi.d.ts.map +1 -1
- package/dist/api/openapi.js +64 -3
- package/dist/api/openapi.js.map +1 -1
- package/dist/api/runner.d.ts.map +1 -1
- package/dist/api/runner.js +18 -14
- package/dist/api/runner.js.map +1 -1
- package/dist/api/two-actor.d.ts +165 -0
- package/dist/api/two-actor.d.ts.map +1 -0
- package/dist/api/two-actor.js +627 -0
- package/dist/api/two-actor.js.map +1 -0
- package/dist/artifacts/contract.d.ts +1 -1
- package/dist/artifacts/contract.d.ts.map +1 -1
- package/dist/artifacts/index.d.ts +5 -0
- package/dist/artifacts/index.d.ts.map +1 -1
- package/dist/artifacts/index.js +14 -10
- package/dist/artifacts/index.js.map +1 -1
- package/dist/artifacts/report.d.ts +29 -2
- package/dist/artifacts/report.d.ts.map +1 -1
- package/dist/artifacts/report.js +65 -1
- package/dist/artifacts/report.js.map +1 -1
- package/dist/artifacts/testcase-md.d.ts +18 -0
- package/dist/artifacts/testcase-md.d.ts.map +1 -1
- package/dist/artifacts/testcase-md.js +15 -1
- package/dist/artifacts/testcase-md.js.map +1 -1
- package/dist/browser/api-traffic.d.ts +85 -0
- package/dist/browser/api-traffic.d.ts.map +1 -0
- package/dist/browser/api-traffic.js +283 -0
- package/dist/browser/api-traffic.js.map +1 -0
- package/dist/browser/backends/playwright-cli.d.ts.map +1 -1
- package/dist/browser/backends/playwright-cli.js +3 -0
- package/dist/browser/backends/playwright-cli.js.map +1 -1
- package/dist/browser/backends/playwright-lib.d.ts +84 -1
- package/dist/browser/backends/playwright-lib.d.ts.map +1 -1
- package/dist/browser/backends/playwright-lib.js +677 -32
- package/dist/browser/backends/playwright-lib.js.map +1 -1
- package/dist/browser/click-effect.d.ts +84 -0
- package/dist/browser/click-effect.d.ts.map +1 -0
- package/dist/browser/click-effect.js +235 -0
- package/dist/browser/click-effect.js.map +1 -0
- package/dist/browser/gateway.d.ts +9 -1
- package/dist/browser/gateway.d.ts.map +1 -1
- package/dist/browser/index.d.ts +3 -0
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/index.js +5 -0
- package/dist/browser/index.js.map +1 -1
- package/dist/browser/types.d.ts +196 -1
- package/dist/browser/types.d.ts.map +1 -1
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +123 -5
- package/dist/cli/index.js.map +1 -1
- package/dist/codegen/index.d.ts +10 -1
- package/dist/codegen/index.d.ts.map +1 -1
- package/dist/codegen/index.js +28 -7
- package/dist/codegen/index.js.map +1 -1
- package/dist/codegen/lint.d.ts +32 -1
- package/dist/codegen/lint.d.ts.map +1 -1
- package/dist/codegen/lint.js +286 -1
- package/dist/codegen/lint.js.map +1 -1
- package/dist/codegen/mailbox.d.ts +19 -0
- package/dist/codegen/mailbox.d.ts.map +1 -0
- package/dist/codegen/mailbox.js +78 -0
- package/dist/codegen/mailbox.js.map +1 -0
- package/dist/codegen/schema.d.ts.map +1 -1
- package/dist/codegen/schema.js +3 -2
- package/dist/codegen/schema.js.map +1 -1
- package/dist/config/profiles.d.ts +2 -0
- package/dist/config/profiles.d.ts.map +1 -1
- package/dist/config/profiles.js +2 -0
- package/dist/config/profiles.js.map +1 -1
- package/dist/core/modalities/api.d.ts.map +1 -1
- package/dist/core/modalities/api.js +265 -29
- package/dist/core/modalities/api.js.map +1 -1
- package/dist/core/modalities/check-docs.d.ts +3 -0
- package/dist/core/modalities/check-docs.d.ts.map +1 -0
- package/dist/core/modalities/check-docs.js +64 -0
- package/dist/core/modalities/check-docs.js.map +1 -0
- package/dist/core/modalities/collect-docs.d.ts +3 -0
- package/dist/core/modalities/collect-docs.d.ts.map +1 -0
- package/dist/core/modalities/collect-docs.js +48 -0
- package/dist/core/modalities/collect-docs.js.map +1 -0
- package/dist/core/modalities/explore.d.ts.map +1 -1
- package/dist/core/modalities/explore.js +2 -0
- package/dist/core/modalities/explore.js.map +1 -1
- package/dist/core/modalities/mcp-test.d.ts +3 -0
- package/dist/core/modalities/mcp-test.d.ts.map +1 -0
- package/dist/core/modalities/mcp-test.js +26 -0
- package/dist/core/modalities/mcp-test.js.map +1 -0
- package/dist/core/registry.d.ts.map +1 -1
- package/dist/core/registry.js +11 -3
- package/dist/core/registry.js.map +1 -1
- package/dist/decider/uses/repair-triage.d.ts +9 -0
- package/dist/decider/uses/repair-triage.d.ts.map +1 -1
- package/dist/decider/uses/repair-triage.js +20 -3
- package/dist/decider/uses/repair-triage.js.map +1 -1
- package/dist/design/critique.d.ts +1 -1
- package/dist/design/index.d.ts +7 -1
- package/dist/design/index.d.ts.map +1 -1
- package/dist/design/index.js +20 -2
- package/dist/design/index.js.map +1 -1
- package/dist/design/schema.d.ts +9 -3
- package/dist/design/schema.d.ts.map +1 -1
- package/dist/design/schema.js +4 -1
- package/dist/design/schema.js.map +1 -1
- package/dist/documentarian/check.d.ts +91 -0
- package/dist/documentarian/check.d.ts.map +1 -0
- package/dist/documentarian/check.js +230 -0
- package/dist/documentarian/check.js.map +1 -0
- package/dist/documentarian/docs.d.ts +103 -0
- package/dist/documentarian/docs.d.ts.map +1 -0
- package/dist/documentarian/docs.js +243 -0
- package/dist/documentarian/docs.js.map +1 -0
- package/dist/documentarian/index.d.ts +2 -0
- package/dist/documentarian/index.d.ts.map +1 -1
- package/dist/documentarian/index.js +5 -4
- package/dist/documentarian/index.js.map +1 -1
- package/dist/environment/apply.js +1 -1
- package/dist/environment/apply.js.map +1 -1
- package/dist/flow/crawl.d.ts +4 -0
- package/dist/flow/crawl.d.ts.map +1 -1
- package/dist/flow/crawl.js +9 -2
- package/dist/flow/crawl.js.map +1 -1
- package/dist/fs/inside-dir.d.ts +8 -0
- package/dist/fs/inside-dir.d.ts.map +1 -0
- package/dist/fs/inside-dir.js +15 -0
- package/dist/fs/inside-dir.js.map +1 -0
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/index.d.ts +1 -1
- package/dist/llm/index.d.ts.map +1 -1
- package/dist/llm/index.js +1 -1
- package/dist/llm/index.js.map +1 -1
- package/dist/llm/structured.d.ts +19 -0
- package/dist/llm/structured.d.ts.map +1 -1
- package/dist/llm/structured.js +61 -0
- package/dist/llm/structured.js.map +1 -1
- package/dist/mailbox/doctor.d.ts +10 -0
- package/dist/mailbox/doctor.d.ts.map +1 -0
- package/dist/mailbox/doctor.js +33 -0
- package/dist/mailbox/doctor.js.map +1 -0
- package/dist/mailbox/rule.d.ts +34 -0
- package/dist/mailbox/rule.d.ts.map +1 -0
- package/dist/mailbox/rule.js +47 -0
- package/dist/mailbox/rule.js.map +1 -0
- package/dist/mailbox/session.d.ts +5 -0
- package/dist/mailbox/session.d.ts.map +1 -1
- package/dist/mailbox/session.js +8 -0
- package/dist/mailbox/session.js.map +1 -1
- package/dist/mcp/server.d.ts +15 -5
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +75 -27
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/tools.d.ts +194 -82
- package/dist/mcp/tools.d.ts.map +1 -1
- package/dist/mcp/tools.js +82 -8
- package/dist/mcp/tools.js.map +1 -1
- package/dist/mcp-test/adversarial.d.ts +80 -0
- package/dist/mcp-test/adversarial.d.ts.map +1 -0
- package/dist/mcp-test/adversarial.js +99 -0
- package/dist/mcp-test/adversarial.js.map +1 -0
- package/dist/mcp-test/advice.d.ts +20 -0
- package/dist/mcp-test/advice.d.ts.map +1 -0
- package/dist/mcp-test/advice.js +22 -0
- package/dist/mcp-test/advice.js.map +1 -0
- package/dist/mcp-test/call.d.ts +76 -0
- package/dist/mcp-test/call.d.ts.map +1 -0
- package/dist/mcp-test/call.js +105 -0
- package/dist/mcp-test/call.js.map +1 -0
- package/dist/mcp-test/cases.d.ts +154 -0
- package/dist/mcp-test/cases.d.ts.map +1 -0
- package/dist/mcp-test/cases.js +643 -0
- package/dist/mcp-test/cases.js.map +1 -0
- package/dist/mcp-test/connect.d.ts +70 -0
- package/dist/mcp-test/connect.d.ts.map +1 -0
- package/dist/mcp-test/connect.js +426 -0
- package/dist/mcp-test/connect.js.map +1 -0
- package/dist/mcp-test/coverage.d.ts +61 -0
- package/dist/mcp-test/coverage.d.ts.map +1 -0
- package/dist/mcp-test/coverage.js +76 -0
- package/dist/mcp-test/coverage.js.map +1 -0
- package/dist/mcp-test/discover.d.ts +40 -0
- package/dist/mcp-test/discover.d.ts.map +1 -0
- package/dist/mcp-test/discover.js +149 -0
- package/dist/mcp-test/discover.js.map +1 -0
- package/dist/mcp-test/guard.d.ts +161 -0
- package/dist/mcp-test/guard.d.ts.map +1 -0
- package/dist/mcp-test/guard.js +363 -0
- package/dist/mcp-test/guard.js.map +1 -0
- package/dist/mcp-test/model.d.ts +89 -0
- package/dist/mcp-test/model.d.ts.map +1 -0
- package/dist/mcp-test/model.js +88 -0
- package/dist/mcp-test/model.js.map +1 -0
- package/dist/mcp-test/payloads.d.ts +20 -0
- package/dist/mcp-test/payloads.d.ts.map +1 -0
- package/dist/mcp-test/payloads.js +20 -0
- package/dist/mcp-test/payloads.js.map +1 -0
- package/dist/mcp-test/report.d.ts +55 -0
- package/dist/mcp-test/report.d.ts.map +1 -0
- package/dist/mcp-test/report.js +157 -0
- package/dist/mcp-test/report.js.map +1 -0
- package/dist/mcp-test/run.d.ts +68 -0
- package/dist/mcp-test/run.d.ts.map +1 -0
- package/dist/mcp-test/run.js +467 -0
- package/dist/mcp-test/run.js.map +1 -0
- package/dist/mcp-test/runner.d.ts +133 -0
- package/dist/mcp-test/runner.d.ts.map +1 -0
- package/dist/mcp-test/runner.js +412 -0
- package/dist/mcp-test/runner.js.map +1 -0
- package/dist/mcp-test/schema.d.ts +103 -0
- package/dist/mcp-test/schema.d.ts.map +1 -0
- package/dist/mcp-test/schema.js +513 -0
- package/dist/mcp-test/schema.js.map +1 -0
- package/dist/mcp-test/secrets.d.ts +25 -0
- package/dist/mcp-test/secrets.d.ts.map +1 -0
- package/dist/mcp-test/secrets.js +67 -0
- package/dist/mcp-test/secrets.js.map +1 -0
- package/dist/observe/index.d.ts +3 -1
- package/dist/observe/index.d.ts.map +1 -1
- package/dist/observe/index.js +1 -0
- package/dist/observe/index.js.map +1 -1
- package/dist/observe/locator-hints.d.ts +18 -0
- package/dist/observe/locator-hints.d.ts.map +1 -0
- package/dist/observe/locator-hints.js +36 -0
- package/dist/observe/locator-hints.js.map +1 -0
- package/dist/observe/overlays.d.ts +135 -0
- package/dist/observe/overlays.d.ts.map +1 -0
- package/dist/observe/overlays.js +242 -0
- package/dist/observe/overlays.js.map +1 -0
- package/dist/observe/parse-aria.d.ts +7 -1
- package/dist/observe/parse-aria.d.ts.map +1 -1
- package/dist/observe/parse-aria.js +79 -4
- package/dist/observe/parse-aria.js.map +1 -1
- package/dist/probe/index.d.ts +3 -1
- package/dist/probe/index.d.ts.map +1 -1
- package/dist/probe/index.js +3 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/project/index.d.ts +2 -0
- package/dist/project/index.d.ts.map +1 -1
- package/dist/project/index.js +10 -2
- package/dist/project/index.js.map +1 -1
- package/dist/prompts/local/describe-screen.d.ts +7 -0
- package/dist/prompts/local/describe-screen.d.ts.map +1 -0
- package/dist/prompts/local/describe-screen.js +29 -0
- package/dist/prompts/local/describe-screen.js.map +1 -0
- package/dist/prompts/local/index.d.ts.map +1 -1
- package/dist/prompts/local/index.js +7 -0
- package/dist/prompts/local/index.js.map +1 -1
- package/dist/prompts/local/name-overlays.d.ts +6 -0
- package/dist/prompts/local/name-overlays.d.ts.map +1 -0
- package/dist/prompts/local/name-overlays.js +16 -0
- package/dist/prompts/local/name-overlays.js.map +1 -0
- package/dist/prompts/local/qa-api-flows.d.ts +8 -0
- package/dist/prompts/local/qa-api-flows.d.ts.map +1 -0
- package/dist/prompts/local/qa-api-flows.js +19 -0
- package/dist/prompts/local/qa-api-flows.js.map +1 -0
- package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
- package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
- package/dist/prompts/local/qa-playwright-ts-writer.js +5 -1
- package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
- package/dist/prompts/local/qa-testcase-from-ui.js +2 -0
- package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
- package/dist/session/index.d.ts.map +1 -1
- package/dist/session/index.js +24 -2
- package/dist/session/index.js.map +1 -1
- package/dist/validate/index.d.ts +11 -0
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +21 -0
- package/dist/validate/index.js.map +1 -1
- package/dist/validate/runner.d.ts +15 -1
- package/dist/validate/runner.d.ts.map +1 -1
- package/dist/validate/runner.js +158 -25
- package/dist/validate/runner.js.map +1 -1
- package/dist/validate/write-guard.d.ts +24 -0
- package/dist/validate/write-guard.d.ts.map +1 -0
- package/dist/validate/write-guard.js +210 -0
- package/dist/validate/write-guard.js.map +1 -0
- package/dist/view/index.d.ts +9 -0
- package/dist/view/index.d.ts.map +1 -0
- package/dist/view/index.js +126 -0
- package/dist/view/index.js.map +1 -0
- package/package.json +3 -2
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #233 — the two-actor check of the `hacker` style: IDOR and privilege escalation. The single-request `hacker` case
|
|
3
|
+
* (`adversarial.ts`) only strips auth; these cases need state and two identities, so they run as their own check.
|
|
4
|
+
*
|
|
5
|
+
* Actor A (the owner) creates a resource through a saved API flow (#230). Actor B (the other user, or a lower role)
|
|
6
|
+
* then tries to read, change and delete it, and reads the ids next to it. A 2xx to B is a finding, tagged with its
|
|
7
|
+
* OWASP WSTG id: WSTG-ATHZ-04 (IDOR) when B is another user of the same role, WSTG-ATHZ-03 (privilege escalation) when
|
|
8
|
+
* B is a lower role. Neighbouring ids are always WSTG-ATHZ-04, and count only when BOTH actors can read the same id:
|
|
9
|
+
* an id one of them owns answers the other with a refusal on a fixed server, so a neighbour both read is private to
|
|
10
|
+
* neither.
|
|
11
|
+
*
|
|
12
|
+
* Every request goes through the run's {@link RequestGuard} (`--allow-mutations`, `--allowed-methods`,
|
|
13
|
+
* `--allowed-paths`, `--max-requests`, `--rps`): there is no second safety mechanism. The check creates data, so it
|
|
14
|
+
* sends nothing without `--allow-mutations`, and a check whose flow or cleanup a flag forbids is not started at all —
|
|
15
|
+
* Cairn never creates what it may not delete. The flow's own cleanup runs in a `finally`, after a failure too.
|
|
16
|
+
*/
|
|
17
|
+
import { readFile } from "node:fs/promises";
|
|
18
|
+
import { dirname, resolve } from "node:path";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import { SessionStore } from "../session/index.js";
|
|
21
|
+
import { isExactNumber, loadApiFlows, numbersAsWritten, secretHeaderProblems, stepTemplateNames, templateNames } from "./flows.js";
|
|
22
|
+
const PROBES = ["read", "change", "delete", "neighbours"];
|
|
23
|
+
export const WSTG_IDOR = "WSTG-ATHZ-04";
|
|
24
|
+
export const WSTG_PRIVILEGE_ESCALATION = "WSTG-ATHZ-03";
|
|
25
|
+
const ActorSchema = z
|
|
26
|
+
.strictObject({
|
|
27
|
+
/** A saved session's name, as everywhere in Cairn: `.auth/<name>.storageState.json` (`cairn session capture --name`). */
|
|
28
|
+
session: z.string().regex(/^[\w.-]+$/, "a session name, as given to cairn session capture --name").optional(),
|
|
29
|
+
/** Headers for this actor, e.g. `"Authorization": "Bearer {{env.BOB_TOKEN}}"`; a secret only as {{env.NAME}}. */
|
|
30
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
31
|
+
})
|
|
32
|
+
.refine((a) => a.session !== undefined || a.headers !== undefined, "an actor needs a session or headers");
|
|
33
|
+
const CheckSchema = z.strictObject({
|
|
34
|
+
/** The data flow actor A runs to create the resource; its cleanup deletes it. */
|
|
35
|
+
flow: z.string(),
|
|
36
|
+
/** The resource's path, with the flow's captured values: `/api/projects/{{projectId}}`. */
|
|
37
|
+
resource: z
|
|
38
|
+
.string()
|
|
39
|
+
.regex(/^\/(?!\/)/, "a path starts with a single '/' and is relative to the base URL")
|
|
40
|
+
.refine((s) => /\{\{\s*\w+\s*\}\}/.test(s), "the resource path names the created id, e.g. /api/projects/{{projectId}}")
|
|
41
|
+
.refine((s) => !s.includes("?") && !s.includes("#"), "a resource path has no '?' or '#'"),
|
|
42
|
+
/** How actor B tries to change it (default PATCH with an empty JSON object). */
|
|
43
|
+
change: z
|
|
44
|
+
.strictObject({
|
|
45
|
+
method: z
|
|
46
|
+
.string()
|
|
47
|
+
.transform((s) => s.toUpperCase())
|
|
48
|
+
.pipe(z.enum(["PATCH", "PUT", "POST"])),
|
|
49
|
+
body: z.unknown().optional(),
|
|
50
|
+
})
|
|
51
|
+
.default({ method: "PATCH", body: {} }),
|
|
52
|
+
/** How many ids on each side of a numeric id actor B reads (0 = none). */
|
|
53
|
+
neighbours: z.number().int().min(0).max(10).default(2),
|
|
54
|
+
/** Which probes run (default all four). */
|
|
55
|
+
probes: z.array(z.enum(PROBES)).min(1).default([...PROBES]),
|
|
56
|
+
});
|
|
57
|
+
const TwoActorFileSchema = z.strictObject({
|
|
58
|
+
version: z.literal(1),
|
|
59
|
+
/** The API flow file (#230), relative to this file. */
|
|
60
|
+
flows: z.string().min(1),
|
|
61
|
+
/** Where the named sessions are, relative to this file (default `.auth` in the working directory, as elsewhere). */
|
|
62
|
+
sessionsDir: z.string().min(1).optional(),
|
|
63
|
+
actors: z.strictObject({
|
|
64
|
+
/** Actor A: creates the resource. */
|
|
65
|
+
owner: ActorSchema,
|
|
66
|
+
/** Actor B: another user of the same role (`peer`, default) or a lower role (`lower`). */
|
|
67
|
+
other: z.intersection(ActorSchema, z.object({ role: z.enum(["peer", "lower"]).default("peer") })),
|
|
68
|
+
}),
|
|
69
|
+
checks: z.array(CheckSchema).min(1),
|
|
70
|
+
});
|
|
71
|
+
const TEMPLATE = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
72
|
+
const UID = /\{\{\s*uid\s*\}\}/g;
|
|
73
|
+
/** Read and check a two-actor file's text against its (already read) flow file. Throws one error listing every problem. */
|
|
74
|
+
export function parseTwoActorFile(text, flows, source = "the two-actor file") {
|
|
75
|
+
let raw;
|
|
76
|
+
try {
|
|
77
|
+
raw = JSON.parse(text);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// The parser quotes the text around the error, and nothing has checked yet that this text holds no secret.
|
|
81
|
+
throw new Error(`${source} is not valid JSON.`);
|
|
82
|
+
}
|
|
83
|
+
const parsed = TwoActorFileSchema.safeParse(raw);
|
|
84
|
+
const problems = parsed.success
|
|
85
|
+
? checkAgainstFlows(parsed.data, flows)
|
|
86
|
+
: parsed.error.issues.map((i) => `${i.path.map((p) => (typeof p === "number" ? `[${p}]` : `.${String(p)}`)).join("").replace(/^\./, "") || "(file)"}: ${i.message}`);
|
|
87
|
+
if (problems.length || !parsed.success) {
|
|
88
|
+
throw new Error(`${source} is not a valid two-actor file:\n${problems.map((p) => ` - ${p}`).join("\n")}`);
|
|
89
|
+
}
|
|
90
|
+
return parsed.data;
|
|
91
|
+
}
|
|
92
|
+
function checkAgainstFlows(file, flows) {
|
|
93
|
+
const errors = [
|
|
94
|
+
...secretHeaderProblems(file.actors.owner.headers, "actors.owner"),
|
|
95
|
+
...secretHeaderProblems(file.actors.other.headers, "actors.other"),
|
|
96
|
+
];
|
|
97
|
+
file.checks.forEach((check, i) => {
|
|
98
|
+
const at = `checks[${i}]`;
|
|
99
|
+
const flow = flows.flows.find((f) => f.name === check.flow);
|
|
100
|
+
if (!flow)
|
|
101
|
+
return errors.push(`${at}: no flow "${check.flow}" in the flow file`);
|
|
102
|
+
if (flow.kind !== "data")
|
|
103
|
+
return errors.push(`${at}: "${check.flow}" is a sign-in flow; the owner creates the resource with a data flow`);
|
|
104
|
+
if (flow.cleanup.length === 0)
|
|
105
|
+
errors.push(`${at}: "${check.flow}" has no cleanup — the check never creates what it cannot delete`);
|
|
106
|
+
const captured = new Set(flow.steps.flatMap((s) => Object.keys(s.capture ?? {})));
|
|
107
|
+
for (const name of templateNames([check.resource, check.change.body])) {
|
|
108
|
+
if (name === "uid" || name.startsWith("env.") || captured.has(name))
|
|
109
|
+
continue;
|
|
110
|
+
errors.push(`${at}: {{${name}}} is not captured by flow "${check.flow}"`);
|
|
111
|
+
}
|
|
112
|
+
return undefined;
|
|
113
|
+
});
|
|
114
|
+
return errors;
|
|
115
|
+
}
|
|
116
|
+
/** Read a two-actor file and the flow file it names (relative to it). */
|
|
117
|
+
export async function loadTwoActorPlan(path) {
|
|
118
|
+
let text;
|
|
119
|
+
try {
|
|
120
|
+
text = await readFile(path, "utf8");
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
throw new Error(`Cannot read the two-actor file ${path}: ${e.message}`);
|
|
124
|
+
}
|
|
125
|
+
let flowsPath;
|
|
126
|
+
try {
|
|
127
|
+
flowsPath = resolve(dirname(path), z.object({ flows: z.string() }).parse(JSON.parse(text)).flows);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
// Let the full parse say what is wrong.
|
|
131
|
+
parseTwoActorFile(text, { version: 1, flows: [] }, path);
|
|
132
|
+
throw new Error(`${path} is not a valid two-actor file`);
|
|
133
|
+
}
|
|
134
|
+
const flows = await loadApiFlows(flowsPath);
|
|
135
|
+
const file = parseTwoActorFile(text, flows, path);
|
|
136
|
+
const sessionsDir = file.sessionsDir ? resolve(dirname(path), file.sessionsDir) : resolve(".auth");
|
|
137
|
+
return { file, flows, sessionsDir };
|
|
138
|
+
}
|
|
139
|
+
// ── actors ──────────────────────────────────────────────────────────────────
|
|
140
|
+
/** The cookies of a storageState that a request to `baseUrl` would carry, as one `Cookie` header value. */
|
|
141
|
+
export function cookieHeaderFor(state, baseUrl, now = Date.now() / 1000) {
|
|
142
|
+
const url = new URL(baseUrl);
|
|
143
|
+
const pairs = state.cookies
|
|
144
|
+
.filter((c) => {
|
|
145
|
+
const domain = c.domain.replace(/^\./, "").toLowerCase();
|
|
146
|
+
const host = url.hostname.toLowerCase();
|
|
147
|
+
const domainOk = host === domain || host.endsWith(`.${domain}`);
|
|
148
|
+
const pathOk = (url.pathname || "/").startsWith(c.path || "/") || c.path === "/";
|
|
149
|
+
const alive = c.expires === undefined || c.expires === -1 || c.expires > now;
|
|
150
|
+
const secureOk = c.secure !== true || url.protocol === "https:";
|
|
151
|
+
return domainOk && pathOk && alive && secureOk;
|
|
152
|
+
})
|
|
153
|
+
.map((c) => `${c.name}=${c.value}`);
|
|
154
|
+
return pairs.length ? pairs.join("; ") : undefined;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Merge header maps left to right with names compared case-insensitively: a later `authorization` replaces an earlier
|
|
158
|
+
* `Authorization`, so one name never goes out with two values (fetch would join them with a comma).
|
|
159
|
+
*/
|
|
160
|
+
export function mergeHeaders(...maps) {
|
|
161
|
+
const out = new Map();
|
|
162
|
+
for (const map of maps)
|
|
163
|
+
for (const [name, value] of Object.entries(map ?? {}))
|
|
164
|
+
out.set(name.toLowerCase(), [name, value]);
|
|
165
|
+
return Object.fromEntries(out.values());
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The only flow-file headers the other actor takes: they describe the request's format, never who sends it. Any other
|
|
169
|
+
* name — `Authorization`, but also `X-Session-Id`, `X-User-Id`, `X-Tenant`, `DPoP`, a name nobody can list in advance —
|
|
170
|
+
* may carry the owner's identity, so it stays with the owner.
|
|
171
|
+
*/
|
|
172
|
+
const FORMAT_HEADERS = new Set(["accept", "accept-language", "content-type", "user-agent"]);
|
|
173
|
+
/**
|
|
174
|
+
* One actor's request headers: the flow file's, then the actor's own, then the saved session's cookies (which replace
|
|
175
|
+
* any `Cookie` the actor wrote). The flow file's headers belong to the owner (its token, as the flow docs show), so
|
|
176
|
+
* only the owner — `plan.file.actors.owner` itself — gets them whole. Every other actor takes from them only Accept,
|
|
177
|
+
* Accept-Language, Content-Type and User-Agent, and none filled from the environment: everything else it sends comes
|
|
178
|
+
* from its own actor definition. The other actor carries no identity but its own, by construction.
|
|
179
|
+
*/
|
|
180
|
+
export async function actorHeaders(actor, plan, baseUrl, env = process.env) {
|
|
181
|
+
const isOwner = actor === plan.file.actors.owner;
|
|
182
|
+
const shared = Object.fromEntries(Object.entries(plan.flows.headers ?? {}).filter(([name, value]) => isOwner || (FORMAT_HEADERS.has(name.toLowerCase()) && !/\{\{\s*env\./.test(value))));
|
|
183
|
+
const headers = fillHeaders(mergeHeaders(shared, actor.headers), env);
|
|
184
|
+
if (actor.session) {
|
|
185
|
+
const state = await new SessionStore(plan.sessionsDir).load(actor.session);
|
|
186
|
+
const cookie = cookieHeaderFor(state, baseUrl);
|
|
187
|
+
if (!cookie)
|
|
188
|
+
throw new Error(`The saved session "${actor.session}" has no cookie for ${new URL(baseUrl).origin}.`);
|
|
189
|
+
return mergeHeaders(headers, { Cookie: cookie });
|
|
190
|
+
}
|
|
191
|
+
return headers;
|
|
192
|
+
}
|
|
193
|
+
function fillHeaders(headers, env) {
|
|
194
|
+
return Object.fromEntries(Object.entries(headers).map(([k, v]) => {
|
|
195
|
+
const filled = v.replace(TEMPLATE, (m, key) => {
|
|
196
|
+
if (key === "uid")
|
|
197
|
+
return m; // one value for each check: filled when a request goes out
|
|
198
|
+
if (!key.startsWith("env."))
|
|
199
|
+
throw new Error(`Header "${k}": only {{env.NAME}} and {{uid}} may be used in an actor's headers`);
|
|
200
|
+
const value = env[key.slice(4)];
|
|
201
|
+
if (value === undefined || value === "")
|
|
202
|
+
throw new Error(`Header "${k}": the environment variable ${key.slice(4)} is not set`);
|
|
203
|
+
return value;
|
|
204
|
+
});
|
|
205
|
+
const refusal = headerRefusal(k, v, filled);
|
|
206
|
+
if (refusal)
|
|
207
|
+
throw new Error(`${refusal}; nothing was sent`);
|
|
208
|
+
return [k, filled];
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Whether a header's characters can go on the wire, as one line that names the header and the `{{env.NAME}}` it was
|
|
213
|
+
* built from and never its value: fetch quotes a bad value in its own error text, and the value may be a secret.
|
|
214
|
+
*/
|
|
215
|
+
function headerRefusal(name, template, value) {
|
|
216
|
+
const category = !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) ? "invalid header name" : /[^\t\x20-\x7e\x80-\xff]/.test(value) ? "invalid header value" : undefined;
|
|
217
|
+
if (!category)
|
|
218
|
+
return undefined;
|
|
219
|
+
const from = [...(template ?? "").matchAll(TEMPLATE)].map((m) => `{{${m[1]}}}`);
|
|
220
|
+
return `header "${name}" is not valid (${category}${from.length ? `, built from ${from.join(", ")}` : ""})`;
|
|
221
|
+
}
|
|
222
|
+
class RequestFailed extends Error {
|
|
223
|
+
}
|
|
224
|
+
/** The codes fetch fails with: Node's socket and TLS errors and undici's own. A code is only a string on an error: no other is repeated. */
|
|
225
|
+
const NETWORK_CODES = new Set([
|
|
226
|
+
"ECONNREFUSED", "ECONNRESET", "ECONNABORTED", "ENOTFOUND", "ETIMEDOUT", "EAI_AGAIN", "EPIPE", "EHOSTUNREACH", "ENETUNREACH",
|
|
227
|
+
"CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "ERR_TLS_CERT_ALTNAME_INVALID",
|
|
228
|
+
"UND_ERR_ABORTED", "UND_ERR_BODY_TIMEOUT", "UND_ERR_BPL_MISSING_UPSTREAM", "UND_ERR_CLOSED", "UND_ERR_CONNECT_TIMEOUT",
|
|
229
|
+
"UND_ERR_DESTROYED", "UND_ERR_HEADERS_OVERFLOW", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_INFO", "UND_ERR_INVALID_ARG",
|
|
230
|
+
"UND_ERR_INVALID_RETURN_VALUE", "UND_ERR_NOT_SUPPORTED", "UND_ERR_PRX_TLS", "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH",
|
|
231
|
+
"UND_ERR_REQ_RETRY", "UND_ERR_RES_CONTENT_LENGTH_MISMATCH", "UND_ERR_RES_EXCEEDED_MAX_SIZE", "UND_ERR_RESPONSE_STATUS_CODE",
|
|
232
|
+
"UND_ERR_SOCKET",
|
|
233
|
+
]);
|
|
234
|
+
/**
|
|
235
|
+
* Why a request failed, as a fixed category taken from the error's name or code, never from its message: fetch quotes
|
|
236
|
+
* the URL and the header value it was given, and either may hold a secret from the environment.
|
|
237
|
+
*/
|
|
238
|
+
const failureCategory = (e) => {
|
|
239
|
+
const err = e;
|
|
240
|
+
if (err?.name === "TimeoutError" || err?.name === "AbortError")
|
|
241
|
+
return "timeout";
|
|
242
|
+
const code = err?.cause?.code ?? err?.code;
|
|
243
|
+
return typeof code === "string" && NETWORK_CODES.has(code) ? `network: ${code}` : "network error";
|
|
244
|
+
};
|
|
245
|
+
/** The built-in error types, the only names repeated: an error's `name` can be set to any text. */
|
|
246
|
+
const BUILTIN_ERRORS = new Set(["Error", "TypeError", "RangeError", "URIError", "SyntaxError", "ReferenceError", "EvalError", "AggregateError"]);
|
|
247
|
+
/** What a caught error may add to the report: our own messages (built from safe parts), never an unknown error's text. */
|
|
248
|
+
const reportable = (e) => {
|
|
249
|
+
if (e instanceof RequestFailed)
|
|
250
|
+
return e.message;
|
|
251
|
+
const name = e?.name;
|
|
252
|
+
return typeof name === "string" && BUILTIN_ERRORS.has(name) ? `unexpected failure (${name})` : "unexpected failure";
|
|
253
|
+
};
|
|
254
|
+
const fillValue = (value, vars, env, encode = false) => {
|
|
255
|
+
if (typeof value === "string") {
|
|
256
|
+
return value.replace(TEMPLATE, (_m, key) => {
|
|
257
|
+
const v = key.startsWith("env.") ? env[key.slice(4)] : vars[key];
|
|
258
|
+
if (v === undefined)
|
|
259
|
+
throw new RequestFailed(key.startsWith("env.") ? `the environment variable ${key.slice(4)} is not set` : `no value for {{${key}}}`);
|
|
260
|
+
if (encode && (v === "" || v === "." || v === ".." || v.includes("/"))) {
|
|
261
|
+
// The value may be a secret, or anything the server answered: name it, never print it.
|
|
262
|
+
throw new RequestFailed(`{{${key}}} is a value, which cannot stand in the path ${value}`);
|
|
263
|
+
}
|
|
264
|
+
return encode ? encodeURIComponent(v) : v;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
if (Array.isArray(value))
|
|
268
|
+
return value.map((v) => fillValue(v, vars, env, encode));
|
|
269
|
+
if (value && typeof value === "object")
|
|
270
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fillValue(v, vars, env, encode)]));
|
|
271
|
+
return value;
|
|
272
|
+
};
|
|
273
|
+
/** The values of every `{{env.NAME}}` the flow file and the two-actor file name. */
|
|
274
|
+
const namedEnvValues = (plan, env) => new Set(templateNames([plan.flows, plan.file]).flatMap((name) => {
|
|
275
|
+
const value = name.startsWith("env.") ? env[name.slice(4)] : undefined;
|
|
276
|
+
return value === undefined ? [] : [value];
|
|
277
|
+
}));
|
|
278
|
+
/**
|
|
279
|
+
* The one place that decides whether a captured value may be shown. A value from the server can hold anything: an
|
|
280
|
+
* environment value it echoed, a token it issued, a newline that forges a report line. So only a whole number is
|
|
281
|
+
* shown, and not when it equals the value of a named `{{env.NAME}}`.
|
|
282
|
+
*/
|
|
283
|
+
const showable = (value, envValues) => /^\d{1,18}$/.test(value) && !envValues.has(value);
|
|
284
|
+
/**
|
|
285
|
+
* A path as error text and the report show it: a captured value only when it is {@link showable} (`/api/projects/3`),
|
|
286
|
+
* otherwise its `{{name}}`, and every `{{env.NAME}}` and the whole query as the flow file wrote them. The real values
|
|
287
|
+
* go only on the wire.
|
|
288
|
+
*/
|
|
289
|
+
export const shownPath = (path, vars, envValues, query) => {
|
|
290
|
+
const shown = path.replace(TEMPLATE, (m, key) => (!key.startsWith("env.") && vars[key] !== undefined && showable(vars[key], envValues) ? vars[key] : m));
|
|
291
|
+
const q = query ? Object.entries(query).map(([k, v]) => `${k}=${v}`).join("&") : "";
|
|
292
|
+
return shown + (q ? `?${q}` : "");
|
|
293
|
+
};
|
|
294
|
+
const pointerAt = (body, pointer) => {
|
|
295
|
+
let cur = body;
|
|
296
|
+
for (const raw of pointer.split("/").slice(1)) {
|
|
297
|
+
if (cur === null || typeof cur !== "object")
|
|
298
|
+
return undefined;
|
|
299
|
+
cur = cur[raw.replace(/~1/g, "/").replace(/~0/g, "~")];
|
|
300
|
+
}
|
|
301
|
+
return cur;
|
|
302
|
+
};
|
|
303
|
+
const NO_ANSWER = "no probe got an answer from the other actor";
|
|
304
|
+
const is2xx = (s) => s >= 200 && s < 300;
|
|
305
|
+
/**
|
|
306
|
+
* The answers that mean "refused": 401, 403 and 404 (a fixed server may hide that the resource exists). Anything else
|
|
307
|
+
* that is not a 2xx — a redirect, 400, 405, 410, 422, a 5xx — says nothing about access (a `PATCH {}` refused by
|
|
308
|
+
* validation never reached the access check), so the case is inconclusive, never a pass.
|
|
309
|
+
*/
|
|
310
|
+
const DENIED = new Set([401, 403, 404]);
|
|
311
|
+
const outcomeOf = (s) => (is2xx(s) ? "finding" : DENIED.has(s) ? "denied" : "inconclusive");
|
|
312
|
+
const inconclusiveDetail = (s) => s >= 500
|
|
313
|
+
? `the server failed (${s}); not known whether it is protected`
|
|
314
|
+
: `answered ${s}, neither a refusal (401, 403, 404) nor a success; not known whether it is protected`;
|
|
315
|
+
/**
|
|
316
|
+
* Run every check of the plan. Never throws for a failed request: a check that stops midway records its error, and
|
|
317
|
+
* its cleanup has run if anything had gone out. Findings are 2xx answers to actor B (and neighbours both actors read).
|
|
318
|
+
*/
|
|
319
|
+
export async function runTwoActorChecks(plan, opts) {
|
|
320
|
+
const env = opts.env ?? process.env;
|
|
321
|
+
const doFetch = opts.fetch ?? globalThis.fetch;
|
|
322
|
+
const timeoutMs = opts.timeoutMs ?? 30_000;
|
|
323
|
+
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
324
|
+
const results = [];
|
|
325
|
+
const envValues = namedEnvValues(plan, env);
|
|
326
|
+
/** Whether the current check's flow sent a request yet (so it may have created something). */
|
|
327
|
+
let sentAny = false;
|
|
328
|
+
/** The current check's `{{uid}}`, for the actors' headers, which are filled once for the whole run. */
|
|
329
|
+
let uid = "";
|
|
330
|
+
/** The names the current check's requests send: a capture no request sends is not read. */
|
|
331
|
+
let used = new Set();
|
|
332
|
+
const refuseHeaders = (at, headers, templates = {}) => {
|
|
333
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
334
|
+
const refusal = headerRefusal(name, templates[name], value);
|
|
335
|
+
if (refusal)
|
|
336
|
+
throw new RequestFailed(`${at} not sent: ${refusal}`);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
/** One request through the guard. A transport failure throws: the check stops there. */
|
|
340
|
+
const send = async (method, path, headers, body, mustSend, shown) => {
|
|
341
|
+
const filled = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, v.replace(UID, uid)]));
|
|
342
|
+
const sent = body ? mergeHeaders({ "content-type": body.type }, filled) : filled;
|
|
343
|
+
// Characters fetch cannot carry are refused here, before anything is counted or sent, without quoting the value.
|
|
344
|
+
// A header fetch rejects for its own reasons (`Expect`, `Transfer-Encoding`) goes on and ends in "got no answer".
|
|
345
|
+
refuseHeaders(`${method} ${shown}`, sent);
|
|
346
|
+
try {
|
|
347
|
+
new URL(base + path);
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
throw new RequestFailed(`${method} ${shown} not sent: invalid URL`);
|
|
351
|
+
}
|
|
352
|
+
// The budget was reserved for the whole check before it started; the cleanup goes out even if it ran short.
|
|
353
|
+
if (!(await opts.guard.acquire()) && !mustSend)
|
|
354
|
+
throw new RequestFailed(`the request budget ran out (--max-requests ${opts.guard.maxRequests})`);
|
|
355
|
+
const init = { method, headers: sent, redirect: "manual" };
|
|
356
|
+
if (body)
|
|
357
|
+
init.body = body.text;
|
|
358
|
+
if (timeoutMs > 0)
|
|
359
|
+
init.signal = AbortSignal.timeout(timeoutMs);
|
|
360
|
+
try {
|
|
361
|
+
sentAny = true;
|
|
362
|
+
const res = await doFetch(base + path, init);
|
|
363
|
+
opts.guard.recordExecuted();
|
|
364
|
+
return res;
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
// Method, the path as written and a category: the text of the error is never used.
|
|
368
|
+
throw new RequestFailed(`${method} ${shown} got no answer: ${failureCategory(e)}`);
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
const json = (value) => value === undefined ? undefined : { text: JSON.stringify(value), type: "application/json" };
|
|
372
|
+
/**
|
|
373
|
+
* One flow step as the owner, with the flow's `expect` (plus `alsoOk`) and its captures. A flow step without
|
|
374
|
+
* `expect` takes any 2xx or 3xx, as in #230; a cleanup step without `expect` is done only on a 2xx — a 302 to a
|
|
375
|
+
* login page (the owner's session ended) leaves the resource where it was.
|
|
376
|
+
*/
|
|
377
|
+
const runStep = async (flow, step, vars, cleanup = false, alsoOk = []) => {
|
|
378
|
+
let path = fillValue(step.path, vars, env, true);
|
|
379
|
+
if (step.query)
|
|
380
|
+
path += `?${new URLSearchParams(fillValue(step.query, vars, env)).toString()}`;
|
|
381
|
+
// Error text names the path without any environment value: `path` itself goes only on the wire.
|
|
382
|
+
const shown = shownPath(step.path, vars, envValues, step.query);
|
|
383
|
+
const label = cleanup
|
|
384
|
+
? `flow "${flow.name}" cleanup "${step.name ?? step.method}": ${step.method} ${shown}`
|
|
385
|
+
: `flow "${flow.name}" step "${step.name ?? `${step.method} ${step.path}`}"`;
|
|
386
|
+
const headers = mergeHeaders(opts.owner, fillValue(step.headers ?? {}, vars, env));
|
|
387
|
+
const body = step.form
|
|
388
|
+
? { text: new URLSearchParams(fillValue(step.form, vars, env)).toString(), type: "application/x-www-form-urlencoded" }
|
|
389
|
+
: json(step.body === undefined ? undefined : fillValue(step.body, vars, env));
|
|
390
|
+
const res = await send(step.method, path, headers, body, cleanup, shown);
|
|
391
|
+
const want = step.expect === undefined ? undefined : [].concat(step.expect);
|
|
392
|
+
const ok = (want ? want.includes(res.status) : cleanup ? is2xx(res.status) : res.status >= 200 && res.status < 400) || alsoOk.includes(res.status);
|
|
393
|
+
if (!ok)
|
|
394
|
+
throw new RequestFailed(`${label} answered ${res.status} (want ${want ? want.join(" or ") : cleanup ? "2xx" : "2xx or 3xx"})`);
|
|
395
|
+
// Only what a request sends counts: a capture nothing sends cannot stop the check, whatever the answer holds.
|
|
396
|
+
const captures = Object.entries(step.capture ?? {}).filter(([name]) => used.has(name));
|
|
397
|
+
if (captures.length === 0) {
|
|
398
|
+
await res.arrayBuffer().catch(() => undefined);
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
let text;
|
|
402
|
+
let answer;
|
|
403
|
+
try {
|
|
404
|
+
text = await res.text();
|
|
405
|
+
answer = JSON.parse(text);
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
throw new RequestFailed(`${label}: the answer is not JSON, so nothing can be captured from it`);
|
|
409
|
+
}
|
|
410
|
+
const missing = [];
|
|
411
|
+
const inexact = [];
|
|
412
|
+
for (const [name, pointer] of captures) {
|
|
413
|
+
const v = pointerAt(answer, pointer);
|
|
414
|
+
if (v === undefined || v === null || typeof v === "object" || String(v) === "")
|
|
415
|
+
missing.push(`${pointer} for ${name}`);
|
|
416
|
+
// JSON.parse has already rounded a number past the safe range, made it Infinity, or dropped digits of a fraction
|
|
417
|
+
// (#253): it may be another record's id, so it is never kept.
|
|
418
|
+
else if (typeof v === "number" && !isExactNumber(v, String(pointerAt(numbersAsWritten(text), pointer))))
|
|
419
|
+
inexact.push(`{{${name}}}`);
|
|
420
|
+
else
|
|
421
|
+
vars[name] = String(v);
|
|
422
|
+
}
|
|
423
|
+
if (missing.length)
|
|
424
|
+
throw new RequestFailed(`${label}: the answer has no value at ${missing.join(", ")}`);
|
|
425
|
+
if (inexact.length)
|
|
426
|
+
throw new RequestFailed(`${label}: ${inexact.join(", ")} is not a safe integer (the number may have been rounded), so it is not used`);
|
|
427
|
+
};
|
|
428
|
+
const status = async (method, path, shown, headers, body) => {
|
|
429
|
+
const res = await send(method, path, headers, json(body), false, shown);
|
|
430
|
+
await res.arrayBuffer().catch(() => undefined);
|
|
431
|
+
return res.status;
|
|
432
|
+
};
|
|
433
|
+
for (const check of plan.file.checks) {
|
|
434
|
+
const flow = plan.flows.flows.find((f) => f.name === check.flow);
|
|
435
|
+
const result = { check: `${check.flow} ${check.resource}`, flow: flow.name, cleanupErrors: [], cases: [] };
|
|
436
|
+
results.push(result);
|
|
437
|
+
const wstgDirect = opts.role === "lower" ? WSTG_PRIVILEGE_ESCALATION : WSTG_IDOR;
|
|
438
|
+
const probeMethod = { read: "GET", change: check.change.method, delete: "DELETE", neighbours: "GET" };
|
|
439
|
+
// The guard's own rules, asked before anything is created: the check creates data, and its cleanup must be allowed.
|
|
440
|
+
if (!opts.guard.allowsMutations) {
|
|
441
|
+
result.notRun = "mutations disabled — the owner's flow creates data; pass --allow-mutations for a staging address";
|
|
442
|
+
opts.guard.recordSkip("mutations disabled");
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
const refused = [...flow.steps, ...flow.cleanup].find((s) => !opts.guard.allowsMethod(s.method) || !opts.guard.allowsPath(s.path));
|
|
446
|
+
if (refused) {
|
|
447
|
+
result.notRun = `not allowed — flow "${flow.name}" sends ${refused.method} ${refused.path}, which --allowed-methods/--allowed-paths refuse`;
|
|
448
|
+
result.notTested = NO_ANSWER;
|
|
449
|
+
opts.guard.recordSkip("not allowed");
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const probes = check.probes.filter((p) => {
|
|
453
|
+
const allowed = opts.guard.allowsMethod(probeMethod[p]) && opts.guard.allowsPath(check.resource);
|
|
454
|
+
if (!allowed) {
|
|
455
|
+
result.cases.push({ check: result.check, probe: p, wstgId: p === "neighbours" ? WSTG_IDOR : wstgDirect, method: probeMethod[p], path: check.resource, outcome: "skipped", detail: "not allowed by --allowed-methods/--allowed-paths" });
|
|
456
|
+
opts.guard.recordSkip("not allowed");
|
|
457
|
+
}
|
|
458
|
+
return allowed;
|
|
459
|
+
});
|
|
460
|
+
const needed = flow.steps.length + flow.cleanup.length + probes.filter((p) => p !== "neighbours").length + (probes.includes("neighbours") ? 4 * check.neighbours : 0);
|
|
461
|
+
const left = opts.guard.maxRequests - opts.guard.report().requestsUsed;
|
|
462
|
+
if (needed > left) {
|
|
463
|
+
result.notRun = `budget exhausted — the check needs up to ${needed} request(s), ${left} left (raise --max-requests)`;
|
|
464
|
+
opts.guard.recordSkip("budget exhausted");
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const vars = { uid: Date.now().toString(36) + Math.random().toString(36).slice(2, 8) };
|
|
468
|
+
let deletedByOther = false;
|
|
469
|
+
sentAny = false;
|
|
470
|
+
uid = vars.uid;
|
|
471
|
+
used = new Set([...[...flow.steps, ...flow.cleanup].flatMap(stepTemplateNames), ...templateNames([check.resource, check.change.body])]);
|
|
472
|
+
try {
|
|
473
|
+
// Everything known by now is refused before the first request, so the flow creates nothing its cleanup is already
|
|
474
|
+
// known not to be able to send. A stand-in takes the place of each name that is not an {{env.NAME}}: a real
|
|
475
|
+
// {{uid}} is always sendable, and what a captured value holds is known only when it is sent.
|
|
476
|
+
for (const step of [...flow.steps, ...flow.cleanup]) {
|
|
477
|
+
const standIns = Object.fromEntries(stepTemplateNames(step).map((name) => [name, "0"]));
|
|
478
|
+
fillValue(step.path, standIns, env, true);
|
|
479
|
+
fillValue([step.query, step.body, step.form], standIns, env);
|
|
480
|
+
refuseHeaders(`${step.method} ${shownPath(step.path, {}, envValues, step.query)}`, mergeHeaders(opts.owner, fillValue(step.headers ?? {}, standIns, env)), step.headers);
|
|
481
|
+
}
|
|
482
|
+
if (probes[0])
|
|
483
|
+
refuseHeaders(`${probeMethod[probes[0]]} ${check.resource}`, opts.other);
|
|
484
|
+
for (const step of flow.steps)
|
|
485
|
+
await runStep(flow, step, vars);
|
|
486
|
+
const path = fillValue(check.resource, vars, env, true);
|
|
487
|
+
// What the report and error text name: no environment value in it, no captured value but a whole number.
|
|
488
|
+
const shown = shownPath(check.resource, vars, envValues);
|
|
489
|
+
const record = (probe, method, at, s, what, wstgId = wstgDirect) => {
|
|
490
|
+
const outcome = outcomeOf(s);
|
|
491
|
+
const detail = outcome === "finding"
|
|
492
|
+
? `the other actor ${what} the owner's resource (${s})`
|
|
493
|
+
: outcome === "denied"
|
|
494
|
+
? `refused (${s})`
|
|
495
|
+
: inconclusiveDetail(s);
|
|
496
|
+
result.cases.push({ check: result.check, probe, wstgId, method, path: at, outcome, status: s, detail });
|
|
497
|
+
};
|
|
498
|
+
// Delete last: after it the resource may be gone.
|
|
499
|
+
if (probes.includes("read"))
|
|
500
|
+
record("read", "GET", shown, await status("GET", path, shown, opts.other), "read");
|
|
501
|
+
if (probes.includes("change")) {
|
|
502
|
+
const body = fillValue(check.change.body, vars, env);
|
|
503
|
+
record("change", check.change.method, shown, await status(check.change.method, path, shown, opts.other, body), "changed");
|
|
504
|
+
}
|
|
505
|
+
if (probes.includes("neighbours")) {
|
|
506
|
+
const idName = [...check.resource.matchAll(TEMPLATE)].pop()[1];
|
|
507
|
+
const id = vars[idName] ?? "";
|
|
508
|
+
// Past the safe range `id ± d` would be rounded to some other number, so a string id that large is not counted from.
|
|
509
|
+
const unusable = !/^\d+$/.test(id) ? "is not a number" : !Number.isSafeInteger(Number(id)) ? "is too large to count from" : undefined;
|
|
510
|
+
if (unusable) {
|
|
511
|
+
result.cases.push({ check: result.check, probe: "neighbours", wstgId: WSTG_IDOR, method: "GET", path: shown, outcome: "skipped", detail: `the id {{${idName}}} ${unusable}` });
|
|
512
|
+
}
|
|
513
|
+
else {
|
|
514
|
+
for (let d = 1; d <= check.neighbours; d++) {
|
|
515
|
+
for (const n of [Number(id) - d, Number(id) + d]) {
|
|
516
|
+
if (n < 0 || !Number.isSafeInteger(n))
|
|
517
|
+
continue;
|
|
518
|
+
const wire = fillValue(check.resource, { ...vars, [idName]: String(n) }, env, true);
|
|
519
|
+
// A neighbour is a number made here, so it names the record it reached, unless the id itself is not
|
|
520
|
+
// shown: id ± d would give it away.
|
|
521
|
+
const at = showable(id, envValues) ? shownPath(check.resource, { ...vars, [idName]: String(n) }, envValues) : shown;
|
|
522
|
+
const s = await status("GET", wire, at, opts.other);
|
|
523
|
+
if (!is2xx(s)) {
|
|
524
|
+
const outcome = outcomeOf(s);
|
|
525
|
+
result.cases.push({ check: result.check, probe: "neighbours", wstgId: WSTG_IDOR, method: "GET", path: at, outcome, status: s, detail: outcome === "denied" ? `refused or absent (${s})` : inconclusiveDetail(s) });
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
// B can read it: a finding only when A can too — an id B owns refuses A on a fixed server.
|
|
529
|
+
const o = await status("GET", wire, at, opts.owner);
|
|
530
|
+
const ownerOutcome = outcomeOf(o);
|
|
531
|
+
result.cases.push({
|
|
532
|
+
check: result.check,
|
|
533
|
+
probe: "neighbours",
|
|
534
|
+
wstgId: WSTG_IDOR,
|
|
535
|
+
method: "GET",
|
|
536
|
+
path: at,
|
|
537
|
+
outcome: ownerOutcome,
|
|
538
|
+
status: s,
|
|
539
|
+
ownerStatus: o,
|
|
540
|
+
detail: ownerOutcome === "finding"
|
|
541
|
+
? `both actors read it, so it is private to neither (${s} / ${o})`
|
|
542
|
+
: ownerOutcome === "denied"
|
|
543
|
+
? `the other actor reads it and the owner is refused (${o}): it is the other actor's own`
|
|
544
|
+
: `the other actor reads it; the owner's answer (${o}) is neither a refusal nor a success, so not known whose it is`,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (probes.includes("delete")) {
|
|
551
|
+
const s = await status("DELETE", path, shown, opts.other);
|
|
552
|
+
deletedByOther = is2xx(s);
|
|
553
|
+
record("delete", "DELETE", shown, s, "deleted");
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
catch (e) {
|
|
557
|
+
result.error = reportable(e);
|
|
558
|
+
}
|
|
559
|
+
finally {
|
|
560
|
+
// The flow's own cleanup, as the owner, whatever happened above: a check that sent nothing created nothing, so it
|
|
561
|
+
// has none. A step whose values were never captured cannot be sent; that is a cleanup error, since what the flow
|
|
562
|
+
// created may still be there.
|
|
563
|
+
for (const step of sentAny ? flow.cleanup : []) {
|
|
564
|
+
const missing = [...new Set(stepTemplateNames(step).filter((n) => !n.startsWith("env.") && n !== "uid" && !(n in vars)))];
|
|
565
|
+
if (missing.length) {
|
|
566
|
+
const which = missing.map((n) => `{{${n}}}`).join(", ");
|
|
567
|
+
result.cleanupErrors.push(`flow "${flow.name}" cleanup "${step.name ?? step.method}": ${step.method} ${step.path} was not sent: ${which} was never captured, ` +
|
|
568
|
+
`so the resource ${check.resource} the flow created may still be on the server`);
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
// Only after the other actor's DELETE went through does a 404/410 here mean the cleanup's goal is reached.
|
|
573
|
+
await runStep(flow, step, vars, true, deletedByOther ? [404, 410] : []);
|
|
574
|
+
}
|
|
575
|
+
catch (e) {
|
|
576
|
+
result.cleanupErrors.push(reportable(e));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
const answers = result.cases.filter((c) => c.status !== undefined);
|
|
581
|
+
// A 401 to everything says the server never looked at the resource: the credentials may be dead, so it is no refusal.
|
|
582
|
+
if (answers.every((c) => c.status === 401)) {
|
|
583
|
+
for (const c of answers) {
|
|
584
|
+
c.outcome = "inconclusive";
|
|
585
|
+
c.detail = "the other actor got 401 to every probe: its credentials may not be valid, so access was not checked";
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (answers.length === 0 && result.error === undefined)
|
|
589
|
+
result.notTested = NO_ANSWER;
|
|
590
|
+
}
|
|
591
|
+
return { baseUrl: opts.baseUrl, role: opts.role, checks: results, findings: results.flatMap((r) => r.cases).filter((c) => c.outcome === "finding").length };
|
|
592
|
+
}
|
|
593
|
+
/** Console lines: one per case, with its WSTG id; then what was not run, what stopped, and what the cleanup left. */
|
|
594
|
+
export function renderTwoActorReport(r) {
|
|
595
|
+
const lines = ["", `=== Two-actor check (${r.role === "lower" ? "lower role" : "two users"}) against ${r.baseUrl} ===`];
|
|
596
|
+
const mark = { finding: "✗", denied: "✓", inconclusive: "?", skipped: "⊘" };
|
|
597
|
+
for (const c of r.checks) {
|
|
598
|
+
lines.push(` ${c.check} (flow "${c.flow}")`);
|
|
599
|
+
if (c.notRun)
|
|
600
|
+
lines.push(` ⊘ not run: ${c.notRun}`);
|
|
601
|
+
for (const k of c.cases)
|
|
602
|
+
lines.push(` ${mark[k.outcome]} [${k.wstgId}] ${k.probe}: ${k.method} ${k.path} — ${k.detail}`);
|
|
603
|
+
if (c.notTested)
|
|
604
|
+
lines.push(` ✗ not tested: ${c.notTested}`);
|
|
605
|
+
if (c.error)
|
|
606
|
+
lines.push(` ✗ stopped: ${c.error}`);
|
|
607
|
+
for (const e of c.cleanupErrors)
|
|
608
|
+
lines.push(` ✗ cleanup failed, the data may still be there: ${e}`);
|
|
609
|
+
}
|
|
610
|
+
const all = r.checks.flatMap((c) => c.cases);
|
|
611
|
+
lines.push(` ${r.findings} finding(s) · ${all.filter((c) => c.outcome === "denied").length} refused · ` +
|
|
612
|
+
`${all.filter((c) => c.outcome === "inconclusive").length} inconclusive · ${all.filter((c) => c.outcome === "skipped").length} skipped`);
|
|
613
|
+
return lines;
|
|
614
|
+
}
|
|
615
|
+
/** Whether any probe of the run got an answer from the other actor: the owner's steps and cleanup do not count. */
|
|
616
|
+
export function twoActorAnswered(r) {
|
|
617
|
+
return r.checks.some((c) => c.cases.some((k) => k.status !== undefined));
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Whether a report should fail the run: a finding, an inconclusive case, a check that stopped, a cleanup that failed,
|
|
621
|
+
* or a check no probe of which got an answer while another check's did.
|
|
622
|
+
*/
|
|
623
|
+
export function twoActorFailed(r) {
|
|
624
|
+
return (r.checks.some((c) => c.error !== undefined || c.cleanupErrors.length > 0 || c.cases.some((k) => k.outcome === "finding" || k.outcome === "inconclusive")) ||
|
|
625
|
+
(twoActorAnswered(r) && r.checks.some((c) => c.notTested !== undefined)));
|
|
626
|
+
}
|
|
627
|
+
//# sourceMappingURL=two-actor.js.map
|