torusguard 1.3.3 → 1.3.5
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/.torusguard/.manifest.json +66 -63
- package/.torusguard/rules/business-logic/TG-BIZ-001-client-controlled-sensitive-business-value.md +30 -14
- package/.torusguard/rules/business-logic/TG-BIZ-002-replayable-one-time-operation.md +33 -16
- package/.torusguard/rules/business-logic/TG-BIZ-003-missing-workflow-state-validation.md +31 -15
- package/.torusguard/rules/business-logic/TG-BIZ-004-unrestricted-sensitive-business-flow.md +26 -16
- package/.torusguard/rules/cache/TG-CACHE-001-sensitive-response-publicly-cacheable.md +24 -16
- package/.torusguard/rules/cache/TG-CACHE-002-missing-user-cache-isolation.md +32 -18
- package/.torusguard/rules/cache/TG-CACHE-003-sensitive-data-in-url.md +24 -17
- package/.torusguard/rules/csrf/TG-CSRF-001-missing-csrf-protection.md +31 -18
- package/.torusguard/rules/csrf/TG-CSRF-002-unsafe-credentialed-cross-origin-request.md +28 -17
- package/.torusguard/rules/graphql/TG-GQL-002-resolver-missing-authorization.md +33 -17
- package/.torusguard/rules/graphql/TG-GQL-003-unbounded-graphql-pagination-or-batching.md +31 -16
- package/.torusguard/rules/graphql/TG-GQL-004-unnecessary-production-introspection.md +25 -16
- package/.torusguard/rules/secrets/TG-SEC-005-secret-in-git-history.md +24 -19
- package/.torusguard/rules/secrets/TG-SEC-006-secret-in-build-artifact.md +36 -19
- package/.torusguard/rules/secrets/TG-SEC-007-secret-in-test-or-example-fixture.md +21 -16
- package/.torusguard/rules/ssrf/TG-SSRF-002-missing-internal-network-protection.md +45 -18
- package/.torusguard/rules/ssrf/TG-SSRF-003-unsafe-redirect-following.md +20 -16
- package/.torusguard/rules/ssrf/TG-SSRF-004-unbounded-outbound-request.md +28 -19
- package/.torusguard/rules/supply-chain/TG-SUPPLY-001-missing-or-ignored-dependency-lockfile.md +25 -18
- package/.torusguard/rules/supply-chain/TG-SUPPLY-003-unsafe-ci-cd-secret-exposure.md +29 -19
- package/.torusguard/rules/supply-chain/TG-SUPPLY-004-unpinned-ci-action.md +23 -18
- package/.torusguard/rules/supply-chain/TG-SUPPLY-005-unsafe-dependency-install-script.md +23 -18
- package/.torusguard/rules/webhook/TG-WEBHOOK-001-missing-webhook-signature-verification.md +36 -16
- package/.torusguard/rules/webhook/TG-WEBHOOK-002-replayable-webhook.md +26 -17
- package/.torusguard/rules/webhook/TG-WEBHOOK-003-missing-webhook-idempotency.md +30 -16
- package/.torusguard/rules/webhook/TG-WEBHOOK-004-unvalidated-webhook-event-type.md +25 -16
- package/.torusguard/rules/websocket/TG-WS-002-missing-channel-level-authorization.md +28 -17
- package/.torusguard/rules/websocket/TG-WS-003-unvalidated-websocket-message.md +31 -17
- package/.torusguard/rules/websocket/TG-WS-004-unbounded-websocket-connections.md +31 -17
- package/.torusguard/rules_catalog.json +520 -0
- package/.torusguard/runs/report-latest.html +93 -7
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/metadata.json +15 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/patch.diff +9 -0
- package/.torusguard/runs/run-20260910-120238-audit/findings.json +1520 -0
- package/.torusguard/runs/run-20260910-120238-audit/findings.md +560 -0
- package/.torusguard/runs/run-20260910-120238-audit/manifest.json +13 -0
- package/.torusguard/runs/run-20260910-120238-audit/recheck.md +86 -0
- package/.torusguard/runs/run-20260910-120238-audit/remediation.md +262 -0
- package/.torusguard/runs/run-20260910-120238-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260910-121238-audit/findings.json +794 -0
- package/.torusguard/runs/run-20260910-121238-audit/findings.md +344 -0
- package/.torusguard/runs/run-20260910-121238-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260910-121238-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260910-130454-audit/findings.json +893 -0
- package/.torusguard/runs/run-20260910-130454-audit/findings.md +386 -0
- package/.torusguard/runs/run-20260910-130454-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260910-130454-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260910-130519-audit/findings.json +563 -0
- package/.torusguard/runs/run-20260910-130519-audit/findings.md +246 -0
- package/.torusguard/runs/run-20260910-130519-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260910-130519-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-214110-audit/findings.json +1256 -0
- package/.torusguard/runs/run-20260912-214110-audit/findings.md +534 -0
- package/.torusguard/runs/run-20260912-214110-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260912-214110-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-214813-audit/findings.json +992 -0
- package/.torusguard/runs/run-20260912-214813-audit/findings.md +422 -0
- package/.torusguard/runs/run-20260912-214813-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260912-214813-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-auth-003-49-7c96f3/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-auth-003-49-7c96f3/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-auth-003-49-7c96f3/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-input-003-53-d167b4/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-input-003-53-d167b4/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-input-003-53-d167b4/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-platform-001-12-cf8156/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-platform-001-12-cf8156/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-platform-001-12-cf8156/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-rate-001-26-affcfa/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-rate-001-26-affcfa/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-rate-001-26-affcfa/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-sec-001-9-e22e50/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-sec-001-9-e22e50/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-sec-001-9-e22e50/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-ssrf-004-9-9803ad/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-ssrf-004-9-9803ad/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215555-audit/bundles/bnd-tg-ssrf-004-9-9803ad/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215555-audit/findings.json +530 -0
- package/.torusguard/runs/run-20260912-215555-audit/findings.md +232 -0
- package/.torusguard/runs/run-20260912-215555-audit/manifest.json +13 -0
- package/.torusguard/runs/run-20260912-215555-audit/remediation.md +102 -0
- package/.torusguard/runs/run-20260912-215555-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-215731-audit/apply_plan.md +6 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-client-001-7-587129/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-client-001-7-587129/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-client-001-7-587129/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-db-002-9-5f7850/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-db-002-9-5f7850/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-db-002-9-5f7850/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-001-27-2486f1/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-001-27-2486f1/minimal_patch_plan.md +22 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-001-27-2486f1/patch.diff +10 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-003-53-d167b4/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-003-53-d167b4/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-input-003-53-d167b4/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-001-12-cf8156/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-001-12-cf8156/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-001-12-cf8156/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-17-876973/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-17-876973/minimal_patch_plan.md +23 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-17-876973/patch.diff +11 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-5-40c794/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-5-40c794/minimal_patch_plan.md +23 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-platform-002-5-40c794/patch.diff +11 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-001-26-affcfa/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-001-26-affcfa/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-001-26-affcfa/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-002-54-0b38d2/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-002-54-0b38d2/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-rate-002-54-0b38d2/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-18-a3c1e8/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-18-a3c1e8/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-18-a3c1e8/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-9-e22e50/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-9-e22e50/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-001-9-e22e50/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-28-a1a0a1/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-28-a1a0a1/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-28-a1a0a1/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-30-00569e/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-30-00569e/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-sec-004-30-00569e/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-ssrf-004-9-9803ad/metadata.json +17 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-ssrf-004-9-9803ad/minimal_patch_plan.md +21 -0
- package/.torusguard/runs/run-20260912-215731-audit/bundles/bnd-tg-ssrf-004-9-9803ad/patch.diff +9 -0
- package/.torusguard/runs/run-20260912-215731-audit/diff_summary.md +186 -0
- package/.torusguard/runs/run-20260912-215731-audit/findings.json +497 -0
- package/.torusguard/runs/run-20260912-215731-audit/findings.md +218 -0
- package/.torusguard/runs/run-20260912-215731-audit/manifest.json +14 -0
- package/.torusguard/runs/run-20260912-215731-audit/recheck.md +76 -0
- package/.torusguard/runs/run-20260912-215731-audit/remediation.md +234 -0
- package/.torusguard/runs/run-20260912-215731-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-220134-audit/findings.json +68 -0
- package/.torusguard/runs/run-20260912-220134-audit/findings.md +36 -0
- package/.torusguard/runs/run-20260912-220134-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260912-220134-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-220200-audit/findings.json +1 -0
- package/.torusguard/runs/run-20260912-220200-audit/findings.md +8 -0
- package/.torusguard/runs/run-20260912-220200-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260912-220200-audit/recheck.md +6 -0
- package/.torusguard/runs/run-20260912-220200-audit/summary.md +5 -0
- package/.torusguard/runs/run-20260912-220227-audit/findings.json +1 -0
- package/.torusguard/runs/run-20260912-220227-audit/findings.md +8 -0
- package/.torusguard/runs/run-20260912-220227-audit/manifest.json +12 -0
- package/.torusguard/runs/run-20260912-220227-audit/recheck.md +6 -0
- package/.torusguard/runs/run-20260912-220227-audit/summary.md +5 -0
- package/.torusguard/scripts/__pycache__/audit_runner.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/diff_guard.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/finding_scorer.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/html_reporter.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/report_sync.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/rules_sync.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/stack_detect.cpython-311.pyc +0 -0
- package/.torusguard/scripts/__pycache__/term_ui.cpython-311.pyc +0 -0
- package/.torusguard/scripts/apply_runner.py +383 -339
- package/.torusguard/scripts/audit_runner.py +1306 -550
- package/.torusguard/scripts/finding_scorer.py +14 -2
- package/.torusguard/scripts/harden_runner.py +628 -375
- package/.torusguard/scripts/recheck_runner.py +248 -221
- package/.torusguard/scripts/recipes_runner.py +137 -130
- package/.torusguard/scripts/report_sync.py +423 -0
- package/.torusguard/scripts/sarif_exporter.py +116 -116
- package/.torusguard/scripts/term_ui.py +162 -0
- package/.torusguard/skills/torusguard/SKILL.md +61 -31
- package/.torusguard/skills/torusguard-apply/SKILL.md +80 -46
- package/.torusguard/skills/torusguard-audit/SKILL.md +83 -70
- package/.torusguard/skills/torusguard-authorize/SKILL.md +5 -4
- package/.torusguard/skills/torusguard-exploit-check/SKILL.md +6 -5
- package/.torusguard/skills/torusguard-full/SKILL.md +1 -1
- package/.torusguard/skills/torusguard-harden/SKILL.md +94 -63
- package/.torusguard/skills/torusguard-init/SKILL.md +64 -52
- package/.torusguard/skills/torusguard-recheck/SKILL.md +77 -53
- package/.torusguard/skills/torusguard-report/SKILL.md +72 -54
- package/.torusguard/skills/torusguard-status/SKILL.md +58 -42
- package/.torusguard/skills/torusguard-verify/SKILL.md +8 -7
- package/.torusguard/skills/torusguard-web-validate/SKILL.md +8 -7
- package/.torusguard/snapshots/run-20260912-215731-audit/demo/playground/vulnerable_nextjs/actions.ts.bak +24 -0
- package/.torusguard/snapshots/run-20260912-215731-audit/examples/hardened-react-express/server/index.js.bak +121 -0
- package/.torusguard/snapshots/run-20260912-215731-audit/examples/python/fastapi-vuln/main.py.bak +20 -0
- package/.torusguard/snapshots/run-20260912-215731-audit/examples/vulnerable-react-express/client/src/App.jsx.bak +63 -0
- package/.torusguard/snapshots/run-20260912-215731-audit/examples/vulnerable-react-express/client/vite.config.js.bak +12 -0
- package/.torusguard/snapshots/run-20260912-215731-audit/examples/vulnerable-react-express/server/index.js.bak +82 -0
- package/.torusguard/workflows/apply.md +11 -4
- package/.torusguard/workflows/audit.md +7 -1
- package/.torusguard/workflows/authorize.md +2 -1
- package/.torusguard/workflows/exploit-check.md +2 -1
- package/.torusguard/workflows/harden.md +7 -1
- package/.torusguard/workflows/init.md +6 -1
- package/.torusguard/workflows/memory.md +2 -1
- package/.torusguard/workflows/recheck.md +7 -1
- package/.torusguard/workflows/report.md +7 -1
- package/.torusguard/workflows/status.md +6 -1
- package/.torusguard/workflows/verify.md +6 -1
- package/.torusguard/workflows/web-validate.md +2 -1
- package/README.md +470 -344
- package/bin/torusguard.js +209 -97
- package/package.json +1 -1
- package/skills/torusguard/SKILL.md +73 -42
- package/skills/torusguard/payload/.manifest.json +66 -63
- package/skills/torusguard/payload/rules/business-logic/TG-BIZ-001-client-controlled-sensitive-business-value.md +30 -14
- package/skills/torusguard/payload/rules/business-logic/TG-BIZ-002-replayable-one-time-operation.md +33 -16
- package/skills/torusguard/payload/rules/business-logic/TG-BIZ-003-missing-workflow-state-validation.md +31 -15
- package/skills/torusguard/payload/rules/business-logic/TG-BIZ-004-unrestricted-sensitive-business-flow.md +26 -16
- package/skills/torusguard/payload/rules/cache/TG-CACHE-001-sensitive-response-publicly-cacheable.md +24 -16
- package/skills/torusguard/payload/rules/cache/TG-CACHE-002-missing-user-cache-isolation.md +32 -18
- package/skills/torusguard/payload/rules/cache/TG-CACHE-003-sensitive-data-in-url.md +24 -17
- package/skills/torusguard/payload/rules/csrf/TG-CSRF-001-missing-csrf-protection.md +31 -18
- package/skills/torusguard/payload/rules/csrf/TG-CSRF-002-unsafe-credentialed-cross-origin-request.md +28 -17
- package/skills/torusguard/payload/rules/graphql/TG-GQL-002-resolver-missing-authorization.md +33 -17
- package/skills/torusguard/payload/rules/graphql/TG-GQL-003-unbounded-graphql-pagination-or-batching.md +31 -16
- package/skills/torusguard/payload/rules/graphql/TG-GQL-004-unnecessary-production-introspection.md +25 -16
- package/skills/torusguard/payload/rules/secrets/TG-SEC-005-secret-in-git-history.md +24 -19
- package/skills/torusguard/payload/rules/secrets/TG-SEC-006-secret-in-build-artifact.md +36 -19
- package/skills/torusguard/payload/rules/secrets/TG-SEC-007-secret-in-test-or-example-fixture.md +21 -16
- package/skills/torusguard/payload/rules/ssrf/TG-SSRF-002-missing-internal-network-protection.md +45 -18
- package/skills/torusguard/payload/rules/ssrf/TG-SSRF-003-unsafe-redirect-following.md +20 -16
- package/skills/torusguard/payload/rules/ssrf/TG-SSRF-004-unbounded-outbound-request.md +28 -19
- package/skills/torusguard/payload/rules/supply-chain/TG-SUPPLY-001-missing-or-ignored-dependency-lockfile.md +25 -18
- package/skills/torusguard/payload/rules/supply-chain/TG-SUPPLY-003-unsafe-ci-cd-secret-exposure.md +29 -19
- package/skills/torusguard/payload/rules/supply-chain/TG-SUPPLY-004-unpinned-ci-action.md +23 -18
- package/skills/torusguard/payload/rules/supply-chain/TG-SUPPLY-005-unsafe-dependency-install-script.md +23 -18
- package/skills/torusguard/payload/rules/webhook/TG-WEBHOOK-001-missing-webhook-signature-verification.md +36 -16
- package/skills/torusguard/payload/rules/webhook/TG-WEBHOOK-002-replayable-webhook.md +26 -17
- package/skills/torusguard/payload/rules/webhook/TG-WEBHOOK-003-missing-webhook-idempotency.md +30 -16
- package/skills/torusguard/payload/rules/webhook/TG-WEBHOOK-004-unvalidated-webhook-event-type.md +25 -16
- package/skills/torusguard/payload/rules/websocket/TG-WS-002-missing-channel-level-authorization.md +28 -17
- package/skills/torusguard/payload/rules/websocket/TG-WS-003-unvalidated-websocket-message.md +31 -17
- package/skills/torusguard/payload/rules/websocket/TG-WS-004-unbounded-websocket-connections.md +31 -17
- package/skills/torusguard/payload/rules_catalog.json +520 -0
- package/skills/torusguard/payload/scripts/apply_runner.py +383 -339
- package/skills/torusguard/payload/scripts/audit_runner.py +1306 -550
- package/skills/torusguard/payload/scripts/finding_scorer.py +14 -2
- package/skills/torusguard/payload/scripts/harden_runner.py +628 -375
- package/skills/torusguard/payload/scripts/recheck_runner.py +248 -221
- package/skills/torusguard/payload/scripts/recipes_runner.py +137 -130
- package/skills/torusguard/payload/scripts/report_sync.py +423 -0
- package/skills/torusguard/payload/scripts/sarif_exporter.py +116 -116
- package/skills/torusguard/payload/scripts/term_ui.py +162 -0
- package/skills/torusguard/payload/skills/torusguard/SKILL.md +75 -42
- package/skills/torusguard/payload/skills/torusguard-apply/SKILL.md +63 -25
- package/skills/torusguard/payload/skills/torusguard-audit/SKILL.md +62 -45
- package/skills/torusguard/payload/skills/torusguard-authorize/SKILL.md +11 -5
- package/skills/torusguard/payload/skills/torusguard-exploit-check/SKILL.md +12 -6
- package/skills/torusguard/payload/skills/torusguard-full/SKILL.md +7 -2
- package/skills/torusguard/payload/skills/torusguard-harden/SKILL.md +71 -36
- package/skills/torusguard/payload/skills/torusguard-init/SKILL.md +45 -29
- package/skills/torusguard/payload/skills/torusguard-recheck/SKILL.md +59 -31
- package/skills/torusguard/payload/skills/torusguard-report/SKILL.md +52 -30
- package/skills/torusguard/payload/skills/torusguard-status/SKILL.md +40 -20
- package/skills/torusguard/payload/skills/torusguard-verify/SKILL.md +14 -8
- package/skills/torusguard/payload/skills/torusguard-web-validate/SKILL.md +14 -8
- package/skills/torusguard/payload/workflows/apply.md +11 -4
- package/skills/torusguard/payload/workflows/audit.md +7 -1
- package/skills/torusguard/payload/workflows/authorize.md +2 -1
- package/skills/torusguard/payload/workflows/exploit-check.md +2 -1
- package/skills/torusguard/payload/workflows/harden.md +7 -1
- package/skills/torusguard/payload/workflows/init.md +6 -1
- package/skills/torusguard/payload/workflows/memory.md +2 -1
- package/skills/torusguard/payload/workflows/recheck.md +7 -1
- package/skills/torusguard/payload/workflows/report.md +7 -1
- package/skills/torusguard/payload/workflows/status.md +6 -1
- package/skills/torusguard/payload/workflows/verify.md +6 -1
- package/skills/torusguard/payload/workflows/web-validate.md +2 -1
- package/skills/torusguard-apply/SKILL.md +63 -27
- package/skills/torusguard-audit/SKILL.md +62 -50
- package/skills/torusguard-authorize/SKILL.md +7 -2
- package/skills/torusguard-exploit-check/SKILL.md +7 -2
- package/skills/torusguard-full/SKILL.md +7 -2
- package/skills/torusguard-harden/SKILL.md +71 -40
- package/skills/torusguard-init/SKILL.md +45 -30
- package/skills/torusguard-recheck/SKILL.md +59 -32
- package/skills/torusguard-report/SKILL.md +52 -31
- package/skills/torusguard-status/SKILL.md +40 -21
- package/skills/torusguard-verify/SKILL.md +7 -2
- package/skills/torusguard-web-validate/SKILL.md +7 -2
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-input-002-107-516a40
|
|
2
|
+
- **Rule ID:** `TG-INPUT-002`
|
|
3
|
+
- **Target File:** `harness/validate_v1_1_0_advanced_memory.py:107`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/harness/validate_v1_1_0_advanced_memory.py
|
|
12
|
+
+++ b/harness/validate_v1_1_0_advanced_memory.py
|
|
13
|
+
@@ -105,5 +105,5 @@
|
|
14
|
+
memory_engine.ensure_memory_structure(root_dir=test_root)
|
|
15
|
+
|
|
16
|
+
- valid_before = "cursor.execute(f'SELECT * FROM users WHERE id = {uid}')"
|
|
17
|
+
+ valid_before = "cursor.execute('SELECT * FROM users WHERE id = %s')"
|
|
18
|
+
valid_after = "cursor.execute('SELECT * FROM users WHERE id = %s', (uid,))"
|
|
19
|
+
valid_diff = "- cursor.execute(f'SELECT * FROM users WHERE id = {uid}')\n+ cursor.execute('SELECT * FROM users WHERE id = %s', (uid,))"
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/harness/validate_v1_1_0_advanced_memory.py
|
|
2
|
+
+++ b/harness/validate_v1_1_0_advanced_memory.py
|
|
3
|
+
@@ -105,5 +105,5 @@
|
|
4
|
+
memory_engine.ensure_memory_structure(root_dir=test_root)
|
|
5
|
+
|
|
6
|
+
- valid_before = "cursor.execute(f'SELECT * FROM users WHERE id = {uid}')"
|
|
7
|
+
+ valid_before = "cursor.execute('SELECT * FROM users WHERE id = %s')"
|
|
8
|
+
valid_after = "cursor.execute('SELECT * FROM users WHERE id = %s', (uid,))"
|
|
9
|
+
valid_diff = "- cursor.execute(f'SELECT * FROM users WHERE id = {uid}')\n+ cursor.execute('SELECT * FROM users WHERE id = %s', (uid,))"
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/metadata.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bundle_id": "bnd-tg-input-002-128-7809a1",
|
|
3
|
+
"finding_id": "TG-INPUT-002-02f8e274",
|
|
4
|
+
"rule_id": "TG-INPUT-002",
|
|
5
|
+
"title": "Unescaped Raw SQL Query Concatenation",
|
|
6
|
+
"target_file": "harness/engine/fixture_manager.py",
|
|
7
|
+
"line_number": 128,
|
|
8
|
+
"what_is_wrong": "Python f-string interpolation in raw SQL query",
|
|
9
|
+
"why_it_matters": "Security vulnerability violating TorusGuard strict production safety invariant.",
|
|
10
|
+
"what_should_change": "Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder",
|
|
11
|
+
"proposed_diff": "--- a/harness/engine/fixture_manager.py\n+++ b/harness/engine/fixture_manager.py\n@@ -126,5 +126,5 @@\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/sqlalchemy-vuln\",\n- code_pattern=\"session.execute(f'SELECT * FROM items WHERE name LIKE {q}')\",\n+ code_pattern=\"session.execute('SELECT * FROM items WHERE name LIKE %s')\",\n expected_findings_count=4,\n ),\n",
|
|
12
|
+
"additions": 1,
|
|
13
|
+
"deletions": 1,
|
|
14
|
+
"patched_content": "\"\"\"\nTorusGuard Fixture Manager (v0.5.3)\nLoads, indexes, and validates structured fixture definitions and paired differential targets for Python web applications.\n\"\"\"\n\nfrom pathlib import Path\nfrom typing import List, Dict, Optional\nfrom .models import FixtureDefinition, FixtureVariant, ValidationOutcome\n\n\nclass FixtureManager:\n \"\"\"\n Manages the catalog of validation fixtures, paired differential applications, and regression test suites.\n \"\"\"\n\n def __init__(self, root_dir: str = \".\"):\n self.root_dir = Path(root_dir).resolve()\n self.fixtures: Dict[str, FixtureDefinition] = {}\n self._load_standard_fixtures()\n\n def _load_standard_fixtures(self):\n # 1. Django Reference Pair (IDOR & Settings Exposure)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-django-idor-scoping\",\n framework=\"django\",\n scenario=\"Django ViewSet object-level authorization & settings DEBUG exposure\",\n target_rule_id=\"TG-AUTH-007\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/django-vuln\",\n code_pattern=\"Invoice.objects.all()\",\n expected_findings_count=6,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/django-hardened\",\n code_pattern=\"Invoice.objects.filter(owner=request.user)\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"python manage.py test\",\n expected_diff_summary=\"DEBUG set to False; ALLOWED_HOSTS populated; get_queryset scoped to request.user.\",\n )\n )\n\n # 2. DRF Reference Pair (Mass Assignment & Throttling)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-drf-mass-assignment-throttle\",\n framework=\"drf\",\n scenario=\"DRF Serializer field protection, rate throttling, and pagination caps\",\n target_rule_id=\"TG-AUTH-006\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/drf-vuln\",\n code_pattern=\"fields = '__all__'\",\n expected_findings_count=5,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/drf-hardened\",\n code_pattern=\"read_only_fields = ('role', 'is_staff')\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest\",\n expected_diff_summary=\"read_only_fields explicit; ScopedRateThrottle attached; max_page_size set.\",\n )\n )\n\n # 3. FastAPI Reference Pair (SSRF & Pydantic Boundaries)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-fastapi-ssrf-pydantic\",\n framework=\"fastapi\",\n scenario=\"FastAPI outbound SSRF URL validation and Pydantic v2 extra field forbidding\",\n target_rule_id=\"TG-SSRF-001\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/fastapi-vuln\",\n code_pattern=\"httpx.get(target_url)\",\n expected_findings_count=5,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/fastapi-hardened\",\n code_pattern=\"validate_outbound_destination(url)\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest\",\n expected_diff_summary=\"IP destination validation filtering RFC 1918 blocks; Pydantic extra='forbid'.\",\n )\n )\n\n # 4. Flask Reference Pair (CSRF, Upload Sanitization, Session Cookies)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-flask-csrf-upload\",\n framework=\"flask\",\n scenario=\"Flask CSRFProtect, secure cookie flags, and upload filename sanitization\",\n target_rule_id=\"TG-CSRF-001\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/flask-vuln\",\n code_pattern=\"file.save(os.path.join(UPLOAD_DIR, file.filename))\",\n expected_findings_count=5,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/flask-hardened\",\n code_pattern=\"secure_filename(file.filename)\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest\",\n expected_diff_summary=\"CSRFProtect(app) enabled; SESSION_COOKIE_SECURE=True; secure_filename with UUID prefix.\",\n )\n )\n\n # 5. SQLAlchemy Reference Pair (Parameterized Queries & Bound Parameters)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-sqlalchemy-bound-parameters\",\n framework=\"sqlalchemy\",\n scenario=\"SQLAlchemy named text(:param) bindings and tenant query scoping\",\n target_rule_id=\"TG-INPUT-002\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/sqlalchemy-vuln\",\n code_pattern=\"session.execute('SELECT * FROM items WHERE name LIKE %s')\",\n expected_findings_count=4,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/sqlalchemy-hardened\",\n code_pattern=\"session.execute(text('SELECT * FROM items WHERE name LIKE :q'), {'q': f'%{q}%'})\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest\",\n expected_diff_summary=\"Parameterized text(:param) queries; tenant_id enforced on query filters.\",\n )\n )\n\n # 6. FastAPI Header Role Injection Pair (v0.5.3 TG-AUTH-008)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-fastapi-header-role-injection\",\n framework=\"fastapi\",\n scenario=\"FastAPI unverified client header role trust vs cryptographically signed token dependencies\",\n target_rule_id=\"TG-AUTH-008\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/fastapi-vuln\",\n code_pattern=\"x_user_role: str = Header(None)\",\n expected_findings_count=1,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/fastapi-hardened\",\n code_pattern=\"roles: list[str] = Depends(get_current_user_roles)\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest tests/test_auth_headers.py\",\n expected_diff_summary=\"Extract roles from verified JWT claims rather than raw HTTP headers.\",\n )\n )\n\n # 7. Flask Unsafe Template Rendering (v0.5.3 TG-INPUT-005)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-flask-unsafe-template-rendering\",\n framework=\"flask\",\n scenario=\"Flask render_template_string concatenation vs autoescaped render_template context\",\n target_rule_id=\"TG-INPUT-005\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/flask-vuln\",\n code_pattern=\"render_template_string(f'<h1>Hello {name}</h1>')\",\n expected_findings_count=1,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/flask-hardened\",\n code_pattern=\"render_template('greet.html', name=name)\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest tests/test_ssti.py\",\n expected_diff_summary=\"Pass input as template context variable avoiding SSTI.\",\n )\n )\n\n # 8. SQLAlchemy Multi-Tenant Query Isolation (v0.5.3 TG-DB-004)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-sqlalchemy-multi-tenant-isolation\",\n framework=\"sqlalchemy\",\n scenario=\"Multi-tenant item lookups with mandatory tenant_id filter enforcement\",\n target_rule_id=\"TG-DB-004\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/sqlalchemy-vuln\",\n code_pattern=\"session.query(Item).filter(Item.id == item_id).first()\",\n expected_findings_count=1,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/sqlalchemy-hardened\",\n code_pattern=\"session.query(Item).filter(Item.id == item_id, Item.tenant_id == tenant_id).first()\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest tests/test_tenant_isolation.py\",\n expected_diff_summary=\"Enforce Item.tenant_id == user.tenant_id on every item lookup query.\",\n )\n )\n\n # 9. Django Tenant Header & Invoice IDOR Pair (TG-AUTH-008 + TG-DB-004)\n self.register_fixture(\n FixtureDefinition(\n fixture_id=\"TG-FIX-django-tenant-header-invoice-idor\",\n framework=\"django\",\n scenario=\"Django client-controlled X-Tenant-ID header trust combined with unscoped Invoice.objects.get()\",\n target_rule_id=\"TG-AUTH-008\",\n expected_outcome=ValidationOutcome.VULNERABLE_CONFIRMED,\n vulnerable_variant=FixtureVariant(\n relative_path=\"examples/python/django-vuln\",\n code_pattern=\"tenant_id = request.headers.get('X-Tenant-ID')\\nrecord = Invoice.objects.get(id=invoice_id)\",\n expected_findings_count=2,\n ),\n hardened_variant=FixtureVariant(\n relative_path=\"examples/python/django-hardened\",\n code_pattern=\"tenant_id = request.user.tenant_id\\nrecord = Invoice.objects.filter(id=invoice_id, tenant_id=tenant_id).first()\",\n expected_findings_count=0,\n is_hardened=True,\n ),\n reproduction_command=\"pytest tests/test_invoice_tenant.py\",\n expected_diff_summary=\"Derive tenant from authenticated request.user.tenant_id and scope Invoice lookup by tenant_id.\",\n )\n )\n\n def register_fixture(self, fixture: FixtureDefinition):\n self.fixtures[fixture.fixture_id] = fixture\n\n def get_fixture(self, fixture_id: str) -> Optional[FixtureDefinition]:\n return self.fixtures.get(fixture_id)\n\n def list_fixtures(self) -> List[FixtureDefinition]:\n return list(self.fixtures.values())"
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-input-002-128-7809a1
|
|
2
|
+
- **Rule ID:** `TG-INPUT-002`
|
|
3
|
+
- **Target File:** `harness/engine/fixture_manager.py:128`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/harness/engine/fixture_manager.py
|
|
12
|
+
+++ b/harness/engine/fixture_manager.py
|
|
13
|
+
@@ -126,5 +126,5 @@
|
|
14
|
+
vulnerable_variant=FixtureVariant(
|
|
15
|
+
relative_path="examples/python/sqlalchemy-vuln",
|
|
16
|
+
- code_pattern="session.execute(f'SELECT * FROM items WHERE name LIKE {q}')",
|
|
17
|
+
+ code_pattern="session.execute('SELECT * FROM items WHERE name LIKE %s')",
|
|
18
|
+
expected_findings_count=4,
|
|
19
|
+
),
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/harness/engine/fixture_manager.py
|
|
2
|
+
+++ b/harness/engine/fixture_manager.py
|
|
3
|
+
@@ -126,5 +126,5 @@
|
|
4
|
+
vulnerable_variant=FixtureVariant(
|
|
5
|
+
relative_path="examples/python/sqlalchemy-vuln",
|
|
6
|
+
- code_pattern="session.execute(f'SELECT * FROM items WHERE name LIKE {q}')",
|
|
7
|
+
+ code_pattern="session.execute('SELECT * FROM items WHERE name LIKE %s')",
|
|
8
|
+
expected_findings_count=4,
|
|
9
|
+
),
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/metadata.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bundle_id": "bnd-tg-input-002-256-c8a22e",
|
|
3
|
+
"finding_id": "TG-INPUT-002-30b66221",
|
|
4
|
+
"rule_id": "TG-INPUT-002",
|
|
5
|
+
"title": "Unescaped Raw SQL Query Concatenation",
|
|
6
|
+
"target_file": "harness/runner.py",
|
|
7
|
+
"line_number": 256,
|
|
8
|
+
"what_is_wrong": "Python f-string interpolation in raw SQL query",
|
|
9
|
+
"why_it_matters": "Security vulnerability violating TorusGuard strict production safety invariant.",
|
|
10
|
+
"what_should_change": "Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder",
|
|
11
|
+
"proposed_diff": "--- a/harness/runner.py\n+++ b/harness/runner.py\n@@ -254,5 +254,5 @@\n framework_pattern=FrameworkPattern(\n framework=\"Django\",\n- unsafe_snippet=\"User.objects.raw(f'SELECT * FROM users WHERE name = {name}')\",\n+ unsafe_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s')\",\n safe_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s', [name])\",\n ),\n",
|
|
12
|
+
"additions": 1,
|
|
13
|
+
"deletions": 1,
|
|
14
|
+
"patched_content": "\"\"\"\nTorusGuard Validation Harness & Engine Runner (v0.5.4)\nExecutes comprehensive validation engine cycles: deterministic replay, differential comparison, regression tracking, and schema validation.\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport glob\nimport shutil\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple, Any\n\n# Add project root to sys.path\nPROJECT_ROOT = Path(__file__).resolve().parent.parent\nsys.path.insert(0, str(PROJECT_ROOT))\n\nfrom core.models import (\n Finding,\n Evidence,\n Remediation,\n FrameworkPattern,\n AffectedComponent,\n ReproductionMethod,\n RetestRecord,\n NotesRecord,\n FindingTimestamps,\n ProvenanceChain,\n ConfidenceScore,\n ConfidenceFactors,\n ConfidenceBand,\n SeverityLevel,\n SeverityInfo,\n RemediationPriority,\n FindingStatus,\n LifecycleStage,\n TaxonomyCategory,\n EvidenceType,\n AuditReport,\n mask_sensitive_data,\n)\nfrom core.lifecycle import FindingLifecycleManager, LifecycleTransitionError\nfrom core.formatter import ReportFormatter\n\nfrom harness.engine.models import (\n ValidationOutcome,\n FixtureDefinition,\n FixtureVariant,\n ReplayResult,\n ComparisonResult,\n RegressionRecord,\n ValidationRunReport,\n)\nfrom harness.engine.fixture_manager import FixtureManager\nfrom harness.engine.replay_runner import ReplayRunner\nfrom harness.engine.comparator import ResultComparator\nfrom harness.engine.regression_tracker import RegressionTracker\nfrom harness.engine.fp_analyzer import FalsePositiveAnalyzer\nfrom harness.engine.evidence_collector import ValidationEvidenceCollector\nfrom harness.engine.report_emitter import ValidationReportEmitter\n\nfrom core.run_folder import RunFolder\n\n\nclass ValidationHarnessRunner:\n def __init__(self, root_dir: str = \".\"):\n self.root_dir = Path(root_dir).resolve()\n self.passed_tests = 0\n self.failed_tests = 0\n self.results: List[Dict[str, Any]] = []\n\n def log_test(self, test_name: str, passed: bool, message: str = \"\"):\n if passed:\n self.passed_tests += 1\n print(f\" [PASS] {test_name}\")\n else:\n self.failed_tests += 1\n print(f\" [FAIL] {test_name}: {message}\")\n self.results.append({\"name\": test_name, \"passed\": passed, \"message\": message})\n\n def run_all(self) -> bool:\n print(\"=\" * 80)\n print(\"TORUSGUARD v0.5.4 REPORTING USABILITY & VALIDATION HARNESS\")\n print(\"=\" * 80)\n\n self.test_schema_integrity()\n self.test_rule_catalog()\n self.test_skill_definition()\n self.test_confidence_scoring_model()\n self.test_provenance_and_evidence_hashing()\n self.test_sensitive_data_masking()\n self.test_retest_lifecycle_closure()\n self.test_validation_engine_subsystem()\n self.test_stack_detection_fixtures()\n self.test_educational_differential_fixtures()\n self.test_regression_fixtures()\n self.test_report_formatting()\n self.test_run_context_and_ponytail()\n self.test_v6_governed_remediation_suite()\n\n print(\"-\" * 80)\n print(f\"SUMMARY: {self.passed_tests} Passed | {self.failed_tests} Failed\")\n print(\"=\" * 80)\n return self.failed_tests == 0\n\n def test_schema_integrity(self):\n print(\"\\n1. Testing Formal Schema Integrity (v0.5.4)...\")\n schemas_dir = self.root_dir / \"schemas\"\n required_schemas = [\n \"finding.schema.json\",\n \"evidence.schema.json\",\n \"remediation.schema.json\",\n \"rule.schema.json\",\n \"lifecycle.schema.json\",\n \"provenance.schema.json\",\n \"confidence.schema.json\",\n \"retest.schema.json\",\n \"fixture.schema.json\",\n \"validation-run.schema.json\",\n ]\n for s in required_schemas:\n schema_path = schemas_dir / s\n if not schema_path.exists():\n self.log_test(f\"Schema file exists: {s}\", False, \"File missing\")\n continue\n try:\n with open(schema_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n valid = \"$schema\" in data and \"title\" in data\n self.log_test(f\"Schema valid JSON: {s}\", valid, \"Missing $schema or title\")\n except Exception as e:\n self.log_test(f\"Schema valid JSON: {s}\", False, str(e))\n\n def test_rule_catalog(self):\n print(\"\\n2. Testing Rule Catalog & ID Uniqueness...\")\n rules_dir = self.root_dir / \"rules\"\n rule_files = list(rules_dir.glob(\"**/*.md\"))\n rule_ids = {}\n\n for rf in rule_files:\n if rf.name == \"README.md\":\n continue\n with open(rf, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n match = re.search(r\"^(TG-[A-Z0-9]+-[0-9]{3})\", rf.name)\n if not match:\n match = re.search(r\"#\\s+(TG-[A-Z0-9]+-[0-9]{3})\", content)\n\n if match:\n rid = match.group(1)\n if rid in rule_ids:\n self.log_test(f\"Rule ID unique: {rid}\", False, f\"Duplicate found in {rf.name} and {rule_ids[rid]}\")\n else:\n rule_ids[rid] = rf.name\n else:\n self.log_test(f\"Rule ID parseable in {rf.name}\", False, \"No valid TG-* rule ID found in header\")\n\n self.log_test(f\"Total Rules Cataloged ({len(rule_ids)})\", len(rule_ids) >= 64, f\"Found {len(rule_ids)} rules\")\n\n def test_skill_definition(self):\n print(\"\\n3. Testing Skill Definition & References...\")\n skill_file = self.root_dir / \"skills\" / \"TorusGuard\" / \"SKILL.md\"\n if not skill_file.exists():\n self.log_test(\"SKILL.md exists\", False, \"Missing skills/TorusGuard/SKILL.md\")\n return\n\n with open(skill_file, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n has_frontmatter = content.startswith(\"---\") and \"name: torusguard\" in content\n self.log_test(\"SKILL.md YAML Frontmatter\", has_frontmatter)\n\n has_commands = all(cmd in content for cmd in [\"/torusguard init\", \"/torusguard audit\", \"/torusguard harden\", \"/torusguard apply\", \"/torusguard verify\", \"/torusguard recheck\"])\n self.log_test(\"SKILL.md Core Commands Documented (including apply & recheck)\", has_commands)\n\n refs_dir = self.root_dir / \"skills\" / \"TorusGuard\" / \"references\"\n ref_files = list(refs_dir.glob(\"*.md\"))\n self.log_test(f\"Skill Reference Modules ({len(ref_files)})\", len(ref_files) >= 7)\n\n def test_confidence_scoring_model(self):\n print(\"\\n4. Testing Auditable Confidence Scoring Model...\")\n c_confirmed = ConfidenceScore.calculate(\n evidence_quality=35,\n reproduction_success=25,\n independent_confirmations=15,\n environmental_clarity=15,\n manual_review_status=5,\n rationale=\"Direct AST match with deterministic reproduction.\",\n )\n self.log_test(\"Confidence calculation: Confirmed band (>= 90)\", c_confirmed.score == 95 and c_confirmed.band == ConfidenceBand.CONFIRMED)\n\n c_high = ConfidenceScore.calculate(\n evidence_quality=30,\n reproduction_success=20,\n independent_confirmations=10,\n environmental_clarity=15,\n manual_review_status=0,\n rationale=\"Strong static indicator without manual validation.\",\n )\n self.log_test(\"Confidence calculation: High Confidence band (70-89)\", c_high.score == 75 and c_high.band == ConfidenceBand.HIGH_CONFIDENCE)\n\n def test_provenance_and_evidence_hashing(self):\n print(\"\\n5. Testing Provenance Chain & SHA-256 Evidence Integrity...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"server/auth.py:42\",\n raw_snippet=\"SECRET_KEY = 'super_secret_jwt_key'\",\n rationale=\"Hardcoded secret credential.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n has_hash = bool(ev.sha256_checksum) and len(ev.sha256_checksum) == 64\n self.log_test(\"Evidence SHA-256 Checksum Computed\", has_hash)\n\n def test_sensitive_data_masking(self):\n print(\"\\n6. Testing Sensitive Secret & Token Masking...\")\n sample_secret = \"API_KEY = 'sk_live_998877665544332211'\"\n masked = mask_sensitive_data(sample_secret)\n self.log_test(\"Stripe Secret Key Redaction\", \"sk_live_***REDACTED***\" in masked and \"998877665544332211\" not in masked)\n\n sample_jwt = \"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.doNotLeakSignature\"\n masked_jwt = mask_sensitive_data(sample_jwt)\n self.log_test(\"JWT Token Redaction\", \"***REDACTED_JWT***\" in masked_jwt and \"doNotLeakSignature\" not in masked_jwt)\n\n def test_retest_lifecycle_closure(self):\n print(\"\\n7. Testing Retest Execution & Closure State Machine...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"views.py:15\",\n raw_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s')\",\n rationale=\"Direct string concatenation into SQL query.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n sev = SeverityInfo(\n level=SeverityLevel.CRITICAL,\n rationale=\"Allows arbitrary SQL execution and data exfiltration.\",\n rubric_justification=\"Critical because unauthenticated user input reaches raw SQL interpreter.\",\n )\n conf = ConfidenceScore.calculate(35, 25, 15, 15, 5, \"Direct AST concatenation match.\")\n prov = ProvenanceChain(\n discovery_module=\"rules/input/TG-INPUT-002-raw-sql-concatenation.md\",\n triggering_input=\"Raw SQL execution with f-string formatting\",\n evidence_collected=[\"views.py:15\"],\n decision_path=[\"Detected raw SQL method\", \"Verified unparameterized input\"],\n verification_step=\"Inspect query parameterization.\",\n )\n rem = Remediation(\n problem_statement=\"Raw SQL string concatenation vulnerable to SQL injection.\",\n risk_explanation=\"Attackers can inject malicious SQL payloads.\",\n recommended_fix=\"Use parameterized queries.\",\n framework_pattern=FrameworkPattern(\n framework=\"Django\",\n unsafe_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s')\",\n safe_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s', [name])\",\n ),\n verification_method=\"Test with quote payload and verify parameterized execution.\",\n residual_risk_notes=\"Ensure database permissions are restricted.\",\n )\n finding = Finding(\n rule_id=\"TG-INPUT-002\",\n title=\"Raw SQL Concatenation\",\n category=TaxonomyCategory.INPUT,\n severity=sev,\n confidence=conf,\n status=FindingStatus.CONFIRMED,\n affected_component=AffectedComponent(component_name=\"UserSearch\", target_path=\"views.py\", start_line=15),\n evidence=[ev],\n provenance=prov,\n reproduction_method=ReproductionMethod(step_by_step=[\"Pass ' OR '1'='1 into search endpoint\"], test_command=\"pytest tests/test_search.py\"),\n remediation=rem,\n asvs_control=\"V5.3.4\",\n cwe=\"CWE-89\",\n nist_ssdf=\"PW.5.1\",\n )\n\n FindingLifecycleManager.transition(finding, LifecycleStage.CLASSIFY)\n FindingLifecycleManager.transition(finding, LifecycleStage.VERIFY)\n FindingLifecycleManager.transition(finding, LifecycleStage.REMEDIATE)\n\n ok, msg = FindingLifecycleManager.execute_retest(\n finding,\n post_fix_code=\"User.objects.raw('SELECT * FROM users WHERE name = %s', [name])\",\n safe_pattern_verified=True,\n verifier_notes=\"Verified parameterized binding query.\",\n )\n self.log_test(\"Retest execution -> Verified Fixed\", ok and finding.status == FindingStatus.VERIFIED_FIXED)\n\n def test_validation_engine_subsystem(self):\n print(\"\\n8. Testing Validation Engine Subsystem (v0.5.4)...\")\n fm = FixtureManager(str(self.root_dir))\n fixtures = fm.list_fixtures()\n self.log_test(f\"Fixture Manager Catalog Loaded ({len(fixtures)} fixtures)\", len(fixtures) >= 8)\n\n rr = ReplayRunner(str(self.root_dir))\n comparator = ResultComparator(str(self.root_dir))\n comparison_results = []\n\n for f in fixtures:\n replay_res = rr.replay_fixture(f, passes=3)\n self.log_test(f\"Deterministic Replay (3 passes): {f.fixture_id}\", replay_res.deterministic)\n\n comp_res = comparator.compare_fixture(f, replay_deterministic=replay_res.deterministic)\n comparison_results.append(comp_res)\n self.log_test(f\"Differential Comparison ({comp_res.outcome.value}): {f.fixture_id}\", comp_res.diff_verified)\n\n # Regression tracker\n rt = RegressionTracker(str(self.root_dir))\n reg_records = rt.evaluate_all_regressions()\n all_clean = all(r.regression_status == \"Clean\" for r in reg_records)\n self.log_test(f\"Regression Tracker Verification ({len(reg_records)} baseline cases clean)\", all_clean)\n\n # FP Analyzer\n diagnostics = FalsePositiveAnalyzer.analyze_results(comparison_results)\n self.log_test(\"False Positive Analyzer Diagnostic Check (0 false alarms)\", len(diagnostics) == 0)\n\n # Evidence Collector & Report Emitter\n collector = ValidationEvidenceCollector(str(self.root_dir))\n env_snap = collector.capture_environment_snapshot()\n self.log_test(\"Validation Evidence Collector Environment Snapshot\", \"os\" in env_snap and \"python_version\" in env_snap)\n\n val_report = ValidationRunReport(\n environment=env_snap,\n fixture_results=comparison_results,\n regression_records=reg_records,\n )\n report_md = ValidationReportEmitter.render_markdown(val_report)\n self.log_test(\"Validation Report Emitter Markdown Rendering\", \"# TorusGuard Validation Engine\" in report_md and \"Execution Summary\" in report_md)\n\n def test_stack_detection_fixtures(self):\n print(\"\\n9. Testing Stack Detection Layouts...\")\n stack_dir = self.root_dir / \"tests\" / \"fixtures\" / \"python\" / \"stack-detection\"\n expected_stacks = [\n \"django\",\n \"django-drf\",\n \"fastapi\",\n \"flask\",\n \"flask-sqlalchemy\",\n \"python-library\",\n \"mixed-monorepo\",\n ]\n for s in expected_stacks:\n target = stack_dir / s\n exists = target.exists() and any(target.iterdir())\n self.log_test(f\"Stack layout fixture: {s}\", exists)\n\n def test_educational_differential_fixtures(self):\n print(\"\\n10. Testing Educational Differential Fixtures...\")\n pairs = [\n (\"examples/python/django-vuln\", \"examples/python/django-hardened\"),\n (\"examples/python/drf-vuln\", \"examples/python/drf-hardened\"),\n (\"examples/python/fastapi-vuln\", \"examples/python/fastapi-hardened\"),\n (\"examples/python/flask-vuln\", \"examples/python/flask-hardened\"),\n (\"examples/python/sqlalchemy-vuln\", \"examples/python/sqlalchemy-hardened\"),\n ]\n for vuln_rel, hard_rel in pairs:\n vuln_path = self.root_dir / vuln_rel\n hard_path = self.root_dir / hard_rel\n exists = vuln_path.exists() and hard_path.exists()\n has_fixes = (hard_path / \"fixes.md\").exists() or (vuln_path / \"README.md\").exists()\n self.log_test(f\"Paired differential fixture: {Path(vuln_rel).name}\", exists and has_fixes)\n\n def test_regression_fixtures(self):\n print(\"\\n11. Testing Python Regression Fixtures Suite...\")\n regression_dir = self.root_dir / \"tests\" / \"fixtures\" / \"python\"\n cases = [\n \"django/safe-service-layer-auth\",\n \"django/missing-owner-scope\",\n \"drf/safe-read-only-fields\",\n \"drf/unbounded-pagination\",\n \"fastapi/safe-pydantic-boundary\",\n \"fastapi/unsafe-outbound-url\",\n \"flask/csrf-enabled\",\n \"flask/unsafe-upload\",\n \"sqlalchemy/safe-bound-query\",\n \"sqlalchemy/missing-tenant-scope\",\n ]\n for c in cases:\n c_path = regression_dir / c\n exists = c_path.exists() and (c_path / \"README.md\").exists()\n self.log_test(f\"Regression fixture: {c}\", exists)\n\n def test_report_formatting(self):\n print(\"\\n12. Testing Canonical v0.5.4 9-Section Actionable Markdown Report...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"settings.py:10\",\n raw_snippet=\"DEBUG = True\\nSECRET_KEY = 'sk_live_secret_key_12345'\",\n rationale=\"Production debug mode exposure and hardcoded secret.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n sev = SeverityInfo(\n level=SeverityLevel.CRITICAL,\n rationale=\"Exposes internal stack traces and hardcoded production secret.\",\n rubric_justification=\"Critical because secret key enables session forgery and debug leaks internals.\",\n )\n conf = ConfidenceScore.calculate(35, 25, 15, 15, 5, \"Direct settings file check.\")\n prov = ProvenanceChain(\n discovery_module=\"rules/TG-PLATFORM-003-production-stack-trace-exposure.md\",\n triggering_input=\"DEBUG = True assignment in settings.py\",\n evidence_collected=[\"settings.py:10\"],\n decision_path=[\"Loaded Django settings\", \"Found DEBUG enabled\"],\n verification_step=\"Assert DEBUG is False.\",\n )\n rem = Remediation(\n problem_statement=\"Debug mode is enabled and hardcoded secret present.\",\n risk_explanation=\"Stack traces leak environment variables and secret allows token forgery.\",\n recommended_fix=\"Set DEBUG = False and load secret from environment.\",\n framework_pattern=FrameworkPattern(\n framework=\"Django\",\n unsafe_snippet=\"DEBUG = True\",\n safe_snippet=\"DEBUG = False\",\n ),\n verification_method=\"Assert DEBUG is False in production.\",\n residual_risk_notes=\"Ensure 500.html template exists.\",\n )\n f = Finding(\n rule_id=\"TG-PLATFORM-003\",\n title=\"Production Stack Trace Exposure\",\n category=TaxonomyCategory.CLIENT_PLATFORM,\n severity=sev,\n confidence=conf,\n status=FindingStatus.CONFIRMED,\n remediation_priority=RemediationPriority.IMMEDIATE,\n affected_component=AffectedComponent(component_name=\"Config\", target_path=\"settings.py\", start_line=10),\n evidence=[ev],\n provenance=prov,\n reproduction_method=ReproductionMethod(step_by_step=[\"Trigger 500 error and inspect response body\"]),\n remediation=rem,\n asvs_control=\"V14.4.1\",\n cwe=\"CWE-209\",\n nist_ssdf=\"PW.5.1\",\n )\n report = AuditReport(\n project_name=\"DemoApp\",\n detected_stack={\"language\": \"Python\", \"framework\": \"Django\", \"confidence\": \"Confirmed\"},\n findings=[f],\n )\n\n md_output = ReportFormatter.render_markdown(report)\n has_header = \"# TorusGuard Security Audit & Remediation Report\" in md_output\n has_exec_summary = \"## 1. \ud83d\udccb Executive Summary\" in md_output\n has_scope = \"## 2. \ud83d\udd0d Scope and Methodology\" in md_output\n has_summary_table = \"## 3. \ud83d\udcd1 Key Findings Summary Table\" in md_output\n has_detailed = \"## 4. \ud83d\udee1\ufe0f Detailed Findings\" in md_output\n has_business_context = \"\ud83c\udfe2 Business Impact & Executive Context\" in md_output\n has_remediation_roadmap = \"## 5. \ud83c\udfaf Remediation Priorities & Triage Roadmap\" in md_output\n has_ticket_payload = \"\ud83c\udfab Copy-Paste Issue Tracker Payload\" in md_output\n has_redaction = \"sk_live_***REDACTED***\" in md_output\n\n self.log_test(\n \"Render v0.5.4 9-Section Actionable Report\",\n has_header and has_exec_summary and has_scope and has_summary_table and has_detailed and has_business_context and has_remediation_roadmap and has_ticket_payload and has_redaction\n )\n\n def test_run_context_and_ponytail(self):\n print(\"\\n13. Testing v0.5.5 RunFolder Structure...\")\n import shutil\n test_root = self.root_dir / \".torusguard\" / \"runs_test\"\n if test_root.exists():\n shutil.rmtree(test_root)\n \n rf = RunFolder(output_root=str(test_root), run_name=\"test-run-001\")\n \n # Test directory initialization\n has_dirs = rf.run_path.exists() and rf.patches_dir.exists() and rf.logs_dir.exists()\n \n # Test metadata file initialization\n has_metadata = rf.metadata_file.exists()\n if has_metadata:\n with open(rf.metadata_file, \"r\", encoding=\"utf-8\") as f:\n metadata = json.load(f)\n has_metadata = metadata.get(\"run_id\") == \"test-run-001\"\n \n self.log_test(\"RunFolder Initialization\", has_dirs and has_metadata)\n \n # Cleanup\n shutil.rmtree(test_root)\n\n def test_v6_governed_remediation_suite(self):\n print(\"\\n14. Testing TorusGuard v0.6.0 Governed Remediation & Targeted Recheck Engine...\")\n import tempfile\n from core.identity import IdentityEngine\n from core.clustering import ClusteringEngine\n from core.bundle import BundleManager\n from core.governance import PatchGovernor\n from core.rechecker import TargetedRechecker, RecheckOutcome\n from core.run_manager import RunManager\n from core.sarif import SarifExporter\n from core.v6_workflow import V6Workflow\n\n temp_dir = Path(tempfile.mkdtemp(prefix=\"tg-v0-6-harness-\"))\n try:\n # 1. Run Folder\n rm = RunManager(base_dir=temp_dir, target_name=\"test-target\", command=\"audit\", run_id=\"run-harness-01\")\n rm.write_manifest(status_counts={\"total_findings\": 1, \"confirmed\": 1, \"high_confidence\": 0, \"needs_review\": 0, \"remediated\": 0, \"verified_fixed\": 0, \"regressed\": 0})\n self.log_test(\"v0.6.0 RunFolder & Manifest.json Generation\", rm.manifest_file.exists() and rm.patches_dir.exists())\n\n # 2. Stable Finding Identity\n code_a = \"def view():\\n return Item.objects.get(id=id)\"\n code_b = \"# Shifted comment\\ndef view():\\n return Item.objects.get(id=id)\"\n fp1 = IdentityEngine.generate_identity(\"TG-DB-004\", \"views.py\", code_a, sink_signature=\"Item.objects.get\")\n fp2 = IdentityEngine.generate_identity(\"TG-DB-004\", \"views.py\", code_b, sink_signature=\"Item.objects.get\")\n self.log_test(\"v0.6.0 Stable Finding Identity (Line Shift Invariance)\", fp1.fingerprint_id == fp2.fingerprint_id and fp1.fingerprint_id.startswith(\"TG-DB-\"))\n\n # 3. Root-Cause Clustering\n raw_f = [\n {\"finding_id\": \"f1\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"severity\": \"High\", \"target\": {\"file_path\": \"a.py\"}},\n {\"finding_id\": \"f2\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"severity\": \"High\", \"target\": {\"file_path\": \"b.py\"}},\n ]\n clusters = ClusteringEngine.cluster_findings(raw_f)\n self.log_test(\"v0.6.0 Root-Cause Clustering (Multi-Tenant Pattern)\", len(clusters) == 1 and clusters[0].cluster_id == \"cluster-tenant-isolation\")\n\n # 4. Remediation Bundle\n bundle = BundleManager.create_bundle(raw_f[0], cluster_id=\"cluster-tenant-isolation\")\n b_dir = bundle.write_to_directory(temp_dir)\n self.log_test(\"v0.6.0 Remediation Bundle Packaging (5 Artifacts)\", (b_dir / \"finding.md\").exists() and (b_dir / \"minimal_patch_plan.md\").exists())\n\n # 5. Patch Governance\n gov = PatchGovernor(max_additions_per_file=10)\n clean_diff = \"--- a/x.py\\n+++ b/x.py\\n@@ -1 +1 @@\\n-old()\\n+new()\\n\"\n oversized_diff = \"--- a/x.py\\n+++ b/x.py\\n\" + \"\\n\".join(f\"+line_{i}()\" for i in range(20))\n d_clean = gov.evaluate_diff(clean_diff, \"x.py\")\n d_over = gov.evaluate_diff(oversized_diff, \"x.py\")\n self.log_test(\"v0.6.0 Minimal Patch Governance (Line Churn Policy)\", d_clean.allowed_auto_apply and not d_over.allowed_auto_apply)\n\n # 6. Targeted Recheck\n r_fix = TargetedRechecker.verify_finding(\"f1\", \"TG-DB-004\", \"a.py\", \"old\", \"new\", is_safe_pattern_present=True, is_unsafe_pattern_present=False)\n r_reg = TargetedRechecker.verify_finding(\"f2\", \"TG-DB-004\", \"b.py\", \"old\", \"bad\", is_safe_pattern_present=False, is_unsafe_pattern_present=True, introduced_new_flaws=[\"TG-SEC-001\"])\n self.log_test(\"v0.6.0 Targeted Recheck Transitions (Confirmed Fixed & Regressed)\", r_fix.outcome == RecheckOutcome.CONFIRMED_FIXED and r_reg.outcome == RecheckOutcome.REGRESSED)\n\n # 7. SARIF Export\n sarif = SarifExporter.generate_sarif([{\"finding_id\": \"f1\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"target\": {\"file_path\": \"a.py\"}}])\n self.log_test(\"v0.6.0 SARIF v2.1.0 Structured Export\", sarif[\"version\"] == \"2.1.0\" and len(sarif[\"runs\"]) == 1)\n\n # 8. End-to-End Workflow\n wf = V6Workflow(target_root=temp_dir, output_base=temp_dir / \"runs\")\n run_wf = wf.execute_audit(raw_f, target_name=\"e2e-demo\", export_sarif=True)\n self.log_test(\"v0.6.0 End-to-End Workflow Execution\", run_wf.manifest_file.exists() and run_wf.sarif_file.exists())\n\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n\n\nif __name__ == \"__main__\":\n runner = ValidationHarnessRunner()\n success = runner.run_all()\n sys.exit(0 if success else 1)"
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-input-002-256-c8a22e
|
|
2
|
+
- **Rule ID:** `TG-INPUT-002`
|
|
3
|
+
- **Target File:** `harness/runner.py:256`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/harness/runner.py
|
|
12
|
+
+++ b/harness/runner.py
|
|
13
|
+
@@ -254,5 +254,5 @@
|
|
14
|
+
framework_pattern=FrameworkPattern(
|
|
15
|
+
framework="Django",
|
|
16
|
+
- unsafe_snippet="User.objects.raw(f'SELECT * FROM users WHERE name = {name}')",
|
|
17
|
+
+ unsafe_snippet="User.objects.raw('SELECT * FROM users WHERE name = %s')",
|
|
18
|
+
safe_snippet="User.objects.raw('SELECT * FROM users WHERE name = %s', [name])",
|
|
19
|
+
),
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/harness/runner.py
|
|
2
|
+
+++ b/harness/runner.py
|
|
3
|
+
@@ -254,5 +254,5 @@
|
|
4
|
+
framework_pattern=FrameworkPattern(
|
|
5
|
+
framework="Django",
|
|
6
|
+
- unsafe_snippet="User.objects.raw(f'SELECT * FROM users WHERE name = {name}')",
|
|
7
|
+
+ unsafe_snippet="User.objects.raw('SELECT * FROM users WHERE name = %s')",
|
|
8
|
+
safe_snippet="User.objects.raw('SELECT * FROM users WHERE name = %s', [name])",
|
|
9
|
+
),
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/metadata.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bundle_id": "bnd-tg-input-003-53-d167b4",
|
|
3
|
+
"finding_id": "TG-INPUT-003-fea9421e",
|
|
4
|
+
"rule_id": "TG-INPUT-003",
|
|
5
|
+
"title": "Unsafe Dynamic Code or HTML Execution",
|
|
6
|
+
"target_file": "examples/vulnerable-react-express/client/src/App.jsx",
|
|
7
|
+
"line_number": 53,
|
|
8
|
+
"what_is_wrong": "React dangerouslySetInnerHTML rendering raw unescaped HTML",
|
|
9
|
+
"why_it_matters": "Security vulnerability violating TorusGuard strict production safety invariant.",
|
|
10
|
+
"what_should_change": "Replaced raw dangerouslySetInnerHTML injection with safe React text interpolation",
|
|
11
|
+
"proposed_diff": "--- a/examples/vulnerable-react-express/client/src/App.jsx\n+++ b/examples/vulnerable-react-express/client/src/App.jsx\n@@ -51,5 +51,5 @@\n \n {/* TG-INPUT-003: Unsafe HTML rendering */}\n- <div dangerouslySetInnerHTML={{ __html: bio }} />\n+ <div>{bio}</div>\n \n <button onClick={fetchUser}>Fetch user (IDOR demo)</button>\n",
|
|
12
|
+
"additions": 1,
|
|
13
|
+
"deletions": 1,
|
|
14
|
+
"patched_content": "import { useState } from 'react';\nimport { clientConfig } from './config';\n\n// TG-DB-001: SQL query construction in frontend (never do this)\nfunction buildSearchQuery(email) {\n return `SELECT id, email FROM users WHERE email LIKE '%${email}%'`;\n}\n\n// TG-DB-003: Documented anti-pattern \u2014 Prisma must never run in browser\n// import { PrismaClient } from '@prisma/client'; // FORBIDDEN in client\n\nexport default function App() {\n const [email, setEmail] = useState('');\n const [password, setPassword] = useState('');\n const [bio, setBio] = useState('<img src=x onerror=alert(1)>');\n const [userId, setUserId] = useState('1');\n const [isAdmin] = useState(localStorage.getItem('role') === 'admin'); // TG-AUTH-002\n const [message, setMessage] = useState('');\n\n async function login(e) {\n e.preventDefault();\n const res = await fetch('/api/login', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ email, password }),\n });\n const data = await res.json();\n // TG-CLIENT-002: Sensitive console logging\n console.log('Login token:', data.token, 'config:', clientConfig);\n setMessage(JSON.stringify(data));\n }\n\n async function fetchUser() {\n const res = await fetch(`/api/users/${userId}`);\n setMessage(await res.text());\n }\n\n return (\n <div style={{ maxWidth: 560, margin: '2rem auto', fontFamily: 'sans-serif' }}>\n <h1>Vulnerable Demo</h1>\n <p style={{ color: 'crimson' }}>Intentionally insecure \u2014 localhost lab only</p>\n\n <form onSubmit={login}>\n <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder=\"email\" />\n <input value={password} onChange={(e) => setPassword(e.target.value)} placeholder=\"password\" type=\"password\" />\n <button type=\"submit\">Login</button>\n </form>\n\n <p>Frontend SQL preview: {buildSearchQuery(email)}</p>\n\n {/* TG-INPUT-003: Unsafe HTML rendering */}\n <div>{bio}</div>\n\n <button onClick={fetchUser}>Fetch user (IDOR demo)</button>\n\n {/* TG-AUTH-002: Client-only admin gate */}\n {isAdmin && <section><h2>Admin Panel</h2><p>Visible if localStorage role=admin \u2014 not real security</p></section>}\n\n {message && <pre>{message}</pre>}\n </div>\n );\n}"
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-input-003-53-d167b4
|
|
2
|
+
- **Rule ID:** `TG-INPUT-003`
|
|
3
|
+
- **Target File:** `examples/vulnerable-react-express/client/src/App.jsx:53`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced raw dangerouslySetInnerHTML injection with safe React text interpolation
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/examples/vulnerable-react-express/client/src/App.jsx
|
|
12
|
+
+++ b/examples/vulnerable-react-express/client/src/App.jsx
|
|
13
|
+
@@ -51,5 +51,5 @@
|
|
14
|
+
|
|
15
|
+
{/* TG-INPUT-003: Unsafe HTML rendering */}
|
|
16
|
+
- <div dangerouslySetInnerHTML={{ __html: bio }} />
|
|
17
|
+
+ <div>{bio}</div>
|
|
18
|
+
|
|
19
|
+
<button onClick={fetchUser}>Fetch user (IDOR demo)</button>
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/examples/vulnerable-react-express/client/src/App.jsx
|
|
2
|
+
+++ b/examples/vulnerable-react-express/client/src/App.jsx
|
|
3
|
+
@@ -51,5 +51,5 @@
|
|
4
|
+
|
|
5
|
+
{/* TG-INPUT-003: Unsafe HTML rendering */}
|
|
6
|
+
- <div dangerouslySetInnerHTML={{ __html: bio }} />
|
|
7
|
+
+ <div>{bio}</div>
|
|
8
|
+
|
|
9
|
+
<button onClick={fetchUser}>Fetch user (IDOR demo)</button>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bundle_id": "bnd-tg-platform-001-183-47fd5e",
|
|
3
|
+
"finding_id": "TG-PLATFORM-001-ed5dae35",
|
|
4
|
+
"rule_id": "TG-PLATFORM-001",
|
|
5
|
+
"title": "Wildcard Permissive CORS Configuration with Credentials",
|
|
6
|
+
"target_file": "skills/torusguard/payload/scripts/harden_runner.py",
|
|
7
|
+
"line_number": 183,
|
|
8
|
+
"what_is_wrong": "Wildcard CORS origin enabled across entire application",
|
|
9
|
+
"why_it_matters": "Security vulnerability violating TorusGuard strict production safety invariant.",
|
|
10
|
+
"what_should_change": "Replaced wildcard CORS configuration with strict origin whitelist environment variable",
|
|
11
|
+
"proposed_diff": "--- a/skills/torusguard/payload/scripts/harden_runner.py\n+++ b/skills/torusguard/payload/scripts/harden_runner.py\n@@ -181,5 +181,5 @@\n # Strategy 5: Permissive CORS with Credentials (TG-PLATFORM-001)\n elif rule_id == \"TG-PLATFORM-001\":\n- if \"CORS_ALLOW_ALL_ORIGINS = True\" in target_line:\n+ CORS_ALLOWED_ORIGINS = [os.environ.get(\"ALLOWED_ORIGIN\", \"https://app.example.com\")]\n replacement = f'{indent}CORS_ALLOWED_ORIGINS = [os.environ.get(\"ALLOWED_ORIGIN\", \"https://app.example.com\")]'\n new_lines[line_number - 1] = replacement\n",
|
|
12
|
+
"additions": 1,
|
|
13
|
+
"deletions": 1,
|
|
14
|
+
"patched_content": "#!/usr/bin/env python3\n\"\"\"\nTorusGuard Autonomous Remediation Engine (v1.3.0)\nEvaluates audit findings against canonical patch templates, enforces Ponytail bounds\n(<= 35 additions, <= 25 deletions), packages structured candidate remediation bundles,\nand renders unified patch diffs.\n\nPure Python 3.10+ standard library (zero external dependencies).\n\"\"\"\n\nimport sys\nimport os\nimport re\nimport json\nimport difflib\nimport hashlib\nimport argparse\nimport datetime\nimport unicodedata\nfrom pathlib import Path\nfrom typing import Dict, List, Any, Optional, Tuple\n\n# Windows console UTF-8 support\nif sys.stdout and hasattr(sys.stdout, \"reconfigure\"):\n try:\n getattr(sys.stdout, \"reconfigure\")(encoding=\"utf-8\", errors=\"replace\")\n except Exception:\n pass\n\n# \u2500\u2500\u2500 Timezone Configuration: Indian Standard Time (IST, UTC+05:30) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nIST = datetime.timezone(datetime.timedelta(hours=5, minutes=30), name=\"IST\")\n\ndef get_ist_now() -> datetime.datetime:\n return datetime.datetime.now(IST)\n\n# \u2500\u2500\u2500 ANSI Colors & Formatter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nBOLD = \"\\033[1m\"\nDIM = \"\\033[2m\"\nRESET = \"\\033[0m\"\nCYAN = \"\\033[36m\"\nGREEN = \"\\033[32m\"\nYELLOW = \"\\033[33m\"\nWHITE = \"\\033[97m\"\nGRAY = \"\\033[90m\"\nRED = \"\\033[31m\"\n\nANSI_REGEX = re.compile(r'\\033\\[[0-9;]*m')\n\ndef get_visual_width(text: str) -> int:\n clean = ANSI_REGEX.sub('', text)\n width = 0\n for ch in clean:\n ea = unicodedata.east_asian_width(ch)\n if ea in ('W', 'F'):\n width += 2\n elif ord(ch) >= 0x1F300:\n width += 2\n else:\n width += 1\n return width\n\ndef format_box_line(content: str, width: int = 71, border: str = \"\u2502\", border_color: str = CYAN) -> str:\n vis = get_visual_width(content)\n pad = \" \" * max(0, width - vis)\n return f\" {border_color}{border}{RESET} {content}{pad}{border_color}{border}{RESET}\"\n\n\ndef find_latest_audit_run(runs_dir: Path) -> Optional[Path]:\n \"\"\"Locate the most recent audit run folder containing findings.json.\"\"\"\n if not runs_dir.is_dir():\n return None\n runs = sorted(runs_dir.glob(\"run-*-audit\"), key=lambda p: p.stat().st_mtime, reverse=True)\n for r in runs:\n if (r / \"findings.json\").is_file():\n return r\n return None\n\n\ndef generate_patch_for_finding(finding: Dict[str, Any], target_root: Path) -> Optional[Dict[str, Any]]:\n \"\"\"\n Formulate a minimal, surgical fix for a finding adhering to Ponytail bounds\n (<= 35 additions, <= 25 deletions).\n \"\"\"\n rule_id = finding.get(\"rule_id\", \"\")\n file_path = finding.get(\"file_path\", \"\")\n line_number = finding.get(\"line_number\", 1)\n description = finding.get(\"description\", \"\")\n\n full_target = target_root / file_path\n if not full_target.is_file():\n return None\n\n try:\n content = full_target.read_text(encoding=\"utf-8\", errors=\"replace\")\n except Exception:\n return None\n\n lines = content.splitlines()\n if not (1 <= line_number <= len(lines)):\n return None\n\n target_line = lines[line_number - 1]\n indent = re.match(r'^\\s*', target_line).group(0) # type: ignore\n new_lines = list(lines)\n applied_rule = False\n fix_explanation = \"\"\n\n # Strategy 1: Hardcoded Secrets (TG-SEC-001 / TG-SEC-002)\n if rule_id in (\"TG-SEC-001\", \"TG-SEC-002\"):\n if file_path.endswith((\".js\", \".jsx\", \".ts\", \".tsx\", \".mjs\")):\n # const secret = \"...\" -> const secret = process.env.JWT_SECRET || \"...\";\n if re.search(r'(jwt_secret|jwtSecret|JWT_SECRET)', target_line, re.IGNORECASE):\n replacement = f'{indent}const secret = process.env.JWT_SECRET || \"\";'\n new_lines[line_number - 1] = replacement\n applied_rule = True\n fix_explanation = \"Migrated hardcoded JWT secret to environment variable process.env.JWT_SECRET\"\n elif re.search(r'(:=|=)\\s*[\"\\'][A-Za-z0-9_\\-]{8,}[\"\\']', target_line):\n var_match = re.search(r'(const|let|var)?\\s*([A-Za-z0-9_]+)\\s*[:=]', target_line)\n var_name = var_match.group(2) if var_match else \"API_KEY\"\n env_key = re.sub(r'(?<!^)(?=[A-Z])', '_', var_name).upper()\n replacement = f'{indent}const {var_name} = process.env.{env_key} || \"\";'\n new_lines[line_number - 1] = replacement\n applied_rule = True\n fix_explanation = f\"Replaced hardcoded credential with process.env.{env_key}\"\n elif file_path.endswith(\".py\"):\n if re.search(r'(:=|=)\\s*[\"\\'][A-Za-z0-9_\\-]{8,}[\"\\']', target_line):\n var_match = re.search(r'([A-Za-z0-9_]+)\\s*=', target_line)\n var_name = var_match.group(1) if var_match else \"SECRET_KEY\"\n env_key = var_name.upper()\n replacement = f'{indent}{var_name} = os.environ.get(\"{env_key}\", \"\")'\n new_lines[line_number - 1] = replacement\n applied_rule = True\n fix_explanation = f\"Replaced hardcoded credential with os.environ.get('{env_key}')\"\n\n # Strategy 2: Dangerous React HTML rendering & DOM innerHTML (TG-INPUT-003)\n elif rule_id == \"TG-INPUT-003\":\n if \"dangerouslySetInnerHTML\" in target_line:\n # <div dangerouslySetInnerHTML={{ __html: bio }} /> -> <div>{bio}</div>\n var_match = re.search(r'__html\\s*:\\s*([A-Za-z0-9_]+)', target_line)\n var_name = var_match.group(1) if var_match else \"content\"\n replacement = f'{indent}<div>{{{var_name}}}</div>'\n new_lines[line_number - 1] = replacement\n applied_rule = True\n fix_explanation = \"Replaced raw dangerouslySetInnerHTML injection with safe React text interpolation\"\n elif \".innerHTML\" in target_line:\n # Pattern A: el.innerHTML = '' or \"\" -> el.textContent = \"\"\n if re.search(r'\\.innerHTML\\s*=\\s*[\"\\'][\"\\']', target_line):\n fixed_line = re.sub(r'([a-zA-Z0-9_$]+)\\.innerHTML\\s*=\\s*[\"\\'][\"\\']', r'\\1.textContent = \"\"', target_line)\n if fixed_line != target_line:\n new_lines[line_number - 1] = fixed_line\n applied_rule = True\n fix_explanation = \"Replaced unsafe innerHTML DOM reset with safe textContent assignment\"\n # Pattern B: el.innerHTML = someVar -> el.textContent = someVar\n elif re.search(r'([a-zA-Z0-9_$]+)\\.innerHTML\\s*=\\s*([a-zA-Z0-9_$.]+)\\s*;?$', target_line):\n fixed_line = re.sub(r'([a-zA-Z0-9_$]+)\\.innerHTML\\s*=\\s*([a-zA-Z0-9_$.]+)', r'\\1.textContent = \\2', target_line)\n if fixed_line != target_line:\n new_lines[line_number - 1] = fixed_line\n applied_rule = True\n fix_explanation = \"Replaced raw DOM innerHTML assignment with XSS-safe textContent\"\n\n # Strategy 3: Raw SQL Concatenation (TG-INPUT-002)\n elif rule_id == \"TG-INPUT-002\":\n if file_path.endswith(\".py\") and (\"f\\\"SELECT\" in target_line or \"f'SELECT\" in target_line):\n # Replace f-string injection with parameterized query\n fixed_line = re.sub(r'f([\"\\']SELECT.*?WHERE.*?)(\\{[^}]+\\})', r'\\1%s', target_line)\n if fixed_line != target_line:\n new_lines[line_number - 1] = fixed_line\n applied_rule = True\n fix_explanation = \"Replaced unsafe Python SQL f-string interpolation with parameterized SQL query placeholder\"\n\n # Strategy 4: Multi-Tenant Query Scoping (TG-DB-004)\n elif rule_id == \"TG-DB-004\":\n if \".objects.get(\" in target_line and \"tenant\" not in target_line.lower() and \"org\" not in target_line.lower():\n # .objects.get(id=...) -> .objects.get(id=..., organization_id=request.user.organization_id)\n fixed_line = target_line.replace(\".objects.get(\", \".objects.get(organization_id=request.user.organization_id, \")\n if fixed_line != target_line:\n new_lines[line_number - 1] = fixed_line\n applied_rule = True\n fix_explanation = \"Added explicit organization_id tenant boundary filter to ORM query\"\n\n # Strategy 5: Permissive CORS with Credentials (TG-PLATFORM-001)\n elif rule_id == \"TG-PLATFORM-001\":\n CORS_ALLOWED_ORIGINS = [os.environ.get(\"ALLOWED_ORIGIN\", \"https://app.example.com\")]\n replacement = f'{indent}CORS_ALLOWED_ORIGINS = [os.environ.get(\"ALLOWED_ORIGIN\", \"https://app.example.com\")]'\n new_lines[line_number - 1] = replacement\n applied_rule = True\n fix_explanation = \"Replaced wildcard CORS configuration with strict origin whitelist environment variable\"\n\n if not applied_rule:\n return None\n\n # Calculate unified diff\n orig_lines = [l + \"\\n\" for l in lines]\n patched_lines = [l + \"\\n\" for l in new_lines]\n diff = \"\".join(difflib.unified_diff(\n orig_lines, patched_lines,\n fromfile=f\"a/{file_path}\", tofile=f\"b/{file_path}\",\n n=2\n ))\n\n additions = sum(1 for l in diff.splitlines() if l.startswith(\"+\") and not l.startswith(\"+++\"))\n deletions = sum(1 for l in diff.splitlines() if l.startswith(\"-\") and not l.startswith(\"---\"))\n\n # Ponytail bounds validation\n if additions > 35 or deletions > 25:\n return None\n\n bundle_id = f\"bnd-{rule_id.lower()}-{line_number}-{hashlib.sha256(diff.encode('utf-8')).hexdigest()[:6]}\"\n\n return {\n \"bundle_id\": bundle_id,\n \"finding_id\": finding.get(\"finding_id\", f\"{rule_id}-{line_number}\"),\n \"rule_id\": rule_id,\n \"title\": finding.get(\"title\", rule_id),\n \"target_file\": file_path,\n \"line_number\": line_number,\n \"what_is_wrong\": description,\n \"why_it_matters\": \"Security vulnerability violating TorusGuard strict production safety invariant.\",\n \"what_should_change\": fix_explanation,\n \"proposed_diff\": diff,\n \"additions\": additions,\n \"deletions\": deletions,\n \"patched_content\": \"\\n\".join(new_lines)\n }\n\n\ndef execute_harden(target_root: Path, run_id_arg: Optional[str] = None) -> Dict[str, Any]:\n \"\"\"Execute autonomous remediation formulation and package candidate bundles.\"\"\"\n runs_dir = target_root / \".torusguard\" / \"runs\"\n if run_id_arg:\n run_folder = runs_dir / run_id_arg\n else:\n run_folder = find_latest_audit_run(runs_dir)\n\n if not run_folder or not run_folder.is_dir():\n print(f\"\\n {RED}\u2716 No audit runs found to harden.{RESET}\")\n print(f\" Run {CYAN}npx torusguard audit{RESET} first to discover actionable findings.\\n\")\n sys.exit(1)\n\n findings_file = run_folder / \"findings.json\"\n if not findings_file.is_file():\n print(f\"\\n {RED}\u2716 Missing findings.json in run folder:{RESET} {run_folder}\\n\")\n sys.exit(1)\n\n try:\n findings = json.loads(findings_file.read_text(encoding=\"utf-8\"))\n except Exception as e:\n print(f\"\\n {RED}\u2716 Failed to parse findings.json:{RESET} {e}\\n\")\n sys.exit(1)\n\n bundles_dir = run_folder / \"bundles\"\n bundles_dir.mkdir(parents=True, exist_ok=True)\n\n bundles = []\n for f in findings:\n candidate = generate_patch_for_finding(f, target_root)\n if candidate:\n bundles.append(candidate)\n b_dir = bundles_dir / candidate[\"bundle_id\"]\n b_dir.mkdir(parents=True, exist_ok=True)\n\n # 1. patch.diff\n (b_dir / \"patch.diff\").write_text(candidate[\"proposed_diff\"], encoding=\"utf-8\")\n\n # 2. minimal_patch_plan.md\n plan_content = [\n f\"# Remediation Plan: {candidate['bundle_id']}\",\n f\"- **Rule ID:** `{candidate['rule_id']}`\",\n f\"- **Target File:** `{candidate['target_file']}:{candidate['line_number']}`\",\n f\"- **Ponytail Churn:** `+{candidate['additions']} / -{candidate['deletions']}` (Compliant <=35/<=25)\",\n f\"\\n## Proposed Change\\n{candidate['what_should_change']}\\n\",\n \"## Unified Diff Preview\\n```diff\",\n candidate[\"proposed_diff\"],\n \"```\"\n ]\n (b_dir / \"minimal_patch_plan.md\").write_text(\"\\n\".join(plan_content), encoding=\"utf-8\")\n\n # 3. metadata.json\n with open(b_dir / \"metadata.json\", \"w\", encoding=\"utf-8\") as mf:\n json.dump(candidate, mf, indent=2)\n\n # Render run-level remediation.md\n remediation_lines = [\n f\"# TorusGuard Governed Remediation Catalog\",\n f\"**Run ID:** `{run_folder.name}` \",\n f\"**Generated:** `{get_ist_now().strftime('%Y-%m-%d %H:%M:%S IST')}` \",\n f\"**Candidate Bundles Formulated:** `{len(bundles)}` \\n\",\n \"---\",\n \"## Formulated Candidate Patches\\n\"\n ]\n\n for b in bundles:\n remediation_lines.append(f\"### [{b['rule_id']}] {b['title']}\")\n remediation_lines.append(f\"- **Target:** `{b['target_file']}:{b['line_number']}` | **Bundle ID:** `{b['bundle_id']}`\")\n remediation_lines.append(f\"- **Strategy:** {b['what_should_change']}\")\n remediation_lines.append(f\"- **Ponytail Churn:** `+{b['additions']} / -{b['deletions']}`\")\n remediation_lines.append(\"```diff\")\n remediation_lines.append(b[\"proposed_diff\"].strip())\n remediation_lines.append(\"```\\n\")\n\n (run_folder / \"remediation.md\").write_text(\"\\n\".join(remediation_lines), encoding=\"utf-8\")\n\n # Update manifest\n manifest_file = run_folder / \"manifest.json\"\n if manifest_file.is_file():\n try:\n mdata = json.loads(manifest_file.read_text(encoding=\"utf-8\"))\n mdata[\"remediation_bundles_count\"] = len(bundles)\n manifest_file.write_text(json.dumps(mdata, indent=2), encoding=\"utf-8\")\n except Exception:\n pass\n\n # Print 75-column Terminal Card\n print(f\"\\n {CYAN}\u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e{RESET}\")\n print(f\" {CYAN}\u2502 \u2502{RESET}\")\n print(format_box_line(f\"{BOLD}\ud83d\udee1\ufe0f TORUSGUARD GOVERNED REMEDIATION ENGINE v1.3.1{RESET}\", border_color=CYAN))\n print(format_box_line(f\"{DIM}Autonomous Minimal Patch Formulation & Ponytail Packaging{RESET}\", border_color=CYAN))\n print(f\" {CYAN}\u2502 \u2502{RESET}\")\n print(f\" {CYAN}\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f{RESET}\\n\")\n\n print(f\" {CYAN}\u250c\u2500 Remediation Scope \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510{RESET}\")\n print(format_box_line(f\"Active Run: {WHITE}{run_folder.name}{RESET}\"))\n print(format_box_line(f\"Target Scope: {WHITE}{target_root}{RESET}\"))\n print(format_box_line(f\"Total Findings: {len(findings)} evaluated | {GREEN}{len(bundles)} surgical patches formulated{RESET}\"))\n print(format_box_line(f\"Ponytail Guard: {GREEN}All patches strictly <= 35 additions, <= 25 deletions{RESET}\"))\n print(f\" {CYAN}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518{RESET}\\n\")\n\n if bundles:\n print(f\" {CYAN}\u250c\u2500 Formulated Candidate Patches ({len(bundles)}) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510{RESET}\")\n for b in bundles[:5]:\n print(format_box_line(f\"{YELLOW}[{b['rule_id']}]{RESET} {WHITE}{b['target_file']}:{b['line_number']}{RESET} (+{b['additions']}/-{b['deletions']})\"))\n print(format_box_line(f\" \u2514\u2500 {DIM}{b['what_should_change']}{RESET}\"))\n if len(bundles) > 5:\n print(format_box_line(f\" ... and {len(bundles) - 5} more patches cataloged in remediation.md\"))\n print(f\" {CYAN}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518{RESET}\\n\")\n\n print(f\" {GREEN}\u2554\u2550 Next Governed Action \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557{RESET}\")\n print(format_box_line(f\"Review & Apply: {BOLD}{WHITE}npx torusguard apply{RESET} (CLI Human Gate)\", border=\"\u2551\", border_color=GREEN))\n print(format_box_line(f\"Auto-Apply Flag: {CYAN}npx torusguard apply --yes{RESET} (Automated mode)\", border=\"\u2551\", border_color=GREEN))\n print(format_box_line(f\"AI IDE Chat: Run {CYAN}/torusguard-apply{RESET} in your AI chat\", border=\"\u2551\", border_color=GREEN))\n print(f\" {GREEN}\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d{RESET}\\n\")\n else:\n print(f\" {YELLOW}\u2139 No automatic patch templates matched current findings.{RESET}\")\n print(f\" {GRAY}Findings require architectural refactoring or AI-assisted guidance.{RESET}\\n\")\n print(f\" {CYAN}\u250c\u2500 Recommended Next Steps \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510{RESET}\")\n print(format_box_line(\"1. In AI Chat (Antigravity/Cursor/Claude): Run /torusguard-harden\"))\n print(format_box_line(\" to synthesize custom architectural fixes with your AI agent.\"))\n print(format_box_line(\"2. View visual posture report: npx torusguard report --html\"))\n print(format_box_line(f\"3. Inspect finding details: .torusguard/runs/{run_folder.name}/findings.md\"))\n print(f\" {CYAN}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518{RESET}\\n\")\n\n return {\n \"status\": \"success\",\n \"run_folder\": str(run_folder),\n \"bundles_count\": len(bundles),\n \"bundles\": bundles\n }\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"TorusGuard Autonomous Governed Remediation Engine\")\n parser.add_argument(\"path\", nargs=\"?\", default=\".\", help=\"Target project root directory\")\n parser.add_argument(\"--run\", \"-r\", help=\"Explicit run ID to harden (default: latest audit run)\")\n parser.add_argument(\"--json\", action=\"store_true\", help=\"Output raw JSON\")\n args = parser.parse_args()\n\n target = Path(args.path).resolve()\n result = execute_harden(target, run_id_arg=args.run)\n\n if args.json:\n print(json.dumps(result, indent=2))\n\n\nif __name__ == \"__main__\":\n main()"
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-platform-001-183-47fd5e
|
|
2
|
+
- **Rule ID:** `TG-PLATFORM-001`
|
|
3
|
+
- **Target File:** `skills/torusguard/payload/scripts/harden_runner.py:183`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced wildcard CORS configuration with strict origin whitelist environment variable
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/skills/torusguard/payload/scripts/harden_runner.py
|
|
12
|
+
+++ b/skills/torusguard/payload/scripts/harden_runner.py
|
|
13
|
+
@@ -181,5 +181,5 @@
|
|
14
|
+
# Strategy 5: Permissive CORS with Credentials (TG-PLATFORM-001)
|
|
15
|
+
elif rule_id == "TG-PLATFORM-001":
|
|
16
|
+
- if "CORS_ALLOW_ALL_ORIGINS = True" in target_line:
|
|
17
|
+
+ CORS_ALLOWED_ORIGINS = [os.environ.get("ALLOWED_ORIGIN", "https://app.example.com")]
|
|
18
|
+
replacement = f'{indent}CORS_ALLOWED_ORIGINS = [os.environ.get("ALLOWED_ORIGIN", "https://app.example.com")]'
|
|
19
|
+
new_lines[line_number - 1] = replacement
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/skills/torusguard/payload/scripts/harden_runner.py
|
|
2
|
+
+++ b/skills/torusguard/payload/scripts/harden_runner.py
|
|
3
|
+
@@ -181,5 +181,5 @@
|
|
4
|
+
# Strategy 5: Permissive CORS with Credentials (TG-PLATFORM-001)
|
|
5
|
+
elif rule_id == "TG-PLATFORM-001":
|
|
6
|
+
- if "CORS_ALLOW_ALL_ORIGINS = True" in target_line:
|
|
7
|
+
+ CORS_ALLOWED_ORIGINS = [os.environ.get("ALLOWED_ORIGIN", "https://app.example.com")]
|
|
8
|
+
replacement = f'{indent}CORS_ALLOWED_ORIGINS = [os.environ.get("ALLOWED_ORIGIN", "https://app.example.com")]'
|
|
9
|
+
new_lines[line_number - 1] = replacement
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/metadata.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bundle_id": "bnd-tg-sec-001-209-4f6424",
|
|
3
|
+
"finding_id": "TG-SEC-001-950e367b",
|
|
4
|
+
"rule_id": "TG-SEC-001",
|
|
5
|
+
"title": "Hardcoded Secret or API Key in Tracked Source",
|
|
6
|
+
"target_file": "harness/runner.py",
|
|
7
|
+
"line_number": 209,
|
|
8
|
+
"what_is_wrong": "Hardcoded credential or API secret string",
|
|
9
|
+
"why_it_matters": "Security vulnerability violating TorusGuard strict production safety invariant.",
|
|
10
|
+
"what_should_change": "Replaced hardcoded credential with os.environ.get('RAW_SNIPPET')",
|
|
11
|
+
"proposed_diff": "--- a/harness/runner.py\n+++ b/harness/runner.py\n@@ -207,5 +207,5 @@\n type=EvidenceType.SOURCE,\n location=\"server/auth.py:42\",\n- raw_snippet=\"SECRET_KEY = 'super_secret_jwt_key'\",\n+ raw_snippet = os.environ.get(\"RAW_SNIPPET\", \"\")\n rationale=\"Hardcoded secret credential.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n",
|
|
12
|
+
"additions": 1,
|
|
13
|
+
"deletions": 1,
|
|
14
|
+
"patched_content": "\"\"\"\nTorusGuard Validation Harness & Engine Runner (v0.5.4)\nExecutes comprehensive validation engine cycles: deterministic replay, differential comparison, regression tracking, and schema validation.\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport glob\nimport shutil\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple, Any\n\n# Add project root to sys.path\nPROJECT_ROOT = Path(__file__).resolve().parent.parent\nsys.path.insert(0, str(PROJECT_ROOT))\n\nfrom core.models import (\n Finding,\n Evidence,\n Remediation,\n FrameworkPattern,\n AffectedComponent,\n ReproductionMethod,\n RetestRecord,\n NotesRecord,\n FindingTimestamps,\n ProvenanceChain,\n ConfidenceScore,\n ConfidenceFactors,\n ConfidenceBand,\n SeverityLevel,\n SeverityInfo,\n RemediationPriority,\n FindingStatus,\n LifecycleStage,\n TaxonomyCategory,\n EvidenceType,\n AuditReport,\n mask_sensitive_data,\n)\nfrom core.lifecycle import FindingLifecycleManager, LifecycleTransitionError\nfrom core.formatter import ReportFormatter\n\nfrom harness.engine.models import (\n ValidationOutcome,\n FixtureDefinition,\n FixtureVariant,\n ReplayResult,\n ComparisonResult,\n RegressionRecord,\n ValidationRunReport,\n)\nfrom harness.engine.fixture_manager import FixtureManager\nfrom harness.engine.replay_runner import ReplayRunner\nfrom harness.engine.comparator import ResultComparator\nfrom harness.engine.regression_tracker import RegressionTracker\nfrom harness.engine.fp_analyzer import FalsePositiveAnalyzer\nfrom harness.engine.evidence_collector import ValidationEvidenceCollector\nfrom harness.engine.report_emitter import ValidationReportEmitter\n\nfrom core.run_folder import RunFolder\n\n\nclass ValidationHarnessRunner:\n def __init__(self, root_dir: str = \".\"):\n self.root_dir = Path(root_dir).resolve()\n self.passed_tests = 0\n self.failed_tests = 0\n self.results: List[Dict[str, Any]] = []\n\n def log_test(self, test_name: str, passed: bool, message: str = \"\"):\n if passed:\n self.passed_tests += 1\n print(f\" [PASS] {test_name}\")\n else:\n self.failed_tests += 1\n print(f\" [FAIL] {test_name}: {message}\")\n self.results.append({\"name\": test_name, \"passed\": passed, \"message\": message})\n\n def run_all(self) -> bool:\n print(\"=\" * 80)\n print(\"TORUSGUARD v0.5.4 REPORTING USABILITY & VALIDATION HARNESS\")\n print(\"=\" * 80)\n\n self.test_schema_integrity()\n self.test_rule_catalog()\n self.test_skill_definition()\n self.test_confidence_scoring_model()\n self.test_provenance_and_evidence_hashing()\n self.test_sensitive_data_masking()\n self.test_retest_lifecycle_closure()\n self.test_validation_engine_subsystem()\n self.test_stack_detection_fixtures()\n self.test_educational_differential_fixtures()\n self.test_regression_fixtures()\n self.test_report_formatting()\n self.test_run_context_and_ponytail()\n self.test_v6_governed_remediation_suite()\n\n print(\"-\" * 80)\n print(f\"SUMMARY: {self.passed_tests} Passed | {self.failed_tests} Failed\")\n print(\"=\" * 80)\n return self.failed_tests == 0\n\n def test_schema_integrity(self):\n print(\"\\n1. Testing Formal Schema Integrity (v0.5.4)...\")\n schemas_dir = self.root_dir / \"schemas\"\n required_schemas = [\n \"finding.schema.json\",\n \"evidence.schema.json\",\n \"remediation.schema.json\",\n \"rule.schema.json\",\n \"lifecycle.schema.json\",\n \"provenance.schema.json\",\n \"confidence.schema.json\",\n \"retest.schema.json\",\n \"fixture.schema.json\",\n \"validation-run.schema.json\",\n ]\n for s in required_schemas:\n schema_path = schemas_dir / s\n if not schema_path.exists():\n self.log_test(f\"Schema file exists: {s}\", False, \"File missing\")\n continue\n try:\n with open(schema_path, \"r\", encoding=\"utf-8\") as f:\n data = json.load(f)\n valid = \"$schema\" in data and \"title\" in data\n self.log_test(f\"Schema valid JSON: {s}\", valid, \"Missing $schema or title\")\n except Exception as e:\n self.log_test(f\"Schema valid JSON: {s}\", False, str(e))\n\n def test_rule_catalog(self):\n print(\"\\n2. Testing Rule Catalog & ID Uniqueness...\")\n rules_dir = self.root_dir / \"rules\"\n rule_files = list(rules_dir.glob(\"**/*.md\"))\n rule_ids = {}\n\n for rf in rule_files:\n if rf.name == \"README.md\":\n continue\n with open(rf, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n match = re.search(r\"^(TG-[A-Z0-9]+-[0-9]{3})\", rf.name)\n if not match:\n match = re.search(r\"#\\s+(TG-[A-Z0-9]+-[0-9]{3})\", content)\n\n if match:\n rid = match.group(1)\n if rid in rule_ids:\n self.log_test(f\"Rule ID unique: {rid}\", False, f\"Duplicate found in {rf.name} and {rule_ids[rid]}\")\n else:\n rule_ids[rid] = rf.name\n else:\n self.log_test(f\"Rule ID parseable in {rf.name}\", False, \"No valid TG-* rule ID found in header\")\n\n self.log_test(f\"Total Rules Cataloged ({len(rule_ids)})\", len(rule_ids) >= 64, f\"Found {len(rule_ids)} rules\")\n\n def test_skill_definition(self):\n print(\"\\n3. Testing Skill Definition & References...\")\n skill_file = self.root_dir / \"skills\" / \"TorusGuard\" / \"SKILL.md\"\n if not skill_file.exists():\n self.log_test(\"SKILL.md exists\", False, \"Missing skills/TorusGuard/SKILL.md\")\n return\n\n with open(skill_file, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n has_frontmatter = content.startswith(\"---\") and \"name: torusguard\" in content\n self.log_test(\"SKILL.md YAML Frontmatter\", has_frontmatter)\n\n has_commands = all(cmd in content for cmd in [\"/torusguard init\", \"/torusguard audit\", \"/torusguard harden\", \"/torusguard apply\", \"/torusguard verify\", \"/torusguard recheck\"])\n self.log_test(\"SKILL.md Core Commands Documented (including apply & recheck)\", has_commands)\n\n refs_dir = self.root_dir / \"skills\" / \"TorusGuard\" / \"references\"\n ref_files = list(refs_dir.glob(\"*.md\"))\n self.log_test(f\"Skill Reference Modules ({len(ref_files)})\", len(ref_files) >= 7)\n\n def test_confidence_scoring_model(self):\n print(\"\\n4. Testing Auditable Confidence Scoring Model...\")\n c_confirmed = ConfidenceScore.calculate(\n evidence_quality=35,\n reproduction_success=25,\n independent_confirmations=15,\n environmental_clarity=15,\n manual_review_status=5,\n rationale=\"Direct AST match with deterministic reproduction.\",\n )\n self.log_test(\"Confidence calculation: Confirmed band (>= 90)\", c_confirmed.score == 95 and c_confirmed.band == ConfidenceBand.CONFIRMED)\n\n c_high = ConfidenceScore.calculate(\n evidence_quality=30,\n reproduction_success=20,\n independent_confirmations=10,\n environmental_clarity=15,\n manual_review_status=0,\n rationale=\"Strong static indicator without manual validation.\",\n )\n self.log_test(\"Confidence calculation: High Confidence band (70-89)\", c_high.score == 75 and c_high.band == ConfidenceBand.HIGH_CONFIDENCE)\n\n def test_provenance_and_evidence_hashing(self):\n print(\"\\n5. Testing Provenance Chain & SHA-256 Evidence Integrity...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"server/auth.py:42\",\n raw_snippet = os.environ.get(\"RAW_SNIPPET\", \"\")\n rationale=\"Hardcoded secret credential.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n has_hash = bool(ev.sha256_checksum) and len(ev.sha256_checksum) == 64\n self.log_test(\"Evidence SHA-256 Checksum Computed\", has_hash)\n\n def test_sensitive_data_masking(self):\n print(\"\\n6. Testing Sensitive Secret & Token Masking...\")\n sample_secret = \"API_KEY = 'sk_live_998877665544332211'\"\n masked = mask_sensitive_data(sample_secret)\n self.log_test(\"Stripe Secret Key Redaction\", \"sk_live_***REDACTED***\" in masked and \"998877665544332211\" not in masked)\n\n sample_jwt = \"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.doNotLeakSignature\"\n masked_jwt = mask_sensitive_data(sample_jwt)\n self.log_test(\"JWT Token Redaction\", \"***REDACTED_JWT***\" in masked_jwt and \"doNotLeakSignature\" not in masked_jwt)\n\n def test_retest_lifecycle_closure(self):\n print(\"\\n7. Testing Retest Execution & Closure State Machine...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"views.py:15\",\n raw_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s')\",\n rationale=\"Direct string concatenation into SQL query.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n sev = SeverityInfo(\n level=SeverityLevel.CRITICAL,\n rationale=\"Allows arbitrary SQL execution and data exfiltration.\",\n rubric_justification=\"Critical because unauthenticated user input reaches raw SQL interpreter.\",\n )\n conf = ConfidenceScore.calculate(35, 25, 15, 15, 5, \"Direct AST concatenation match.\")\n prov = ProvenanceChain(\n discovery_module=\"rules/input/TG-INPUT-002-raw-sql-concatenation.md\",\n triggering_input=\"Raw SQL execution with f-string formatting\",\n evidence_collected=[\"views.py:15\"],\n decision_path=[\"Detected raw SQL method\", \"Verified unparameterized input\"],\n verification_step=\"Inspect query parameterization.\",\n )\n rem = Remediation(\n problem_statement=\"Raw SQL string concatenation vulnerable to SQL injection.\",\n risk_explanation=\"Attackers can inject malicious SQL payloads.\",\n recommended_fix=\"Use parameterized queries.\",\n framework_pattern=FrameworkPattern(\n framework=\"Django\",\n unsafe_snippet=\"User.objects.raw(f'SELECT * FROM users WHERE name = {name}')\",\n safe_snippet=\"User.objects.raw('SELECT * FROM users WHERE name = %s', [name])\",\n ),\n verification_method=\"Test with quote payload and verify parameterized execution.\",\n residual_risk_notes=\"Ensure database permissions are restricted.\",\n )\n finding = Finding(\n rule_id=\"TG-INPUT-002\",\n title=\"Raw SQL Concatenation\",\n category=TaxonomyCategory.INPUT,\n severity=sev,\n confidence=conf,\n status=FindingStatus.CONFIRMED,\n affected_component=AffectedComponent(component_name=\"UserSearch\", target_path=\"views.py\", start_line=15),\n evidence=[ev],\n provenance=prov,\n reproduction_method=ReproductionMethod(step_by_step=[\"Pass ' OR '1'='1 into search endpoint\"], test_command=\"pytest tests/test_search.py\"),\n remediation=rem,\n asvs_control=\"V5.3.4\",\n cwe=\"CWE-89\",\n nist_ssdf=\"PW.5.1\",\n )\n\n FindingLifecycleManager.transition(finding, LifecycleStage.CLASSIFY)\n FindingLifecycleManager.transition(finding, LifecycleStage.VERIFY)\n FindingLifecycleManager.transition(finding, LifecycleStage.REMEDIATE)\n\n ok, msg = FindingLifecycleManager.execute_retest(\n finding,\n post_fix_code=\"User.objects.raw('SELECT * FROM users WHERE name = %s', [name])\",\n safe_pattern_verified=True,\n verifier_notes=\"Verified parameterized binding query.\",\n )\n self.log_test(\"Retest execution -> Verified Fixed\", ok and finding.status == FindingStatus.VERIFIED_FIXED)\n\n def test_validation_engine_subsystem(self):\n print(\"\\n8. Testing Validation Engine Subsystem (v0.5.4)...\")\n fm = FixtureManager(str(self.root_dir))\n fixtures = fm.list_fixtures()\n self.log_test(f\"Fixture Manager Catalog Loaded ({len(fixtures)} fixtures)\", len(fixtures) >= 8)\n\n rr = ReplayRunner(str(self.root_dir))\n comparator = ResultComparator(str(self.root_dir))\n comparison_results = []\n\n for f in fixtures:\n replay_res = rr.replay_fixture(f, passes=3)\n self.log_test(f\"Deterministic Replay (3 passes): {f.fixture_id}\", replay_res.deterministic)\n\n comp_res = comparator.compare_fixture(f, replay_deterministic=replay_res.deterministic)\n comparison_results.append(comp_res)\n self.log_test(f\"Differential Comparison ({comp_res.outcome.value}): {f.fixture_id}\", comp_res.diff_verified)\n\n # Regression tracker\n rt = RegressionTracker(str(self.root_dir))\n reg_records = rt.evaluate_all_regressions()\n all_clean = all(r.regression_status == \"Clean\" for r in reg_records)\n self.log_test(f\"Regression Tracker Verification ({len(reg_records)} baseline cases clean)\", all_clean)\n\n # FP Analyzer\n diagnostics = FalsePositiveAnalyzer.analyze_results(comparison_results)\n self.log_test(\"False Positive Analyzer Diagnostic Check (0 false alarms)\", len(diagnostics) == 0)\n\n # Evidence Collector & Report Emitter\n collector = ValidationEvidenceCollector(str(self.root_dir))\n env_snap = collector.capture_environment_snapshot()\n self.log_test(\"Validation Evidence Collector Environment Snapshot\", \"os\" in env_snap and \"python_version\" in env_snap)\n\n val_report = ValidationRunReport(\n environment=env_snap,\n fixture_results=comparison_results,\n regression_records=reg_records,\n )\n report_md = ValidationReportEmitter.render_markdown(val_report)\n self.log_test(\"Validation Report Emitter Markdown Rendering\", \"# TorusGuard Validation Engine\" in report_md and \"Execution Summary\" in report_md)\n\n def test_stack_detection_fixtures(self):\n print(\"\\n9. Testing Stack Detection Layouts...\")\n stack_dir = self.root_dir / \"tests\" / \"fixtures\" / \"python\" / \"stack-detection\"\n expected_stacks = [\n \"django\",\n \"django-drf\",\n \"fastapi\",\n \"flask\",\n \"flask-sqlalchemy\",\n \"python-library\",\n \"mixed-monorepo\",\n ]\n for s in expected_stacks:\n target = stack_dir / s\n exists = target.exists() and any(target.iterdir())\n self.log_test(f\"Stack layout fixture: {s}\", exists)\n\n def test_educational_differential_fixtures(self):\n print(\"\\n10. Testing Educational Differential Fixtures...\")\n pairs = [\n (\"examples/python/django-vuln\", \"examples/python/django-hardened\"),\n (\"examples/python/drf-vuln\", \"examples/python/drf-hardened\"),\n (\"examples/python/fastapi-vuln\", \"examples/python/fastapi-hardened\"),\n (\"examples/python/flask-vuln\", \"examples/python/flask-hardened\"),\n (\"examples/python/sqlalchemy-vuln\", \"examples/python/sqlalchemy-hardened\"),\n ]\n for vuln_rel, hard_rel in pairs:\n vuln_path = self.root_dir / vuln_rel\n hard_path = self.root_dir / hard_rel\n exists = vuln_path.exists() and hard_path.exists()\n has_fixes = (hard_path / \"fixes.md\").exists() or (vuln_path / \"README.md\").exists()\n self.log_test(f\"Paired differential fixture: {Path(vuln_rel).name}\", exists and has_fixes)\n\n def test_regression_fixtures(self):\n print(\"\\n11. Testing Python Regression Fixtures Suite...\")\n regression_dir = self.root_dir / \"tests\" / \"fixtures\" / \"python\"\n cases = [\n \"django/safe-service-layer-auth\",\n \"django/missing-owner-scope\",\n \"drf/safe-read-only-fields\",\n \"drf/unbounded-pagination\",\n \"fastapi/safe-pydantic-boundary\",\n \"fastapi/unsafe-outbound-url\",\n \"flask/csrf-enabled\",\n \"flask/unsafe-upload\",\n \"sqlalchemy/safe-bound-query\",\n \"sqlalchemy/missing-tenant-scope\",\n ]\n for c in cases:\n c_path = regression_dir / c\n exists = c_path.exists() and (c_path / \"README.md\").exists()\n self.log_test(f\"Regression fixture: {c}\", exists)\n\n def test_report_formatting(self):\n print(\"\\n12. Testing Canonical v0.5.4 9-Section Actionable Markdown Report...\")\n ev = Evidence(\n type=EvidenceType.SOURCE,\n location=\"settings.py:10\",\n raw_snippet=\"DEBUG = True\\nSECRET_KEY = 'sk_live_secret_key_12345'\",\n rationale=\"Production debug mode exposure and hardcoded secret.\",\n confidence_level=ConfidenceBand.CONFIRMED,\n is_sufficient_for_confirmed=True,\n )\n sev = SeverityInfo(\n level=SeverityLevel.CRITICAL,\n rationale=\"Exposes internal stack traces and hardcoded production secret.\",\n rubric_justification=\"Critical because secret key enables session forgery and debug leaks internals.\",\n )\n conf = ConfidenceScore.calculate(35, 25, 15, 15, 5, \"Direct settings file check.\")\n prov = ProvenanceChain(\n discovery_module=\"rules/TG-PLATFORM-003-production-stack-trace-exposure.md\",\n triggering_input=\"DEBUG = True assignment in settings.py\",\n evidence_collected=[\"settings.py:10\"],\n decision_path=[\"Loaded Django settings\", \"Found DEBUG enabled\"],\n verification_step=\"Assert DEBUG is False.\",\n )\n rem = Remediation(\n problem_statement=\"Debug mode is enabled and hardcoded secret present.\",\n risk_explanation=\"Stack traces leak environment variables and secret allows token forgery.\",\n recommended_fix=\"Set DEBUG = False and load secret from environment.\",\n framework_pattern=FrameworkPattern(\n framework=\"Django\",\n unsafe_snippet=\"DEBUG = True\",\n safe_snippet=\"DEBUG = False\",\n ),\n verification_method=\"Assert DEBUG is False in production.\",\n residual_risk_notes=\"Ensure 500.html template exists.\",\n )\n f = Finding(\n rule_id=\"TG-PLATFORM-003\",\n title=\"Production Stack Trace Exposure\",\n category=TaxonomyCategory.CLIENT_PLATFORM,\n severity=sev,\n confidence=conf,\n status=FindingStatus.CONFIRMED,\n remediation_priority=RemediationPriority.IMMEDIATE,\n affected_component=AffectedComponent(component_name=\"Config\", target_path=\"settings.py\", start_line=10),\n evidence=[ev],\n provenance=prov,\n reproduction_method=ReproductionMethod(step_by_step=[\"Trigger 500 error and inspect response body\"]),\n remediation=rem,\n asvs_control=\"V14.4.1\",\n cwe=\"CWE-209\",\n nist_ssdf=\"PW.5.1\",\n )\n report = AuditReport(\n project_name=\"DemoApp\",\n detected_stack={\"language\": \"Python\", \"framework\": \"Django\", \"confidence\": \"Confirmed\"},\n findings=[f],\n )\n\n md_output = ReportFormatter.render_markdown(report)\n has_header = \"# TorusGuard Security Audit & Remediation Report\" in md_output\n has_exec_summary = \"## 1. \ud83d\udccb Executive Summary\" in md_output\n has_scope = \"## 2. \ud83d\udd0d Scope and Methodology\" in md_output\n has_summary_table = \"## 3. \ud83d\udcd1 Key Findings Summary Table\" in md_output\n has_detailed = \"## 4. \ud83d\udee1\ufe0f Detailed Findings\" in md_output\n has_business_context = \"\ud83c\udfe2 Business Impact & Executive Context\" in md_output\n has_remediation_roadmap = \"## 5. \ud83c\udfaf Remediation Priorities & Triage Roadmap\" in md_output\n has_ticket_payload = \"\ud83c\udfab Copy-Paste Issue Tracker Payload\" in md_output\n has_redaction = \"sk_live_***REDACTED***\" in md_output\n\n self.log_test(\n \"Render v0.5.4 9-Section Actionable Report\",\n has_header and has_exec_summary and has_scope and has_summary_table and has_detailed and has_business_context and has_remediation_roadmap and has_ticket_payload and has_redaction\n )\n\n def test_run_context_and_ponytail(self):\n print(\"\\n13. Testing v0.5.5 RunFolder Structure...\")\n import shutil\n test_root = self.root_dir / \".torusguard\" / \"runs_test\"\n if test_root.exists():\n shutil.rmtree(test_root)\n \n rf = RunFolder(output_root=str(test_root), run_name=\"test-run-001\")\n \n # Test directory initialization\n has_dirs = rf.run_path.exists() and rf.patches_dir.exists() and rf.logs_dir.exists()\n \n # Test metadata file initialization\n has_metadata = rf.metadata_file.exists()\n if has_metadata:\n with open(rf.metadata_file, \"r\", encoding=\"utf-8\") as f:\n metadata = json.load(f)\n has_metadata = metadata.get(\"run_id\") == \"test-run-001\"\n \n self.log_test(\"RunFolder Initialization\", has_dirs and has_metadata)\n \n # Cleanup\n shutil.rmtree(test_root)\n\n def test_v6_governed_remediation_suite(self):\n print(\"\\n14. Testing TorusGuard v0.6.0 Governed Remediation & Targeted Recheck Engine...\")\n import tempfile\n from core.identity import IdentityEngine\n from core.clustering import ClusteringEngine\n from core.bundle import BundleManager\n from core.governance import PatchGovernor\n from core.rechecker import TargetedRechecker, RecheckOutcome\n from core.run_manager import RunManager\n from core.sarif import SarifExporter\n from core.v6_workflow import V6Workflow\n\n temp_dir = Path(tempfile.mkdtemp(prefix=\"tg-v0-6-harness-\"))\n try:\n # 1. Run Folder\n rm = RunManager(base_dir=temp_dir, target_name=\"test-target\", command=\"audit\", run_id=\"run-harness-01\")\n rm.write_manifest(status_counts={\"total_findings\": 1, \"confirmed\": 1, \"high_confidence\": 0, \"needs_review\": 0, \"remediated\": 0, \"verified_fixed\": 0, \"regressed\": 0})\n self.log_test(\"v0.6.0 RunFolder & Manifest.json Generation\", rm.manifest_file.exists() and rm.patches_dir.exists())\n\n # 2. Stable Finding Identity\n code_a = \"def view():\\n return Item.objects.get(id=id)\"\n code_b = \"# Shifted comment\\ndef view():\\n return Item.objects.get(id=id)\"\n fp1 = IdentityEngine.generate_identity(\"TG-DB-004\", \"views.py\", code_a, sink_signature=\"Item.objects.get\")\n fp2 = IdentityEngine.generate_identity(\"TG-DB-004\", \"views.py\", code_b, sink_signature=\"Item.objects.get\")\n self.log_test(\"v0.6.0 Stable Finding Identity (Line Shift Invariance)\", fp1.fingerprint_id == fp2.fingerprint_id and fp1.fingerprint_id.startswith(\"TG-DB-\"))\n\n # 3. Root-Cause Clustering\n raw_f = [\n {\"finding_id\": \"f1\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"severity\": \"High\", \"target\": {\"file_path\": \"a.py\"}},\n {\"finding_id\": \"f2\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"severity\": \"High\", \"target\": {\"file_path\": \"b.py\"}},\n ]\n clusters = ClusteringEngine.cluster_findings(raw_f)\n self.log_test(\"v0.6.0 Root-Cause Clustering (Multi-Tenant Pattern)\", len(clusters) == 1 and clusters[0].cluster_id == \"cluster-tenant-isolation\")\n\n # 4. Remediation Bundle\n bundle = BundleManager.create_bundle(raw_f[0], cluster_id=\"cluster-tenant-isolation\")\n b_dir = bundle.write_to_directory(temp_dir)\n self.log_test(\"v0.6.0 Remediation Bundle Packaging (5 Artifacts)\", (b_dir / \"finding.md\").exists() and (b_dir / \"minimal_patch_plan.md\").exists())\n\n # 5. Patch Governance\n gov = PatchGovernor(max_additions_per_file=10)\n clean_diff = \"--- a/x.py\\n+++ b/x.py\\n@@ -1 +1 @@\\n-old()\\n+new()\\n\"\n oversized_diff = \"--- a/x.py\\n+++ b/x.py\\n\" + \"\\n\".join(f\"+line_{i}()\" for i in range(20))\n d_clean = gov.evaluate_diff(clean_diff, \"x.py\")\n d_over = gov.evaluate_diff(oversized_diff, \"x.py\")\n self.log_test(\"v0.6.0 Minimal Patch Governance (Line Churn Policy)\", d_clean.allowed_auto_apply and not d_over.allowed_auto_apply)\n\n # 6. Targeted Recheck\n r_fix = TargetedRechecker.verify_finding(\"f1\", \"TG-DB-004\", \"a.py\", \"old\", \"new\", is_safe_pattern_present=True, is_unsafe_pattern_present=False)\n r_reg = TargetedRechecker.verify_finding(\"f2\", \"TG-DB-004\", \"b.py\", \"old\", \"bad\", is_safe_pattern_present=False, is_unsafe_pattern_present=True, introduced_new_flaws=[\"TG-SEC-001\"])\n self.log_test(\"v0.6.0 Targeted Recheck Transitions (Confirmed Fixed & Regressed)\", r_fix.outcome == RecheckOutcome.CONFIRMED_FIXED and r_reg.outcome == RecheckOutcome.REGRESSED)\n\n # 7. SARIF Export\n sarif = SarifExporter.generate_sarif([{\"finding_id\": \"f1\", \"rule_id\": \"TG-DB-004\", \"title\": \"Missing Tenant Isolation\", \"target\": {\"file_path\": \"a.py\"}}])\n self.log_test(\"v0.6.0 SARIF v2.1.0 Structured Export\", sarif[\"version\"] == \"2.1.0\" and len(sarif[\"runs\"]) == 1)\n\n # 8. End-to-End Workflow\n wf = V6Workflow(target_root=temp_dir, output_base=temp_dir / \"runs\")\n run_wf = wf.execute_audit(raw_f, target_name=\"e2e-demo\", export_sarif=True)\n self.log_test(\"v0.6.0 End-to-End Workflow Execution\", run_wf.manifest_file.exists() and run_wf.sarif_file.exists())\n\n finally:\n shutil.rmtree(temp_dir, ignore_errors=True)\n\n\nif __name__ == \"__main__\":\n runner = ValidationHarnessRunner()\n success = runner.run_all()\n sys.exit(0 if success else 1)"
|
|
15
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Remediation Plan: bnd-tg-sec-001-209-4f6424
|
|
2
|
+
- **Rule ID:** `TG-SEC-001`
|
|
3
|
+
- **Target File:** `harness/runner.py:209`
|
|
4
|
+
- **Ponytail Churn:** `+1 / -1` (Compliant <=35/<=25)
|
|
5
|
+
|
|
6
|
+
## Proposed Change
|
|
7
|
+
Replaced hardcoded credential with os.environ.get('RAW_SNIPPET')
|
|
8
|
+
|
|
9
|
+
## Unified Diff Preview
|
|
10
|
+
```diff
|
|
11
|
+
--- a/harness/runner.py
|
|
12
|
+
+++ b/harness/runner.py
|
|
13
|
+
@@ -207,5 +207,5 @@
|
|
14
|
+
type=EvidenceType.SOURCE,
|
|
15
|
+
location="server/auth.py:42",
|
|
16
|
+
- raw_snippet="SECRET_KEY = 'super_secret_jwt_key'",
|
|
17
|
+
+ raw_snippet = os.environ.get("RAW_SNIPPET", "")
|
|
18
|
+
rationale="Hardcoded secret credential.",
|
|
19
|
+
confidence_level=ConfidenceBand.CONFIRMED,
|
|
20
|
+
|
|
21
|
+
```
|
package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/patch.diff
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
--- a/harness/runner.py
|
|
2
|
+
+++ b/harness/runner.py
|
|
3
|
+
@@ -207,5 +207,5 @@
|
|
4
|
+
type=EvidenceType.SOURCE,
|
|
5
|
+
location="server/auth.py:42",
|
|
6
|
+
- raw_snippet="SECRET_KEY = 'super_secret_jwt_key'",
|
|
7
|
+
+ raw_snippet = os.environ.get("RAW_SNIPPET", "")
|
|
8
|
+
rationale="Hardcoded secret credential.",
|
|
9
|
+
confidence_level=ConfidenceBand.CONFIRMED,
|