diff --git a/.appsurface/evidence/evidence.policy.json b/.appsurface/evidence/evidence.policy.json new file mode 100644 index 000000000..ac889cb52 --- /dev/null +++ b/.appsurface/evidence/evidence.policy.json @@ -0,0 +1,531 @@ +{ + "id": "appsurface-pr-evidence", + "version": "1", + "conservativeProfileId": "pr-conservative", + "profiles": [ + { + "id": "documentation-only", + "scope": "Targeted", + "resources": [], + "producers": [], + "obligations": [] + }, + { + "id": "code-coverage", + "scope": "Targeted", + "resources": [], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + } + ] + }, + { + "id": "postgresql-integration", + "scope": "Targeted", + "resources": [ + { "id": "postgresql-16-5", "readiness": "aspire_health", "deadlineSeconds": 180, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "postgresql-contract", + "kind": "postgresql-integration", + "version": "1.0.0", + "requiredResources": ["postgresql-16-5"], + "assertionIds": ["appsurface/durable/postgresql-16.5-assertions@1"], + "artifactSlots": [ + { "logicalName": "scenario-results", "relativeRoot": "postgresql/scenarios", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "run-metadata", "relativeRoot": "postgresql/run", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 900 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "postgresql-integration-contract", + "riskClass": "resource-backed-integration", + "rationale": "Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.", + "requiredProducerIds": ["postgresql-contract"], + "requiredAssertionId": "appsurface/durable/postgresql-16.5-assertions@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + } + ] + }, + { + "id": "keycloak-theme-integration", + "scope": "Targeted", + "resources": [ + { "id": "keycloak-pinned-image", "readiness": "aspire_health", "deadlineSeconds": 240, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "keycloak-theme-contract", + "kind": "keycloak-theme-integration", + "version": "1.0.0", + "requiredResources": ["keycloak-pinned-image"], + "assertionIds": ["appsurface/keycloak/served-theme-assets@1"], + "artifactSlots": [ + { "logicalName": "theme-proof", "relativeRoot": "keycloak/theme", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "theme-summary", "relativeRoot": "keycloak/summary", "mediaType": "text/markdown", "required": true, "maximumBytes": 524288 }, + { "logicalName": "runtime-metadata", "relativeRoot": "keycloak/runtime", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 600 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "keycloak-theme-rendering", + "riskClass": "resource-backed-integration", + "rationale": "Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.", + "requiredProducerIds": ["keycloak-theme-contract"], + "requiredAssertionId": "appsurface/keycloak/served-theme-assets@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + } + ] + }, + { + "id": "package-release-preparation", + "scope": "Targeted", + "resources": [ + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + }, + { + "id": "release-preparation-contract", + "kind": "release-preparation-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": ["appsurface/release/preparation-base-and-artifacts-verified@1"], + "artifactSlots": [ + { "logicalName": "preparation-projection", "relativeRoot": "release/preparation", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "prepared-artifact-digests", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 900 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + }, + { + "id": "release-preparation-evidence", + "riskClass": "release-preparation", + "rationale": "Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.", + "requiredProducerIds": ["release-preparation-contract"], + "requiredAssertionId": "appsurface/release/preparation-base-and-artifacts-verified@1" + } + ] + }, + { + "id": "pr-conservative", + "scope": "Targeted", + "resources": [ + { "id": "postgresql-16-5", "readiness": "aspire_health", "deadlineSeconds": 180, "requires": [] }, + { "id": "keycloak-pinned-image", "readiness": "aspire_health", "deadlineSeconds": 240, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "control-plane-validation", + "kind": "control-plane-validation", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/control-plane/base-owned-validation@1"], + "artifactSlots": [ + { "logicalName": "validation-report", "relativeRoot": "control-plane/report", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 } + ], + "timeoutSeconds": 300 + }, + { + "id": "postgresql-contract", + "kind": "postgresql-integration", + "version": "1.0.0", + "requiredResources": ["postgresql-16-5"], + "assertionIds": ["appsurface/durable/postgresql-16.5-assertions@1"], + "artifactSlots": [ + { "logicalName": "scenario-results", "relativeRoot": "postgresql/scenarios", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "run-metadata", "relativeRoot": "postgresql/run", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 900 + }, + { + "id": "keycloak-theme-contract", + "kind": "keycloak-theme-integration", + "version": "1.0.0", + "requiredResources": ["keycloak-pinned-image"], + "assertionIds": ["appsurface/keycloak/served-theme-assets@1"], + "artifactSlots": [ + { "logicalName": "theme-proof", "relativeRoot": "keycloak/theme", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "theme-summary", "relativeRoot": "keycloak/summary", "mediaType": "text/markdown", "required": true, "maximumBytes": 524288 }, + { "logicalName": "runtime-metadata", "relativeRoot": "keycloak/runtime", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 600 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + }, + { + "id": "release-preparation-contract", + "kind": "release-preparation-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": ["appsurface/release/preparation-base-and-artifacts-verified@1"], + "artifactSlots": [ + { "logicalName": "preparation-projection", "relativeRoot": "release/preparation", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "prepared-artifact-digests", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 900 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "control-plane-integrity", + "riskClass": "trusted-control-plane", + "rationale": "Workflow, policy, runner, host, and gate implementation changes require base-owned validation and cannot waive evidence.", + "requiredProducerIds": ["control-plane-validation"], + "requiredAssertionId": "appsurface/control-plane/base-owned-validation@1" + }, + { + "id": "postgresql-integration-contract", + "riskClass": "resource-backed-integration", + "rationale": "Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.", + "requiredProducerIds": ["postgresql-contract"], + "requiredAssertionId": "appsurface/durable/postgresql-16.5-assertions@1" + }, + { + "id": "keycloak-theme-rendering", + "riskClass": "resource-backed-integration", + "rationale": "Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.", + "requiredProducerIds": ["keycloak-theme-contract"], + "requiredAssertionId": "appsurface/keycloak/served-theme-assets@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + }, + { + "id": "release-preparation-evidence", + "riskClass": "release-preparation", + "rationale": "Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.", + "requiredProducerIds": ["release-preparation-contract"], + "requiredAssertionId": "appsurface/release/preparation-base-and-artifacts-verified@1" + } + ] + }, + { + "id": "protected-release", + "scope": "Release", + "resources": [], + "producers": [ + { + "id": "release-inspection", + "kind": "release-inspection", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/release/protected-tag-and-preparation-base@1"], + "artifactSlots": [ + { "logicalName": "release-projection", "relativeRoot": "release/projection", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "release-digest-index", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 600 + } + ], + "obligations": [ + { + "id": "protected-release-subject", + "riskClass": "protected-release", + "rationale": "Only a protected release invocation may attest the tag object, peeled commit, validated preparation base, and exact package digests without publishing.", + "requiredProducerIds": ["release-inspection"], + "requiredAssertionId": "appsurface/release/protected-tag-and-preparation-base@1" + } + ] + } + ], + "rules": [ + { "id": "documentation-reference", "pattern": "docs/*.md", "profileId": "documentation-only" }, + { "id": "documentation-guides", "pattern": "guides/*.md", "profileId": "documentation-only" }, + { "id": "documentation-start-here", "pattern": "start-here/*.md", "profileId": "documentation-only" }, + { "id": "documentation-root-readme", "pattern": "README.md", "profileId": "documentation-only" }, + { "id": "documentation-contributor-guide", "pattern": "CONTRIBUTING.md", "profileId": "documentation-only" }, + { "id": "control-github", "pattern": ".github/**", "profileId": "pr-conservative" }, + { "id": "control-policy", "pattern": ".appsurface/**", "profileId": "pr-conservative" }, + { "id": "control-design-documents", "pattern": "docs/designs/**", "profileId": "pr-conservative" }, + { "id": "control-issue-plans", "pattern": "docs/plans/**", "profileId": "pr-conservative" }, + { "id": "control-policy-matrix", "pattern": "docs/evidence-gate-policy-matrix.md", "profileId": "pr-conservative" }, + { "id": "control-rollout-guide", "pattern": "docs/evidence-gate-rollout.md", "profileId": "pr-conservative" }, + { "id": "control-diagnostics-guide", "pattern": "docs/evidence-gate-diagnostics.md", "profileId": "pr-conservative" }, + { "id": "control-gate-documentation", "pattern": "docs/evidence-gate-*.md", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "control-checked-in-fixtures", "pattern": "docs/fixtures/**", "profileId": "pr-conservative" }, + { "id": "control-scripts", "pattern": "scripts/**", "profileId": "pr-conservative" }, + { "id": "control-agent-guidance", "pattern": "AGENTS.md", "profileId": "pr-conservative" }, + { "id": "control-nested-agent-guidance", "pattern": "**/AGENTS.md", "profileId": "pr-conservative" }, + { "id": "control-evidence-implementation", "pattern": "Evidence/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-cli", "pattern": "Cli/ForgeTrust.AppSurface.Cli/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-cli-tests", "pattern": "Cli/ForgeTrust.AppSurface.Cli.Tests/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-gate-runner", "pattern": "tools/ForgeTrust.AppSurface.EvidenceGate/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-gate-runner-tests", "pattern": "tools/ForgeTrust.AppSurface.EvidenceGate.Tests/**", "profileId": "pr-conservative" }, + { "id": "coverage-csharp", "pattern": "**/*.cs", "profileId": "code-coverage" }, + { "id": "package-project-files", "pattern": "**/*.csproj", "profileId": "package-release-preparation" }, + { "id": "unknown-typescript", "pattern": "**/*.ts", "profileId": "pr-conservative" }, + { "id": "unknown-tsx", "pattern": "**/*.tsx", "profileId": "pr-conservative" }, + { "id": "unknown-javascript", "pattern": "**/*.js", "profileId": "pr-conservative" }, + { "id": "unknown-css", "pattern": "**/*.css", "profileId": "pr-conservative" }, + { "id": "unknown-scss", "pattern": "**/*.scss", "profileId": "pr-conservative" }, + { "id": "unknown-razor", "pattern": "**/*.razor", "profileId": "pr-conservative" }, + { "id": "unknown-sql", "pattern": "**/*.sql", "profileId": "pr-conservative" }, + { "id": "integration-durable-postgresql", "pattern": "Durable/**", "profileId": "postgresql-integration" }, + { "id": "integration-durable-package-projects", "pattern": "Durable/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-durable-package-locks", "pattern": "Durable/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-durable-postgresql-example", "pattern": "examples/durable-postgresql/**", "profileId": "postgresql-integration" }, + { "id": "integration-keycloak-theme", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-theme-package-projects", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-theme-package-locks", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-library", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-library-package-projects", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-library-package-locks", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-apphost", "pattern": "examples/auth-aspire-keycloak-apphost/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-examples", "pattern": "examples/auth-aspire-keycloak-*/**", "profileId": "keycloak-theme-integration" }, + { "id": "packages-index", "pattern": "packages/**", "profileId": "package-release-preparation" }, + { "id": "control-package-tool", "pattern": "tools/ForgeTrust.AppSurface.PackageIndex/**", "profileId": "pr-conservative" }, + { "id": "control-package-tool-tests", "pattern": "tools/ForgeTrust.AppSurface.PackageIndex.Tests/**", "profileId": "pr-conservative" }, + { "id": "packages-lockfiles", "pattern": "**/packages.lock.json", "profileId": "package-release-preparation" }, + { "id": "packages-msbuild-files", "pattern": "**/*.props", "profileId": "package-release-preparation" }, + { "id": "packages-msbuild-targets", "pattern": "**/*.targets", "profileId": "package-release-preparation" }, + { "id": "packages-pnpm-lockfile", "pattern": "**/pnpm-lock.yaml", "profileId": "package-release-preparation" }, + { "id": "packages-dotnet-build-config", "pattern": "Directory.Build.*", "profileId": "package-release-preparation" }, + { "id": "packages-directory-package-config", "pattern": "Directory.Packages.props", "profileId": "package-release-preparation" }, + { "id": "packages-sdk-config", "pattern": "global.json", "profileId": "package-release-preparation" }, + { "id": "packages-nuget-config", "pattern": "NuGet.config", "profileId": "package-release-preparation" }, + { "id": "packages-gate-config", "pattern": "NuGet.package-gate.config", "profileId": "package-release-preparation" }, + { "id": "control-release-tool", "pattern": "tools/ForgeTrust.AppSurface.Release/**", "profileId": "pr-conservative" }, + { "id": "control-release-tool-tests", "pattern": "tools/ForgeTrust.AppSurface.Release.Tests/**", "profileId": "pr-conservative" }, + { "id": "release-preparation-documents", "pattern": "releases/**", "profileId": "package-release-preparation" }, + { "id": "release-preparation-version", "pattern": "VERSION", "profileId": "package-release-preparation" }, + { "id": "release-preparation-changelog", "pattern": "CHANGELOG.md", "profileId": "package-release-preparation" } + ] +} diff --git a/.gitattributes b/.gitattributes index dd0138b23..840794d54 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ Web/ForgeTrust.AppSurface.Web.Tailwind/tailwind.release.json text eol=lf +# A captured Git diff marks an unchanged empty line with one leading context space. +docs/fixtures/issue-777-docs-only/source.diff -whitespace diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 362f85a3f..960a29eb6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -13,12 +13,37 @@ on: branches: - main workflow_dispatch: + inputs: + validate_subject_image: + description: Validate the non-claiming evidence subject image and cold offline restore on native Linux x64. + required: false + type: boolean + default: false concurrency: group: build-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.head.label || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + evidence-subject-image-validation: + name: Evidence subject image validation (non-claiming) + if: ${{ github.event_name == 'workflow_dispatch' && inputs.validate_subject_image }} + runs-on: ubuntu-24.04 + timeout-minutes: 45 + permissions: + contents: read + steps: + - name: Checkout the implementation branch without credentials + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up .NET 10 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.401 + - name: Verify real feed, build image, and restore from empty cache + run: bash ./scripts/evidence-gate-subject-image/validate-native.sh + config-package-contract: name: Config package contract (${{ matrix.os }}) runs-on: ${{ matrix.os }} @@ -395,7 +420,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 1 }} + fetch-depth: ${{ github.event_name == 'workflow_dispatch' && '0' || github.event_name == 'pull_request' && '2' || '1' }} - name: Setup .NET SDK id: setup-dotnet @@ -475,7 +500,7 @@ jobs: BUILD_CONFIGURATION: Release BUILD_NO_RESTORE: true COVERAGE_PARALLELISM: 2 - COVERAGE_GATE_DIFF_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }} + COVERAGE_GATE_DIFF_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || github.event_name == 'workflow_dispatch' && 'origin/main' || '' }} APP_SURFACE_TEST_ARTIFACTS_DIR: ${{ runner.temp }}/docs-outline-layout-evidence run: | ./scripts/coverage-solution.sh diff --git a/.github/workflows/evidence-gate-shadow.yml b/.github/workflows/evidence-gate-shadow.yml new file mode 100644 index 000000000..a9cea61e4 --- /dev/null +++ b/.github/workflows/evidence-gate-shadow.yml @@ -0,0 +1,101 @@ +name: evidence-gate-shadow.yml + +on: + pull_request: + branches: [main] + types: [opened, synchronize, reopened, ready_for_review, edited] + push: + branches: [main] + paths: + - .appsurface/** + - Evidence/** + - tools/ForgeTrust.AppSurface.EvidenceGate/** + - tools/ForgeTrust.AppSurface.EvidenceGate.Tests/** + - tools/ForgeTrust.AppSurface.Release/** + - .github/workflows/evidence-gate*.yml + - scripts/evidence-gate-* + +permissions: + contents: read + +concurrency: + group: evidence-gate-shadow-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + non-claiming-contract-check: + name: Evidence gate shadow (non-claiming) + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - name: Checkout candidate code for non-claiming validation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Setup .NET SDK + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.x + - name: Restore focused evidence tests with lock files + run: | + dotnet restore Cli/ForgeTrust.AppSurface.Cli.Tests/ForgeTrust.AppSurface.Cli.Tests.csproj --locked-mode + dotnet restore tools/ForgeTrust.AppSurface.EvidenceGate.Tests/ForgeTrust.AppSurface.EvidenceGate.Tests.csproj --locked-mode + dotnet restore tools/ForgeTrust.AppSurface.Release.Tests/ForgeTrust.AppSurface.Release.Tests.csproj --locked-mode + - name: Validate policy, revision, verifier, and extraction contracts + run: >- + dotnet test Cli/ForgeTrust.AppSurface.Cli.Tests/ForgeTrust.AppSurface.Cli.Tests.csproj + --no-restore + --filter "FullyQualifiedName~Evidence|FullyQualifiedName~AppSurfaceEvidencePolicyTests" + - name: Validate first-party host behavior + run: dotnet test tools/ForgeTrust.AppSurface.EvidenceGate.Tests/ForgeTrust.AppSurface.EvidenceGate.Tests.csproj --no-restore + - name: Validate non-mutating release inspection + run: >- + dotnet test tools/ForgeTrust.AppSurface.Release.Tests/ForgeTrust.AppSurface.Release.Tests.csproj + --no-restore + --filter "FullyQualifiedName~Release" + - name: Validate controller capture and credentialless subject isolation + run: python3 -m unittest discover -s scripts/tests -p 'test_evidence_gate_*.py' + - name: Validate protected-main image publisher guards + run: python3 -m unittest discover -s scripts/evidence-gate-subject-image -p 'test_publish_guard.py' + - name: Rehearse exact docs-only plan, host, and local verification + shell: bash + run: | + set -euo pipefail + fixture_dir="$(mktemp -d)" + git clone --quiet docs/fixtures/issue-777-docs-only/repository.bundle "$fixture_dir/repository" + base_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["baseRevision"])')" + head_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["headRevision"])')" + policy=docs/fixtures/issue-777-docs-only/policy.json + dotnet run --project Cli/ForgeTrust.AppSurface.Cli --no-restore -- evidence explain \ + --policy "$policy" --repository "$fixture_dir/repository" \ + --base-revision "$base_revision" --head-revision "$head_revision" \ + --diff-file docs/fixtures/issue-777-docs-only/source.diff --gate-mode \ + --output "$fixture_dir/explain" + dotnet run --project tools/ForgeTrust.AppSurface.EvidenceGate --no-restore -- run \ + --plan "$fixture_dir/explain/evidence-plan.json" --policy "$policy" \ + --repository "$fixture_dir/repository" --output-dir "$fixture_dir/host" + dotnet run --project Cli/ForgeTrust.AppSurface.Cli --no-restore -- evidence verify \ + "$fixture_dir/host/evidence-manifest.json" \ + --plan "$fixture_dir/host/evidence-plan.json" --policy "$policy" \ + --repository "$fixture_dir/repository" + python3 - "$fixture_dir" <<'PY' + import json + from pathlib import Path + import sys + root = Path(sys.argv[1]) + explained = json.loads((root / "explain/evidence-plan.json").read_text()) + hosted = json.loads((root / "host/evidence-plan.json").read_text()) + manifest = json.loads((root / "host/evidence-manifest.json").read_text()) + assert explained["PlanDigest"] == hosted["PlanDigest"] + assert hosted["Profile"]["Id"] == "documentation-only" + assert manifest["ClaimKind"] == "NoEvidenceRequired" + assert manifest["Eligibility"] == "PullRequestGate" + PY + - name: Explain shadow status + if: ${{ always() }} + run: | + { + echo '## AppSurface evidence gate shadow' + echo '' + echo 'This branch-owned check validates implementation contracts only. It is not the base-owned verifier, does not issue an EvidenceHost claim, and must not be configured as the required evidence check.' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/evidence-gate-subject-image-publish.yml b/.github/workflows/evidence-gate-subject-image-publish.yml new file mode 100644 index 000000000..e56e840dc --- /dev/null +++ b/.github/workflows/evidence-gate-subject-image-publish.yml @@ -0,0 +1,289 @@ +name: Evidence gate subject image publish (non-claiming) + +on: + push: + branches: [main] + paths: + - .github/workflows/evidence-gate-subject-image-publish.yml + - scripts/evidence-gate-subject-image/** + - scripts/evidence-gate-build-offline-feed.py + - scripts/evidence-gate-subject-entrypoint.py + - ForgeTrust.AppSurface.slnx + - global.json + - Directory.*.props + - Directory.*.targets + - '**/Directory.*.props' + - '**/Directory.*.targets' + - '**/*.csproj' + - '**/packages*.lock.json' + - NuGet.*.config + - '**/NuGet.Config' + - '**/nuget.config' + +permissions: + contents: read + +concurrency: + group: evidence-gate-subject-image-publish-${{ github.ref }} + cancel-in-progress: false + +jobs: + validate: + name: Validate exact local subject image + if: ${{ github.repository == 'forge-trust/AppSurface' && github.ref == 'refs/heads/main' && github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + outputs: + image-id: ${{ steps.image.outputs.image-id }} + archive-sha256: ${{ steps.image.outputs.archive-sha256 }} + permissions: + contents: read + steps: + - name: Check out the protected-main push without persisted credentials + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Set up .NET SDK + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.401 + + - name: Validate publisher context and configured image name + id: context + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REPOSITORY: ${{ github.repository }} + REF: ${{ github.ref }} + IMAGE: ${{ vars.EVIDENCE_GATE_SUBJECT_IMAGE }} + SHA: ${{ github.sha }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + set -euo pipefail + python3 scripts/evidence-gate-subject-image/publish_guard.py context \ + --event-name "$EVENT_NAME" \ + --repository "$REPOSITORY" \ + --ref "$REF" \ + --image "$IMAGE" \ + --sha "$SHA" \ + --run-id "$RUN_ID" \ + --run-attempt "$RUN_ATTEMPT" >> "$GITHUB_OUTPUT" + + - name: Build and validate the exact local image + shell: bash + run: bash ./scripts/evidence-gate-subject-image/validate-native.sh + + - name: Save and identify the validated local image + id: image + shell: bash + run: | + set -euo pipefail + image_tag='appsurface-subject-native-validation:local' + identity="$(docker image inspect --format '{{.Id}}|{{.Os}}|{{.Architecture}}' "$image_tag")" + IFS='|' read -r image_id image_os image_arch <<< "$identity" + python3 scripts/evidence-gate-subject-image/publish_guard.py image-identity \ + --image-id "$image_id" --os "$image_os" --architecture "$image_arch" + archive="$RUNNER_TEMP/appsurface-subject-image.tar" + docker save --output "$archive" "$image_tag" + archive_sha256="$(sha256sum "$archive" | cut -d ' ' -f 1)" + { + echo "image-id=$image_id" + echo "archive-sha256=$archive_sha256" + } >> "$GITHUB_OUTPUT" + + - name: Upload exact image for the credentialed publisher job + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-subject-image-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/appsurface-subject-image.tar + if-no-files-found: error + retention-days: 1 + compression-level: 0 + + publish: + name: Publish validated image and attest registry digest + needs: validate + if: ${{ needs.validate.result == 'success' && github.repository == 'forge-trust/AppSurface' && github.ref == 'refs/heads/main' && github.event_name == 'push' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + environment: + name: evidence-gate-subject-image-publish + url: https://github.com/${{ github.repository }}/pkgs/container/appsurface-subject-native-validation + permissions: + actions: read + contents: read + packages: write + attestations: write + artifact-metadata: write + id-token: write + outputs: + image-reference: ${{ steps.registry.outputs.image-reference }} + image-digest: ${{ steps.registry.outputs.digest }} + steps: + - name: Check out the attested protected-main revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Validate protected publisher context + id: context + shell: bash + env: + EVENT_NAME: ${{ github.event_name }} + REPOSITORY: ${{ github.repository }} + REF: ${{ github.ref }} + IMAGE: ${{ vars.EVIDENCE_GATE_SUBJECT_IMAGE }} + SHA: ${{ github.sha }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + set -euo pipefail + python3 scripts/evidence-gate-subject-image/publish_guard.py context \ + --event-name "$EVENT_NAME" \ + --repository "$REPOSITORY" \ + --ref "$REF" \ + --image "$IMAGE" \ + --sha "$SHA" \ + --run-id "$RUN_ID" \ + --run-attempt "$RUN_ATTEMPT" >> "$GITHUB_OUTPUT" + + - name: Require the publisher environment to be main-only and reviewed + shell: bash + env: + GH_TOKEN: ${{ github.token }} + PUBLISH_ENVIRONMENT: evidence-gate-subject-image-publish + run: | + set -euo pipefail + environment_json="$RUNNER_TEMP/publisher-environment.json" + branch_policies_json="$RUNNER_TEMP/publisher-branch-policies.json" + gh api "repos/$GITHUB_REPOSITORY/environments/$PUBLISH_ENVIRONMENT" > "$environment_json" + gh api "repos/$GITHUB_REPOSITORY/environments/$PUBLISH_ENVIRONMENT/deployment-branch-policies" \ + > "$branch_policies_json" + python3 scripts/evidence-gate-subject-image/publish_guard.py environment \ + --environment-json "$environment_json" \ + --branch-policies-json "$branch_policies_json" + + - name: Require reviewed main with no ruleset bypass + shell: bash + env: + GH_TOKEN: ${{ secrets.EVIDENCE_GATE_RULESET_INSPECTION_TOKEN }} + run: | + set -euo pipefail + : "${GH_TOKEN:?Configure the protected publisher environment's EVIDENCE_GATE_RULESET_INSPECTION_TOKEN}" + default_branch="$(gh api "repos/$GITHUB_REPOSITORY" --jq '.default_branch')" + ruleset_json="$RUNNER_TEMP/publisher-main-ruleset.json" + gh api "repos/$GITHUB_REPOSITORY/rulesets/7295365" > "$ruleset_json" + python3 scripts/evidence-gate-subject-image/publish_guard.py main-ruleset \ + --ruleset-json "$ruleset_json" \ + --default-branch "$default_branch" + + - name: Download the exact validated image archive + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: evidence-gate-subject-image-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/validated-subject-image + + - name: Verify and load the unchanged image + shell: bash + env: + EXPECTED_ARCHIVE_SHA256: ${{ needs.validate.outputs.archive-sha256 }} + EXPECTED_IMAGE_ID: ${{ needs.validate.outputs.image-id }} + run: | + set -euo pipefail + archive="$RUNNER_TEMP/validated-subject-image/appsurface-subject-image.tar" + python3 scripts/evidence-gate-subject-image/publish_guard.py verify-archive \ + --archive "$archive" --expected-sha256 "$EXPECTED_ARCHIVE_SHA256" + docker load --input "$archive" + identity="$(docker image inspect --format '{{.Id}}|{{.Os}}|{{.Architecture}}' \ + appsurface-subject-native-validation:local)" + IFS='|' read -r image_id image_os image_arch <<< "$identity" + python3 scripts/evidence-gate-subject-image/publish_guard.py image-identity \ + --image-id "$image_id" --os "$image_os" --architecture "$image_arch" \ + --expected-image-id "$EXPECTED_IMAGE_ID" + + - name: Log in to GHCR for this publish step only + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + printf '%s' "$GH_TOKEN" | docker login ghcr.io \ + --username "$GITHUB_ACTOR" --password-stdin + + - name: Push validated image and capture registry manifest digest + id: registry + shell: bash + env: + IMAGE_NAME: ${{ steps.context.outputs.image_name }} + IMAGE_TAG: ${{ steps.context.outputs.image_tag }} + EXPECTED_IMAGE_ID: ${{ needs.validate.outputs.image-id }} + GH_TOKEN: ${{ github.token }} + RULESET_INSPECTION_TOKEN: ${{ secrets.EVIDENCE_GATE_RULESET_INSPECTION_TOKEN }} + SOURCE_SHA: ${{ github.sha }} + run: | + set -euo pipefail + docker tag appsurface-subject-native-validation:local "$IMAGE_TAG" + current_main_sha="$(gh api "repos/$GITHUB_REPOSITORY/commits/main" --jq .sha)" + python3 scripts/evidence-gate-subject-image/publish_guard.py main-head \ + --source-sha "$SOURCE_SHA" --current-main-sha "$current_main_sha" + current_default_branch="$(gh api "repos/$GITHUB_REPOSITORY" --jq '.default_branch')" + current_ruleset_json="$RUNNER_TEMP/publisher-main-ruleset-current.json" + : "${RULESET_INSPECTION_TOKEN:?Configure the protected publisher environment's EVIDENCE_GATE_RULESET_INSPECTION_TOKEN}" + GH_TOKEN="$RULESET_INSPECTION_TOKEN" gh api "repos/$GITHUB_REPOSITORY/rulesets/7295365" > "$current_ruleset_json" + python3 scripts/evidence-gate-subject-image/publish_guard.py main-ruleset \ + --ruleset-json "$current_ruleset_json" \ + --default-branch "$current_default_branch" + unset RULESET_INSPECTION_TOKEN + docker push "$IMAGE_TAG" + + descriptor="$RUNNER_TEMP/subject-image-registry-descriptor.json" + raw_manifest="$RUNNER_TEMP/subject-image-registry-manifest.json" + docker buildx imagetools inspect "$IMAGE_TAG" --format '{{json .Manifest}}' > "$descriptor" + docker buildx imagetools inspect --raw "$IMAGE_TAG" > "$raw_manifest" + digest="$(python3 scripts/evidence-gate-subject-image/publish_guard.py manifest-digest \ + --descriptor "$descriptor" --raw-manifest "$raw_manifest" \ + --expected-image-id "$EXPECTED_IMAGE_ID")" + image_reference="${IMAGE_NAME}@${digest}" + docker pull "$image_reference" + published_identity="$(docker image inspect --format '{{.Id}}|{{.Os}}|{{.Architecture}}' \ + "$image_reference")" + IFS='|' read -r published_image_id published_image_os published_image_arch \ + <<< "$published_identity" + python3 scripts/evidence-gate-subject-image/publish_guard.py image-identity \ + --image-id "$published_image_id" --os "$published_image_os" \ + --architecture "$published_image_arch" --expected-image-id "$EXPECTED_IMAGE_ID" + { + echo "digest=$digest" + echo "image-reference=$image_reference" + } >> "$GITHUB_OUTPUT" + + - name: Attest the immutable GHCR image digest + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ steps.context.outputs.image_name }} + subject-digest: ${{ steps.registry.outputs.digest }} + push-to-registry: true + + - name: Publish reviewer-friendly digest summary + shell: bash + env: + IMAGE_REFERENCE: ${{ steps.registry.outputs.image-reference }} + IMAGE_ID: ${{ needs.validate.outputs.image-id }} + SOURCE_SHA: ${{ github.sha }} + run: | + set -euo pipefail + { + echo '## Evidence gate subject image (non-claiming)' + echo + echo "- Immutable GHCR reference: `$IMAGE_REFERENCE`" + echo "- Validated local image ID: `$IMAGE_ID`" + echo "- Protected-main source commit: `$SOURCE_SHA`" + echo '- GitHub artifact attestation: published for this immutable image digest.' + echo '- This publication does not establish evidence-gate eligibility or a coverage claim.' + echo + printf '%s\n' "- Verify: \`gh attestation verify \"oci://$IMAGE_REFERENCE\" --repo forge-trust/AppSurface --signer-workflow forge-trust/AppSurface/.github/workflows/evidence-gate-subject-image-publish.yml --source-ref refs/heads/main --source-digest $SOURCE_SHA\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/evidence-gate.yml b/.github/workflows/evidence-gate.yml new file mode 100644 index 000000000..9ba1e3eff --- /dev/null +++ b/.github/workflows/evidence-gate.yml @@ -0,0 +1,545 @@ +name: Evidence gate pilot + +on: + pull_request_target: + branches: + - main + types: + - opened + - synchronize + - reopened + - ready_for_review + - edited + +permissions: {} + +concurrency: + group: evidence-gate-pilot-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: true + +jobs: + controller-capture: + name: Evidence gate controller capture (non-claiming) + runs-on: ubuntu-24.04 + timeout-minutes: 15 + outputs: + profile_id: ${{ steps.profile.outputs.profile_id }} + permissions: + contents: read + pull-requests: read + steps: + - name: Checkout the workflow's trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.workflow_sha }} + path: trusted + persist-credentials: false + fetch-depth: 1 + + - name: Capture the exact pull-request revision pair + id: capture + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + capture_directory="$RUNNER_TEMP/evidence-gate-capture" + + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-controller.py" \ + --event "$GITHUB_EVENT_PATH" \ + --output "$capture_directory" \ + --target-branch main + + if [[ -f "$capture_directory/source.diff" && ! -L "$capture_directory/source.diff" ]]; then + printf '%s\n' 'mode=same-repository' >> "$GITHUB_OUTPUT" + elif [[ -f "$capture_directory/observation.json" && ! -L "$capture_directory/observation.json" ]]; then + printf '%s\n' 'mode=observation-only' >> "$GITHUB_OUTPUT" + else + echo 'The controller did not produce a recognized bounded capture.' >&2 + exit 1 + fi + + - name: Set up the trusted policy planner + if: ${{ steps.capture.outputs.mode == 'same-repository' }} + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.401 + + - name: Resolve the base-owned policy for the exact captured change + if: ${{ steps.capture.outputs.mode == 'same-repository' }} + shell: bash + run: | + set -euo pipefail + capture_directory="$RUNNER_TEMP/evidence-gate-capture" + identity="$capture_directory/pull-request-run-identity.json" + base_revision=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["BaseRevision"])' "$identity") + head_revision=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["HeadRevision"])' "$identity") + planner_project="$GITHUB_WORKSPACE/trusted/Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj" + policy="$GITHUB_WORKSPACE/trusted/.appsurface/evidence/evidence.policy.json" + + dotnet restore "$planner_project" --locked-mode --verbosity quiet + dotnet run --no-restore --project "$planner_project" -- evidence explain \ + --gate-mode \ + --policy "$policy" \ + --repository "$capture_directory/repository.git" \ + --base-revision "$base_revision" \ + --head-revision "$head_revision" \ + --diff-file "$capture_directory/source.diff" \ + --pr-run-identity "$identity" \ + --output "$RUNNER_TEMP/evidence-gate-plan" + + - name: Export the bounded policy-selected profile + id: profile + if: ${{ steps.capture.outputs.mode == 'same-repository' }} + shell: bash + run: | + set -euo pipefail + python3 - "$RUNNER_TEMP/evidence-gate-plan/evidence-plan.json" "$GITHUB_OUTPUT" <<'PY' + import json + import re + import sys + + with open(sys.argv[1], encoding="utf-8") as plan_file: + profile_id = json.load(plan_file)["Profile"]["Id"] + if not isinstance(profile_id, str) or re.fullmatch(r"[a-z0-9-]{1,64}", profile_id) is None: + raise SystemExit("The policy-selected profile cannot be exported safely.") + with open(sys.argv[2], "a", encoding="utf-8") as output_file: + output_file.write(f"profile_id={profile_id}\n") + PY + + - name: Compare the captured policy with protected-base policy fixtures + if: ${{ steps.capture.outputs.mode == 'same-repository' }} + shell: bash + run: | + set -euo pipefail + capture_directory="$RUNNER_TEMP/evidence-gate-capture" + protected_base="$GITHUB_WORKSPACE/trusted" + candidate_directory="$RUNNER_TEMP/evidence-gate-policy-shadow-inputs" + planner_project="$protected_base/Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj" + + python3 "$protected_base/scripts/evidence-gate-policy-shadow.py" \ + --capture-directory "$capture_directory" \ + --protected-base "$protected_base" \ + --output-directory "$candidate_directory" + + dotnet run --no-restore --project "$planner_project" -- evidence shadow-policy \ + --base-policy "$protected_base/.appsurface/evidence/evidence.policy.json" \ + --candidate-policy "$candidate_directory/.appsurface/evidence/evidence.policy.json" \ + --base-fixtures "$protected_base/docs/fixtures/issue-777-policy-shadow/fixtures.json" \ + --candidate-fixtures "$candidate_directory/docs/fixtures/issue-777-policy-shadow/fixtures.json" \ + --output "$RUNNER_TEMP/evidence-gate-policy-shadow-result" + + - name: Create the bounded subject handoff + shell: bash + run: | + set -euo pipefail + capture_directory="$RUNNER_TEMP/evidence-gate-capture" + handoff_directory="$RUNNER_TEMP/evidence-gate-handoff" + plan_arguments=() + if [[ -f "$capture_directory/source.diff" ]]; then + plan_arguments=(--plan-file "$RUNNER_TEMP/evidence-gate-plan/evidence-plan.json") + fi + + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-handoff.py" create \ + --capture-directory "$capture_directory" \ + --trusted-scripts-directory "$GITHUB_WORKSPACE/trusted/scripts" \ + --output-directory "$handoff_directory" \ + "${plan_arguments[@]}" + + - name: Upload the bounded same-run handoff + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-controller-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-handoff/* + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + subject-image-preflight: + name: Evidence gate subject image provenance (non-claiming) + needs: controller-capture + if: ${{ needs.controller-capture.result == 'success' && needs.controller-capture.outputs.profile_id == 'code-coverage' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + packages: read + attestations: read + outputs: + image: ${{ steps.verify.outputs.image }} + steps: + - name: Verify the protected-main publisher and registry digest + id: verify + shell: bash + env: + GH_TOKEN: ${{ github.token }} + SUBJECT_IMAGE: ${{ vars.EVIDENCE_GATE_SUBJECT_IMAGE_DIGEST }} + run: | + set -euo pipefail + if [[ ! "$SUBJECT_IMAGE" =~ ^ghcr\.io/forge-trust/appsurface-subject-native-validation@sha256:[0-9a-f]{64}$ ]]; then + echo 'The configured subject image must be the reviewed GHCR package at its registry digest.' >&2 + exit 1 + fi + printf '%s' "$GH_TOKEN" | docker login ghcr.io --username "$GITHUB_ACTOR" --password-stdin >/dev/null + gh attestation verify "oci://$SUBJECT_IMAGE" \ + --repo forge-trust/AppSurface \ + --signer-workflow forge-trust/AppSurface/.github/workflows/evidence-gate-subject-image-publish.yml \ + --source-ref refs/heads/main \ + --deny-self-hosted-runners \ + --format json > "$RUNNER_TEMP/evidence-gate-image-attestation.json" + python3 - "$RUNNER_TEMP/evidence-gate-image-attestation.json" "${SUBJECT_IMAGE##*@sha256:}" <<'PY' + import json + import sys + + with open(sys.argv[1], encoding="utf-8") as verified_file: + results = json.load(verified_file) + expected_digest = sys.argv[2] + if not isinstance(results, list) or not any( + isinstance(subject.get("digest"), dict) + and subject["digest"].get("sha256") == expected_digest + for result in results + for subject in result.get("verificationResult", {}).get("statement", {}).get("subject", []) + if isinstance(subject, dict) + ): + raise SystemExit("The verified provenance does not name the configured registry digest.") + PY + printf 'image=%s\n' "$SUBJECT_IMAGE" >> "$GITHUB_OUTPUT" + + credentialless-subject: + name: Evidence gate subject (credentialless, non-claiming) + needs: + - controller-capture + - subject-image-preflight + if: ${{ always() && needs.controller-capture.result == 'success' && (needs.controller-capture.outputs.profile_id != 'code-coverage' || needs.subject-image-preflight.result == 'success') }} + runs-on: ubuntu-24.04 + timeout-minutes: 40 + permissions: {} + steps: + - name: Download this run's controller handoff + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: evidence-gate-controller-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-controller-handoff + + - name: Pull only the attested image digest without credentials + if: ${{ needs.controller-capture.outputs.profile_id == 'code-coverage' }} + shell: bash + env: + SUBJECT_IMAGE: ${{ needs.subject-image-preflight.outputs.image }} + run: | + set -euo pipefail + if [[ ! "$SUBJECT_IMAGE" =~ ^ghcr\.io/forge-trust/appsurface-subject-native-validation@sha256:[0-9a-f]{64}$ ]]; then + echo 'The subject image digest is missing or malformed.' >&2 + exit 1 + fi + auth_file="$RUNNER_TEMP/evidence-gate-empty-registry-auth.json" + ( umask 077; printf '{}\n' > "$auth_file" ) + env REGISTRY_AUTH_FILE="$auth_file" podman pull --authfile "$auth_file" --tls-verify=true "$SUBJECT_IMAGE" + env REGISTRY_AUTH_FILE="$auth_file" podman image inspect "$SUBJECT_IMAGE" --format '{{json .RepoDigests}}' | + python3 -c 'import json,sys; ref=sys.argv[1]; refs=json.load(sys.stdin); sys.exit(0 if isinstance(refs,list) and ref in refs else 1)' "$SUBJECT_IMAGE" + + - name: Execute the bounded non-claiming subject profile + shell: bash + env: + EVIDENCE_GATE_SUBJECT_IMAGE: ${{ needs.subject-image-preflight.outputs.image }} + run: | + set -euo pipefail + python3 "$RUNNER_TEMP/evidence-gate-controller-handoff/evidence-gate-handoff.py" execute \ + --handoff-directory "$RUNNER_TEMP/evidence-gate-controller-handoff" \ + --subject-checkout "$RUNNER_TEMP/evidence-gate-subject-checkout" \ + --scratch-directory "$RUNNER_TEMP/evidence-gate-subject-scratch" \ + --artifact-export-directory "$RUNNER_TEMP/evidence-gate-subject-artifacts" \ + --result "$RUNNER_TEMP/evidence-gate-subject-result.json" \ + --image-digest "$EVIDENCE_GATE_SUBJECT_IMAGE" + + - name: Upload bounded non-claiming coverage artifacts + if: ${{ needs.controller-capture.outputs.profile_id == 'code-coverage' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-artifacts-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-subject-artifacts/ + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + - name: Require independent subject cleanup to attest completion + if: ${{ always() && needs.controller-capture.outputs.profile_id == 'code-coverage' }} + shell: bash + timeout-minutes: 11 + run: | + set -euo pipefail + python3 "$RUNNER_TEMP/evidence-gate-controller-handoff/evidence-gate-cleanup-attestation-check.py" \ + --runner-temp "$RUNNER_TEMP" \ + --output "$RUNNER_TEMP/evidence-gate-cleanup-attestation.json" + + - name: Upload the bounded non-claiming cleanup attestation + if: ${{ always() && needs.controller-capture.outputs.profile_id == 'code-coverage' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-cleanup-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-cleanup-attestation.json + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + - name: Ensure a fixed non-claiming result exists + if: ${{ always() }} + shell: bash + run: | + set -euo pipefail + python3 - "$RUNNER_TEMP/evidence-gate-subject-result.json" <<'PY' + import os + import stat + import sys + + result_path = sys.argv[1] + fallback = ( + b'{"claimEligible":false,"execution":"failed","schemaVersion":1,' + b'"diagnostic":{"code":"ASEHB011","message":"The credentialless subject handoff failed before recording its bounded result."}}\n' + ) + try: + descriptor = os.open( + result_path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + except FileExistsError: + metadata = os.lstat(result_path) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > 16 * 1024: + raise SystemExit("The subject result path is not a bounded regular file.") + else: + with os.fdopen(descriptor, "wb") as result_file: + result_file.write(fallback) + PY + + - name: Upload the fixed non-claiming subject result + if: ${{ always() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-subject-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-subject-result.json + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + trusted-verifier: + name: Evidence gate verifier (pilot) + needs: + - controller-capture + - subject-image-preflight + - credentialless-subject + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Checkout the workflow's trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.workflow_sha }} + path: trusted + persist-credentials: false + fetch-depth: 1 + + - name: Download same-run handoffs when both producer jobs succeeded + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: evidence-gate-*-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-verifier-inputs + merge-multiple: false + + - name: Recapture the current pull-request revision for independent verification + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-controller.py" \ + --event "$GITHUB_EVENT_PATH" \ + --output "$RUNNER_TEMP/evidence-gate-verifier-capture" \ + --target-branch main + test -f "$RUNNER_TEMP/evidence-gate-verifier-capture/pull-request-run-identity.json" + + - name: Bind the downloaded handoff to the fresh Git tree + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + env: + EVIDENCE_PROFILE_ID: ${{ needs.controller-capture.outputs.profile_id }} + EXPECTED_SUBJECT_IMAGE: ${{ needs.subject-image-preflight.outputs.image }} + run: | + set -euo pipefail + handoff="$RUNNER_TEMP/evidence-gate-verifier-inputs/evidence-gate-controller-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + subject="$RUNNER_TEMP/evidence-gate-verifier-inputs/evidence-gate-subject-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}/evidence-gate-subject-result.json" + artifacts="$RUNNER_TEMP/evidence-gate-verifier-inputs/evidence-gate-artifacts-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + artifact_args=() + if [[ "$EVIDENCE_PROFILE_ID" == code-coverage ]]; then + artifact_args=(--subject-artifacts "$artifacts" --expected-image-digest "$EXPECTED_SUBJECT_IMAGE") + fi + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-handoff.py" verify \ + --handoff-directory "$handoff" \ + --fresh-capture-directory "$RUNNER_TEMP/evidence-gate-verifier-capture" \ + --subject-result "$subject" \ + "${artifact_args[@]}" \ + --output-plan "$RUNNER_TEMP/evidence-gate-verified-plan.json" + + - name: Require the subject's independent cleanup completion record + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + run: | + set -euo pipefail + cleanup="$RUNNER_TEMP/evidence-gate-verifier-inputs/evidence-gate-cleanup-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}/evidence-gate-cleanup-attestation.json" + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-verify-cleanup.py" \ + --plan "$RUNNER_TEMP/evidence-gate-verified-plan.json" \ + --attestation "$cleanup" + + - name: Set up the trusted verifier + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.401 + + - name: Replay the downloaded coverage against the freshly captured diff (non-claiming) + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' && needs.controller-capture.outputs.profile_id == 'code-coverage' }} + shell: bash + run: | + set -euo pipefail + capture="$RUNNER_TEMP/evidence-gate-verifier-capture" + artifacts="$RUNNER_TEMP/evidence-gate-verifier-inputs/evidence-gate-artifacts-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + project="$GITHUB_WORKSPACE/trusted/Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj" + + python3 - "$RUNNER_TEMP/evidence-gate-verified-plan.json" <<'PY' + import json + import sys + + with open(sys.argv[1], encoding="utf-8") as plan_file: + profile = json.load(plan_file)["Profile"] + producers = [producer for producer in profile["Producers"] if producer["Id"] == "coverage"] + expected = { + "MinLinePercent": 95, + "MinBranchPercent": 85, + "MinPatchLinePercent": 95, + "MinPatchBranchPercent": 85, + "PatchLineMode": "codecov", + "TolerancePercent": 0.5, + } + if profile["Id"] != "code-coverage" or len(producers) != 1 or producers[0]["CoverageGate"] != expected: + raise SystemExit("The trusted coverage replay no longer matches the selected base-owned policy.") + PY + + # Cobertura paths from the fixed subject entrypoint are rooted at /subject. + # The verifier needs only an existing normalization root; it does not + # execute or trust any file from the subject's checkout here. + test ! -e /subject && test ! -L /subject + sudo -n install -d -m 0755 /subject + dotnet restore "$project" --locked-mode --verbosity quiet + dotnet run --no-restore --configuration Release --project "$project" -- coverage gate \ + --coverage "$artifacts/cobertura.xml" \ + --repository-root /subject \ + --diff-file "$capture/source.diff" \ + --diff-label captured-source-diff \ + --min-line 95 --min-branch 85 \ + --min-patch-line 95 --min-patch-branch 85 \ + --patch-line-mode codecov --tolerance 0.5 \ + --output "$RUNNER_TEMP/evidence-gate-trusted-coverage-replay" \ + --no-github-summary + + - name: Resolve current workflow and subject-job identity + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-verifier-context.py" \ + --fresh-identity "$RUNNER_TEMP/evidence-gate-verifier-capture/pull-request-run-identity.json" \ + --output "$RUNNER_TEMP/evidence-gate-expected-identity.json" + + - name: Record bounded non-claiming subject observation + id: observation + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + env: + EVIDENCE_PROFILE_ID: ${{ needs.controller-capture.outputs.profile_id }} + EXPECTED_SUBJECT_IMAGE: ${{ needs.subject-image-preflight.outputs.image }} + run: | + set -euo pipefail + inputs="$RUNNER_TEMP/evidence-gate-verifier-inputs" + args=( + --verified-plan "$RUNNER_TEMP/evidence-gate-verified-plan.json" + --verifier-identity "$RUNNER_TEMP/evidence-gate-expected-identity.json" + --subject-result "$inputs/evidence-gate-subject-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}/evidence-gate-subject-result.json" + --output "$RUNNER_TEMP/evidence-gate-observation.json" + ) + if [[ "$EVIDENCE_PROFILE_ID" == code-coverage ]]; then + args+=( + --cleanup-record "$inputs/evidence-gate-cleanup-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}/evidence-gate-cleanup-attestation.json" + --subject-artifacts-directory "$inputs/evidence-gate-artifacts-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + --expected-image-digest "$EXPECTED_SUBJECT_IMAGE" + ) + fi + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-observation.py" "${args[@]}" + + - name: Upload bounded non-claiming subject observation + if: ${{ steps.observation.outcome == 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-observation-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-observation.json + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + - name: Recompute the host manifest and independently verify the gate + id: gate_verifier + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + capture="$RUNNER_TEMP/evidence-gate-verifier-capture" + plan="$RUNNER_TEMP/evidence-gate-verified-plan.json" + project="$GITHUB_WORKSPACE/trusted/tools/ForgeTrust.AppSurface.EvidenceGate/ForgeTrust.AppSurface.EvidenceGate.csproj" + policy="$GITHUB_WORKSPACE/trusted/.appsurface/evidence/evidence.policy.json" + identity="$RUNNER_TEMP/evidence-gate-expected-identity.json" + host="$RUNNER_TEMP/evidence-gate-host" + verdict="$RUNNER_TEMP/evidence-gate-verdict" + + dotnet restore "$project" --locked-mode --verbosity quiet + host_status=0 + dotnet run --no-restore --project "$project" -- run \ + --plan "$plan" --policy "$policy" \ + --repository "$capture/repository.git" --output-dir "$host" || host_status=$? + if [[ ! -f "$host/evidence-manifest.json" ]]; then + echo "The trusted host did not produce a bounded manifest (exit $host_status)." >&2 + exit 1 + fi + dotnet run --no-restore --project "$project" -- verify-gate \ + --plan "$plan" --manifest "$host/evidence-manifest.json" \ + --policy "$policy" --repository "$capture/repository.git" \ + --identity "$identity" --output-dir "$verdict" + + - name: Publish the independent bounded gate verdict + if: ${{ always() }} + shell: bash + env: + CONTROLLER_RESULT: ${{ needs.controller-capture.result }} + SUBJECT_RESULT: ${{ needs.credentialless-subject.result }} + VERIFIER_RESULT: ${{ steps.gate_verifier.outcome }} + run: | + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-finalize.py" \ + --verdict-directory "$RUNNER_TEMP/evidence-gate-verdict" \ + --step-summary "$GITHUB_STEP_SUMMARY" \ + --controller-outcome "$CONTROLLER_RESULT" \ + --subject-outcome "$SUBJECT_RESULT" \ + --verifier-outcome "$VERIFIER_RESULT" diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index aa8a3c5f1..c7ba78a02 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -41,6 +41,7 @@ jobs: version: ${{ steps.release.outputs.version }} tag: ${{ steps.release.outputs.tag }} base_ref: ${{ steps.base.outputs.base_ref }} + tag_object_id: ${{ steps.release.outputs.tag_object_id }} tag_commit: ${{ steps.release.outputs.tag_commit }} notes_file: ${{ steps.release.outputs.notes_file }} prerelease: ${{ steps.release.outputs.prerelease }} @@ -50,7 +51,44 @@ jobs: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ github.workflow_sha }} fetch-depth: 0 + persist-credentials: false + + - name: Require the protected workflow commit + shell: bash + env: + TRUSTED_WORKFLOW_REF: ${{ github.workflow_ref }} + TRUSTED_WORKFLOW_SHA: ${{ github.workflow_sha }} + run: | + set -euo pipefail + if [[ "$GITHUB_EVENT_NAME" != workflow_dispatch \ + || "$GITHUB_REF" != refs/heads/main \ + || "$TRUSTED_WORKFLOW_REF" != 'forge-trust/AppSurface/.github/workflows/release-publish.yml@refs/heads/main' \ + || ! "$TRUSTED_WORKFLOW_SHA" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then + echo 'Release publication must be dispatched from the protected main workflow revision.' >&2 + exit 1 + fi + actual_commit="$(git rev-parse HEAD^{commit})" + if [[ "$actual_commit" != "$TRUSTED_WORKFLOW_SHA" ]]; then + echo 'The release tool checkout differs from the protected workflow commit.' >&2 + exit 1 + fi + + - name: Require the protected release publication environment + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + environment_json="$RUNNER_TEMP/release-publication-environment.json" + branch_policies_json="$RUNNER_TEMP/release-publication-branches.json" + gh api "repos/$GITHUB_REPOSITORY/environments/release-publish" > "$environment_json" + gh api "repos/$GITHUB_REPOSITORY/environments/release-publish/deployment-branch-policies" \ + > "$branch_policies_json" + python3 scripts/evidence-gate-subject-image/publish_guard.py environment \ + --environment-json "$environment_json" \ + --branch-policies-json "$branch_policies_json" - name: Setup .NET SDK uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 @@ -104,6 +142,7 @@ jobs: needs: validate-release runs-on: ubuntu-latest timeout-minutes: 30 + environment: release-publish permissions: contents: write # Required to create or reuse the draft GitHub Release and upload docs archive assets. outputs: @@ -309,6 +348,7 @@ jobs: set -euo pipefail test "$(git -C release-verifier rev-parse HEAD)" = "${GITHUB_SHA}" dotnet build release-verifier/Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj -c Release + dotnet build release-verifier/tools/ForgeTrust.AppSurface.Release/ForgeTrust.AppSurface.Release.csproj -c Release - name: Verify staged docs archive env: @@ -332,19 +372,38 @@ jobs: env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.validate-release.outputs.tag }} + TAG_OBJECT_ID: ${{ needs.validate-release.outputs.tag_object_id }} TAG_COMMIT: ${{ needs.validate-release.outputs.tag_commit }} VERSION: ${{ needs.validate-release.outputs.version }} TITLE: AppSurface ${{ needs.validate-release.outputs.tag }} - ARCHIVE_PATH: ${{ steps.docs.outputs.archive_path }} - SHA256_PATH: ${{ steps.docs.outputs.sha256_path }} run: | set -euo pipefail - git fetch --force origin "refs/tags/${TAG}:refs/tags/${TAG}" - actual_tag_commit="$(git rev-parse "refs/tags/${TAG}^{commit}")" - if [[ "${actual_tag_commit}" != "${TAG_COMMIT}" ]]; then - echo "Expected ${TAG} to resolve to ${TAG_COMMIT}; got ${actual_tag_commit}." >&2 - exit 1 - fi + archive_path="${RUNNER_TEMP}/appsurface-docs-v${VERSION}.tar.gz" + sidecar_path="${archive_path}.sha256" + publication_plan="${RUNNER_TEMP}/docs-publication-plan.json" + require_remote_tag_identity() { + local remote_tag_refs actual_tag_object_id actual_tag_commit remote_ref_count + remote_tag_refs="$(git ls-remote --exit-code origin "refs/tags/${TAG}" "refs/tags/${TAG}^{}")" + remote_ref_count="$(awk 'END { print NR }' <<< "${remote_tag_refs}")" + actual_tag_object_id="$(awk -F '\t' -v ref="refs/tags/${TAG}" '$2 == ref { print $1 }' <<< "${remote_tag_refs}")" + actual_tag_commit="$(awk -F '\t' -v ref="refs/tags/${TAG}^{}" '$2 == ref { print $1 }' <<< "${remote_tag_refs}")" + if [[ "${remote_ref_count}" != 2 \ + || ! "${actual_tag_object_id}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ \ + || ! "${actual_tag_commit}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ \ + || "${#actual_tag_object_id}" -ne "${#actual_tag_commit}" \ + || "${actual_tag_object_id}" != "${TAG_OBJECT_ID}" \ + || "${actual_tag_commit}" != "${TAG_COMMIT}" ]]; then + echo "Remote ${TAG} identity does not match validated tag object ${TAG_OBJECT_ID} and commit ${TAG_COMMIT}." >&2 + exit 1 + fi + } + require_remote_tag_identity + dotnet run --project release-verifier/tools/ForgeTrust.AppSurface.Release/ForgeTrust.AppSurface.Release.csproj -c Release --no-build --no-restore -- \ + verify-docs-archive-tuple \ + --version "${VERSION}" \ + --archive "${archive_path}" \ + --plan "${publication_plan}" \ + --sha256 "${sidecar_path}" notes_file="${RUNNER_TEMP}/release-notes.md" git show "${TAG_COMMIT}:releases/v${VERSION}.md" > "${notes_file}" if gh release view "${TAG}" --json isDraft --jq '.isDraft' | grep -qx true; then @@ -353,7 +412,8 @@ jobs: else gh release create "${TAG}" --verify-tag --draft --title "${TITLE}" --notes-file "${notes_file}" fi - gh release upload "${TAG}" "${ARCHIVE_PATH}" "${SHA256_PATH}" --clobber + require_remote_tag_identity + gh release upload "${TAG}" "${archive_path}" "${sidecar_path}" --clobber - name: Upload docs publication artifacts uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -401,6 +461,7 @@ jobs: - deploy-docs-pages runs-on: ubuntu-latest timeout-minutes: 10 + environment: release-publish permissions: contents: write # Required because draft release assets are not downloadable with the workflow token under contents: read. @@ -478,6 +539,7 @@ jobs: - verify-public-docs runs-on: ubuntu-latest timeout-minutes: 10 + environment: release-publish permissions: contents: write # Required to promote the verified draft GitHub Release to public. @@ -493,20 +555,33 @@ jobs: env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.validate-release.outputs.tag }} + TAG_OBJECT_ID: ${{ needs.validate-release.outputs.tag_object_id }} TAG_COMMIT: ${{ needs.validate-release.outputs.tag_commit }} PRERELEASE: ${{ needs.validate-release.outputs.prerelease }} run: | set -euo pipefail - git fetch --force origin "refs/tags/${TAG}:refs/tags/${TAG}" - actual_tag_commit="$(git rev-parse "refs/tags/${TAG}^{commit}")" - if [[ "${actual_tag_commit}" != "${TAG_COMMIT}" ]]; then - echo "Expected ${TAG} to resolve to ${TAG_COMMIT}; got ${actual_tag_commit}." >&2 - exit 1 - fi + require_remote_tag_identity() { + local remote_tag_refs actual_tag_object_id actual_tag_commit remote_ref_count + remote_tag_refs="$(git ls-remote --exit-code origin "refs/tags/${TAG}" "refs/tags/${TAG}^{}")" + remote_ref_count="$(awk 'END { print NR }' <<< "${remote_tag_refs}")" + actual_tag_object_id="$(awk -F '\t' -v ref="refs/tags/${TAG}" '$2 == ref { print $1 }' <<< "${remote_tag_refs}")" + actual_tag_commit="$(awk -F '\t' -v ref="refs/tags/${TAG}^{}" '$2 == ref { print $1 }' <<< "${remote_tag_refs}")" + if [[ "${remote_ref_count}" != 2 \ + || ! "${actual_tag_object_id}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ \ + || ! "${actual_tag_commit}" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ \ + || "${#actual_tag_object_id}" -ne "${#actual_tag_commit}" \ + || "${actual_tag_object_id}" != "${TAG_OBJECT_ID}" \ + || "${actual_tag_commit}" != "${TAG_COMMIT}" ]]; then + echo "Remote ${TAG} identity does not match validated tag object ${TAG_OBJECT_ID} and commit ${TAG_COMMIT}." >&2 + exit 1 + fi + } + require_remote_tag_identity args=(release edit "${TAG}" --draft=false) if [[ "${PRERELEASE}" == "true" ]]; then args+=(--prerelease) else args+=(--latest) fi + require_remote_tag_identity gh "${args[@]}" diff --git a/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs b/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs index 7c41e4015..878a10b3d 100644 --- a/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs +++ b/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs @@ -419,6 +419,309 @@ [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, Ma } } + [Fact] + public async Task ArtifactWriter_StreamWriteShouldHashAndVerifyWithoutTakingStreamOwnership() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-stream-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 512 * 1024); + var contents = Enumerable.Range(0, 200_000).Select(static value => (byte)(value % 251)).ToArray(); + await using var source = new NonSeekableReadStream(contents); + + var artifact = await writer.WriteAsync("report", "coverage/report.bin", source, contents.LongLength); + + Assert.Equal(contents.LongLength, artifact.LengthBytes); + Assert.Equal(EvidenceDigest.Sha256(contents), artifact.Sha256); + Assert.Equal(contents, await File.ReadAllBytesAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + Assert.True(source.CanRead); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldHandleTheV1MaximumWithBoundedReads() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-maximum-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, EvidenceArtifactWriter.MaximumTotalArtifactBytes); + await using var source = new GeneratedReadStream(EvidenceArtifactWriter.MaximumTotalArtifactBytes); + + var artifact = await writer.WriteAsync( + "report", + "coverage/report.bin", + source, + EvidenceArtifactWriter.MaximumTotalArtifactBytes); + + Assert.Equal(EvidenceArtifactWriter.MaximumTotalArtifactBytes, artifact.LengthBytes); + Assert.Equal(EvidenceArtifactWriter.MaximumTotalArtifactBytes, source.BytesRead); + Assert.InRange(source.MaximumRequestedReadSize, 1, 81_920); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldRejectSlotAndProducerLimitsBeforeReading() + { + var slotWriter = CreateArtifactWriter(TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-slot-{Guid.NewGuid():N}"), maximumBytes: 4); + await using var slotSource = new MemoryStream("12345"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await slotWriter.WriteAsync("report", "coverage/report.bin", slotSource, 5)); + Assert.Equal(0, slotSource.Position); + + var producerWriter = CreateArtifactWriter( + TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-producer-{Guid.NewGuid():N}"), + maximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1); + await using var producerSource = new MemoryStream(); + + await Assert.ThrowsAsync(async () => await producerWriter.WriteAsync( + "report", + "coverage/report.bin", + producerSource, + EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1)); + Assert.Equal(0, producerSource.Position); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldEnforceTheProducerLimitAcrossConcurrentSlots() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-total-{Guid.NewGuid():N}"); + var producer = new EvidenceProducerDeclaration( + "coverage", + "coverage", + "1.0.0", + [], + [], + [ + new EvidenceArtifactSlot("report", "coverage", "application/octet-stream", Required: false, MaximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes), + new EvidenceArtifactSlot("summary", "coverage", "application/octet-stream", Required: false, MaximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes), + ], + 30); + var writer = new EvidenceArtifactWriter(producer, artifactDirectory); + using var cancellation = new CancellationTokenSource(); + await using var firstSource = new BlockingAfterFirstReadStream("partial"u8.ToArray()); + var firstWrite = writer.WriteAsync( + "report", + "coverage/report.bin", + firstSource, + EvidenceArtifactWriter.MaximumTotalArtifactBytes, + cancellation.Token).AsTask(); + await firstSource.FirstReadCompleted.Task; + await using var secondSource = new MemoryStream("x"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await writer.WriteAsync("summary", "coverage/summary.bin", secondSource, 1)); + Assert.Equal(0, secondSource.Position); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => firstWrite); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldRejectShortAndLongStreamsAndReleaseReservations() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-length-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + await using var shortSource = new MemoryStream("short"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await writer.WriteAsync("report", "coverage/report.bin", shortSource, 6)); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + + await using var longSource = new MemoryStream("long"u8.ToArray(), writable: false); + await Assert.ThrowsAsync(async () => await writer.WriteAsync("report", "coverage/report.bin", longSource, 3)); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + + await using var validSource = new MemoryStream("valid"u8.ToArray(), writable: false); + var artifact = await writer.WriteAsync("report", "coverage/report.bin", validSource, 5); + Assert.Equal(5, artifact.LengthBytes); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamVerificationShouldDetectTampering() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-tamper-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + await using var source = new MemoryStream("original"u8.ToArray(), writable: false); + await writer.WriteAsync("report", "coverage/report.bin", source, source.Length); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => writer.VerifyWrittenArtifactsAsync(cancellation.Token)); + + await File.WriteAllTextAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"), "tampered"); + + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + await File.WriteAllTextAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"), "tampered-size"); + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldCleanUpAndReleaseReservationWhenCancelledMidCopy() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-cancel-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + using var cancellation = new CancellationTokenSource(); + await using var source = new BlockingAfterFirstReadStream("partial"u8.ToArray()); + + var write = writer.WriteAsync("report", "coverage/report.bin", source, 16, cancellation.Token).AsTask(); + await source.FirstReadCompleted.Task; + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => write); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + Assert.Empty(Directory.EnumerateFiles(artifactDirectory, "*", SearchOption.AllDirectories)); + + await using var validSource = new MemoryStream("valid"u8.ToArray(), writable: false); + Assert.Equal(5, (await writer.WriteAsync("report", "coverage/report.bin", validSource, 5)).LengthBytes); + Directory.Delete(artifactDirectory, recursive: true); + } + + private static EvidenceArtifactWriter CreateArtifactWriter(string artifactDirectory, long maximumBytes) => new( + new EvidenceProducerDeclaration( + "coverage", + "coverage", + "1.0.0", + [], + [], + [new EvidenceArtifactSlot("report", "coverage", "application/octet-stream", Required: false, MaximumBytes: maximumBytes)], + 30), + artifactDirectory); + + private sealed class NonSeekableReadStream(byte[] contents) : Stream + { + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) + { + var bytesToCopy = Math.Min(Math.Min(count, 4_096), contents.Length - _position); + contents.AsSpan(_position, bytesToCopy).CopyTo(buffer.AsSpan(offset, bytesToCopy)); + _position += bytesToCopy; + return bytesToCopy; + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var bytesToCopy = Math.Min(Math.Min(buffer.Length, 4_096), contents.Length - _position); + contents.AsMemory(_position, bytesToCopy).CopyTo(buffer); + _position += bytesToCopy; + return ValueTask.FromResult(bytesToCopy); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class GeneratedReadStream(long length) : Stream + { + private long _position; + + public long BytesRead => _position; + + public int MaximumRequestedReadSize { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + MaximumRequestedReadSize = Math.Max(MaximumRequestedReadSize, buffer.Length); + var bytesToRead = (int)Math.Min(buffer.Length, length - _position); + buffer.Span[..bytesToRead].Clear(); + _position += bytesToRead; + return ValueTask.FromResult(bytesToRead); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class BlockingAfterFirstReadStream(byte[] firstChunk) : Stream + { + private bool _firstRead = true; + + public TaskCompletionSource FirstReadCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_firstRead) + { + _firstRead = false; + var bytesToCopy = Math.Min(buffer.Length, firstChunk.Length); + firstChunk.AsMemory(0, bytesToCopy).CopyTo(buffer); + FirstReadCompleted.TrySetResult(); + return bytesToCopy; + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return 0; + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + [Fact] public async Task RunAsync_ShouldProtectLifecycleBoundsSharedDependenciesAndCallerCancelledProducers() { diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs new file mode 100644 index 000000000..9c6fa6cc4 --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs @@ -0,0 +1,416 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; +using ForgeTrust.AppSurface.Testing; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class AppSurfaceEvidencePolicyTests +{ + private const string PolicyRelativePath = ".appsurface/evidence/evidence.policy.json"; + private const string ShadowFixturesRelativePath = "docs/fixtures/issue-777-policy-shadow/fixtures.json"; + private static readonly EvidencePolicy Policy = LoadPolicy(); + private static readonly EvidencePlanner Planner = new(); + + [Theory] + [InlineData("docs/overview.md")] + [InlineData("guides/evidencehost-cookbook.md")] + [InlineData("start-here/evidencehost.md")] + [InlineData("README.md")] + [InlineData("CONTRIBUTING.md")] + public void ReviewedNarrativeDocumentation_ShouldProduceExplicitNoEvidenceClaim(string path) + { + // These paths contain human-facing reference and onboarding content only. The separately tested + // workflow, policy, design, script, and gate-implementation paths retain evidence obligations. + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + Assert.Equal("documentation-only", plan.Profile.Id); + Assert.Equal(EvidenceProfileScope.Targeted, plan.Profile.Scope); + Assert.Empty(plan.Profile.Resources); + Assert.Empty(plan.Profile.Producers); + Assert.Empty(plan.Profile.Obligations); + + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, manifest.ClaimKind); + Assert.Equal(EvidenceClaimEligibility.PullRequestGate, manifest.Eligibility); + } + + [Theory] + [InlineData("docs/designs/new-design.md")] + [InlineData("docs/plans/new-plan.md")] + [InlineData("docs/evidence-gate-rollout.md")] + [InlineData("guides/nested/behavior-contract.md")] + public void DesignPlanRolloutAndNestedDocumentation_ShouldRemainFailClosed(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + } + + [Fact] + public void ExecutableCode_ShouldSelectBoundedCoverageObligation() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("examples/web-app/ExampleModule.cs")]); + + Assert.Equal("code-coverage", plan.Profile.Id); + var coverage = Assert.Single(plan.Profile.Producers); + Assert.Equal("coverage", coverage.Id); + Assert.Equal(1200, coverage.TimeoutSeconds); + Assert.Equal( + new EvidenceCoverageGateRequirements(95, 85, 95, 85, "codecov", 0.5m), + coverage.CoverageGate); + Assert.All(coverage.ArtifactSlots, slot => Assert.InRange(slot.MaximumBytes, 1, 20_971_520)); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "behavioral-coverage"); + + var unregistered = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, unregistered.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, unregistered.ClaimKind); + } + + [Theory] + [InlineData("Durable/ForgeTrust.AppSurface.Durable.PostgreSql/Store.cs", "postgresql-integration", "postgresql-contract")] + [InlineData("examples/auth-aspire-keycloak-apphost/Program.cs", "keycloak-theme-integration", "keycloak-theme-contract")] + [InlineData("packages/package-index.yml", "package-release-preparation", "package-contract")] + [InlineData("src/Example/Example.csproj", "package-release-preparation", "package-contract")] + public void ResourceAndPackagePaths_ShouldKeepTheirRequiredProducers(string path, string profileId, string producerId) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + Assert.Equal(profileId, plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == producerId); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + if (profileId != "postgresql-integration" && profileId != "keycloak-theme-integration") + { + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "package-contract"); + } + Assert.NotEmpty(plan.Profile.Obligations); + Assert.All(plan.Profile.Producers, producer => Assert.InRange(producer.TimeoutSeconds, 1, 1800)); + Assert.All(plan.Profile.Resources, resource => Assert.InRange(resource.DeadlineSeconds, 1, 300)); + + // Policy selection is not producer registration or a successful execution. With no host results, + // every behavior-bearing profile must stay incomplete and ineligible. + var missing = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, missing.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, missing.ClaimKind); + } + + [Fact] + public void MixedDocumentationAndCode_ShouldUseTheConservativeUnion() + { + var plan = Planner.ResolveForGate( + Policy, + [ + new NormalizedDiffPath("guides/evidencehost-cookbook.md"), + new NormalizedDiffPath("examples/web-app/ExampleModule.cs"), + ]); + + AssertConservativeUnion(plan); + Assert.Contains("documentation-guides", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("coverage-csharp", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void RenameAcrossDocumentationAndResourcePaths_ShouldEvaluateBothNames() + { + var renamed = new NormalizedDiffPath( + "guides/evidencehost-cookbook.md", + "renamed", + "Durable/verify-postgresql.sh"); + var plan = Planner.ResolveForGate(Policy, [renamed]); + + AssertConservativeUnion(plan); + Assert.Contains("documentation-guides", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("integration-durable-postgresql", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Equal("Durable/verify-postgresql.sh", Assert.Single(plan.ChangedPaths).PreviousPath); + } + + [Fact] + public void DeletedCodePath_ShouldStillRequireCoverage() + { + var plan = Planner.ResolveForGate( + Policy, + [new NormalizedDiffPath("examples/web-app/ExampleModule.cs", "deleted")]); + + Assert.Equal("code-coverage", plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "behavioral-coverage"); + Assert.Equal("deleted", Assert.Single(plan.ChangedPaths).Kind); + } + + [Theory] + [InlineData("Durable/ForgeTrust.AppSurface.Durable.PostgreSql/ForgeTrust.AppSurface.Durable.PostgreSql.csproj")] + [InlineData("Web/ForgeTrust.AppSurface.Web.Tailwind/ForgeTrust.AppSurface.Web.Tailwind.csproj")] + [InlineData("Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/ForgeTrust.AppSurface.Auth.Aspire.Keycloak.csproj")] + public void ResourceProjectFiles_ShouldRetainPackageAndIntegrationObligations(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "package-locked-build-and-artifacts"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "postgresql-integration-contract"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "keycloak-theme-rendering"); + } + + [Theory] + [InlineData("src/client/app.ts")] + [InlineData("src/client/app.tsx")] + [InlineData("src/client/app.js")] + [InlineData("src/client/app.css")] + [InlineData("src/client/theme.scss")] + [InlineData("Web/Pages/Index.razor")] + [InlineData("data/migrations/0001_contract.sql")] + public void NonDotNetBehavior_ShouldRemainFailClosedUntilAProducerCanProveIt(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, manifest.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, manifest.ClaimKind); + } + + [Fact] + public void DurableSql_ShouldRequireResourceBackedDatabaseEvidence() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("Durable/Migrations/0001_contract.sql")]); + + Assert.Equal("postgresql-integration", plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "postgresql-contract"); + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, manifest.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, manifest.ClaimKind); + } + + [Theory] + [InlineData(".github/workflows/build.yml")] + [InlineData(".appsurface/evidence/evidence.policy.json")] + [InlineData("docs/designs/issue-777-policy-driven-ci-evidence-gate.md")] + [InlineData("docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md")] + [InlineData("docs/evidence-gate-policy-matrix.md")] + [InlineData("docs/evidence-gate-rollout.md")] + [InlineData("docs/evidence-gate-diagnostics.md")] + [InlineData("docs/evidence-gate-migration.md")] + [InlineData("docs/fixtures/issue-777-docs-only/fixture.json")] + [InlineData("scripts/coverage-solution.sh")] + [InlineData("Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs")] + [InlineData("Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs")] + [InlineData("tools/ForgeTrust.AppSurface.EvidenceGate/Program.cs")] + [InlineData("tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateVerifierTests.cs")] + [InlineData("tools/ForgeTrust.AppSurface.Release/ReleaseCommands.cs")] + [InlineData("tools/ForgeTrust.AppSurface.Release.Tests/ReleaseToolTests.cs")] + [InlineData("tools/ForgeTrust.AppSurface.PackageIndex/Program.cs")] + [InlineData("tools/ForgeTrust.AppSurface.PackageIndex.Tests/PackageIndexTests.cs")] + [InlineData("docs/fixtures/issue-777-policy-shadow/fixtures.json")] + public void ControlPlanePaths_ShouldNeverUseNoEvidenceProfile(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.NotEqual("documentation-only", plan.Profile.Id); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + } + + [Fact] + public void UnclassifiedRepositoryPath_ShouldUseConservativeFallback() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("new-area/unrecognized-input.bin")]); + + AssertConservativeUnion(plan); + Assert.Contains("conservative:pr-conservative", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void CheckedInShadowFixtures_ShouldRemainCompatibleWithReviewedPolicy() + { + var fixtures = EvidenceCanonicalJson.Deserialize( + File.ReadAllBytes(FindRepositoryFile(ShadowFixturesRelativePath))); + + var result = EvidencePolicyShadowValidator.Validate(Policy, Policy, fixtures, fixtures); + + Assert.True(result.IsCompatible); + Assert.Equal(11, result.Selections.Count); + Assert.Empty(result.Diagnostics); + Assert.False(result.DiagnosticsTruncated); + Assert.Contains(result.Selections, selection => + selection.Kind == EvidencePolicyShadowFixtureKind.ControlPlane + && selection.FixtureId == "fixture-control-plane" + && selection.BaseProfileId == "pr-conservative"); + } + + [Fact] + public void ConservativeProfile_ShouldPreserveEveryTargetedPrRequirement() + { + EvidencePlanner.ValidateGatePolicy(Policy); + + var conservative = GetProfile("pr-conservative"); + Assert.Equal(EvidenceProfileScope.Targeted, conservative.Scope); + Assert.Equal(conservative.Producers.Count, conservative.Producers.Select(producer => producer.Id).Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(conservative.Obligations.Count, conservative.Obligations.Select(obligation => obligation.Id).Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(conservative.Resources.Count, conservative.Resources.Select(resource => resource.Id).Distinct(StringComparer.Ordinal).Count()); + + var profilesById = Policy.Profiles.ToDictionary(profile => profile.Id, StringComparer.Ordinal); + foreach (var targeted in Policy.Rules.Select(rule => profilesById[rule.ProfileId]).DistinctBy(profile => profile.Id)) + { + Assert.All(targeted.Resources, required => AssertResourceIncluded(required, conservative.Resources)); + Assert.All(targeted.Producers, required => AssertProducerIncluded(required, conservative.Producers)); + Assert.All(targeted.Obligations, required => AssertObligationIncluded(required, conservative.Obligations)); + } + + var weakenedProfiles = Policy.Profiles + .Select(profile => profile.Id == conservative.Id + ? profile with + { + Producers = profile.Producers + .Select(producer => producer.Id == "package-contract" + ? producer with { TimeoutSeconds = producer.TimeoutSeconds + 1 } + : producer) + .ToArray(), + } + : profile) + .ToArray(); + var weakened = Policy with { Profiles = weakenedProfiles }; + var error = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(weakened)); + + Assert.Equal("ASEVD129", error.Code); + Assert.Contains("package-contract", error.Message, StringComparison.Ordinal); + + var weakenedReleaseProfile = Policy.Profiles + .Select(profile => profile.Id == conservative.Id + ? profile with + { + Producers = profile.Producers + .Select(producer => producer.Id == "release-preparation-contract" + ? producer with { TimeoutSeconds = producer.TimeoutSeconds + 1 } + : producer) + .ToArray(), + } + : profile) + .ToArray(); + var missingReleaseProducer = Policy with + { + Profiles = weakenedReleaseProfile, + }; + var releaseError = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(missingReleaseProducer)); + Assert.Equal("ASEVD129", releaseError.Code); + Assert.Contains("release-preparation-contract", releaseError.Message, StringComparison.Ordinal); + } + + [Fact] + public void ProtectedReleaseProfile_ShouldNotBeSelectableByAnyPrRule() + { + var release = GetProfile("protected-release"); + Assert.Equal(EvidenceProfileScope.Release, release.Scope); + Assert.NotEmpty(release.Obligations); + Assert.All(Policy.Rules, rule => Assert.Equal(EvidenceProfileScope.Targeted, GetProfile(rule.ProfileId).Scope)); + + var invalidRules = Policy.Rules + .Append(new EvidencePolicyRule("invalid-pr-release-selection", "release/**", release.Id)) + .ToArray(); + var invalidPrPolicy = Policy with { Rules = invalidRules }; + var error = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(invalidPrPolicy)); + + Assert.Equal("ASEVD129", error.Code); + Assert.Contains("non-targeted", error.Message, StringComparison.OrdinalIgnoreCase); + } + + private static void AssertConservativeUnion(EvidencePlan plan) + { + Assert.Equal("pr-conservative", plan.Profile.Id); + Assert.Equal(EvidenceProfileScope.Targeted, plan.Profile.Scope); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "postgresql-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "keycloak-theme-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "package-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "release-preparation-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "control-plane-validation"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "release-preparation-evidence"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, EvidenceManifestBuilder.Build(plan, []).ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, EvidenceManifestBuilder.Build(plan, []).ClaimKind); + } + + private static EvidenceProfile GetProfile(string id) => + Policy.Profiles.Single(profile => string.Equals(profile.Id, id, StringComparison.Ordinal)); + + private static void AssertResourceIncluded( + EvidenceResourceDeclaration required, + IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.Readiness, actual.Readiness); + Assert.True(actual.DeadlineSeconds <= required.DeadlineSeconds); + Assert.All(required.Requires, dependency => Assert.Contains(dependency, actual.Requires, StringComparer.Ordinal)); + } + + private static void AssertProducerIncluded( + EvidenceProducerDeclaration required, + IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.Kind, actual.Kind); + Assert.Equal(required.Version, actual.Version); + Assert.True(actual.TimeoutSeconds <= required.TimeoutSeconds); + AssertCoverageGateIncluded(required.CoverageGate, actual.CoverageGate); + Assert.All(required.RequiredResources, resource => Assert.Contains(resource, actual.RequiredResources, StringComparer.Ordinal)); + Assert.All(required.AssertionIds, assertion => Assert.Contains(assertion, actual.AssertionIds, StringComparer.Ordinal)); + + foreach (var slot in required.ArtifactSlots) + { + var actualSlot = Assert.Single(actual.ArtifactSlots, candidate => candidate.LogicalName == slot.LogicalName); + Assert.Equal(slot.RelativeRoot, actualSlot.RelativeRoot); + Assert.Equal(slot.MediaType, actualSlot.MediaType); + Assert.True(!slot.Required || actualSlot.Required); + Assert.True(actualSlot.MaximumBytes <= slot.MaximumBytes); + } + } + + private static void AssertObligationIncluded(EvidenceObligation required, IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.RiskClass, actual.RiskClass); + Assert.Equal(required.Rationale, actual.Rationale); + Assert.Equal(required.RequiredAssertionId, actual.RequiredAssertionId); + Assert.All(required.RequiredProducerIds, producer => Assert.Contains(producer, actual.RequiredProducerIds, StringComparer.Ordinal)); + } + + private static void AssertCoverageGateIncluded( + EvidenceCoverageGateRequirements? required, + EvidenceCoverageGateRequirements? actual) + { + if (required is null) + { + return; + } + + Assert.NotNull(actual); + Assert.True(actual.MinLinePercent >= required.MinLinePercent); + Assert.True(actual.MinBranchPercent >= required.MinBranchPercent); + Assert.True(required.MinPatchLinePercent is null || actual.MinPatchLinePercent >= required.MinPatchLinePercent); + Assert.True(required.MinPatchBranchPercent is null || actual.MinPatchBranchPercent >= required.MinPatchBranchPercent); + Assert.Equal(required.PatchLineMode, actual.PatchLineMode, ignoreCase: true); + Assert.True(actual.TolerancePercent <= required.TolerancePercent); + } + + private static EvidencePolicy LoadPolicy() + { + return EvidenceCanonicalJson.Deserialize( + File.ReadAllBytes(FindRepositoryFile(PolicyRelativePath))); + } + + private static string FindRepositoryFile(string relativePath) + { + var current = new DirectoryInfo(AppContext.BaseDirectory); + while (current is not null) + { + var candidate = TestPathUtils.PathUnder(current.FullName, relativePath); + if (File.Exists(candidate)) + { + return candidate; + } + + current = current.Parent; + } + + throw new DirectoryNotFoundException($"Could not find the checked-in {relativePath} file from the test assembly directory."); + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunArtifactReaderTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunArtifactReaderTests.cs index bd92fbf11..1faa3059b 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunArtifactReaderTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunArtifactReaderTests.cs @@ -8,6 +8,28 @@ namespace ForgeTrust.AppSurface.Cli.Tests; public sealed class CoverageRunArtifactReaderTests { + [Fact] + public void OpenRegularFile_ShouldReadCoverageArtifactOnLinuxArm64() + { + if (!OperatingSystem.IsLinux() || RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + { + return; + } + + using var repo = ArtifactTempDirectory.Create("appsurface-coverage-arm64-artifact-"); + var projectOutput = Path.Join(repo.Path, "project"); + var raw = Path.Join(projectOutput, "collector-results", "invocation"); + Directory.CreateDirectory(raw); + var candidate = repo.WriteFile( + "project/collector-results/invocation/coverage.cobertura.xml", + ""); + + using var stream = CoverageRunArtifactReader.OpenRegularFile(projectOutput, raw, candidate); + using var reader = new StreamReader(stream); + + Assert.Equal("", reader.ReadToEnd()); + } + [Fact] public void WindowsInteropStructures_ShouldMatchNativeLayouts() { diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunOutputGuardSecurityTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunOutputGuardSecurityTests.cs index 00804f705..861878ce2 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunOutputGuardSecurityTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunOutputGuardSecurityTests.cs @@ -13,6 +13,24 @@ public sealed class CoverageRunOutputGuardSecurityTests { private const string MarkerContents = "AppSurface coverage output directory"; + [Fact] + public void Prepare_ShouldAcquireAnOrdinaryOutputDirectoryOnLinuxArm64() + { + if (!OperatingSystem.IsLinux() || RuntimeInformation.ProcessArchitecture != Architecture.Arm64) + { + return; + } + + using var root = TestDirectory.Create(); + var output = Path.Join(root.Path, "coverage"); + using var lease = CoverageRunOutputLease.Acquire(output); + + lease.Prepare(clean: false, beforeMutation: null, beforeCleanup: null); + + Assert.True(Directory.Exists(output)); + Assert.Equal(MarkerContents + Environment.NewLine, File.ReadAllText(Path.Join(output, ".appsurface-coverage-output"))); + } + [Fact] public void Validate_ShouldRejectExistingAncestorLinkWithoutTouchingExternalFiles() { diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunWatchdogTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunWatchdogTests.cs index 261ef28af..ed6310ede 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunWatchdogTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageRunWatchdogTests.cs @@ -704,6 +704,7 @@ public async Task ConsoleSink_ShouldFallbackCriticalErrorWithoutLateDuplicate() await sink.WriteCriticalErrorAsync("critical-error").WaitAsync(TimeSpan.FromSeconds(1)); + await error.FirstWriteCompleted.WaitAsync(TimeSpan.FromSeconds(2)); Assert.Equal(1, error.WriteCount); Assert.Contains("critical-error", error.ReadString(), StringComparison.Ordinal); @@ -1216,6 +1217,7 @@ private sealed class GatedCaptureWriteStream : Stream { private readonly MemoryStream _capture = new(); private readonly TaskCompletionSource _firstWriteStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource _firstWriteCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _releaseFirstWrite = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly TaskCompletionSource _secondWriteCompleted = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly object _sync = new(); @@ -1223,6 +1225,8 @@ private sealed class GatedCaptureWriteStream : Stream public Task FirstWriteStarted => _firstWriteStarted.Task; + public Task FirstWriteCompleted => _firstWriteCompleted.Task; + public Task SecondWriteCompleted => _secondWriteCompleted.Task; public int WriteCount => Volatile.Read(ref _writeCount); @@ -1278,6 +1282,11 @@ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, Cancella _capture.Write(buffer.Span); } + if (ordinal == 1) + { + _firstWriteCompleted.TrySetResult(); + } + if (ordinal == 2) { _secondWriteCompleted.TrySetResult(); diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageSolutionScriptTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageSolutionScriptTests.cs index 92cace049..ac24249a2 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageSolutionScriptTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/CoverageSolutionScriptTests.cs @@ -64,7 +64,7 @@ public async Task Script_ShouldRejectRetiredInputsBeforeStartingDotnetOrCreating } [Fact] - public void BuildWorkflow_ShouldUseCoverageSolutionScriptForDefaultLane() + public void BuildWorkflow_ShouldUseCoverageSolutionScriptForPullRequestsAndManualBranchRuns() { var workflow = ReadWorkflow(); @@ -72,7 +72,8 @@ public void BuildWorkflow_ShouldUseCoverageSolutionScriptForDefaultLane() Assert.Contains("BUILD_CONFIGURATION: Release", workflow, StringComparison.Ordinal); Assert.Contains("BUILD_NO_RESTORE: true", workflow, StringComparison.Ordinal); Assert.Contains("COVERAGE_PARALLELISM: 2", workflow, StringComparison.Ordinal); - Assert.Contains("COVERAGE_GATE_DIFF_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || '' }}", workflow, StringComparison.Ordinal); + Assert.Contains("fetch-depth: ${{ github.event_name == 'workflow_dispatch' && '0' || github.event_name == 'pull_request' && '2' || '1' }}", workflow, StringComparison.Ordinal); + Assert.Contains("COVERAGE_GATE_DIFF_BASE: ${{ github.event_name == 'pull_request' && 'HEAD^1' || github.event_name == 'workflow_dispatch' && 'origin/main' || '' }}", workflow, StringComparison.Ordinal); Assert.Contains("./scripts/coverage-solution.sh", workflow, StringComparison.Ordinal); Assert.Contains("Publish bounded test-result and slow-test diagnostics summary", workflow, StringComparison.Ordinal); Assert.Contains("test-result-diagnostics", workflow, StringComparison.Ordinal); diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs new file mode 100644 index 000000000..84a5e704b --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs @@ -0,0 +1,624 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using ForgeTrust.AppSurface.Evidence.Cli; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +[CollectionDefinition(nameof(GitProcessEnvironmentCollection), DisableParallelization = true)] +public sealed class GitProcessEnvironmentCollection +{ +} + +[Collection(nameof(GitProcessEnvironmentCollection))] +public sealed class EvidenceGitChangeCaptureTests +{ + [Fact] + public void ParseNameStatus_ShouldIncludeNonTextChangesAndBothRenamePaths() + { + var bytes = Encoding.UTF8.GetBytes("A\0src/new.cs\0M\0images/logo.bin\0T\0links/current\0R100\0src/old.cs\0src/moved.cs\0C75\0src/base.cs\0src/copied.cs\0D\0src/gone.cs\0"); + + var paths = EvidenceGitChangeCapture.ParseNameStatus(bytes); + + Assert.Collection( + paths, + path => Assert.Equal(("src/new.cs", "added", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("images/logo.bin", "modified", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("links/current", "typechanged", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/moved.cs", "renamed", "src/old.cs"), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/copied.cs", "copied", "src/base.cs"), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/gone.cs", "deleted", (string?)null), (path.Path, path.Kind, path.PreviousPath))); + } + + [Theory] + [InlineData("A\0src/file.cs")] + [InlineData("\0src/file.cs\0")] + [InlineData("A\0\0")] + [InlineData("U\0src/file.cs\0")] + [InlineData("R\0src/old.cs\0src/new.cs\0")] + [InlineData("Rxyz\0src/old.cs\0src/new.cs\0")] + [InlineData("R-1\0src/old.cs\0src/new.cs\0")] + [InlineData("R1000\0src/old.cs\0src/new.cs\0")] + [InlineData("R101\0src/old.cs\0src/new.cs\0")] + [InlineData("R50\0src/old.cs\0")] + [InlineData("R100\0src/old.cs\0\0")] + [InlineData("C100\0\0src/copied.cs\0")] + [InlineData("A\0../outside\0")] + [InlineData("A\0/absolute/path\0")] + [InlineData("A\0src/trailing/\0")] + [InlineData("A\0src/./file.cs\0")] + [InlineData("A\0src//file.cs\0")] + [InlineData("A\0src\\file.cs\0")] + [InlineData("A\0src/file\n.cs\0")] + [InlineData("A\0src/file\t.cs\0")] + [InlineData("A\0src/file.cs\0A\0src/file.cs\0")] + public void ParseNameStatus_ShouldRejectMalformedOrUnsafeRecords(string output) + { + var exception = Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(Encoding.UTF8.GetBytes(output))); + + Assert.Equal("ASEVD135", exception.Code); + } + + [Fact] + public void ParseNameStatus_ShouldAcceptZeroSimilarityRenameAndCopyRecords() + { + var bytes = Encoding.UTF8.GetBytes( + "R0\0src/old.cs\0src/renamed.cs\0C0\0src/original.cs\0src/copied.cs\0"); + + var paths = EvidenceGitChangeCapture.ParseNameStatus(bytes); + + Assert.Collection( + paths, + path => Assert.Equal(("src/renamed.cs", "renamed", "src/old.cs"), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/copied.cs", "copied", "src/original.cs"), (path.Path, path.Kind, path.PreviousPath))); + } + + [Fact] + public void ParseNameStatus_ShouldRejectInvalidUtf8AndOversizedPath() + { + var invalidUtf8 = new byte[] { (byte)'A', 0, 0xff, 0 }; + var invalidStatusUtf8 = new byte[] { 0xff, 0, (byte)'a', 0 }; + var longPath = Encoding.UTF8.GetBytes($"A\0{new string('x', EvidenceGitChangeCapture.MaximumPathBytes + 1)}\0"); + + Assert.Equal("ASEVD135", Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(invalidUtf8)).Code); + Assert.Equal("ASEVD135", Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(invalidStatusUtf8)).Code); + Assert.Equal("ASEVD135", Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(longPath)).Code); + } + + [Fact] + public void ParseNameStatus_ShouldBoundRecordCount() + { + var builder = new StringBuilder(); + for (var index = 0; index <= EvidenceGitChangeCapture.MaximumChangedRecords; index++) + { + builder.Append("A\0src/file").Append(index).Append(".cs\0"); + } + + var exception = Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(Encoding.UTF8.GetBytes(builder.ToString()))); + + Assert.Equal("ASEVD134", exception.Code); + } + + [Fact] + public void ParseNameStatus_ShouldRejectInputAboveTheByteLimitBeforeParsingRecords() + { + var input = new byte[85 * 1024 * 1024 + 1]; + + var exception = Assert.Throws(() => + EvidenceGitChangeCapture.ParseNameStatus(input)); + + Assert.Equal("ASEVD135", exception.Code); + } + + [Fact] + public async Task CaptureAndVerify_ShouldBindExactCommitsAndIncludeBinaryPath() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "code.cs"), "before\n"); + repository.Run("add", "code.cs"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + + File.WriteAllText(Path.Join(repository.Path, "code.cs"), "after\n"); + File.WriteAllBytes(Path.Join(repository.Path, "blob.bin"), [0, 1, 2, 255, 0, 254]); + repository.Run("add", "code.cs", "blob.bin"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "unrelated.txt"), "later\n"); + repository.Run("add", "unrelated.txt"); + repository.Commit("ambient-head-moved"); + repository.Run("config", "diff.external", "false"); + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + await EvidenceGitChangeCapture.VerifyAsync(repository.Path, snapshot); + + Assert.Equal(baseRevision, snapshot.BaseRevision); + Assert.Equal(headRevision, snapshot.HeadRevision); + Assert.Equal(64, snapshot.SourceDiffDigest.Length); + Assert.Equal(64, snapshot.NameStatusDigest.Length); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "blob.bin" && path.Kind == "added"); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "code.cs" && path.Kind == "modified"); + Assert.DoesNotContain(snapshot.ChangedPaths, path => path.Path == "unrelated.txt"); + Assert.Contains("diff --git", Encoding.UTF8.GetString(snapshot.SourceDiff.Span), StringComparison.Ordinal); + } + + [Fact] + public async Task Capture_ShouldIgnoreInheritedGitRepositoryOverrides() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "before\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "after\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + + var originalGitDirectory = Environment.GetEnvironmentVariable("GIT_DIR"); + var originalWorkTree = Environment.GetEnvironmentVariable("GIT_WORK_TREE"); + try + { + Environment.SetEnvironmentVariable("GIT_DIR", Path.Join(repository.Path, "untrusted-git-dir")); + Environment.SetEnvironmentVariable("GIT_WORK_TREE", Path.Join(repository.Path, "untrusted-work-tree")); + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + Assert.Equal(baseRevision, snapshot.BaseRevision); + Assert.Equal(headRevision, snapshot.HeadRevision); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "readme.md" && path.Kind == "modified"); + } + finally + { + Environment.SetEnvironmentVariable("GIT_DIR", originalGitDirectory); + Environment.SetEnvironmentVariable("GIT_WORK_TREE", originalWorkTree); + } + } + + [Fact] + public async Task Verify_ShouldIgnoreGitReplaceRefsWhenCheckingExactRevisionSnapshot() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "before\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "after\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + File.WriteAllText(Path.Join(repository.Path, "replacement.txt"), "replacement tree\n"); + repository.Run("add", "replacement.txt"); + repository.Commit("replacement"); + var replacementRevision = repository.Run("rev-parse", "HEAD").Trim(); + repository.Run("replace", headRevision, replacementRevision); + + var originalNoReplaceObjects = Environment.GetEnvironmentVariable("GIT_NO_REPLACE_OBJECTS"); + try + { + Environment.SetEnvironmentVariable("GIT_NO_REPLACE_OBJECTS", null); + Assert.Contains("replacement.txt", repository.Run("diff", "--name-only", baseRevision, headRevision), StringComparison.Ordinal); + + await EvidenceGitChangeCapture.VerifyAsync(repository.Path, snapshot); + } + finally + { + Environment.SetEnvironmentVariable("GIT_NO_REPLACE_OBJECTS", originalNoReplaceObjects); + } + } + + [Fact] + public async Task Verify_ShouldRejectSnapshotWhenExactCommitObjectIsRemoved() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "before\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "after\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + var headObject = Path.Join(repository.Path, ".git", "objects", headRevision[..2], headRevision[2..]); + Assert.True(File.Exists(headObject)); + File.Delete(headObject); + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.VerifyAsync(repository.Path, snapshot)); + + Assert.Equal("ASEVD136", exception.Code); + } + + [Fact] + public async Task Verify_ShouldRejectSnapshotWhenItsExposedDiffBufferWasModified() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "before\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "after\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + Assert.True(MemoryMarshal.TryGetArray(snapshot.SourceDiff, out var sourceDiff)); + Assert.NotNull(sourceDiff.Array); + Assert.True(sourceDiff.Count > 0); + sourceDiff.Array![sourceDiff.Offset] ^= 0x01; + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.VerifyAsync(repository.Path, snapshot)); + + Assert.Equal("ASEVD133", exception.Code); + } + + [Fact] + public async Task Capture_ShouldReportWhenGitExecutableIsUnavailable() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "before\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "after\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var emptyPath = Directory.CreateDirectory(Path.Join(repository.Path, "empty-path")).FullName; + + var originalPath = Environment.GetEnvironmentVariable("PATH"); + try + { + Environment.SetEnvironmentVariable("PATH", emptyPath); + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision)); + + Assert.Equal("ASEVD136", exception.Code); + Assert.Contains("unavailable", exception.Message, StringComparison.OrdinalIgnoreCase); + } + finally + { + Environment.SetEnvironmentVariable("PATH", originalPath); + } + } + + [Fact] + public async Task Capture_ShouldSelectRenameModeSymlinkAndSubmoduleWithoutTextHunks() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "mode.sh"), "#!/bin/sh\n"); + File.WriteAllText(Path.Join(repository.Path, "old.txt"), "unchanged\n"); + repository.Run("add", "mode.sh", "old.txt"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + + repository.Run("mv", "old.txt", "moved.txt"); + repository.Run("update-index", "--chmod=+x", "mode.sh"); + if (!OperatingSystem.IsWindows()) + { + File.CreateSymbolicLink(Path.Join(repository.Path, "linked"), "moved.txt"); + repository.Run("add", "linked"); + } + repository.Run("update-index", "--add", "--cacheinfo", $"160000,{baseRevision},submodule"); + repository.Commit("nontext"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "moved.txt" && path.PreviousPath == "old.txt" && path.Kind == "renamed"); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "mode.sh" && path.Kind == "modified"); + if (!OperatingSystem.IsWindows()) + { + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "linked" && path.Kind == "added"); + } + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "submodule" && path.Kind == "added"); + } + + [Theory] + [InlineData(null)] + [InlineData(" ")] + [InlineData("main")] + [InlineData("abc123")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")] + public async Task Capture_ShouldRejectRefsAndNonCanonicalObjectIds(string? revision) + { + using var repository = new GitFixture(); + + var exception = await Assert.ThrowsAsync( + () => EvidenceGitChangeCapture.CaptureAsync(repository.Path, revision!, revision!)); + + Assert.Equal("ASEVD130", exception.Code); + } + + [Fact] + public async Task Capture_ShouldRejectMissingCommitObject() + { + using var repository = new GitFixture(); + var missingRevision = new string('a', 40); + + var exception = await Assert.ThrowsAsync( + () => EvidenceGitChangeCapture.CaptureAsync(repository.Path, missingRevision, missingRevision)); + + Assert.Equal("ASEVD136", exception.Code); + } + + [Fact] + public async Task Capture_ShouldRejectMixedObjectIdFormatsBeforeReadingGit() + { + using var repository = new GitFixture(); + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(repository.Path, new string('a', 40), new string('b', 64))); + + Assert.Equal("ASEVD130", exception.Code); + } + + [Fact] + public async Task Capture_ShouldRejectUnavailableTrustedObjectStore() + { + using var repository = new GitFixture(); + var missingStore = Path.Join(repository.Path, "missing-object-store"); + var revision = new string('a', 40); + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(missingStore, revision, revision)); + + Assert.Equal("ASEVD131", exception.Code); + } + + [Fact] + public async Task Capture_ShouldRejectNonCommitObjectAndUnchangedCommitPair() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "content\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var commitRevision = repository.Run("rev-parse", "HEAD").Trim(); + var blobRevision = repository.Run("rev-parse", "HEAD:readme.md").Trim(); + + var nonCommit = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(repository.Path, commitRevision, blobRevision)); + Assert.Equal("ASEVD131", nonCommit.Code); + + var noChange = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(repository.Path, commitRevision, commitRevision)); + Assert.Equal("ASEVD132", noChange.Code); + } + + [Fact] + public async Task Capture_ShouldRejectARealBinaryDiffAboveTheReviewedByteLimit() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "base\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + + var binary = new byte[EvidenceGitChangeCapture.MaximumSourceDiffBytes + 4 * 1024 * 1024]; + new Random(777).NextBytes(binary); + File.WriteAllBytes(Path.Join(repository.Path, "large.bin"), binary); + repository.Run("add", "large.bin"); + repository.Commit("large-binary"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + + var exception = await Assert.ThrowsAsync(() => + EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision)); + + Assert.Equal("ASEVD134", exception.Code); + } + + [Fact] + public async Task RevisionBoundCli_ShouldRecreateV2IdentityAndRejectTamperedDiffOrPolicy() + { + using var repository = new GitFixture(); + Directory.CreateDirectory(Path.Join(repository.Path, "docs")); + var documentPath = Path.Join(repository.Path, "docs", "readme.md"); + File.WriteAllText(documentPath, "before\n"); + repository.Run("add", "docs/readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(documentPath, "after\n"); + repository.Run("add", "docs/readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + var diffPath = Path.Join(repository.Path, "change.diff"); + await File.WriteAllBytesAsync(diffPath, snapshot.SourceDiff.ToArray()); + var policyPath = Path.Join(repository.Path, "policy.json"); + var policy = CreateGatePolicy(); + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(policy)); + var workflow = new EvidenceCliWorkflow(new EvidencePlanner()); + var request = new EvidencePlanningRequest(policyPath, [], diffPath, baseRevision, headRevision, repository.Path, GateMode: true); + + var first = await workflow.ExplainAsync(request, CancellationToken.None); + var second = await workflow.ExplainAsync(request, CancellationToken.None); + Assert.Equal(first.PlanDigest, second.PlanDigest); + Assert.Equal("2.0", first.ContractVersion); + Assert.Equal(snapshot.SourceDiffDigest, first.SourceDiffDigest); + Assert.Equal(snapshot.NameStatusDigest, first.NameStatusDigest); + var manifest = EvidenceManifestBuilder.Build(first, []); + Assert.True(EvidenceManifestBuilder.Verify(first, manifest)); + Assert.Equal(baseRevision, manifest.BaseRevision); + Assert.Equal(headRevision, manifest.HeadRevision); + + var capturedIdentity = new EvidencePullRequestRunIdentity(123, 123, 777, "main", 456, 1); + var identifiedPlan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot, capturedIdentity); + var identifiedManifest = EvidenceManifestBuilder.Build(identifiedPlan, []); + Assert.Equal(capturedIdentity, identifiedManifest.PullRequestRunIdentity); + await EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy, repository.Path, identifiedPlan, expectedRunIdentity: capturedIdentity); + Assert.Equal("ASEVD139", (await Assert.ThrowsAsync(() => + EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy, repository.Path, identifiedPlan, + expectedRunIdentity: capturedIdentity with { WorkflowRunAttempt = 2 }))).Code); + var identityPath = Path.Join(repository.Path, "pr-run-identity.json"); + await File.WriteAllBytesAsync(identityPath, EvidenceCanonicalJson.Serialize(capturedIdentity)); + var cliIdentified = await workflow.ExplainAsync(request with { PullRequestRunIdentityFile = identityPath }, CancellationToken.None); + Assert.Equal(identifiedPlan.PlanDigest, cliIdentified.PlanDigest); + + var output = Path.Join(repository.Path, "output"); + await workflow.WritePlanAsync(first, output, CancellationToken.None); + await workflow.WriteManifestAsync(manifest, output, CancellationToken.None); + var planPath = Path.Join(output, "evidence-plan.json"); + var manifestPath = Path.Join(output, "evidence-manifest.json"); + await workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path); + Assert.Contains("ASEVD232", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None))).Message, StringComparison.Ordinal); + + await File.AppendAllTextAsync(manifestPath, "\n"); + Assert.Contains("ASEVD209", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path))).Message, StringComparison.Ordinal); + await workflow.WriteManifestAsync(manifest, output, CancellationToken.None); + + File.AppendAllText(diffPath, "tampered"); + Assert.Contains("ASEVD231", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(request, CancellationToken.None))).Message, StringComparison.Ordinal); + + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(policy with { Id = "substituted" })); + Assert.Equal("ASEVD139", (await Assert.ThrowsAsync( + () => EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy with { Id = "substituted" }, repository.Path, first))).Code); + Assert.Contains("ASEVD203", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path))).Message, StringComparison.Ordinal); + } + + [Fact] + public async Task RevisionBoundCli_ShouldRejectPartialAndPathOnlyGateInputs() + { + using var repository = new GitFixture(); + var policyPath = Path.Join(repository.Path, "policy.json"); + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(CreateGatePolicy())); + var workflow = new EvidenceCliWorkflow(new EvidencePlanner()); + + var partial = new EvidencePlanningRequest(policyPath, [], null, BaseRevision: new string('a', 40)); + Assert.Contains("ASEVD230", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(partial, CancellationToken.None))).Message, StringComparison.Ordinal); + var pathOnly = new EvidencePlanningRequest(policyPath, ["docs/readme.md"], null, GateMode: true); + Assert.Contains("ASEVD230", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(pathOnly, CancellationToken.None))).Message, StringComparison.Ordinal); + Assert.Contains("ASEVD233", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(pathOnly with { GateMode = false, PullRequestRunIdentityFile = "identity.json" }, CancellationToken.None))).Message, StringComparison.Ordinal); + } + + [Fact] + public async Task ResolveForPullRequest_ShouldRejectIncompleteControllerRunIdentity() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "base\n"); + repository.Run("add", "readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "readme.md"), "head\n"); + repository.Run("add", "readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + var valid = new EvidencePullRequestRunIdentity(123, 123, 777, "main", 456, 1); + var invalid = new[] + { + valid with { RepositoryId = 0 }, + valid with { HeadRepositoryId = 0 }, + valid with { PullRequestNumber = 0 }, + valid with { TargetBranch = "" }, + valid with { TargetBranch = new string('m', 129) }, + valid with { WorkflowRunId = 0 }, + valid with { WorkflowRunAttempt = 0 }, + }; + + foreach (var runIdentity in invalid) + { + var exception = Assert.Throws(() => + EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), CreateGatePolicy(), snapshot, runIdentity)); + Assert.Equal("ASEVD140", exception.Code); + } + } + + [Fact] + public async Task ResolveForPullRequest_ShouldRejectReleaseOnlyRuleBeforeIssuingAClaim() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "VERSION"), "1.0.0\n"); + repository.Run("add", "VERSION"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "VERSION"), "1.0.1\n"); + repository.Run("add", "VERSION"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + var policy = CreateGatePolicy(); + var conservative = policy.Profiles.Single(profile => profile.Id == policy.ConservativeProfileId); + var release = conservative with { Id = "release", Scope = EvidenceProfileScope.Release }; + policy = policy with + { + Profiles = [.. policy.Profiles, release], + Rules = [.. policy.Rules, new EvidencePolicyRule("version", "VERSION", "release")], + }; + + var exception = Assert.Throws(() => + EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot)); + + Assert.Equal("ASEVD129", exception.Code); + } + + private static EvidencePolicy CreateGatePolicy() + { + var all = new EvidenceProfile( + "all", EvidenceProfileScope.Targeted, [], + [new EvidenceProducerDeclaration("build", "build", "1", [], ["build/pass"], [], 60)], + [new EvidenceObligation("build", "code", "Code requires a build.", ["build"], "build/pass")]); + var docs = new EvidenceProfile("docs", EvidenceProfileScope.Targeted, [], [], []); + return new EvidencePolicy("gate", "1", "all", [all, docs], [new EvidencePolicyRule("docs", "docs/**", "docs")]); + } + + private sealed class GitFixture : IDisposable + { + public GitFixture() + { + Path = System.IO.Path.Join(System.IO.Path.GetTempPath(), $"appsurface-evidence-git-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + Run("init", "-q"); + } + + public string Path { get; } + + public void Commit(string message) => Run( + "-c", "user.name=AppSurface Test", "-c", "user.email=appsurface@example.invalid", + "commit", "-qm", message); + + public string Run(params string[] arguments) + { + var start = new ProcessStartInfo("git") + { + WorkingDirectory = Path, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.True(process.ExitCode == 0, $"git {string.Join(' ', arguments)} failed: {error}"); + return output; + } + + public void Dispose() => Directory.Delete(Path, recursive: true); + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs new file mode 100644 index 000000000..53acc2e35 --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs @@ -0,0 +1,991 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Testing; +using Microsoft.Win32.SafeHandles; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidenceNoFollowArtifactExtractorTests +{ + [Fact] + public async Task ExtractAsync_ShouldStreamRegularFileIntoItsDeclaredArtifactSlot() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var expected = new byte[] { 0, 1, 2, 0xff, 0x80 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), expected); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")]); + + var result = Assert.Single(results); + Assert.Equal("report", result.LogicalName); + Assert.Equal(expected.LongLength, result.LengthBytes); + Assert.Equal(Convert.ToHexString(SHA256.HashData(expected)).ToLowerInvariant(), result.Sha256); + Assert.Equal(expected, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ExtractAsync_ShouldWriteAnEmptyArtifactWithTheEmptyContentDigest() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(TestPathUtils.PathUnder(temp.ScratchRoot, "subject")); + await File.WriteAllBytesAsync(TestPathUtils.PathUnder(temp.ScratchRoot, "subject", "empty.bin"), []); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/empty.bin", "reports/empty.bin")]); + + var result = Assert.Single(results); + Assert.Equal(0, result.LengthBytes); + Assert.Equal(Convert.ToHexString(SHA256.HashData([])).ToLowerInvariant(), result.Sha256); + Assert.Empty(await File.ReadAllBytesAsync(TestPathUtils.PathUnder(temp.ArtifactRoot, "reports", "empty.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ExtractAsync_ShouldPreserveInputOrderAcrossDeclaredArtifactSlots() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var summary = new byte[] { 4, 5, 6 }; + var report = new byte[] { 1, 2 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "summary.bin"), summary); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), report); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter( + temp.ArtifactRoot, + new EvidenceArtifactSlot("summary", "summaries", "application/octet-stream", Required: false, EvidenceArtifactWriter.MaximumTotalArtifactBytes)); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [ + new EvidenceNoFollowArtifact("summary", "subject/summary.bin", "summaries/summary.bin"), + new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin"), + ]); + + Assert.Equal(new[] { "summary", "report" }, results.Select(static result => result.LogicalName)); + Assert.Equal(summary, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "summaries", "summary.bin"))); + Assert.Equal(report, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Theory] + [InlineData("../outside")] + [InlineData("subject/../outside")] + [InlineData("subject/./report.bin")] + [InlineData("/etc/passwd")] + [InlineData("//outside")] + [InlineData("subject//report.bin")] + [InlineData("subject\\report.bin")] + [InlineData("./report.bin")] + public async Task ExtractAsync_ShouldRejectNonCanonicalOrTraversingSourcePaths(string sourcePath) + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var exception = await Assert.ThrowsAsync(() => + EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [new EvidenceNoFollowArtifact("report", sourcePath, "reports/report.bin")])); + Assert.NotNull(exception.ParamName); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectNullInputsAndInvalidArtifactRecordsBeforeOpeningRoot() + { + using var invalidRoot = new SafeFileHandle(new IntPtr(-1), ownsHandle: false); + var writer = CreateWriter(Path.GetTempPath()); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + null!, + writer, + [])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + null!, + [])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + null!)); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [null!])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [new EvidenceNoFollowArtifact(" ", "subject/report.bin", "reports/report.bin")])); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectMalformedOrOverlongSourceAndDestinationPaths() + { + using var invalidRoot = new SafeFileHandle(new IntPtr(-1), ownsHandle: false); + var writer = CreateWriter(Path.GetTempPath()); + string?[] invalidPaths = + [ + null, + "", + " ", + "subject/\0report.bin", + "subject/\u0001report.bin", + "\ud800", + new string('a', 256), + new string('a', 4_097), + ]; + + foreach (var invalidPath in invalidPaths) + { + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [new EvidenceNoFollowArtifact("report", invalidPath!, "reports/report.bin")])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [new EvidenceNoFollowArtifact("report", "subject/report.bin", invalidPath!)])); + } + } + + [Fact] + public async Task ExtractAsync_ShouldRejectDuplicateLogicalSourceAndDestinationEntriesBeforeOpeningRoot() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var writer = CreateWriter(Path.GetTempPath()); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("report", "subject/two.bin", "reports/two.bin"), + ])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("first", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("second", "subject/one.bin", "reports/two.bin"), + ])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("first", "subject/one.bin", "reports/same.bin"), + new EvidenceNoFollowArtifact("second", "subject/two.bin", "reports/same.bin"), + ])); + } + + [Fact] + public async Task ExtractAsync_ShouldEnforceFileCountAndCallerLimitCeilings() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var tooManyFiles = Enumerable.Range(0, EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount + 1) + .Select(index => new EvidenceNoFollowArtifact($"artifact-{index}", $"subject/{index}.bin", $"reports/{index}.bin")) + .ToArray(); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + tooManyFiles)); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [], + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1 })); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [], + new EvidenceNoFollowArtifactExtractionLimits { MaximumDuration = TimeSpan.FromMinutes(3) })); + } + + [Fact] + public async Task ExtractAsync_ShouldAcceptTheMaximumAllowedArtifactCount() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var maximumFileCount = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount; + var additionalSlots = Enumerable.Range(1, maximumFileCount - 1) + .Select(index => new EvidenceArtifactSlot( + $"artifact-{index}", + $"artifacts/{index}", + "application/octet-stream", + Required: false, + MaximumBytes: 1)) + .ToArray(); + var writer = CreateWriter(Path.Join(temp.ArtifactRoot, "maximum-count"), additionalSlots); + var artifacts = new List(maximumFileCount) + { + new("report", "subject/0.bin", "reports/0.bin"), + }; + + for (var index = 0; index < maximumFileCount; index++) + { + await File.WriteAllBytesAsync( + Path.Join(temp.ScratchRoot, "subject", $"{index}.bin"), + [(byte)index]); + if (index > 0) + { + artifacts.Add(new EvidenceNoFollowArtifact( + $"artifact-{index}", + $"subject/{index}.bin", + $"artifacts/{index}/{index}.bin")); + } + } + + using var root = OpenTrustedRoot(temp.ScratchRoot); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync(root, writer, artifacts); + + Assert.Equal(maximumFileCount, results.Count); + Assert.Equal(maximumFileCount, writer.WrittenArtifacts.Count); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectInvalidMinimumLimitsAndCallerFileCountBeforeOpeningRoot() + { + using var invalidRoot = new SafeFileHandle(new IntPtr(-1), ownsHandle: false); + var writer = CreateWriter(Path.GetTempPath()); + var invalidLimits = new[] + { + new EvidenceNoFollowArtifactExtractionLimits { MaximumFileCount = 0 }, + new EvidenceNoFollowArtifactExtractionLimits { MaximumFileCount = -1 }, + new EvidenceNoFollowArtifactExtractionLimits + { + MaximumFileCount = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount + 1, + }, + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = 0 }, + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = -1 }, + new EvidenceNoFollowArtifactExtractionLimits { MaximumDuration = TimeSpan.Zero }, + new EvidenceNoFollowArtifactExtractionLimits { MaximumDuration = TimeSpan.FromTicks(-1) }, + }; + + foreach (var limits in invalidLimits) + { + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [], + limits)); + } + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("summary", "subject/two.bin", "summaries/two.bin"), + ], + new EvidenceNoFollowArtifactExtractionLimits { MaximumFileCount = 1 })); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectSymlinksAndFilesOutsideTheScratchRoot() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + Directory.CreateDirectory(Path.Join(temp.OutsideRoot, "private")); + var outsideFile = Path.Join(temp.OutsideRoot, "private", "secret.bin"); + await File.WriteAllTextAsync(outsideFile, "outside"); + File.CreateSymbolicLink(Path.Join(temp.ScratchRoot, "subject", "linked.bin"), outsideFile); + Directory.CreateSymbolicLink(Path.Join(temp.ScratchRoot, "linked-directory"), Path.Join(temp.OutsideRoot, "private")); + using var root = OpenTrustedRoot(temp.ScratchRoot); + + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/linked.bin", "reports/report.bin")])); + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "linked-directory/secret.bin", "reports/report.bin")])); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectScratchSymlinkTargetingProcFileDescriptorPath() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllTextAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), "inside"); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var rootDescriptorPath = $"/proc/self/fd/{root.DangerousGetHandle().ToInt32()}"; + File.CreateSymbolicLink( + Path.Join(temp.ScratchRoot, "subject", "magic-report.bin"), + $"{rootDescriptorPath}/subject/report.bin"); + var writer = CreateWriter(temp.ArtifactRoot); + + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/magic-report.bin", "reports/report.bin")])); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectHardlinksDirectoriesAndAggregateByteOverflow() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllTextAsync(Path.Join(temp.ScratchRoot, "subject", "one.bin"), "hard-linked"); + if (Link( + Path.Join(temp.ScratchRoot, "subject", "one.bin"), + Path.Join(temp.ScratchRoot, "subject", "second-name.bin")) != 0) + { + throw new IOException($"Could not create the Linux hard-link fixture (errno {Marshal.GetLastPInvokeError()})."); + } + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject", "directory")); + using var root = OpenTrustedRoot(temp.ScratchRoot); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/report.bin")])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/directory", "reports/report.bin")])); + + File.Delete(Path.Join(temp.ScratchRoot, "subject", "second-name.bin")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "small.bin"), [1, 2, 3]); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/small.bin", "reports/report.bin")], + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = 2 })); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectAggregateOverflowBeforePromotingAnyArtifact() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "one.bin"), [1, 2]); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "two.bin"), [3, 4]); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter( + temp.ArtifactRoot, + new EvidenceArtifactSlot("summary", "summaries", "application/octet-stream", Required: false, EvidenceArtifactWriter.MaximumTotalArtifactBytes)); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("summary", "subject/two.bin", "summaries/two.bin"), + ], + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = 3 })); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "one.bin"))); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "summaries", "two.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldAcceptArtifactsAtCallerFileCountAndByteLimits() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var report = new byte[] { 1, 2 }; + var summary = new byte[] { 3, 4 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), report); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "summary.bin"), summary); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter( + temp.ArtifactRoot, + new EvidenceArtifactSlot("summary", "summaries", "application/octet-stream", Required: false, EvidenceArtifactWriter.MaximumTotalArtifactBytes)); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin"), + new EvidenceNoFollowArtifact("summary", "subject/summary.bin", "summaries/summary.bin"), + ], + new EvidenceNoFollowArtifactExtractionLimits { MaximumFileCount = 2, MaximumTotalBytes = 4 }); + + Assert.Equal(new[] { "report", "summary" }, results.Select(static result => result.LogicalName)); + Assert.Equal(report, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.Equal(summary, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "summaries", "summary.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ExtractAsync_ShouldHonorTheArtifactSlotSizeAtItsExactBoundary() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var contents = new byte[] { 1, 2, 3 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), contents); + using var root = OpenTrustedRoot(temp.ScratchRoot); + EvidenceArtifactWriter CreateSlotLimitedWriter(string artifactRoot, long maximumBytes) => CreateWriter( + artifactRoot, + new EvidenceArtifactSlot( + "bounded-report", + "bounded-reports", + "application/octet-stream", + Required: false, + maximumBytes)); + + var exactLimitRoot = Path.Join(temp.ArtifactRoot, "exact-limit"); + var exactLimitWriter = CreateSlotLimitedWriter(exactLimitRoot, contents.Length); + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + exactLimitWriter, + [new EvidenceNoFollowArtifact("bounded-report", "subject/report.bin", "bounded-reports/report.bin")]); + + Assert.Equal(contents, await File.ReadAllBytesAsync(Path.Join(exactLimitRoot, "bounded-reports", "report.bin"))); + Assert.Equal(contents.LongLength, Assert.Single(results).LengthBytes); + Assert.True(await exactLimitWriter.VerifyWrittenArtifactsAsync()); + + var smallerLimitRoot = Path.Join(temp.ArtifactRoot, "smaller-limit"); + var smallerLimitWriter = CreateSlotLimitedWriter(smallerLimitRoot, contents.Length - 1); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + smallerLimitWriter, + [new EvidenceNoFollowArtifact("bounded-report", "subject/report.bin", "bounded-reports/report.bin")])); + + Assert.Empty(smallerLimitWriter.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(smallerLimitRoot, "bounded-reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldKeepEarlierArtifactWhenLaterArtifactExceedsItsSlotLimit() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(TestPathUtils.PathUnder(temp.ScratchRoot, "subject")); + var reportContents = new byte[] { 1, 2, 3 }; + await File.WriteAllBytesAsync(TestPathUtils.PathUnder(temp.ScratchRoot, "subject", "report.bin"), reportContents); + await File.WriteAllBytesAsync(TestPathUtils.PathUnder(temp.ScratchRoot, "subject", "summary.bin"), [4, 5]); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter( + temp.ArtifactRoot, + new EvidenceArtifactSlot("summary", "summaries", "application/octet-stream", Required: false, MaximumBytes: 1)); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin"), + new EvidenceNoFollowArtifact("summary", "subject/summary.bin", "summaries/summary.bin"), + ])); + + Assert.Equal("report", Assert.Single(writer.WrittenArtifacts).LogicalName); + Assert.Equal(reportContents, await File.ReadAllBytesAsync(TestPathUtils.PathUnder(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.False(File.Exists(TestPathUtils.PathUnder(temp.ArtifactRoot, "summaries", "summary.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Theory] + [InlineData("append", "exceeds its declared or allowed length")] + [InlineData("truncate", "ended before its opened descriptor size")] + public async Task ExtractAsyncForTesting_ShouldRejectLaterSourceLengthChangesAfterOpeningAllSources( + string mutation, + string expectedFailure) + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var firstContents = new byte[] { 1, 2, 3 }; + var laterSourcePath = Path.Join(temp.ScratchRoot, "subject", "summary.bin"); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), firstContents); + await File.WriteAllBytesAsync(laterSourcePath, [4, 5]); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter( + temp.ArtifactRoot, + new EvidenceArtifactSlot("summary", "summaries", "application/octet-stream", Required: false, MaximumBytes: 16)); + + void ChangeLaterSourceAfterFirstPass(string sourceRelativePath) + { + if (sourceRelativePath != "subject/report.bin") + { + return; + } + + if (mutation == "append") + { + using var changedSource = new FileStream(laterSourcePath, FileMode.Append, FileAccess.Write, FileShare.Read); + changedSource.WriteByte(6); + return; + } + + Assert.Equal("truncate", mutation); + using var truncatedSource = new FileStream(laterSourcePath, FileMode.Open, FileAccess.Write, FileShare.Read); + truncatedSource.SetLength(1); + } + + var exception = await Assert.ThrowsAsync(() => + EvidenceNoFollowArtifactExtractor.ExtractAsyncForTesting( + root, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin"), + new EvidenceNoFollowArtifact("summary", "subject/summary.bin", "summaries/summary.bin"), + ], + ChangeLaterSourceAfterFirstPass)); + + Assert.Contains(expectedFailure, exception.Message, StringComparison.OrdinalIgnoreCase); + Assert.Equal("report", Assert.Single(writer.WrittenArtifacts).LogicalName); + Assert.Equal(firstContents, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "summaries", "summary.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectNonDirectoryRootAndMissingSourcesWithoutWriting() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + var rootFile = Path.Join(temp.ScratchRoot, "not-a-directory"); + await File.WriteAllTextAsync(rootFile, "not a directory"); + using var nonDirectoryRoot = File.OpenHandle(rootFile); + var writer = CreateWriter(temp.ArtifactRoot); + var request = new[] { new EvidenceNoFollowArtifact("report", "subject/missing.bin", "reports/report.bin") }; + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + nonDirectoryRoot, + writer, + request)); + + using var root = OpenTrustedRoot(temp.ScratchRoot); + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + request)); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectInvalidRootDescriptorBeforeOpeningSources() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var invalidRoot = new SafeFileHandle(new IntPtr(-1), ownsHandle: false); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")])); + } + + [Fact] + public async Task ExtractAsync_ShouldResolveSourcesBeneathTheAlreadyOpenedRootDescriptor() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var expected = new byte[] { 1, 2, 3 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), expected); + using var root = OpenTrustedRoot(temp.ScratchRoot); + + Directory.Move(temp.ScratchRoot, temp.OutsideRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), [9, 8, 7]); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")]); + + Assert.Equal(expected, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.Equal(expected.LongLength, Assert.Single(results).LengthBytes); + Assert.Equal(new byte[] { 9, 8, 7 }, await File.ReadAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"))); + } + + [Theory] + [InlineData("replace")] + [InlineData("append")] + [InlineData("touch")] + public async Task ExtractAsyncForTesting_ShouldRejectSourceMutationBeforeTheVerificationPass(string mutation) + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var sourcePath = Path.Join(temp.ScratchRoot, "subject", "report.bin"); + await File.WriteAllBytesAsync(sourcePath, [1, 2, 3]); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + + void MutateSource(string sourceRelativePath) + { + Assert.Equal("subject/report.bin", sourceRelativePath); + if (mutation == "append") + { + using var changedSource = new FileStream(sourcePath, FileMode.Append, FileAccess.Write, FileShare.Read); + changedSource.WriteByte(4); + return; + } + + if (mutation == "touch") + { + File.SetLastWriteTimeUtc(sourcePath, File.GetLastWriteTimeUtc(sourcePath).AddSeconds(-2)); + return; + } + + Assert.Equal("replace", mutation); + File.WriteAllBytes(sourcePath, [9, 8, 7]); + } + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsyncForTesting( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")], + MutateSource)); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsyncForTesting_ShouldPropagateCallerCancellationDuringVerification() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), [1, 2, 3]); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + using var cancellation = new CancellationTokenSource(); + + void CancelAfterFirstPass(string sourceRelativePath) + { + Assert.Equal("subject/report.bin", sourceRelativePath); + cancellation.Cancel(); + } + + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsyncForTesting( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")], + CancelAfterFirstPass, + cancellationToken: cancellation.Token)); + + Assert.True(cancellation.IsCancellationRequested); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsyncForTesting_ShouldConvertItsDeadlineCancellationToTimeout() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "empty.bin"), []); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + var checkpointReached = false; + + void WaitPastDeadline(string sourceRelativePath) + { + Assert.Equal("subject/empty.bin", sourceRelativePath); + checkpointReached = true; + Thread.Sleep(TimeSpan.FromSeconds(3)); + } + + var exception = await Assert.ThrowsAsync(() => + EvidenceNoFollowArtifactExtractor.ExtractAsyncForTesting( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/empty.bin", "reports/report.bin")], + WaitPastDeadline, + new EvidenceNoFollowArtifactExtractionLimits { MaximumDuration = TimeSpan.FromSeconds(2) })); + + Assert.Contains("exceeded", exception.Message, StringComparison.OrdinalIgnoreCase); + Assert.True(checkpointReached); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectFifoWithoutBlockingOrWriting() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var fifoPath = Path.Join(temp.ScratchRoot, "subject", "pipe"); + if (MakeFifo(fifoPath, 0x180) != 0) + { + throw new IOException($"Could not create the Linux FIFO fixture (errno {Marshal.GetLastPInvokeError()})."); + } + + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/pipe", "reports/report.bin")])); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectPreCanceledRequestsBeforeOpeningRoot() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var invalidRoot = new SafeFileHandle(new IntPtr(-1), ownsHandle: false); + + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [], + cancellationToken: cancellation.Token)); + } + + [Fact] + public async Task ExtractAsync_OnUnsupportedPlatform_ShouldFailClosed() + { + if (OperatingSystem.IsLinux()) + { + return; + } + + await AssertUnsupportedPlatformFailsClosedAsync(); + } + + private static async Task AssertUnsupportedPlatformFailsClosedAsync() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [])); + } + + private static EvidenceArtifactWriter CreateWriter(string artifactRoot, params EvidenceArtifactSlot[] additionalSlots) + { + var slots = new[] + { + new EvidenceArtifactSlot("report", "reports", "application/octet-stream", Required: false, EvidenceArtifactWriter.MaximumTotalArtifactBytes), + }.Concat(additionalSlots); + var producer = new EvidenceProducerDeclaration( + "extractor-test", + "test", + "1.0.0", + [], + [], + slots.ToArray(), + TimeoutSeconds: 120); + return new EvidenceArtifactWriter(producer, artifactRoot); + } + + private static SafeFileHandle OpenTrustedRoot(string path) + { + // The test controls this fixture path; the extractor itself verifies the opened handle is a directory. + var descriptor = Open(path, flags: 0); + if (descriptor < 0) + { + throw new IOException($"Could not open the Linux scratch root (errno {Marshal.GetLastPInvokeError()})."); + } + + return new SafeFileHandle(new IntPtr(descriptor), ownsHandle: true); + } + + [DllImport("libc", EntryPoint = "open", SetLastError = true)] + private static extern int Open([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags); + + [DllImport("libc", EntryPoint = "mkfifo", SetLastError = true)] + private static extern int MakeFifo([MarshalAs(UnmanagedType.LPUTF8Str)] string path, uint mode); + + [DllImport("libc", EntryPoint = "link", SetLastError = true)] + private static extern int Link( + [MarshalAs(UnmanagedType.LPUTF8Str)] string existingPath, + [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath); + + private sealed class TemporaryDirectory : IDisposable + { + private readonly string _path = Path.Join(Path.GetTempPath(), "evidence-nofollow-" + Guid.NewGuid().ToString("N")); + + public string ScratchRoot => Path.Join(_path, "scratch"); + + public string ArtifactRoot => Path.Join(_path, "artifacts"); + + public string OutsideRoot => Path.Join(_path, "outside"); + + public TemporaryDirectory() + { + Directory.CreateDirectory(_path); + } + + public void Dispose() + { + try + { + Directory.Delete(_path, recursive: true); + } + catch (IOException) + { + // Preserve the test result if the operating system still has a transient handle open. + } + catch (UnauthorizedAccessException) + { + // Preserve the test result if the operating system still has a transient handle open. + } + } + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs index 32d4eff50..7f32632d4 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs @@ -95,6 +95,374 @@ public void Resolve_ShouldRejectEmptyConservativeProfile() Assert.Contains("ASEVD105", exception.Message, StringComparison.Ordinal); } + [Fact] + public void ResolveForGate_ShouldUseConservativeProfileForDocumentationAndCodeDiff() + { + var documentation = CreateNoEvidenceProfile(); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "code" }; + var policy = CreateGatePolicy(code with { Id = "conservative" }, documentation, code); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "readme.md"), GatePath(1, "Feature.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains("conservative:conservative", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void ValidateGatePolicy_ShouldKeepLegacyLocalV1ValidationAndSelectionCompatible() + { + var targetedResourceProfile = CreateRequirementProfile("integration"); + var conservative = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "conservative" }; + var policy = CreateGatePolicy(conservative, targetedResourceProfile); + + EvidencePlanner.ValidatePolicy(policy); + var localPlan = new EvidencePlanner().Resolve(policy, [GatePath(0, "integration.cs"), new NormalizedDiffPath("unmapped/file.cs")]); + + Assert.Equal("conservative", localPlan.Profile.Id); + AssertGatePolicyFailure(policy, "resource 'database'"); + } + + [Fact] + public void ResolveForGate_ShouldPreserveResourceAndCodeRequirementsInMixedProfile() + { + var integration = CreateRequirementProfile("integration"); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "code" }; + var conservative = MergeProfiles("conservative", integration, code); + var policy = CreateGatePolicy(conservative, integration, code); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "database-tests.cs"), GatePath(1, "Feature.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "database"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "integration-tests"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + } + + [Fact] + public void ResolveForGate_ShouldPreserveResourceRequirementsInDocumentationAndResourceDiff() + { + var documentation = CreateNoEvidenceProfile(); + var integration = CreateRequirementProfile("integration"); + var conservative = MergeProfiles("conservative", integration); + var policy = CreateGatePolicy(conservative, documentation, integration); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "guide.md"), GatePath(1, "database-tests.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "database"); + Assert.Contains(plan.Profile.Producers, producer => producer.RequiredResources.Contains("database", StringComparer.Ordinal)); + } + + [Fact] + public void ResolveForGate_ShouldPreserveControlPlaneRequirementsWhenRenameCrossesProfileRules() + { + var documentation = CreateNoEvidenceProfile(); + var controlPlane = CreateRequirementProfile("control-plane"); + var conservative = MergeProfiles("conservative", controlPlane); + var policy = CreateGatePolicy(conservative, documentation, controlPlane); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [new NormalizedDiffPath("gate/0/evidence-guide.md", "renamed", "gate/1/evidence.policy.json")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains("target-0", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("target-1", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "integration-tests"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingProducer() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = CreateCoverageProfile(EvidenceProfileScope.Targeted) with + { + Id = "conservative", + Resources = targeted.Resources, + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "producer 'integration-tests'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectReleaseScopeAsThePullRequestFallback() + { + var release = CreateCoverageProfile(EvidenceProfileScope.Release) with { Id = "conservative" }; + + AssertGatePolicyFailure(CreateGatePolicy(release), "not a targeted pull-request profile"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectRulesThatSelectReleaseProfiles() + { + var conservative = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "conservative" }; + var release = CreateCoverageProfile(EvidenceProfileScope.Release); + + AssertGatePolicyFailure(CreateGatePolicy(conservative, release), "selects non-targeted profile"); + } + + [Theory] + [InlineData("completion", 30)] + [InlineData("aspire_health", 31)] + public void ValidateGatePolicy_ShouldRejectWeakenedResourceReadinessOrDeadline(string readiness, int deadlineSeconds) + { + var targeted = CreateRequirementProfile("integration"); + var conservative = targeted with + { + Id = "conservative", + Resources = [targeted.Resources[0] with { Readiness = readiness, DeadlineSeconds = deadlineSeconds }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(conservative, targeted), "resource 'database'"); + } + + [Theory] + [InlineData("risk")] + [InlineData("rationale")] + [InlineData("assertion")] + public void ValidateGatePolicy_ShouldRejectChangedObligationMeaning(string change) + { + var targeted = CreateRequirementProfile("integration"); + var obligation = targeted.Obligations[0]; + var conservative = targeted with + { + Id = "conservative", + Producers = change == "assertion" + ? [targeted.Producers[0] with { AssertionIds = [.. targeted.Producers[0].AssertionIds, "integration/other@1"] }] + : targeted.Producers, + Obligations = + [ + change switch + { + "risk" => obligation with { RiskClass = "lower-risk" }, + "rationale" => obligation with { Rationale = "A different reason." }, + _ => obligation with { RequiredAssertionId = "integration/other@1" }, + }, + ], + }; + + AssertGatePolicyFailure(CreateGatePolicy(conservative, targeted), "obligation 'integration'"); + } + + [Theory] + [InlineData("missing")] + [InlineData("line")] + [InlineData("branch")] + [InlineData("patch-line")] + [InlineData("patch-branch")] + [InlineData("mode")] + [InlineData("tolerance")] + public void ValidateGatePolicy_ShouldRejectWeakenedCoverageGate(string change) + { + var requiredGate = new EvidenceCoverageGateRequirements( + 95, + 85, + MinPatchLinePercent: 95, + MinPatchBranchPercent: 85, + PatchLineMode: "measurable", + TolerancePercent: 0.5m); + var targeted = CreateCoverageProfile(EvidenceProfileScope.Targeted) with + { + Producers = [CreateCoverageProfile(EvidenceProfileScope.Targeted).Producers[0] with { CoverageGate = requiredGate }], + }; + var candidateGate = change switch + { + "line" => requiredGate with { MinLinePercent = 94 }, + "branch" => requiredGate with { MinBranchPercent = 84 }, + "patch-line" => requiredGate with { MinPatchLinePercent = null }, + "patch-branch" => requiredGate with { MinPatchBranchPercent = 84 }, + "mode" => requiredGate with { PatchLineMode = "codecov" }, + "tolerance" => requiredGate with { TolerancePercent = 1 }, + _ => null, + }; + var conservative = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { CoverageGate = candidateGate }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(conservative, targeted), "producer 'coverage'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingResource() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Resources = [], + Producers = [targeted.Producers[0] with { RequiredResources = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource 'database'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingAssertion() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { AssertionIds = ["integration/ready@2"] }], + Obligations = [targeted.Obligations[0] with { RequiredAssertionId = "integration/ready@2" }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "assertion 'integration/passed@1'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingArtifactSlot() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { ArtifactSlots = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "artifact slot 'integration-tests/report'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingObligation() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with { Id = "conservative", Obligations = [] }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "obligation 'integration'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAWeakenedResourceDependency() + { + var database = new EvidenceResourceDeclaration("database", "aspire_health", 30, []); + var migration = new EvidenceResourceDeclaration("migration", "completion", 30, ["database"]); + var targeted = CreateRequirementProfile("integration") with + { + Resources = [database, migration], + Producers = [CreateRequirementProfile("integration").Producers[0] with { RequiredResources = ["migration"] }], + }; + var otherwiseValid = targeted with + { + Id = "conservative", + Resources = [database, migration with { Requires = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource dependency 'database'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAProducerThatNoLongerRequiresATargetedResource() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { RequiredResources = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource 'database' required by producer 'integration-tests'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectWeakenedArtifactBounds() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = + [ + targeted.Producers[0] with + { + ArtifactSlots = [targeted.Producers[0].ArtifactSlots[0] with { MaximumBytes = 2048 }], + }, + ], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "artifact slot 'integration-tests/report'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAnObligationThatNoLongerRequiresItsProducer() + { + var targeted = CreateRequirementProfile("integration"); + var coverage = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var coverageProducer = coverage.Producers[0] with + { + AssertionIds = [.. coverage.Producers[0].AssertionIds, targeted.Obligations[0].RequiredAssertionId], + }; + var otherwiseValid = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + targeted.Resources, + [targeted.Producers[0], coverageProducer], + [ + targeted.Obligations[0] with { RequiredProducerIds = ["coverage"] }, + coverage.Obligations[0], + ]); + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "producer 'integration-tests' required by obligation 'integration'"); + } + + [Fact] + public void ResolveForGate_ShouldAcceptAConservativeSupersetWithAdditionalEvidence() + { + var targeted = CreateRequirementProfile("integration"); + var additionalResource = new EvidenceResourceDeclaration("cache", "completion", 45, []); + var requiredProducer = targeted.Producers[0] with + { + RequiredResources = ["database", "cache"], + AssertionIds = ["integration/passed@1", "integration/details@1"], + ArtifactSlots = + [ + targeted.Producers[0].ArtifactSlots[0] with { MaximumBytes = 512 }, + new EvidenceArtifactSlot("details", "integration", "application/json", Required: false, MaximumBytes: 256), + ], + }; + var coverage = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var conservative = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + [.. targeted.Resources, additionalResource], + [requiredProducer, coverage.Producers[0]], + [ + targeted.Obligations[0], + coverage.Obligations[0], + ]); + var policy = CreateGatePolicy(conservative, targeted); + + var plan = new EvidencePlanner().ResolveForGate(policy, [GatePath(0, "integration.cs"), new NormalizedDiffPath("unmapped/file.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "cache"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Producers.Single(producer => producer.Id == "integration-tests").ArtifactSlots, slot => slot.LogicalName == "details"); + } + + [Fact] + public void ResolveForGate_ShouldKeepExplicitEmptyTargetedDocumentationProfile() + { + var documentation = CreateNoEvidenceProfile(); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var policy = CreateGatePolicy(code with { Id = "conservative" }, documentation, code); + + var plan = new EvidencePlanner().ResolveForGate(policy, [GatePath(0, "guide.md")]); + var manifest = EvidenceManifestBuilder.Build(plan, []); + + Assert.Equal("no-evidence", plan.Profile.Id); + Assert.Empty(plan.Profile.Producers); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, manifest.ClaimKind); + } + [Fact] public void UnifiedDiffReader_ShouldReadAddedDeletedAndModifiedPaths() { @@ -257,6 +625,75 @@ public void ManifestBuilder_ShouldRejectClaimTamperingEvenWhenDigestIsRecomputed Assert.False(EvidenceManifestBuilder.Verify(plan, tampered)); } + [Fact] + public void ManifestBuilder_ShouldVerifyRevisionBoundPlansAndRejectMalformedBindings() + { + static EvidencePlan WithDigest(EvidencePlan plan) + { + var withoutDigest = plan with { PlanDigest = string.Empty }; + return withoutDigest with { PlanDigest = EvidenceDigest.CanonicalSha256(withoutDigest) }; + } + + var localPlan = new EvidencePlanner().Resolve(CreatePolicy(), [new NormalizedDiffPath("src/Feature.cs")]); + var revisionBoundPlan = WithDigest(localPlan with + { + ContractVersion = "2.0", + BaseRevision = new string('a', 40), + HeadRevision = new string('b', 40), + SourceDiffDigest = new string('c', 64), + NameStatusDigest = new string('d', 64), + PullRequestRunIdentity = new EvidencePullRequestRunIdentity(1, 2, 3, "main", 4, 1), + }); + var manifest = EvidenceManifestBuilder.Build(revisionBoundPlan, []); + + Assert.True(EvidenceManifestBuilder.Verify(revisionBoundPlan, manifest)); + + var validSixtyFourCharacterRevision = WithDigest(revisionBoundPlan with + { + BaseRevision = new string('a', 64), + HeadRevision = new string('b', 64), + }); + Assert.True(EvidenceManifestBuilder.Verify( + validSixtyFourCharacterRevision, + EvidenceManifestBuilder.Build(validSixtyFourCharacterRevision, []))); + + var validLocalRevisionBoundPlan = WithDigest(revisionBoundPlan with { PullRequestRunIdentity = null }); + Assert.True(EvidenceManifestBuilder.Verify( + validLocalRevisionBoundPlan, + EvidenceManifestBuilder.Build(validLocalRevisionBoundPlan, []))); + + EvidencePlan[] malformedPlans = + [ + revisionBoundPlan with { ContractVersion = "3.0" }, + revisionBoundPlan with { BaseRevision = new string('A', 40) }, + revisionBoundPlan with { BaseRevision = new string('a', 39) }, + revisionBoundPlan with { HeadRevision = new string('c', 64) }, + revisionBoundPlan with { HeadRevision = new string('B', 40) }, + revisionBoundPlan with { SourceDiffDigest = new string('g', 64) }, + revisionBoundPlan with { NameStatusDigest = new string('d', 63) }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { RepositoryId = 0 } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { HeadRepositoryId = 0 } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { PullRequestNumber = 0 } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { TargetBranch = string.Empty } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { TargetBranch = new string('x', 129) } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { WorkflowRunId = 0 } }, + revisionBoundPlan with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { WorkflowRunAttempt = 0 } }, + ]; + + Assert.All(malformedPlans, invalidPlan => Assert.False(EvidenceManifestBuilder.Verify(invalidPlan, manifest))); + Assert.False(EvidenceManifestBuilder.Verify( + localPlan with { BaseRevision = new string('a', 40) }, + EvidenceManifestBuilder.Build(localPlan, []))); + + Assert.False(EvidenceManifestBuilder.Verify(revisionBoundPlan, manifest with { BaseRevision = new string('e', 40) })); + Assert.False(EvidenceManifestBuilder.Verify(revisionBoundPlan, manifest with { HeadRevision = new string('f', 40) })); + Assert.False(EvidenceManifestBuilder.Verify(revisionBoundPlan, manifest with { SourceDiffDigest = new string('e', 64) })); + Assert.False(EvidenceManifestBuilder.Verify(revisionBoundPlan, manifest with { NameStatusDigest = new string('f', 64) })); + Assert.False(EvidenceManifestBuilder.Verify( + revisionBoundPlan, + manifest with { PullRequestRunIdentity = revisionBoundPlan.PullRequestRunIdentity! with { WorkflowRunAttempt = 2 } })); + } + [Fact] public void ManifestBuilder_ShouldInvalidatePassedProducerThatOmitsRequiredArtifact() { @@ -308,6 +745,115 @@ [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, Ma Assert.False(await writer.VerifyWrittenArtifactsAsync()); } + [Fact] + public async Task ArtifactWriter_ShouldStreamExactlyDeclaredBytesAndDetectLaterMutation() + { + using var directory = TestDirectory.Create(); + var producer = new EvidenceProducerDeclaration( + "coverage", "coverage", "1", [], [], + [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, MaximumBytes: 16)], 60); + var writer = new EvidenceArtifactWriter(producer, directory.Path); + using var source = new MemoryStream("streamed"u8.ToArray()); + + var artifact = await writer.WriteAsync("report", "coverage/streamed.txt", source, 8); + + Assert.True(source.CanRead); + Assert.Equal(8, artifact.LengthBytes); + Assert.Equal(EvidenceDigest.Sha256("streamed"u8), artifact.Sha256); + Assert.Equal("streamed", await File.ReadAllTextAsync(Path.Join(directory.Path, "coverage", "streamed.txt"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + await File.WriteAllTextAsync(Path.Join(directory.Path, "coverage", "streamed.txt"), "altered!"); + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ArtifactWriter_ShouldRejectUndeclaredStreamSlotBeforeReadingOrReserving() + { + using var directory = TestDirectory.Create(); + var producer = new EvidenceProducerDeclaration( + "coverage", "coverage", "1", [], [], + [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, MaximumBytes: 16)], 60); + var writer = new EvidenceArtifactWriter(producer, directory.Path); + using var undeclaredSource = new MemoryStream("report"u8.ToArray()); + + await Assert.ThrowsAsync(() => writer.WriteAsync( + "missing", + "coverage/report.txt", + undeclaredSource, + 6).AsTask()); + + Assert.Equal(0, undeclaredSource.Position); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(directory.Path, "coverage", "report.txt"))); + + using var declaredSource = new MemoryStream("report"u8.ToArray()); + var artifact = await writer.WriteAsync("report", "coverage/report.txt", declaredSource, 6); + + Assert.Equal("report", artifact.LogicalName); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ArtifactWriter_ShouldRejectVerificationWhenWrittenArtifactSlotIsRemoved() + { + using var directory = TestDirectory.Create(); + var slots = new List + { + new("report", "coverage", "text/plain", Required: true, MaximumBytes: 16), + }; + var producer = new EvidenceProducerDeclaration("coverage", "coverage", "1", [], [], slots, 60); + var writer = new EvidenceArtifactWriter(producer, directory.Path); + + await writer.WriteAsync("report", "coverage/report.txt", "report"u8.ToArray()); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + + slots.Clear(); + + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + } + + [Theory] + [InlineData("short", 6)] + [InlineData("too-long", 4)] + public async Task ArtifactWriter_ShouldRejectStreamLengthMismatchWithoutRetainingAReservation(string content, long declaredLength) + { + using var directory = TestDirectory.Create(); + var producer = new EvidenceProducerDeclaration( + "coverage", "coverage", "1", [], [], + [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, MaximumBytes: 16)], 60); + var writer = new EvidenceArtifactWriter(producer, directory.Path); + using var source = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)); + + await Assert.ThrowsAsync(() => writer.WriteAsync("report", "coverage/streamed.txt", source, declaredLength).AsTask()); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(directory.Path, "coverage", "streamed.txt"))); + using var retry = new MemoryStream("retry"u8.ToArray()); + var artifact = await writer.WriteAsync("report", "coverage/streamed.txt", retry, 5); + Assert.Equal(5, artifact.LengthBytes); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Fact] + public async Task ArtifactWriter_ShouldRejectUnreadableAndOutOfBoundsStreamsBeforeWriting() + { + using var directory = TestDirectory.Create(); + var producer = new EvidenceProducerDeclaration( + "coverage", "coverage", "1", [], [], + [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, MaximumBytes: 4)], 60); + var writer = new EvidenceArtifactWriter(producer, directory.Path); + using var closed = new MemoryStream(); + closed.Dispose(); + using var source = new MemoryStream("five!"u8.ToArray()); + + await Assert.ThrowsAsync(() => writer.WriteAsync("report", "coverage/streamed.txt", closed, 0).AsTask()); + await Assert.ThrowsAsync(() => writer.WriteAsync("report", "coverage/streamed.txt", source, -1).AsTask()); + await Assert.ThrowsAsync(() => writer.WriteAsync("report", "coverage/streamed.txt", source, 5).AsTask()); + + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(directory.Path, "coverage", "streamed.txt"))); + } + [Fact] public async Task CliWorkflow_ShouldCreateMarkedStarterAndVerifyGeneratedNoEvidenceManifest() { @@ -421,6 +967,28 @@ public async Task CliWorkflow_ShouldRejectMissingMalformedAndMismatchedEvidenceI Assert.Contains("ASEVD208", missingEvidenceException.Message, StringComparison.Ordinal); } + [Fact] + public async Task CliWorkflow_ShouldRejectAnOversizedManifestBeforeDeserializingIt() + { + using var directory = TestDirectory.Create(); + var workflow = new EvidenceCliWorkflow(new EvidencePlanner()); + var policyPath = Path.Join(directory.Path, "policy.json"); + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(CreatePolicy())); + var plan = await workflow.ExplainAsync( + new EvidencePlanningRequest(policyPath, ["docs/readme.md"], null), + CancellationToken.None); + var output = Path.Join(directory.Path, "output"); + await workflow.WritePlanAsync(plan, output, CancellationToken.None); + var manifestPath = Path.Join(output, "evidence-manifest.json"); + await File.WriteAllBytesAsync(manifestPath, new byte[(4 * 1024 * 1024) + 1]); + + var exception = await Assert.ThrowsAsync(() => workflow.VerifyAsync( + Path.Join(output, "evidence-plan.json"), manifestPath, CancellationToken.None)); + + Assert.Contains("ASEVD209", exception.Message, StringComparison.Ordinal); + Assert.Contains("4 MiB", exception.Message, StringComparison.Ordinal); + } + [Fact] public async Task CliWorkflow_ShouldRejectAnOversizedDiffWhileStreamingIt() { @@ -852,6 +1420,52 @@ private static void AssertPlanningCode(Action action, string code) Assert.Equal(code, exception.Code); } + private static void AssertGatePolicyFailure(EvidencePolicy policy, string expectedRequirement) + { + var exception = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(policy)); + + Assert.Equal("ASEVD129", exception.Code); + Assert.Contains(expectedRequirement, exception.Message, StringComparison.Ordinal); + } + + private static EvidencePolicy CreateGatePolicy(EvidenceProfile conservative, params EvidenceProfile[] targetedProfiles) + { + var profiles = new List { conservative }; + profiles.AddRange(targetedProfiles); + var rules = targetedProfiles + .Select((profile, index) => new EvidencePolicyRule($"target-{index}", $"gate/{index}/*", profile.Id)) + .ToArray(); + + return new EvidencePolicy("gate-policy", "1", conservative.Id, profiles, rules); + } + + private static EvidenceProfile MergeProfiles(string id, params EvidenceProfile[] profiles) => new( + id, + EvidenceProfileScope.Targeted, + profiles.SelectMany(static profile => profile.Resources).ToArray(), + profiles.SelectMany(static profile => profile.Producers).ToArray(), + profiles.SelectMany(static profile => profile.Obligations).ToArray()); + + private static EvidenceProfile CreateRequirementProfile(string id) + { + var assertionId = "integration/passed@1"; + return new EvidenceProfile( + id, + EvidenceProfileScope.Targeted, + [new EvidenceResourceDeclaration("database", "aspire_health", 30, [])], + [new EvidenceProducerDeclaration( + "integration-tests", + "integration-tests", + "1.0.0", + ["database"], + [assertionId], + [new EvidenceArtifactSlot("report", "integration", "application/json", Required: true, MaximumBytes: 1024)], + 60)], + [new EvidenceObligation("integration", "integration", "The integration profile must pass.", ["integration-tests"], assertionId)]); + } + + private static NormalizedDiffPath GatePath(int profileIndex, string path) => new($"gate/{profileIndex}/{path}"); + private static EvidencePolicy CreatePolicy() => new( "sample", "1", diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowCommandTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowCommandTests.cs new file mode 100644 index 000000000..3b44511f7 --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowCommandTests.cs @@ -0,0 +1,815 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using CliFx.Infrastructure; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; +using ForgeTrust.AppSurface.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +[Collection(ProgramEntryPointCollection.Name)] +public sealed class EvidencePolicyShadowCommandTests +{ + private static readonly JsonSerializerOptions FixtureJsonOptions = new(JsonSerializerDefaults.Web) + { + Converters = { new JsonStringEnumConverter() }, + }; + + [Fact] + public async Task Command_Should_Write_CamelCase_NonClaiming_Result_To_New_Output_Directory() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputDirectory = TestPathUtils.PathUnder(temporaryDirectory.Path, "shadow-output"); + + var run = await InvokeAsync(CreateArguments(inputs, outputDirectory)); + + Assert.Equal(0, run.ExitCode); + Assert.Contains("claimEligible=false", run.Output, StringComparison.Ordinal); + var outputPath = TestPathUtils.PathUnder(outputDirectory, "evidence-policy-shadow.json"); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var root = document.RootElement; + Assert.False(root.GetProperty("claimEligible").GetBoolean()); + Assert.False(root.TryGetProperty("manifest", out _)); + Assert.False(root.TryGetProperty("evidenceManifest", out _)); + Assert.True(root.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + var selection = Assert.Single(root.GetProperty("result").GetProperty("selections").EnumerateArray()); + Assert.Equal("docs/guide.md", selection.GetProperty("changedPath").GetProperty("path").GetString()); + Assert.Contains("\"changedPath\"", await File.ReadAllTextAsync(inputs.BaseFixturesPath), StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Write_To_A_New_Explicit_Json_Output_File() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-explicit-json-output-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "nested", "shadow-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.Equal(0, run.ExitCode); + Assert.True(File.Exists(outputPath)); + Assert.False(Directory.Exists(outputPath)); + Assert.False(File.Exists(TestPathUtils.PathUnder( + Path.GetDirectoryName(outputPath)!, + "evidence-policy-shadow.json"))); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + Assert.False(document.RootElement.GetProperty("claimEligible").GetBoolean()); + Assert.True(document.RootElement.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + } + + [Fact] + public async Task Command_Should_Treat_An_Existing_Json_Named_Directory_As_A_Directory() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-json-named-directory-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputDirectory = Directory.CreateDirectory( + TestPathUtils.PathUnder(temporaryDirectory.Path, "shadow-output.json")).FullName; + + var run = await InvokeAsync(CreateArguments(inputs, outputDirectory)); + + Assert.Equal(0, run.ExitCode); + Assert.True(Directory.Exists(outputDirectory)); + Assert.False(File.Exists(outputDirectory)); + var outputPath = TestPathUtils.PathUnder(outputDirectory, "evidence-policy-shadow.json"); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + Assert.True(document.RootElement.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + } + + [Fact] + public async Task Command_Should_Treat_Missing_Candidate_Fixtures_As_Empty_And_Report_Base_Deletion() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-deleted-"); + var fixture = Fixture("required-code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + var inputs = await WriteInputsAsync(temporaryDirectory.Path, Fixtures(fixture), candidateFixturesJson: null); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "deleted-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI010", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var result = document.RootElement.GetProperty("result"); + Assert.False(result.GetProperty("isCompatible").GetBoolean()); + Assert.Contains( + result.GetProperty("diagnostics").EnumerateArray(), + diagnostic => diagnostic.GetProperty("code").GetString() == "ASEPS004"); + Assert.Contains( + result.GetProperty("selections").EnumerateArray(), + selection => selection.GetProperty("fixtureSource").GetString() == "Base"); + } + + [Fact] + public async Task Command_Should_Return_Nonzero_And_Report_Weakened_Candidate_Selection() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-weakened-"); + var fixture = Fixture("database", EvidencePolicyShadowFixtureKind.Resource, "resources/migrations/001.sql"); + var candidatePolicy = CreateWeakenedPolicy(CreatePolicy()); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture), + candidatePolicy: candidatePolicy); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "weakened-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPS007", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var result = document.RootElement.GetProperty("result"); + Assert.False(result.GetProperty("isCompatible").GetBoolean()); + Assert.Contains( + result.GetProperty("diagnostics").EnumerateArray(), + diagnostic => diagnostic.GetProperty("code").GetString() == "ASEPS007"); + Assert.False(document.RootElement.GetProperty("claimEligible").GetBoolean()); + } + + [Fact] + public async Task Command_Should_Fail_Closed_On_Malformed_Candidate_Fixtures_Without_Rendering_Raw_Text() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-malformed-"); + const string hostileText = "candidate-owned-RAW-SENTINEL-###"; + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + hostileText); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "malformed-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI002", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(hostileText, run.AllText, StringComparison.Ordinal); + var outputText = await File.ReadAllTextAsync(outputPath); + Assert.DoesNotContain(hostileText, outputText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(outputText); + Assert.False(document.RootElement.GetProperty("claimEligible").GetBoolean()); + Assert.Equal( + "ASEPSCLI002", + Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()) + .GetProperty("code") + .GetString()); + } + + [Theory] + [InlineData(true, "Base")] + [InlineData(false, "Candidate")] + public async Task Command_Should_Fail_Closed_And_Redact_Oversized_Input( + bool isBasePolicy, + string expectedSource) + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-oversized-"); + const string hostileText = "oversized-input-RAW-SENTINEL"; + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var inputPath = isBasePolicy ? inputs.BasePolicyPath : inputs.CandidateFixturesPath; + var oversizedInput = new byte[(1024 * 1024) + 1]; + Encoding.UTF8.GetBytes(hostileText).CopyTo(oversizedInput, 0); + await File.WriteAllBytesAsync(inputPath, oversizedInput); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "oversized-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI003", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(inputs.BasePolicyPath, run.AllText, StringComparison.Ordinal); + Assert.DoesNotContain(hostileText, run.AllText, StringComparison.Ordinal); + var outputText = await File.ReadAllTextAsync(outputPath); + Assert.DoesNotContain(inputs.BasePolicyPath, outputText, StringComparison.Ordinal); + Assert.DoesNotContain(hostileText, outputText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(outputText); + var root = document.RootElement; + Assert.False(root.GetProperty("claimEligible").GetBoolean()); + Assert.False(root.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + var diagnostic = Assert.Single(root.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI003", diagnostic.GetProperty("code").GetString()); + Assert.Equal(expectedSource, diagnostic.GetProperty("fixtureSource").GetString()); + } + + [Fact] + public async Task Command_Should_Accept_A_Valid_Policy_At_The_One_Mebibyte_Input_Limit() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-exact-input-limit-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var policyBytes = EvidenceCanonicalJson.Serialize(CreatePolicy()); + var exactLimitPolicyBytes = Enumerable.Repeat((byte)' ', 1024 * 1024).ToArray(); + policyBytes.CopyTo(exactLimitPolicyBytes, 0); + await File.WriteAllBytesAsync(inputs.BasePolicyPath, exactLimitPolicyBytes); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "exact-input-limit-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.Equal(0, run.ExitCode); + Assert.Contains("claimEligible=false", run.Output, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + Assert.True(document.RootElement.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + } + + [Fact] + public async Task Command_Should_Reject_Unbounded_Input_When_A_Device_Reports_No_Length() + { + var unboundedInputPath = TestPathUtils.PathUnder(Path.DirectorySeparatorChar.ToString(), "dev", "zero"); + if (!File.Exists(unboundedInputPath)) + { + return; + } + + Assert.Equal(0, new FileInfo(unboundedInputPath).Length); + + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-unbounded-input-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + inputs = inputs with { BasePolicyPath = unboundedInputPath }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "unbounded-input-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI003", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(unboundedInputPath, run.AllText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI003", diagnostic.GetProperty("code").GetString()); + Assert.Equal("Base", diagnostic.GetProperty("fixtureSource").GetString()); + Assert.DoesNotContain(unboundedInputPath, document.RootElement.GetRawText(), StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Omit_A_Result_That_Exceeds_The_Output_Limit() + { + const int maximumPathLength = 512; + const int maximumKindLength = 32; + const int maximumIdentifierLength = 128; + var escapedCharacter = '\u2028'; + var pathSegment = new string(escapedCharacter, maximumPathLength - 2); + var changedPath = $"x{pathSegment}x"; + var previousPath = $"y{pathSegment}y"; + var changeKind = $"m{new string(escapedCharacter, maximumKindLength - 2)}d"; + var identifierSegment = new string(escapedCharacter, maximumIdentifierLength - 3); + + EvidencePolicyShadowFixture[] CreateFixtures(string prefix) => + Enumerable.Range(0, EvidencePolicyShadowValidator.MaximumFixtures) + .Select(index => new EvidencePolicyShadowFixture( + $"{prefix}{identifierSegment}{index:D2}", + EvidencePolicyShadowFixtureKind.Documentation, + new NormalizedDiffPath(changedPath, changeKind, previousPath))) + .ToArray(); + + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-oversized-result-"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(CreateFixtures("b")), + Fixtures(CreateFixtures("c"))); + Assert.InRange(new FileInfo(inputs.BaseFixturesPath).Length, 1, 1024 * 1024); + Assert.InRange(new FileInfo(inputs.CandidateFixturesPath).Length, 1, 1024 * 1024); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "bounded-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI010", run.Error, StringComparison.Ordinal); + Assert.Contains("ASEPSCLI005", run.Error, StringComparison.Ordinal); + var outputText = await File.ReadAllTextAsync(outputPath); + Assert.True(new FileInfo(outputPath).Length < 1024 * 1024); + using var document = JsonDocument.Parse(outputText); + var root = document.RootElement; + Assert.False(root.GetProperty("claimEligible").GetBoolean()); + var result = root.GetProperty("result"); + Assert.False(result.GetProperty("isCompatible").GetBoolean()); + Assert.Empty(result.GetProperty("selections").EnumerateArray()); + var diagnostic = Assert.Single(result.GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI005", diagnostic.GetProperty("code").GetString()); + Assert.Contains("1048576-byte output limit", diagnostic.GetProperty("message").GetString(), StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Reject_A_Missing_Base_Fixture_File() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-missing-base-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + baseFixturesJson: null, + Fixtures(fixture)); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "missing-base-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI001", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + Assert.False(document.RootElement.GetProperty("result").GetProperty("isCompatible").GetBoolean()); + Assert.Contains( + document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray(), + diagnostic => diagnostic.GetProperty("fixtureSource").GetString() == "Base"); + } + + [Theory] + [InlineData(true, "Base", "--base-policy")] + [InlineData(false, "Candidate", "--candidate-policy")] + public async Task Command_Should_Reject_A_Missing_Policy_File_With_Redacted_Diagnostic( + bool isBasePolicy, + string expectedSource, + string optionName) + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-missing-policy-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var missingPolicyPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "private-missing-policy.json"); + inputs = isBasePolicy + ? inputs with { BasePolicyPath = missingPolicyPath } + : inputs with { CandidatePolicyPath = missingPolicyPath }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "missing-policy-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI001", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(missingPolicyPath, run.AllText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI001", diagnostic.GetProperty("code").GetString()); + Assert.Equal(expectedSource, diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + $"{optionName} could not be read; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + Assert.DoesNotContain(missingPolicyPath, document.RootElement.GetRawText(), StringComparison.Ordinal); + } + + [Theory] + [InlineData(true, "Base", "--base-policy")] + [InlineData(false, "Candidate", "--candidate-policy")] + public async Task Command_Should_Reject_Malformed_Policy_Without_Leaking_Path_Or_Raw_Text( + bool isBasePolicy, + string expectedSource, + string optionName) + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-malformed-policy-"); + const string hostileText = "policy-owned-RAW-SENTINEL-###"; + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var policyPath = isBasePolicy ? inputs.BasePolicyPath : inputs.CandidatePolicyPath; + await File.WriteAllTextAsync(policyPath, hostileText); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "malformed-policy-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI002", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(hostileText, run.AllText, StringComparison.Ordinal); + Assert.DoesNotContain(policyPath, run.AllText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI002", diagnostic.GetProperty("code").GetString()); + Assert.Equal(expectedSource, diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + $"{optionName} is malformed Evidence JSON; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + var outputText = document.RootElement.GetRawText(); + Assert.DoesNotContain(hostileText, outputText, StringComparison.Ordinal); + Assert.DoesNotContain(policyPath, outputText, StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Reject_A_Directory_As_A_Policy_Input_With_Redacted_Diagnostic() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-directory-input-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var policyDirectory = Directory.CreateDirectory( + TestPathUtils.PathUnder(temporaryDirectory.Path, "policy-input-directory")).FullName; + inputs = inputs with { BasePolicyPath = policyDirectory }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "directory-policy-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI001", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(policyDirectory, run.AllText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI001", diagnostic.GetProperty("code").GetString()); + Assert.Equal("Base", diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + "--base-policy could not be read; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + } + + [Fact] + public async Task Command_Should_Classify_Null_Candidate_Fixtures_As_Malformed_Without_Leaking_The_Path() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-null-policy-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + "null"); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "null-candidate-fixtures-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI002", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(inputs.CandidateFixturesPath, run.AllText, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI002", diagnostic.GetProperty("code").GetString()); + Assert.Equal("Candidate", diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + "--candidate-fixtures is malformed Evidence JSON; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + Assert.DoesNotContain(inputs.CandidateFixturesPath, document.RootElement.GetRawText(), StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Treat_Candidate_Fixtures_With_Missing_Parent_Directory_As_Empty() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-missing-fixture-parent-"); + var fixture = Fixture("required-code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + inputs = inputs with + { + CandidateFixturesPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "missing-parent", "candidate-fixtures.json") + }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "missing-fixture-parent-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI010", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var result = document.RootElement.GetProperty("result"); + Assert.False(result.GetProperty("isCompatible").GetBoolean()); + Assert.Contains( + result.GetProperty("diagnostics").EnumerateArray(), + diagnostic => diagnostic.GetProperty("code").GetString() == "ASEPS004"); + } + + [Fact] + public async Task Command_Should_Reject_Blank_Base_Policy_Path_With_Redacted_Diagnostic() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-blank-policy-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + inputs = inputs with { BasePolicyPath = string.Empty }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "blank-policy-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI001", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllTextAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI001", diagnostic.GetProperty("code").GetString()); + Assert.Equal("Base", diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + "--base-policy must name an input file; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + } + + [Fact] + public async Task Command_Should_Reject_An_Omitted_Candidate_Fixtures_Path_Even_Though_Missing_Files_Are_Allowed() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-blank-candidate-fixtures-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + inputs = inputs with { CandidateFixturesPath = string.Empty }; + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "blank-candidate-fixtures-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI001", run.Error, StringComparison.Ordinal); + using var document = JsonDocument.Parse(await File.ReadAllBytesAsync(outputPath)); + var diagnostic = Assert.Single(document.RootElement.GetProperty("result").GetProperty("diagnostics").EnumerateArray()); + Assert.Equal("ASEPSCLI001", diagnostic.GetProperty("code").GetString()); + Assert.Equal("Candidate", diagnostic.GetProperty("fixtureSource").GetString()); + Assert.Equal( + "--candidate-fixtures must name an input file; no comparison was performed.", + diagnostic.GetProperty("message").GetString()); + } + + [Fact] + public async Task Command_Should_Map_Missing_Output_Option_To_Redacted_Write_Error() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-missing-output-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + + var run = await InvokeAsync(CreateArgumentsWithoutOutput(inputs)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI006", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(temporaryDirectory.Path, run.AllText, StringComparison.Ordinal); + } + + [Fact] + public async Task Command_Should_Map_Output_Beneath_A_File_To_Redacted_Write_Error() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-unsafe-output-"); + const string blockerContents = "output-parent-KEEP-CONTENTS"; + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputParentFile = TestPathUtils.PathUnder(temporaryDirectory.Path, "output-parent-file"); + await File.WriteAllTextAsync(outputParentFile, blockerContents); + var unsafeOutputPath = TestPathUtils.PathUnder(outputParentFile, "shadow-result.json"); + + var run = await InvokeAsync(CreateArguments(inputs, unsafeOutputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI006: The bounded shadow result could not be written to a new output target.", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(outputParentFile, run.AllText, StringComparison.Ordinal); + Assert.Equal(blockerContents, await File.ReadAllTextAsync(outputParentFile)); + Assert.False(File.Exists(unsafeOutputPath)); + } + + [Fact] + public async Task Command_Should_Honor_PreCanceled_Console_Without_Creating_Output() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-canceled-"); + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "canceled-result.json"); + using var console = new FakeConsole(new MemoryStream(), new MemoryStream(), new MemoryStream()); + var cancellationToken = console.RegisterCancellationHandler(); + console.RequestCancellation(TimeSpan.Zero); + Assert.True(cancellationToken.IsCancellationRequested); + + var originalExitCode = Environment.ExitCode; + try + { + try + { + await AppSurfaceCliApp.RunAsync( + CreateArguments(inputs, outputPath), + options => options.CustomRegistrations.Add( + services => services.AddSingleton(console))); + } + catch (OperationCanceledException) + { + // The command may propagate cancellation or let CliFx handle the canceled execution. + } + } + finally + { + Environment.ExitCode = originalExitCode; + } + + Assert.False(File.Exists(outputPath)); + } + + [Fact] + public async Task Command_Should_Refuse_To_Overwrite_Existing_Output_And_Preserve_Contents() + { + using var temporaryDirectory = TempDirectory.Create("appsurface-policy-shadow-existing-output-"); + const string existingContents = "output-owned-KEEP-EXISTING-CONTENTS"; + var fixture = Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + var inputs = await WriteInputsAsync( + temporaryDirectory.Path, + Fixtures(fixture), + Fixtures(fixture)); + var outputPath = TestPathUtils.PathUnder(temporaryDirectory.Path, "existing-result.json"); + await File.WriteAllTextAsync(outputPath, existingContents); + + var run = await InvokeAsync(CreateArguments(inputs, outputPath)); + + Assert.NotEqual(0, run.ExitCode); + Assert.Contains("ASEPSCLI006: The bounded shadow result could not be written to a new output target.", run.Error, StringComparison.Ordinal); + Assert.DoesNotContain(outputPath, run.AllText, StringComparison.Ordinal); + Assert.Equal(existingContents, await File.ReadAllTextAsync(outputPath)); + } + + private static string[] CreateArguments(CommandInputs inputs, string outputPath) => + [ + "evidence", "shadow-policy", + "--base-policy", inputs.BasePolicyPath, + "--candidate-policy", inputs.CandidatePolicyPath, + "--base-fixtures", inputs.BaseFixturesPath, + "--candidate-fixtures", inputs.CandidateFixturesPath, + "--output", outputPath, + ]; + + private static string[] CreateArgumentsWithoutOutput(CommandInputs inputs) => + [ + "evidence", "shadow-policy", + "--base-policy", inputs.BasePolicyPath, + "--candidate-policy", inputs.CandidatePolicyPath, + "--base-fixtures", inputs.BaseFixturesPath, + "--candidate-fixtures", inputs.CandidateFixturesPath, + ]; + + private static async Task WriteInputsAsync( + string root, + string? baseFixturesJson, + string? candidateFixturesJson, + EvidencePolicy? basePolicy = null, + EvidencePolicy? candidatePolicy = null) + { + var basePolicyPath = TestPathUtils.PathUnder(root, "base-policy.json"); + var candidatePolicyPath = TestPathUtils.PathUnder(root, "candidate-policy.json"); + var baseFixturesPath = TestPathUtils.PathUnder(root, "base-fixtures.json"); + var candidateFixturesPath = TestPathUtils.PathUnder(root, "candidate-fixtures.json"); + await File.WriteAllBytesAsync(basePolicyPath, EvidenceCanonicalJson.Serialize(basePolicy ?? CreatePolicy())); + await File.WriteAllBytesAsync(candidatePolicyPath, EvidenceCanonicalJson.Serialize(candidatePolicy ?? CreatePolicy())); + if (baseFixturesJson is not null) + { + await File.WriteAllTextAsync(baseFixturesPath, baseFixturesJson); + } + + if (candidateFixturesJson is not null) + { + await File.WriteAllTextAsync(candidateFixturesPath, candidateFixturesJson); + } + + return new CommandInputs(basePolicyPath, candidatePolicyPath, baseFixturesPath, candidateFixturesPath); + } + + private static string Fixtures(params EvidencePolicyShadowFixture[] fixtures) => + JsonSerializer.Serialize(fixtures, FixtureJsonOptions); + + private static EvidencePolicyShadowFixture Fixture( + string id, + EvidencePolicyShadowFixtureKind kind, + string path) => + new(id, kind, new NormalizedDiffPath(path)); + + private static async Task InvokeAsync(string[] args) + { + using var console = new FakeInMemoryConsole(); + var originalExitCode = Environment.ExitCode; + try + { + Environment.ExitCode = 0; + await AppSurfaceCliApp.RunAsync( + args, + options => options.CustomRegistrations.Add( + services => services.AddSingleton(console))); + var output = console.ReadOutputString(); + var error = console.ReadErrorString(); + return new CapturedCommand(output, error, Environment.ExitCode); + } + finally + { + Environment.ExitCode = originalExitCode; + } + } + + private static EvidencePolicy CreatePolicy() + { + var documentation = new EvidenceProfile("documentation", EvidenceProfileScope.Targeted, [], [], []); + var code = CreateRequirementProfile("code", "code", hasResource: false); + var resource = CreateRequirementProfile("resource", "resource", hasResource: true); + var control = CreateRequirementProfile("control", "control", hasResource: true); + var conservative = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + [.. code.Resources, .. resource.Resources, .. control.Resources], + [.. code.Producers, .. resource.Producers, .. control.Producers], + [.. code.Obligations, .. resource.Obligations, .. control.Obligations]); + + return new EvidencePolicy( + "shadow-command-test", + "1", + "conservative", + [conservative, documentation, code, resource, control], + [ + new EvidencePolicyRule("docs", "docs/**", documentation.Id), + new EvidencePolicyRule("code", "src/**", code.Id), + new EvidencePolicyRule("resource", "resources/**", resource.Id), + new EvidencePolicyRule("control", ".github/**", control.Id), + ]); + } + + private static EvidencePolicy CreateWeakenedPolicy(EvidencePolicy policy) => + policy with + { + ConservativeProfileId = "code", + Rules = + [ + .. policy.Rules.Where(static rule => rule.Id is "docs" or "code"), + new EvidencePolicyRule("resource", "resources/**", "documentation"), + ], + }; + + private static EvidenceProfile CreateRequirementProfile(string profileId, string prefix, bool hasResource) + { + var resourceId = $"{prefix}-database"; + var producerId = $"{prefix}-tests"; + var assertionId = $"{prefix}/passed@1"; + var resources = hasResource + ? new[] { new EvidenceResourceDeclaration(resourceId, "aspire_health", 30, []) } + : []; + var producer = new EvidenceProducerDeclaration( + producerId, + "integration-tests", + "1.0.0", + hasResource ? [resourceId] : [], + [assertionId], + [new EvidenceArtifactSlot("report", prefix, "application/json", Required: true, MaximumBytes: 1024)], + 60); + var obligation = new EvidenceObligation( + $"{prefix}-obligation", + "integration", + $"The {prefix} profile must pass.", + [producerId], + assertionId); + + return new EvidenceProfile(profileId, EvidenceProfileScope.Targeted, resources, [producer], [obligation]); + } + + private sealed record CommandInputs( + string BasePolicyPath, + string CandidatePolicyPath, + string BaseFixturesPath, + string CandidateFixturesPath); + + private sealed record CapturedCommand(string Output, string Error, int ExitCode) + { + public string AllText => Output + Error; + } + + private sealed class TempDirectory : IDisposable + { + private TempDirectory(string path) + { + Path = path; + } + + public string Path { get; } + + public static TempDirectory Create(string prefix) + { + var path = TestPathUtils.PathUnder( + System.IO.Path.GetTempPath(), + prefix + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(path); + if (!OperatingSystem.IsWindows()) + { + new DirectoryInfo(path).UnixFileMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + } + + return new TempDirectory(path); + } + + public void Dispose() + { + if (Directory.Exists(Path)) + { + Directory.Delete(Path, recursive: true); + } + } + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowValidatorTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowValidatorTests.cs new file mode 100644 index 000000000..dbfd1d3de --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePolicyShadowValidatorTests.cs @@ -0,0 +1,620 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidencePolicyShadowValidatorTests +{ + [Theory] + [InlineData("deleted")] + [InlineData("weakened")] + public void Validate_ShouldDetectDeletedOrWeakenedResourceRule(string change) + { + var basePolicy = CreatePolicy(); + var candidatePolicy = CreatePolicyWithChangedResourceRule(basePolicy, change); + var fixture = Fixture("database", EvidencePolicyShadowFixtureKind.Resource, "resources/migrations/001.sql"); + + var result = EvidencePolicyShadowValidator.Validate(basePolicy, candidatePolicy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + var selection = Assert.Single(result.Selections); + Assert.Equal("resource", selection.BaseProfileId); + Assert.NotEqual(selection.BaseProfileId, selection.CandidateProfileId); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS007" + && diagnostic.Path == fixture.ChangedPath.Path + && diagnostic.Message.Contains("resource 'resource-database'", StringComparison.Ordinal)); + } + + [Fact] + public void Validate_ShouldRetainBaseFixtureWhenCandidateRemovesIt() + { + var basePolicy = CreatePolicy(); + var candidatePolicy = CreatePolicyWithChangedResourceRule(basePolicy, "deleted"); + var baseFixture = Fixture("database", EvidencePolicyShadowFixtureKind.Resource, "resources/migrations/001.sql"); + + var result = EvidencePolicyShadowValidator.Validate(basePolicy, candidatePolicy, [baseFixture], []); + + Assert.False(result.IsCompatible); + var baseSelection = Assert.Single(result.Selections); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, baseSelection.FixtureSource); + Assert.Equal(baseFixture.ChangedPath, baseSelection.ChangedPath); + Assert.Equal("resource", baseSelection.BaseProfileId); + Assert.Equal("code", baseSelection.CandidateProfileId); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS004" + && diagnostic.FixtureId == baseFixture.Id + && diagnostic.Message.Contains("removed", StringComparison.Ordinal)); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "ASEPS007" && diagnostic.Path == baseFixture.ChangedPath.Path); + } + + [Fact] + public void Validate_ShouldKeepBaseFixtureWhenCandidateEditsItsInput() + { + var policy = CreatePolicy(); + var baseFixture = Fixture("control", EvidencePolicyShadowFixtureKind.ControlPlane, ".github/workflows/evidence-gate.yml"); + var candidateFixture = Fixture("control", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"); + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [baseFixture], [candidateFixture]); + + Assert.False(result.IsCompatible); + Assert.Collection( + result.Selections.OrderBy(static selection => selection.FixtureSource), + selection => + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(baseFixture.ChangedPath, selection.ChangedPath); + Assert.Equal("control", selection.BaseProfileId); + Assert.Equal("control", selection.CandidateProfileId); + }, + selection => + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Candidate, selection.FixtureSource); + Assert.Equal(candidateFixture.ChangedPath, selection.ChangedPath); + Assert.Equal("documentation", selection.BaseProfileId); + Assert.Equal("documentation", selection.CandidateProfileId); + }); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS004" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.Message.Contains("edited", StringComparison.Ordinal)); + } + + [Fact] + public void Validate_ShouldReportUnrecognizedControlPlanePathEvenWhenFallbackIsConservative() + { + var basePolicy = CreatePolicy(); + var candidatePolicy = CreatePolicyWithChangedResourceRule(basePolicy, "deleted"); + var fixture = new EvidencePolicyShadowFixture( + "new-workflow", + EvidencePolicyShadowFixtureKind.ControlPlane, + new NormalizedDiffPath( + ".github/workflows/new-gate.yml", + "renamed", + ".github/workflows/old-gate.yml")); + + var result = EvidencePolicyShadowValidator.Validate(basePolicy, candidatePolicy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + var unrecognizedPaths = result.Diagnostics + .Where(diagnostic => diagnostic.Code == "ASEPS008") + .Select(static diagnostic => diagnostic.Path) + .OrderBy(static path => path, StringComparer.Ordinal); + Assert.Equal( + new[] { ".github/workflows/new-gate.yml", ".github/workflows/old-gate.yml" }, + unrecognizedPaths); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "ASEPS007"); + } + + [Fact] + public void Validate_ShouldRequireExplicitControlPlaneMappingInTrustedBasePolicy() + { + var policy = CreatePolicy(); + var basePolicy = policy with + { + Rules = policy.Rules.Where(static rule => rule.Id != "control").ToArray(), + }; + var candidatePolicy = basePolicy with + { + Rules = + [ + .. basePolicy.Rules, + new EvidencePolicyRule("control", ".github/**", policy.ConservativeProfileId), + ], + }; + var fixture = Fixture("new-workflow", EvidencePolicyShadowFixtureKind.ControlPlane, ".github/workflows/new-gate.yml"); + + var result = EvidencePolicyShadowValidator.Validate(basePolicy, candidatePolicy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal("ASEPS008", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, diagnostic.FixtureSource); + Assert.Equal(fixture.Id, diagnostic.FixtureId); + Assert.Equal(fixture.ChangedPath.Path, diagnostic.Path); + Assert.Contains("base policy does not explicitly recognize", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void Validate_ShouldResolveDocumentationCodeResourceControlPlaneAndUnknownCasesUnderBothPolicies() + { + var policy = CreatePolicy(); + EvidencePolicyShadowFixture[] fixtures = + [ + Fixture("docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/guide.md"), + Fixture("code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"), + Fixture("resource", EvidencePolicyShadowFixtureKind.Resource, "resources/database/seed.sql"), + Fixture("control", EvidencePolicyShadowFixtureKind.ControlPlane, ".github/workflows/evidence-gate.yml"), + Fixture("unknown", EvidencePolicyShadowFixtureKind.Unknown, "new-area/unclassified.bin"), + ]; + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, fixtures, fixtures); + + Assert.True(result.IsCompatible); + Assert.Equal(5, result.Selections.Count); + Assert.Collection( + result.Selections, + selection => AssertProfiles(selection, "code", "code"), + selection => AssertProfiles(selection, "control", "control"), + selection => AssertProfiles(selection, "docs", "documentation"), + selection => AssertProfiles(selection, "resource", "resource"), + selection => AssertProfiles(selection, "unknown", "conservative")); + Assert.Empty(result.Diagnostics); + } + + [Fact] + public void Validate_ShouldResolveBothSidesOfRenameFixtures() + { + var policy = CreatePolicy(); + var fixture = new EvidencePolicyShadowFixture( + "cross-class-rename", + EvidencePolicyShadowFixtureKind.Resource, + new NormalizedDiffPath("src/NewFeature.cs", "renamed", "resources/OldFeature.cs")); + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [fixture], [fixture]); + + Assert.True(result.IsCompatible); + var selection = Assert.Single(result.Selections); + Assert.Equal("conservative", selection.BaseProfileId); + Assert.Equal("conservative", selection.CandidateProfileId); + Assert.Equal("resources/OldFeature.cs", selection.ChangedPath.PreviousPath); + } + + [Fact] + public void Validate_ShouldCapDiagnosticsDeterministically() + { + var policy = CreatePolicy(); + var baseFixtures = Enumerable.Range(0, 40) + .Select(index => Fixture($"fixture-{index:D2}", EvidencePolicyShadowFixtureKind.Code, $"src/Feature{index:D2}.cs")) + .ToArray(); + var candidateFixtures = baseFixtures + .Select(fixture => fixture with + { + ChangedPath = new NormalizedDiffPath($"docs/{fixture.Id}.md"), + }) + .ToArray(); + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, baseFixtures, candidateFixtures); + + Assert.False(result.IsCompatible); + Assert.Equal(EvidencePolicyShadowValidator.MaximumDiagnostics, result.Diagnostics.Count); + Assert.True(result.DiagnosticsTruncated); + Assert.Equal( + result.Diagnostics.OrderBy(static diagnostic => diagnostic.Code, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.FixtureSource) + .ThenBy(static diagnostic => diagnostic.FixtureId, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.Path, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.Message, StringComparer.Ordinal), + result.Diagnostics); + } + + [Fact] + public void Validate_ShouldReportInvalidCandidateGatePolicyWithoutClaimingCompatibility() + { + var policy = CreatePolicy(); + var invalidCandidate = policy with { ConservativeProfileId = "documentation" }; + var fixture = Fixture("code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + + var result = EvidencePolicyShadowValidator.Validate(policy, invalidCandidate, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + Assert.Empty(result.Selections); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "ASEPS002"); + } + + [Fact] + public void Validate_ShouldReportIncompletePolicyCollectionsForEitherPolicySide() + { + var policy = CreatePolicy(); + var fixture = Fixture("code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + var invalidPolicies = new[] + { + (EvidencePolicyShadowFixtureSource.Base, policy with { Profiles = null! }), + (EvidencePolicyShadowFixtureSource.Base, policy with { Rules = null! }), + (EvidencePolicyShadowFixtureSource.Candidate, policy with { Profiles = null! }), + (EvidencePolicyShadowFixtureSource.Candidate, policy with { Rules = null! }), + }; + + foreach (var (source, invalidPolicy) in invalidPolicies) + { + var result = source == EvidencePolicyShadowFixtureSource.Base + ? EvidencePolicyShadowValidator.Validate(invalidPolicy, policy, [fixture], [fixture]) + : EvidencePolicyShadowValidator.Validate(policy, invalidPolicy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + Assert.Empty(result.Selections); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal(source == EvidencePolicyShadowFixtureSource.Base ? "ASEPS001" : "ASEPS002", diagnostic.Code); + Assert.Equal(source, diagnostic.FixtureSource); + Assert.Contains("incomplete", diagnostic.Message, StringComparison.Ordinal); + } + } + + [Fact] + public void Validate_ShouldReportInvalidTrustedBaseGatePolicyWithoutClaimingCompatibility() + { + var policy = CreatePolicy(); + var invalidBasePolicy = policy with { ConservativeProfileId = "missing-profile" }; + var fixture = Fixture("code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + + var result = EvidencePolicyShadowValidator.Validate(invalidBasePolicy, policy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + Assert.Empty(result.Selections); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal("ASEPS001", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, diagnostic.FixtureSource); + Assert.Contains("base gate policy is invalid", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void Validate_ShouldPreserveBaseCasesWhenCandidateFixturesExceedTheLimit() + { + var policy = CreatePolicy(); + var baseFixture = Fixture("authoritative", EvidencePolicyShadowFixtureKind.Code, "src/Authoritative.cs"); + var candidateFixtures = Enumerable.Range(0, EvidencePolicyShadowValidator.MaximumFixtures + 1) + .Select(index => Fixture($"candidate-{index:D2}", EvidencePolicyShadowFixtureKind.Code, $"src/Candidate{index:D2}.cs")) + .ToArray(); + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [baseFixture], candidateFixtures); + + Assert.False(result.IsCompatible); + var selection = Assert.Single(result.Selections); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(baseFixture.Id, selection.FixtureId); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS003" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.FixtureId is null + && diagnostic.Path is null + && diagnostic.Message.Contains("authoritative base cases remain active", StringComparison.Ordinal)); + } + + [Fact] + public void Validate_ShouldRejectCandidatePoliciesBeyondProfileAndRuleLimits() + { + var policy = CreatePolicy(); + var fixture = Fixture("code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + var oversizedProfiles = policy with + { + Profiles = Enumerable.Repeat(policy.Profiles[0], 65).ToArray(), + }; + var oversizedRules = policy with + { + Rules = Enumerable.Repeat(policy.Rules[0], 257).ToArray(), + }; + + var profileResult = EvidencePolicyShadowValidator.Validate(policy, oversizedProfiles, [fixture], [fixture]); + var ruleResult = EvidencePolicyShadowValidator.Validate(policy, oversizedRules, [fixture], [fixture]); + + Assert.False(profileResult.IsCompatible); + Assert.Empty(profileResult.Selections); + Assert.Contains(profileResult.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS002" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.Message.Contains("bounded policy shape", StringComparison.Ordinal)); + Assert.False(ruleResult.IsCompatible); + Assert.Empty(ruleResult.Selections); + Assert.Contains(ruleResult.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS002" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.Message.Contains("bounded policy shape", StringComparison.Ordinal)); + } + + [Fact] + public void Validate_ShouldKeepBaseCasesWhenCandidateFixtureDataIsMalformedOrDuplicated() + { + var policy = CreatePolicy(); + var baseFixture = Fixture("base-code", EvidencePolicyShadowFixtureKind.Code, "src/Base.cs"); + EvidencePolicyShadowFixture[] candidateFixtures = + [ + Fixture("supplemental", EvidencePolicyShadowFixtureKind.Code, "src/First.cs"), + Fixture("supplemental", EvidencePolicyShadowFixtureKind.Code, "src/Second.cs"), + Fixture(" ", EvidencePolicyShadowFixtureKind.Code, "src/Invalid.cs"), + ]; + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [baseFixture], candidateFixtures); + + Assert.False(result.IsCompatible); + var selection = Assert.Single(result.Selections); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(baseFixture.Id, selection.FixtureId); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS003" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.Message.Contains("must be unique", StringComparison.Ordinal)); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.Code == "ASEPS003" + && diagnostic.FixtureSource == EvidencePolicyShadowFixtureSource.Candidate + && diagnostic.Message.Contains("incomplete", StringComparison.Ordinal)); + } + + [Fact] + public void Validate_ShouldBoundDiagnosticsForMalformedCandidateFixtureFields() + { + var policy = CreatePolicy(); + var baseFixture = Fixture("base-code", EvidencePolicyShadowFixtureKind.Code, "src/Base.cs"); + var longIdentifier = new string('i', 129); + var longPath = new string('p', 513); + EvidencePolicyShadowFixture[] candidateFixtures = + [ + null!, + new("invalid-kind", (EvidencePolicyShadowFixtureKind)99, new NormalizedDiffPath("src/InvalidKind.cs")), + new("null-path", EvidencePolicyShadowFixtureKind.Code, null!), + Fixture("empty-path", EvidencePolicyShadowFixtureKind.Code, string.Empty), + Fixture(longIdentifier, EvidencePolicyShadowFixtureKind.Code, "src/LongId.cs"), + Fixture("long-path", EvidencePolicyShadowFixtureKind.Code, longPath), + new("long-kind", EvidencePolicyShadowFixtureKind.Code, new NormalizedDiffPath("src/LongKind.cs", new string('k', 33))), + new("long-previous", EvidencePolicyShadowFixtureKind.Code, new NormalizedDiffPath("src/New.cs", "renamed", longPath)), + ]; + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [baseFixture], candidateFixtures); + + Assert.False(result.IsCompatible); + Assert.Collection( + result.Selections, + selection => + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(baseFixture.Id, selection.FixtureId); + }); + Assert.Equal(candidateFixtures.Length, result.Diagnostics.Count); + Assert.All(result.Diagnostics, diagnostic => + { + Assert.Equal("ASEPS003", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Candidate, diagnostic.FixtureSource); + }); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.FixtureId is null + && diagnostic.Kind is null + && diagnostic.Path is null); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.FixtureId == "invalid-kind" + && diagnostic.Kind is null); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.FixtureId == "null-path" + && diagnostic.Kind == EvidencePolicyShadowFixtureKind.Code + && diagnostic.Path is null); + Assert.Contains(result.Diagnostics, diagnostic => + diagnostic.FixtureId == "empty-path" + && diagnostic.Path == string.Empty); + var boundedIdentifierDiagnostic = Assert.Single(result.Diagnostics, diagnostic => diagnostic.FixtureId?.Length == 128); + Assert.Equal(128, boundedIdentifierDiagnostic.FixtureId!.Length); + Assert.EndsWith("…", boundedIdentifierDiagnostic.FixtureId, StringComparison.Ordinal); + var boundedPathDiagnostic = Assert.Single(result.Diagnostics, diagnostic => diagnostic.FixtureId == "long-path"); + Assert.Equal(512, boundedPathDiagnostic.Path!.Length); + Assert.EndsWith("…", boundedPathDiagnostic.Path, StringComparison.Ordinal); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.FixtureId == "long-kind"); + Assert.Contains(result.Diagnostics, diagnostic => diagnostic.FixtureId == "long-previous"); + } + + [Fact] + public void Validate_ShouldReportCandidatePlannerFailureForAmbiguousPathRules() + { + var policy = CreatePolicy(); + var candidatePolicy = policy with + { + Rules = + [ + .. policy.Rules, + new EvidencePolicyRule("conflicting-code", "src/**", "resource"), + ], + }; + var fixture = Fixture("ambiguous-code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + + var result = EvidencePolicyShadowValidator.Validate(policy, candidatePolicy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + Assert.Empty(result.Selections); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal("ASEPS006", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Candidate, diagnostic.FixtureSource); + Assert.Equal(fixture.Id, diagnostic.FixtureId); + Assert.Equal(fixture.ChangedPath.Path, diagnostic.Path); + Assert.Contains("candidate policy could not resolve", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void Validate_ShouldFailClosedForEmptyOrInvalidTrustedBaseFixtureSets() + { + var policy = CreatePolicy(); + var emptyResult = EvidencePolicyShadowValidator.Validate(policy, policy, [], []); + var validCandidateFixture = Fixture("candidate-only", EvidencePolicyShadowFixtureKind.Code, "src/Candidate.cs"); + EvidencePolicyShadowFixture[] invalidBaseFixtures = + [ + Fixture(" ", EvidencePolicyShadowFixtureKind.Code, "src/invalid-id.cs"), + Fixture("duplicate", EvidencePolicyShadowFixtureKind.Code, "src/first.cs"), + Fixture("duplicate", EvidencePolicyShadowFixtureKind.Code, "src/second.cs"), + ]; + var invalidResult = EvidencePolicyShadowValidator.Validate(policy, policy, invalidBaseFixtures, [validCandidateFixture]); + var oversizedBaseFixtures = Enumerable.Range(0, EvidencePolicyShadowValidator.MaximumFixtures + 1) + .Select(index => Fixture($"base-{index:D2}", EvidencePolicyShadowFixtureKind.Code, $"src/Base{index:D2}.cs")) + .ToArray(); + var oversizedResult = EvidencePolicyShadowValidator.Validate(policy, policy, oversizedBaseFixtures, []); + + Assert.False(emptyResult.IsCompatible); + Assert.Empty(emptyResult.Selections); + var emptyDiagnostic = Assert.Single(emptyResult.Diagnostics); + Assert.Equal("ASEPS003", emptyDiagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, emptyDiagnostic.FixtureSource); + Assert.Null(emptyDiagnostic.FixtureId); + Assert.Null(emptyDiagnostic.Path); + Assert.Contains("trusted base fixture set is empty", emptyDiagnostic.Message, StringComparison.Ordinal); + + Assert.False(invalidResult.IsCompatible); + Assert.Empty(invalidResult.Selections); + Assert.Equal(2, invalidResult.Diagnostics.Count); + Assert.All(invalidResult.Diagnostics, diagnostic => + { + Assert.Equal("ASEPS003", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, diagnostic.FixtureSource); + }); + Assert.Contains(invalidResult.Diagnostics, diagnostic => diagnostic.Message.Contains("incomplete", StringComparison.Ordinal)); + Assert.Contains(invalidResult.Diagnostics, diagnostic => diagnostic.Message.Contains("must be unique", StringComparison.Ordinal)); + + Assert.False(oversizedResult.IsCompatible); + Assert.Empty(oversizedResult.Selections); + var oversizedDiagnostic = Assert.Single(oversizedResult.Diagnostics); + Assert.Equal("ASEPS003", oversizedDiagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, oversizedDiagnostic.FixtureSource); + Assert.Contains("base fixture set exceeds", oversizedDiagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void Validate_ShouldIncludeNewCandidateFixturesAsSupplementalSelections() + { + var policy = CreatePolicy(); + var baseFixture = Fixture("base-code", EvidencePolicyShadowFixtureKind.Code, "src/Base.cs"); + var supplementalFixture = Fixture("added-docs", EvidencePolicyShadowFixtureKind.Documentation, "docs/new-guide.md"); + + var result = EvidencePolicyShadowValidator.Validate(policy, policy, [baseFixture], [baseFixture, supplementalFixture]); + + Assert.True(result.IsCompatible); + Assert.Collection( + result.Selections, + selection => + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(baseFixture.Id, selection.FixtureId); + Assert.Equal("code", selection.BaseProfileId); + Assert.Equal("code", selection.CandidateProfileId); + }, + selection => + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Candidate, selection.FixtureSource); + Assert.Equal(supplementalFixture.Id, selection.FixtureId); + Assert.Equal("documentation", selection.BaseProfileId); + Assert.Equal("documentation", selection.CandidateProfileId); + }); + Assert.Empty(result.Diagnostics); + } + + [Fact] + public void Validate_ShouldReportTrustedBasePlannerFailureForAmbiguousPathRules() + { + var policy = CreatePolicy(); + var ambiguousBasePolicy = policy with + { + Rules = + [ + .. policy.Rules, + new EvidencePolicyRule("conflicting-code", "src/**", "resource"), + ], + }; + var fixture = Fixture("ambiguous-base-code", EvidencePolicyShadowFixtureKind.Code, "src/Feature.cs"); + + var result = EvidencePolicyShadowValidator.Validate(ambiguousBasePolicy, policy, [fixture], [fixture]); + + Assert.False(result.IsCompatible); + Assert.Empty(result.Selections); + var diagnostic = Assert.Single(result.Diagnostics); + Assert.Equal("ASEPS005", diagnostic.Code); + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, diagnostic.FixtureSource); + Assert.Equal(fixture.Id, diagnostic.FixtureId); + Assert.Equal(fixture.ChangedPath.Path, diagnostic.Path); + Assert.Contains("base policy could not resolve", diagnostic.Message, StringComparison.Ordinal); + } + + private static void AssertProfiles(EvidencePolicyShadowSelection selection, string fixtureId, string profileId) + { + Assert.Equal(EvidencePolicyShadowFixtureSource.Base, selection.FixtureSource); + Assert.Equal(fixtureId, selection.FixtureId); + Assert.Equal(profileId, selection.BaseProfileId); + Assert.Equal(profileId, selection.CandidateProfileId); + } + + private static EvidencePolicyShadowFixture Fixture( + string id, + EvidencePolicyShadowFixtureKind kind, + string path) => + new(id, kind, new NormalizedDiffPath(path)); + + private static EvidencePolicy CreatePolicy() + { + var documentation = new EvidenceProfile("documentation", EvidenceProfileScope.Targeted, [], [], []); + var code = CreateRequirementProfile("code", "code", hasResource: false); + var resource = CreateRequirementProfile("resource", "resource", hasResource: true); + var control = CreateRequirementProfile("control", "control", hasResource: true); + var conservative = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + [.. code.Resources, .. resource.Resources, .. control.Resources], + [.. code.Producers, .. resource.Producers, .. control.Producers], + [.. code.Obligations, .. resource.Obligations, .. control.Obligations]); + + return new EvidencePolicy( + "shadow-test", + "1", + "conservative", + [conservative, documentation, code, resource, control], + [ + new EvidencePolicyRule("docs", "docs/**", documentation.Id), + new EvidencePolicyRule("code", "src/**", code.Id), + new EvidencePolicyRule("resource", "resources/**", resource.Id), + new EvidencePolicyRule("control", ".github/**", control.Id), + ]); + } + + private static EvidencePolicy CreatePolicyWithChangedResourceRule(EvidencePolicy policy, string change) + { + var rules = policy.Rules + .Where(static rule => rule.Id is "docs" or "code") + .ToList(); + if (change == "weakened") + { + rules.Add(new EvidencePolicyRule("resource", "resources/**", "documentation")); + } + + return policy with + { + ConservativeProfileId = "code", + Rules = rules, + }; + } + + private static EvidenceProfile CreateRequirementProfile(string profileId, string prefix, bool hasResource) + { + var resourceId = $"{prefix}-database"; + var producerId = $"{prefix}-tests"; + var assertionId = $"{prefix}/passed@1"; + var resources = hasResource + ? new[] { new EvidenceResourceDeclaration(resourceId, "aspire_health", 30, []) } + : []; + var producer = new EvidenceProducerDeclaration( + producerId, + "integration-tests", + "1.0.0", + hasResource ? [resourceId] : [], + [assertionId], + [new EvidenceArtifactSlot("report", prefix, "application/json", Required: true, MaximumBytes: 1024)], + 60); + var obligation = new EvidenceObligation( + $"{prefix}-obligation", + "integration", + $"The {prefix} profile must pass.", + [producerId], + assertionId); + + return new EvidenceProfile(profileId, EvidenceProfileScope.Targeted, resources, [producer], [obligation]); + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs new file mode 100644 index 000000000..026cac3d0 --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs @@ -0,0 +1,1614 @@ +using System.Collections; +using System.Diagnostics; +using System.Runtime.InteropServices; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; +using ForgeTrust.AppSurface.Testing; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidencePullRequestGateVerifierTests +{ + [Fact] + public async Task VerifyAsync_ShouldAcceptCompleteRevisionBoundEvidenceAndReturnTrustedSummary() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(); + + Assert.True(result.IsEligible); + Assert.Equal("ASEVG000", result.Code); + Assert.NotNull(result.Summary); + Assert.Equal("targeted", result.Summary.ProfileId); + Assert.Equal("matched-policy-rules", result.Summary.SelectionRationale); + Assert.Equal(["compile"], result.Summary.SelectedObligationIds); + Assert.Equal(["compile"], result.Summary.ClosedObligationIds); + Assert.Empty(result.Summary.MissingObligationIds); + Assert.Equal("source", Assert.Single(result.Summary.MatchedRules).Id); + Assert.Equal(fixture.Plan.BaseRevision![..12], result.Summary.BaseRevisionShort); + Assert.Equal(fixture.Plan.HeadRevision![..12], result.Summary.HeadRevisionShort); + Assert.Equal("compile", Assert.Single(result.Summary.ObligationRationales).Id); + } + + [Fact] + public async Task VerifyAsync_ShouldAcceptExplicitEmptyDocumentationClaimWithoutArtifactHandoff() + { + await using var fixture = await GateFixture.CreateAsync(documentationOnly: true); + + var result = await fixture.VerifyAsync( + trustedArtifactHandoffRootPath: null, + artifactVerifier: null, + omitArtifactRoot: true, + useFakeArtifactVerifier: false); + + Assert.True(result.IsEligible); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, fixture.Manifest.ClaimKind); + Assert.NotNull(result.Summary); + Assert.Equal("docs", result.Summary.ProfileId); + Assert.Empty(result.Summary.SelectedObligationIds); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Empty(result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldAllowNoCheckoutAttestationOnlyForExplicitEmptyProfile() + { + await using var documentation = await GateFixture.CreateAsync(documentationOnly: true); + var noCheckout = documentation.Authority with + { + SubjectJobHeadRevision = string.Empty, + SubjectEnvelopeAttested = false, + }; + + var documentationResult = await documentation.VerifyAsync( + authority: noCheckout, + trustedArtifactHandoffRootPath: null, + artifactVerifier: null, + omitArtifactRoot: true, + useFakeArtifactVerifier: false); + + Assert.True(documentationResult.IsEligible); + Assert.Equal("ASEVG000", documentationResult.Code); + + await using var code = await GateFixture.CreateAsync(); + var codeResult = await code.VerifyAsync(authority: code.Authority with + { + SubjectJobHeadRevision = string.Empty, + SubjectEnvelopeAttested = false, + }); + + Assert.False(codeResult.IsEligible); + Assert.Equal("ASEVG007", codeResult.Code); + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedWhenNonemptyProfileHasNoTrustedArtifactRoot() + { + await using var fixture = await GateFixture.CreateAsync(); + + var missingRoot = await fixture.VerifyAsync( + trustedArtifactHandoffRootPath: null, + artifactVerifier: null, + omitArtifactRoot: true, + useFakeArtifactVerifier: false); + var missingVerifier = await fixture.VerifyAsync( + trustedArtifactHandoffRootPath: fixture.ArtifactRoot, + artifactVerifier: null, + useFakeArtifactVerifier: false); + + Assert.False(missingRoot.IsEligible); + Assert.Equal("ASEVG009", missingRoot.Code); + Assert.NotNull(missingRoot.Summary); + Assert.Empty(missingRoot.Summary.ClosedObligationIds); + Assert.Equal(["compile"], missingRoot.Summary.MissingObligationIds); + Assert.False(missingVerifier.IsEligible); + Assert.Equal("ASEVG009", missingVerifier.Code); + Assert.NotNull(missingVerifier.Summary); + Assert.Empty(missingVerifier.Summary.ClosedObligationIds); + Assert.Equal(["compile"], missingVerifier.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldRequireDeclaredAndIndependentlyAttestedIsolationForNonemptyEvidence() + { + await using var fixture = await GateFixture.CreateAsync(); + var missingManifestEnvelope = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults); + + var missingEnvelopeResult = await fixture.VerifyAsync(manifest: missingManifestEnvelope); + var missingAuthorityResult = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectEnvelopeAttested = false }); + + Assert.Equal("ASEVG004", missingEnvelopeResult.Code); + Assert.Equal("ASEVG007", missingAuthorityResult.Code); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectForgeryEvenWhenPlanAndManifestDigestsAreRecomputed() + { + await using var fixture = await GateFixture.CreateAsync(); + var forgedPlan = fixture.Plan with { MatchedRuleIds = ["forged-rule"], PlanDigest = string.Empty }; + forgedPlan = forgedPlan with { PlanDigest = EvidenceDigest.CanonicalSha256(forgedPlan) }; + var forgedManifest = EvidenceManifestBuilder.Build(forgedPlan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(plan: forgedPlan, manifest: forgedManifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectLegacyV1Plan() + { + await using var fixture = await GateFixture.CreateAsync(); + var legacyPlan = fixture.Plan with { ContractVersion = "1.0", PlanDigest = string.Empty }; + legacyPlan = legacyPlan with { PlanDigest = EvidenceDigest.CanonicalSha256(legacyPlan) }; + + var result = await fixture.VerifyAsync(plan: legacyPlan); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG002", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectTrustedPolicySubstitution() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(policy: fixture.Policy with { Id = "other-policy" }); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectExpectedRunMismatchBeforeReturningSummary() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(expectedIdentity: fixture.ExpectedIdentity with + { + RunIdentity = fixture.ExpectedIdentity.RunIdentity with { WorkflowRunAttempt = 2 }, + }); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG007", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectMalformedControllerIdentityBeforeReadingAuthority() + { + await using var fixture = await GateFixture.CreateAsync(); + var invalidIdentities = new[] + { + fixture.ExpectedIdentity with { Repository = "missing-owner" }, + fixture.ExpectedIdentity with { Repository = "forge-trust/AppSurface\n" }, + fixture.ExpectedIdentity with { EventName = "workflow_dispatch" }, + fixture.ExpectedIdentity with { WorkflowId = string.Empty }, + fixture.ExpectedIdentity with { SubjectJobId = "evidence\nsubject" }, + fixture.ExpectedIdentity with { RunIdentity = null! }, + fixture.ExpectedIdentity with + { + RunIdentity = fixture.RunIdentity with { WorkflowRunAttempt = 0 }, + }, + }; + + foreach (var invalidIdentity in invalidIdentities) + { + var result = await fixture.VerifyAsync( + expectedIdentity: invalidIdentity, + authorityProvider: new ThrowingAuthorityProvider()); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG001", result.Code); + Assert.Null(result.Summary); + } + } + + [Fact] + public async Task VerifyAsync_ShouldRejectMalformedRevisionBeforeReplanning() + { + await using var fixture = await GateFixture.CreateAsync(); + var malformedPlans = new[] + { + fixture.Plan with { BaseRevision = "not-a-revision" }, + fixture.Plan with { HeadRevision = new string('A', 40) }, + fixture.Plan with { HeadRevision = new string('a', 64) }, + }; + + foreach (var plan in malformedPlans) + { + var result = await fixture.VerifyAsync(plan: plan); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG002", result.Code); + Assert.Null(result.Summary); + } + } + + [Fact] + public async Task VerifyAsync_ShouldRejectManifestRunIdentityMismatch() + { + await using var fixture = await GateFixture.CreateAsync(); + var mismatched = fixture.Manifest with + { + PullRequestRunIdentity = fixture.ExpectedIdentity.RunIdentity with { PullRequestNumber = 778 }, + ManifestDigest = string.Empty, + }; + mismatched = mismatched with { ManifestDigest = EvidenceDigest.CanonicalSha256(mismatched) }; + + var result = await fixture.VerifyAsync(manifest: mismatched); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectUnavailableOrMismatchedCurrentAuthority() + { + await using var fixture = await GateFixture.CreateAsync(); + + var unavailable = await fixture.VerifyAsync(authorityProvider: new FakeAuthorityProvider(null)); + var movedBase = await fixture.VerifyAsync(authority: fixture.Authority with { BaseRevision = new string('a', 40) }); + var movedHead = await fixture.VerifyAsync(authority: fixture.Authority with { HeadRevision = new string('b', 40) }); + var wrongJob = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobId = "other-job" }); + var wrongCheckout = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobHeadRevision = new string('c', 40) }); + var failedJob = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobConclusion = "failure" }); + + Assert.Equal("ASEVG006", unavailable.Code); + Assert.All([movedBase, movedHead, wrongJob, wrongCheckout, failedJob], result => Assert.Equal("ASEVG007", result.Code)); + Assert.All([unavailable, movedBase, movedHead, wrongJob, wrongCheckout, failedJob], result => Assert.NotNull(result.Summary)); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectForkedOrSubstitutedCurrentAuthority() + { + await using var fixture = await GateFixture.CreateAsync(); + var invalidSnapshots = new[] + { + fixture.Authority with { Repository = "other/AppSurface" }, + fixture.Authority with { EventName = "pull_request" }, + fixture.Authority with { WorkflowId = "other-workflow.yml" }, + fixture.Authority with { RunIdentity = fixture.RunIdentity with { HeadRepositoryId = 999 } }, + fixture.Authority with { RunIdentity = null! }, + fixture.Authority with { RunIdentity = fixture.RunIdentity with { WorkflowRunAttempt = 2 } }, + fixture.Authority with { SubjectJobConclusion = "cancelled" }, + }; + + foreach (var snapshot in invalidSnapshots) + { + var result = await fixture.VerifyAsync(authority: snapshot); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG007", result.Code); + Assert.NotNull(result.Summary); + } + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedWhenTrustedReadersThrow() + { + await using var fixture = await GateFixture.CreateAsync(); + var artifactFailure = await fixture.VerifyAsync(artifactVerifier: new ThrowingArtifactVerifier()); + var authorityFailure = await fixture.VerifyAsync(authorityProvider: new ThrowingAuthorityProvider()); + + Assert.False(artifactFailure.IsEligible); + Assert.Equal("ASEVG010", artifactFailure.Code); + Assert.NotNull(artifactFailure.Summary); + Assert.Equal(["compile"], artifactFailure.Summary.MissingObligationIds); + Assert.False(authorityFailure.IsEligible); + Assert.Equal("ASEVG006", authorityFailure.Code); + Assert.NotNull(authorityFailure.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectObservationOnlyAndCleanupFailure() + { + await using var fixture = await GateFixture.CreateAsync(); + var observation = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults, + observationOnly: true); + var cleanupFailure = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(CleanupCompleted: false)); + var artifactVerifier = new FakeArtifactVerifier(true); + + var observationResult = await fixture.VerifyAsync(manifest: observation, artifactVerifier: artifactVerifier); + var cleanupResult = await fixture.VerifyAsync(manifest: cleanupFailure, artifactVerifier: artifactVerifier); + + Assert.Equal("ASEVG005", observationResult.Code); + Assert.Equal("ASEVG004", cleanupResult.Code); + Assert.False(observationResult.IsEligible); + Assert.False(cleanupResult.IsEligible); + } + + [Fact] + public async Task VerifyAsync_ShouldReportMissingObligationFromVerifiedPlanForIncompleteManifest() + { + await using var fixture = await GateFixture.CreateAsync(includeRequiredAssertion: false, includeArtifact: false); + var incompleteManifest = EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(manifest: incompleteManifest, artifactVerifier: new FakeArtifactVerifier(true)); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.NotNull(result.Summary); + Assert.Equal(["compile"], result.Summary.SelectedObligationIds); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedForMalformedAndOverBudgetContracts() + { + await using var fixture = await GateFixture.CreateAsync(); + var producer = fixture.Plan.Profile.Producers.Single(); + var obligation = fixture.Plan.Profile.Obligations.Single(); + var invalidPlans = new EvidencePlan[] + { + fixture.Plan with { PullRequestRunIdentity = fixture.RunIdentity with { TargetBranch = new string('m', 129) } }, + fixture.Plan with { PolicyDigest = new string('d', EvidenceGitChangeCapture.MaximumPathBytes + 1) }, + fixture.Plan with { MatchedRuleIds = ["source", new string('r', 129)] }, + fixture.Plan with { ChangedPaths = [null!] }, + fixture.Plan with { ChangedPaths = null! }, + fixture.Plan with { MatchedRuleIds = null! }, + fixture.Plan with { ChangedPaths = [new NormalizedDiffPath("src/Feature.cs", PreviousPath: new string('p', EvidenceGitChangeCapture.MaximumPathBytes + 1))] }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Resources = null! } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = null! } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Obligations = null! } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Resources = [null!] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [null!] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Obligations = [null!] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { AssertionIds = null! }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { RequiredResources = null! }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { RequiredResources = Enumerable.Repeat("database", EvidenceProfileLimits.MaximumResources + 1).ToArray() }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { AssertionIds = Enumerable.Repeat("build/passed", 257).ToArray() }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { ArtifactSlots = null! }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { ArtifactSlots = Enumerable.Repeat(producer.ArtifactSlots.Single(), 129).ToArray() }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Producers = [producer with { ArtifactSlots = [null!] }] } }, + fixture.Plan with { Profile = fixture.Plan.Profile with { Obligations = [obligation with { RequiredProducerIds = null! }] } }, + fixture.Plan with { PolicySnapshot = fixture.Policy with { Profiles = [] } }, + fixture.Plan with { PolicySnapshot = fixture.Policy with { Profiles = [null!] } }, + fixture.Plan with { PolicySnapshot = fixture.Policy with { Rules = null! } }, + fixture.Plan with { PolicySnapshot = fixture.Policy with { Rules = [null!] } }, + fixture.Plan with { PolicySnapshot = fixture.Policy with { Rules = new EvidencePolicyRule[10_001] } }, + fixture.Plan with + { + PolicySnapshot = fixture.Policy with + { + Rules = Enumerable.Range(0, 4_000) + .Select(_ => new EvidencePolicyRule(new string('i', 128), new string('p', 128), "targeted")) + .ToArray(), + }, + }, + }; + + foreach (var plan in invalidPlans) + { + var result = await fixture.VerifyAsync(plan: plan); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG002", result.Code); + Assert.Null(result.Summary); + } + + var producerResult = fixture.Manifest.ProducerResults.Single(); + var artifact = producerResult.Artifacts!.Single(); + var invalidManifests = new EvidenceManifest[] + { + fixture.Manifest with { PullRequestRunIdentity = null! }, + fixture.Manifest with { Metrics = null! }, + fixture.Manifest with { ResourceResults = null! }, + fixture.Manifest with { ResourceResults = new EvidenceResourceResult[EvidenceProfileLimits.MaximumResources + 1] }, + fixture.Manifest with { ResourceResults = [null!] }, + fixture.Manifest with { ResourceResults = [new EvidenceResourceResult("database", EvidenceResourceOutcome.Ready, 0, new string('d', 513))] }, + fixture.Manifest with { SelectedObligationIds = null! }, + fixture.Manifest with { SelectedObligationIds = Enumerable.Repeat("compile", EvidenceProfileLimits.MaximumObligations + 1).ToArray() }, + fixture.Manifest with { ClosedObligationIds = null! }, + fixture.Manifest with { ClosedObligationIds = Enumerable.Repeat("compile", EvidenceProfileLimits.MaximumObligations + 1).ToArray() }, + fixture.Manifest with { UnmediatedObligationIds = null! }, + fixture.Manifest with { UnmediatedObligationIds = Enumerable.Repeat("compile", EvidenceProfileLimits.MaximumObligations + 1).ToArray() }, + fixture.Manifest with { ProducerResults = null! }, + fixture.Manifest with { ProducerResults = [null!] }, + fixture.Manifest with { ProducerResults = new EvidenceProducerResult[EvidenceProfileLimits.MaximumProducers + 1] }, + fixture.Manifest with + { + ProducerResults = [producerResult with { Diagnostic = new string('d', 513) }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { SatisfiedAssertionIds = null! }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { SatisfiedAssertionIds = Enumerable.Repeat("build/passed", 257).ToArray() }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { SatisfiedAssertionIds = [new string('a', 129)] }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { Artifacts = null! }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { Artifacts = Enumerable.Repeat(artifact, 129).ToArray() }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { Artifacts = [null!] }], + }, + fixture.Manifest with + { + ProducerResults = [producerResult with { Artifacts = [artifact with { Sha256 = new string('a', EvidenceGitChangeCapture.MaximumPathBytes + 1) }] }], + }, + }; + + foreach (var manifest in invalidManifests) + { + var result = await fixture.VerifyAsync(manifest: manifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG002", result.Code); + Assert.Null(result.Summary); + } + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedWhenContractCollectionsThrowDuringValidation() + { + await using var fixture = await GateFixture.CreateAsync(); + + var malformedPlan = fixture.Plan with + { + ChangedPaths = new ThrowingReadOnlyList(), + }; + var malformedManifest = fixture.Manifest with + { + ResourceResults = new ThrowingReadOnlyList(), + }; + + var planResult = await fixture.VerifyAsync(plan: malformedPlan); + var manifestResult = await fixture.VerifyAsync(manifest: malformedManifest); + + Assert.Equal("ASEVG002", planResult.Code); + Assert.Null(planResult.Summary); + Assert.Equal("ASEVG002", manifestResult.Code); + Assert.Null(manifestResult.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedWhenManifestCollectionThrowsDuringConsistencyVerification() + { + await using var fixture = await GateFixture.CreateAsync(); + var manifest = fixture.Manifest with + { + ProducerResults = new ThrowOnEnumerationReadOnlyList( + fixture.Manifest.ProducerResults, + throwOnEnumeration: 3), + }; + + var result = await fixture.VerifyAsync(manifest: manifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldReturnCancelledForPlanningArtifactAndAuthorityCancellation() + { + await using var fixture = await GateFixture.CreateAsync(); + using var planningCancellation = new CancellationTokenSource(); + planningCancellation.Cancel(); + using var artifactCancellation = new CancellationTokenSource(); + using var authorityCancellation = new CancellationTokenSource(); + + var planningResult = await fixture.VerifyAsync(cancellationToken: planningCancellation.Token); + var artifactResult = await fixture.VerifyAsync( + artifactVerifier: new CancellingArtifactVerifier(artifactCancellation), + cancellationToken: artifactCancellation.Token); + var authorityResult = await fixture.VerifyAsync( + authorityProvider: new CancellingAuthorityProvider(authorityCancellation), + cancellationToken: authorityCancellation.Token); + + Assert.Equal("ASEVG008", planningResult.Code); + Assert.Null(planningResult.Summary); + Assert.Equal("ASEVG008", artifactResult.Code); + Assert.NotNull(artifactResult.Summary); + Assert.Equal(["compile"], artifactResult.Summary.MissingObligationIds); + Assert.Equal("ASEVG008", authorityResult.Code); + Assert.Null(authorityResult.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectNegativeExecutionDurationsAndInvalidEnvelopes() + { + await using var fixture = await GateFixture.CreateAsync(); + var producerResult = fixture.Manifest.ProducerResults.Single(); + var invalidManifests = new EvidenceManifest[] + { + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.Invalid), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.Unavailable), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.NotRequired), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(PlanningMilliseconds: -1)), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(ResourceReadinessMilliseconds: -1)), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(ProducerMilliseconds: -1)), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(CleanupMilliseconds: -1)), + EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(TotalMilliseconds: -1)), + EvidenceManifestBuilder.Build(fixture.Plan, + [producerResult with { ElapsedMilliseconds = -1 }], + envelopeStatus: EvidenceEnvelopeStatus.ValidatedNotAttested), + }; + + foreach (var manifest in invalidManifests) + { + var result = await fixture.VerifyAsync(manifest: manifest, artifactVerifier: new FakeArtifactVerifier(true)); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.NotNull(result.Summary); + } + + var profile = fixture.Policy.Profiles.Single(candidate => candidate.Id == "targeted") with + { + Resources = [new EvidenceResourceDeclaration("database", "completion", 30, [])], + }; + var policy = fixture.Policy with + { + Profiles = fixture.Policy.Profiles.Select(candidate => candidate.Id == profile.Id ? profile : candidate).ToArray(), + }; + var plan = await fixture.ResolvePlanAsync(policy); + var resourceManifest = EvidenceManifestBuilder.Build( + plan, + fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.ValidatedNotAttested, + resourceResults: [new EvidenceResourceResult("database", EvidenceResourceOutcome.Ready, -1)]); + + var resourceResult = await fixture.VerifyAsync( + plan: plan, + manifest: resourceManifest, + policy: policy, + artifactVerifier: new FakeArtifactVerifier(true)); + + Assert.False(resourceResult.IsEligible); + Assert.Equal("ASEVG004", resourceResult.Code); + Assert.NotNull(resourceResult.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldBoundSummariesAndDescribeConservativeFallback() + { + await using var fixture = await GateFixture.CreateAsync(); + var fallbackPolicy = fixture.Policy with { Rules = [] }; + var fallbackPlan = await fixture.ResolvePlanAsync(fallbackPolicy); + var fallbackManifest = EvidenceManifestBuilder.Build( + fallbackPlan, + fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.ValidatedNotAttested); + + var fallbackResult = await fixture.VerifyAsync( + plan: fallbackPlan, + manifest: fallbackManifest, + policy: fallbackPolicy); + + Assert.True(fallbackResult.IsEligible); + Assert.NotNull(fallbackResult.Summary); + Assert.Equal("conservative-fallback", fallbackResult.Summary.SelectionRationale); + var fallbackRule = Assert.Single(fallbackResult.Summary.MatchedRules); + Assert.Equal("conservative:targeted", fallbackRule.Id); + Assert.Equal("conservative fallback", fallbackRule.Pattern); + + var originalProfile = fixture.Policy.Profiles.Single(candidate => candidate.Id == "targeted"); + var obligations = Enumerable.Range(0, EvidenceProfileLimits.MaximumObligations) + .Select(index => new EvidenceObligation( + $"compile-{index:D3}", + "code", + new string('r', 300), + ["build"], + "build/passed")) + .ToArray(); + var boundedProfile = originalProfile with { Obligations = obligations }; + var boundedPolicy = fixture.Policy with + { + Profiles = fixture.Policy.Profiles + .Select(candidate => candidate.Id == boundedProfile.Id ? boundedProfile : candidate) + .ToArray(), + }; + var boundedPlan = await fixture.ResolvePlanAsync(boundedPolicy); + var boundedManifest = EvidenceManifestBuilder.Build( + boundedPlan, + fixture.Manifest.ProducerResults, + envelopeStatus: EvidenceEnvelopeStatus.ValidatedNotAttested); + + var boundedResult = await fixture.VerifyAsync( + plan: boundedPlan, + manifest: boundedManifest, + policy: boundedPolicy); + + Assert.True(boundedResult.IsEligible); + var summary = Assert.IsType(boundedResult.Summary); + Assert.Equal(EvidencePullRequestGateVerifier.MaximumSummaryItems, summary.SelectedObligationIds.Count); + Assert.Equal(EvidenceProfileLimits.MaximumObligations - EvidencePullRequestGateVerifier.MaximumSummaryItems, summary.OmittedSelectedObligationCount); + Assert.Equal(EvidencePullRequestGateVerifier.MaximumSummaryItems, summary.ClosedObligationIds.Count); + Assert.Equal(EvidenceProfileLimits.MaximumObligations - EvidencePullRequestGateVerifier.MaximumSummaryItems, summary.OmittedClosedObligationCount); + Assert.Empty(summary.MissingObligationIds); + Assert.Equal(EvidenceProfileLimits.MaximumObligations - EvidencePullRequestGateVerifier.MaximumSummaryItems, summary.OmittedObligationRationaleCount); + Assert.All(summary.ObligationRationales, rationale => Assert.Equal(256, rationale.Rationale.Length)); + Assert.Equal("compile-000", summary.SelectedObligationIds[0]); + Assert.Equal("compile-063", summary.SelectedObligationIds[^1]); + } + + [Fact] + public async Task VerifyAsync_ShouldNotCloseSummaryObligationsForInconsistentManifest() + { + await using var fixture = await GateFixture.CreateAsync(); + var inconsistent = fixture.Manifest with + { + ExecutionVerdict = EvidenceExecutionVerdict.Incomplete, + ManifestDigest = string.Empty, + }; + inconsistent = inconsistent with { ManifestDigest = EvidenceDigest.CanonicalSha256(inconsistent) }; + + var result = await fixture.VerifyAsync(manifest: inconsistent); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.NotNull(result.Summary); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectObligationSelectionMutationDuringArtifactVerification() + { + await using var fixture = await GateFixture.CreateAsync(); + var selectedObligationIds = new List(fixture.Manifest.SelectedObligationIds); + var manifest = fixture.Manifest with + { + SelectedObligationIds = selectedObligationIds, + ManifestDigest = string.Empty, + }; + manifest = manifest with { ManifestDigest = EvidenceDigest.CanonicalSha256(manifest) }; + + var result = await fixture.VerifyAsync( + manifest: manifest, + artifactVerifier: new FakeArtifactVerifier(true, () => selectedObligationIds[0] = "forged")); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectReleaseProfileSelectedForPullRequest() + { + await using var fixture = await GateFixture.CreateAsync(); + var releasePlan = fixture.Plan with + { + Profile = fixture.Plan.Profile with { Scope = EvidenceProfileScope.Release }, + PlanDigest = string.Empty, + }; + releasePlan = releasePlan with { PlanDigest = EvidenceDigest.CanonicalSha256(releasePlan) }; + var releaseManifest = EvidenceManifestBuilder.Build(releasePlan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(plan: releasePlan, manifest: releaseManifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectForgedDigestMissingFileAndSymlinkOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + var valid = await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest); + Assert.True(valid); + + EvidenceArtifactResult artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var forged = ReplaceArtifact(fixture.Manifest, artifact with { Sha256 = new string('0', 64) }); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, forged)); + + var linkedRoot = Path.Join(Path.GetDirectoryName(fixture.ArtifactRoot)!, "handoff-link"); + Directory.CreateSymbolicLink(linkedRoot, fixture.ArtifactRoot); + Assert.False(await verifier.VerifyArtifactsAsync(linkedRoot, fixture.Plan, fixture.Manifest)); + + File.Delete(fixture.ArtifactPath); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + + var symlinkTarget = Path.Join(fixture.ArtifactRoot, "symlink-target.txt"); + File.WriteAllText(symlinkTarget, "artifact bytes"); + File.CreateSymbolicLink(fixture.ArtifactPath, symlinkTarget); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectSizeMismatchAndNonRegularFileOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + + File.WriteAllBytes(fixture.ArtifactPath, new byte[checked((int)artifact.LengthBytes + 1)]); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + + File.Delete(fixture.ArtifactPath); + Directory.CreateDirectory(fixture.ArtifactPath); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectInvalidArtifactMetadataAndTraversalOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var invalidArtifacts = new[] + { + artifact with { LogicalName = "undeclared" }, + artifact with { MediaType = "application/json" }, + artifact with { LengthBytes = artifact.LengthBytes + 1 }, + artifact with { RelativePath = "../outside.txt" }, + artifact with { RelativePath = "other/build.txt" }, + artifact with { RelativePath = "reports\\build.txt" }, + artifact with { RelativePath = "reports/bad\nname.txt" }, + artifact with { RelativePath = "reports/build.txt " }, + artifact with { RelativePath = $"reports/{new string('x', EvidenceGitChangeCapture.MaximumPathBytes)}" }, + artifact with { Sha256 = "not-a-sha256" }, + }; + + foreach (var invalidArtifact in invalidArtifacts) + { + Assert.False(await verifier.VerifyArtifactsAsync( + fixture.ArtifactRoot, + fixture.Plan, + ReplaceArtifacts(fixture.Manifest, [invalidArtifact]))); + } + + var producer = fixture.Plan.Profile.Producers.Single(); + var traversalProducer = producer with { Id = "../outside" }; + var traversalPlan = fixture.Plan with + { + Profile = fixture.Plan.Profile with { Producers = [traversalProducer] }, + }; + var traversalResult = fixture.Manifest.ProducerResults.Single() with { ProducerId = traversalProducer.Id }; + var traversalManifest = ReplaceProducerResults(fixture.Manifest, [traversalResult]); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, traversalPlan, traversalManifest)); + + foreach (var invalidProducerId in new[] + { + string.Empty, + "build\n", + "build\\nested", + new string('p', EvidenceGitChangeCapture.MaximumPathBytes), + }) + { + var invalidProducer = producer with { Id = invalidProducerId }; + var invalidPlan = fixture.Plan with + { + Profile = fixture.Plan.Profile with { Producers = [invalidProducer] }, + }; + var invalidResult = fixture.Manifest.ProducerResults.Single() with { ProducerId = invalidProducerId }; + var invalidManifest = ReplaceProducerResults(fixture.Manifest, [invalidResult]); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, invalidPlan, invalidManifest)); + } + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectArtifactMetadataChangedAfterValidationOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producerResult = fixture.Manifest.ProducerResults.Single(); + var artifact = producerResult.Artifacts!.Single(); + var invalidArtifacts = new[] + { + artifact with { LogicalName = "undeclared" }, + artifact with { RelativePath = "outside/build.txt" }, + }; + + foreach (var invalidArtifact in invalidArtifacts) + { + var manifest = fixture.Manifest with + { + ProducerResults = + [ + producerResult with + { + Artifacts = new ChangesAfterFirstEnumerationReadOnlyList( + [artifact], + [invalidArtifact]), + }, + ], + }; + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, manifest)); + } + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRecheckMetadataAfterInitialValidationOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producerResult = fixture.Manifest.ProducerResults.Single(); + var artifact = producerResult.Artifacts!.Single(); + var changedArtifacts = new[] + { + artifact with { LogicalName = "undeclared" }, + artifact with { MediaType = "application/json" }, + artifact with { LengthBytes = -1 }, + artifact with { RelativePath = "reports/../outside.txt" }, + }; + + foreach (var changedArtifact in changedArtifacts) + { + var manifest = fixture.Manifest with + { + ProducerResults = + [ + producerResult with + { + Artifacts = new ChangesAfterTwoEnumerationsReadOnlyList( + [artifact], + [changedArtifact]), + }, + ], + }; + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, manifest)); + } + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectSymlinkedProducerDirectoryOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producerRoot = Path.Join(fixture.ArtifactRoot, "build"); + Directory.Delete(producerRoot, recursive: true); + + var alternateProducerRoot = Path.Join(Path.GetDirectoryName(fixture.ArtifactRoot)!, "alternate-build"); + var alternateArtifactPath = Path.Join(alternateProducerRoot, "reports", "build.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(alternateArtifactPath)!); + await File.WriteAllTextAsync(alternateArtifactPath, "trusted artifact bytes"); + Directory.CreateSymbolicLink(producerRoot, alternateProducerRoot); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectSymlinkedArtifactParentDirectoryOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var expectedBytes = await File.ReadAllBytesAsync(fixture.ArtifactPath); + var alternateReportsRoot = TestPathUtils.PathUnder(Path.GetDirectoryName(fixture.ArtifactRoot)!, "alternate-reports"); + Directory.CreateDirectory(alternateReportsRoot); + var alternateArtifactPath = TestPathUtils.PathUnder(alternateReportsRoot, Path.GetFileName(fixture.ArtifactPath)); + await File.WriteAllBytesAsync(alternateArtifactPath, expectedBytes); + + var reportsRoot = Path.GetDirectoryName(fixture.ArtifactPath)!; + Directory.Delete(reportsRoot, recursive: true); + Directory.CreateSymbolicLink(reportsRoot, alternateReportsRoot); + + Assert.Equal(expectedBytes, await File.ReadAllBytesAsync(fixture.ArtifactPath)); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldAcceptProducerWithoutOptionalArtifactsOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(includeArtifact: false); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + Assert.Empty(fixture.Manifest.ProducerResults.Single().Artifacts!); + Assert.True(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectDuplicateResultsAndArtifactsOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producerResult = fixture.Manifest.ProducerResults.Single(); + var artifact = producerResult.Artifacts!.Single(); + + var duplicateProducerResults = ReplaceProducerResults(fixture.Manifest, [producerResult, producerResult]); + var missingProducerResult = ReplaceProducerResults(fixture.Manifest, []); + var duplicateArtifacts = ReplaceArtifacts(fixture.Manifest, [artifact, artifact]); + var unexpectedProducerResult = ReplaceProducerResults( + fixture.Manifest, + [producerResult, new EvidenceProducerResult("unexpected", EvidenceProducerOutcome.Passed, [])]); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, duplicateProducerResults)); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, missingProducerResult)); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, duplicateArtifacts)); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, unexpectedProducerResult)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectHardLinkedArtifactOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producer = fixture.Plan.Profile.Producers.Single(); + var secondSlot = new EvidenceArtifactSlot("report-copy", "reports", "text/plain", Required: false, MaximumBytes: 1024); + var plan = fixture.Plan with + { + Profile = fixture.Plan.Profile with + { + Producers = [producer with { ArtifactSlots = [.. producer.ArtifactSlots, secondSlot] }], + }, + }; + var linkedArtifactPath = Path.Join(Path.GetDirectoryName(fixture.ArtifactPath)!, "copy.txt"); + Assert.Equal(0, CreateHardLink(fixture.ArtifactPath, linkedArtifactPath)); + + var artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var linkedArtifact = artifact with { LogicalName = secondSlot.LogicalName, RelativePath = "reports/copy.txt" }; + var manifest = ReplaceArtifacts(fixture.Manifest, [artifact, linkedArtifact]); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, plan, manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldStopAtMaximumVerifiedFileCountOnLinux() + { + const int maximumFileCount = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount; + const int fileCountAboveLimit = maximumFileCount + 1; + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var slots = Enumerable.Range(0, fileCountAboveLimit) + .Select(index => new EvidenceArtifactSlot($"slot-{index:D2}", "reports", "text/plain", Required: false, MaximumBytes: 0)) + .ToArray(); + var targetedProfile = fixture.Policy.Profiles.Single(profile => profile.Id == "targeted"); + var producer = targetedProfile.Producers.Single() with { ArtifactSlots = slots }; + var updatedPolicy = fixture.Policy with + { + Profiles = fixture.Policy.Profiles + .Select(profile => profile.Id == targetedProfile.Id + ? profile with { Producers = [producer] } + : profile) + .ToArray(), + }; + var plan = new EvidencePlanner().ResolveForGate(updatedPolicy, fixture.Plan.ChangedPaths); + var producerRoot = Path.GetDirectoryName(Path.GetDirectoryName(fixture.ArtifactPath)!)!; + var writer = new EvidenceArtifactWriter(producer, producerRoot); + for (var index = 0; index < fileCountAboveLimit; index++) + { + await writer.WriteAsync(slots[index].LogicalName, $"reports/empty-{index:D2}.txt", ReadOnlyMemory.Empty); + } + + var artifacts = writer.WrittenArtifacts; + Assert.Equal(fileCountAboveLimit, producer.ArtifactSlots.Count); + Assert.Equal(fileCountAboveLimit, artifacts.Count); + Assert.True(EvidenceArtifactValidation.AreValid(producer, artifacts)); + var manifestAtLimit = EvidenceManifestBuilder.Build( + plan, + [new EvidenceProducerResult("build", EvidenceProducerOutcome.Passed, ["build/passed"], Artifacts: artifacts.Take(maximumFileCount).ToArray())]); + var manifestAboveLimit = EvidenceManifestBuilder.Build( + plan, + [new EvidenceProducerResult("build", EvidenceProducerOutcome.Passed, ["build/passed"], Artifacts: artifacts)]); + + if (!SupportsNoFollowVerifier) + { + return; + } + + Assert.True(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, plan, manifestAtLimit)); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, plan, manifestAboveLimit)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldFailClosedOutsideSupportedLinuxArchitectures() + { + if (SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldAcceptEmptyProfileWithoutArtifactFiles() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(documentationOnly: true); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + Assert.True(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldAcceptEmptyProfileWithFilesystemRootOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(documentationOnly: true); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + Assert.True(await verifier.VerifyArtifactsAsync( + Path.GetPathRoot(fixture.ArtifactRoot)!, + fixture.Plan, + fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectRegularFileAsTrustedRootOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var fileRoot = Path.Join(Path.GetDirectoryName(fixture.ArtifactRoot)!, "handoff-file"); + await File.WriteAllTextAsync(fileRoot, "not a directory"); + + Assert.False(await verifier.VerifyArtifactsAsync(fileRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectMissingTrustedRootOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var missingRoot = Path.Join(Path.GetDirectoryName(fixture.ArtifactRoot)!, "missing-handoff"); + + Assert.False(Directory.Exists(missingRoot)); + Assert.False(await verifier.VerifyArtifactsAsync(missingRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectMissingProducerDirectoryOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + var producerRoot = Path.Join(fixture.ArtifactRoot, "build"); + Directory.Delete(producerRoot, recursive: true); + + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldPropagateCancellation() + { + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => verifier.VerifyArtifactsAsync( + fixture.ArtifactRoot, + fixture.Plan, + fixture.Manifest, + cancellation.Token)); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldPropagateCancellationRaisedDuringVerificationOnLinux() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + using var cancellation = new CancellationTokenSource(); + var manifest = fixture.Manifest with + { + ProducerResults = new CancellingReadOnlyList( + fixture.Manifest.ProducerResults, + cancellation), + }; + + await Assert.ThrowsAnyAsync(() => verifier.VerifyArtifactsAsync( + fixture.ArtifactRoot, + fixture.Plan, + manifest, + cancellation.Token)); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectRecomputedManifestWithForgedArtifactHash() + { + if (!SupportsNoFollowVerifier) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + EvidenceArtifactResult artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var forgedManifest = ReplaceArtifact(fixture.Manifest, artifact with { Sha256 = new string('0', 64) }); + + var result = await fixture.VerifyAsync( + manifest: forgedManifest, + artifactVerifier: new EvidencePullRequestGateNoFollowArtifactVerifier()); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG010", result.Code); + Assert.NotNull(result.Summary); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + private static EvidenceManifest ReplaceArtifact(EvidenceManifest manifest, EvidenceArtifactResult replacement) + => ReplaceArtifacts(manifest, [replacement]); + + private static EvidenceManifest ReplaceArtifacts( + EvidenceManifest manifest, + IReadOnlyList replacements, + string producerId = "build") + { + var producerResults = manifest.ProducerResults + .Select(producer => producer.ProducerId == producerId ? producer with { Artifacts = replacements } : producer) + .ToArray(); + return ReplaceProducerResults(manifest, producerResults); + } + + private static EvidenceManifest ReplaceProducerResults( + EvidenceManifest manifest, + IReadOnlyList producerResults) + { + var updated = manifest with { ProducerResults = producerResults, ManifestDigest = string.Empty }; + return updated with { ManifestDigest = EvidenceDigest.CanonicalSha256(updated) }; + } + + [DllImport("libc", EntryPoint = "link", SetLastError = true)] + private static extern int CreateHardLink(string existingPath, string newPath); + + private static bool SupportsNoFollowVerifier => + OperatingSystem.IsLinux() && RuntimeInformation.ProcessArchitecture is Architecture.X64 or Architecture.Arm64; + + private sealed class FakeArtifactVerifier(bool result, Action? onVerify = null) : IEvidencePullRequestGateArtifactVerifier + { + public Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) + { + onVerify?.Invoke(); + return Task.FromResult(result); + } + } + + private sealed class ThrowingArtifactVerifier : IEvidencePullRequestGateArtifactVerifier + { + public Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) => throw new IOException("Artifact reader failed."); + } + + private sealed class FakeAuthorityProvider(EvidencePullRequestGateAuthoritySnapshot? snapshot) + : IEvidencePullRequestGateAuthorityProvider + { + public Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default) => Task.FromResult(snapshot); + } + + private sealed class ThrowingAuthorityProvider : IEvidencePullRequestGateAuthorityProvider + { + public Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default) => throw new IOException("Authority reader failed."); + } + + private sealed class CancellingArtifactVerifier(CancellationTokenSource cancellation) + : IEvidencePullRequestGateArtifactVerifier + { + public Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) + { + cancellation.Cancel(); + throw new OperationCanceledException(cancellationToken); + } + } + + private sealed class CancellingAuthorityProvider(CancellationTokenSource cancellation) + : IEvidencePullRequestGateAuthorityProvider + { + public Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default) + { + cancellation.Cancel(); + throw new OperationCanceledException(cancellationToken); + } + } + + private sealed class ThrowingReadOnlyList : IReadOnlyList + { + public int Count => 0; + + public T this[int index] => throw new InvalidOperationException("The untrusted collection cannot be indexed."); + + public IEnumerator GetEnumerator() => throw new InvalidOperationException("The untrusted collection cannot be enumerated."); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class ChangesAfterFirstEnumerationReadOnlyList( + IReadOnlyList firstEnumeration, + IReadOnlyList laterEnumerations) : IReadOnlyList + { + private int _enumerations; + + public int Count => firstEnumeration.Count; + + public T this[int index] => firstEnumeration[index]; + + public IEnumerator GetEnumerator() => + (Interlocked.Increment(ref _enumerations) == 1 ? firstEnumeration : laterEnumerations).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class ChangesAfterTwoEnumerationsReadOnlyList( + IReadOnlyList initialEnumerations, + IReadOnlyList laterEnumerations) : IReadOnlyList + { + private int _enumerations; + + public int Count => initialEnumerations.Count; + + public T this[int index] => initialEnumerations[index]; + + public IEnumerator GetEnumerator() => + (Interlocked.Increment(ref _enumerations) <= 2 ? initialEnumerations : laterEnumerations).GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class ThrowOnEnumerationReadOnlyList(IReadOnlyList items, int throwOnEnumeration) : IReadOnlyList + { + private int _enumerations; + + public int Count => items.Count; + + public T this[int index] => items[index]; + + public IEnumerator GetEnumerator() + { + if (Interlocked.Increment(ref _enumerations) == throwOnEnumeration) + { + throw new InvalidOperationException("Manifest enumeration failed."); + } + + return items.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class CancellingReadOnlyList(IReadOnlyList items, CancellationTokenSource cancellation) + : IReadOnlyList + { + public int Count => items.Count; + + public T this[int index] => items[index]; + + public IEnumerator GetEnumerator() + { + cancellation.Cancel(); + return items.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + private sealed class GateFixture : IAsyncDisposable + { + private readonly string _repositoryPath; + + private GateFixture( + string repositoryPath, + string artifactRoot, + string artifactPath, + EvidencePolicy policy, + EvidencePullRequestRunIdentity runIdentity, + EvidencePullRequestGateExpectedIdentity expectedIdentity, + EvidencePlan plan, + EvidenceManifest manifest, + EvidencePullRequestGateAuthoritySnapshot authority) + { + _repositoryPath = repositoryPath; + ArtifactRoot = artifactRoot; + ArtifactPath = artifactPath; + Policy = policy; + RunIdentity = runIdentity; + ExpectedIdentity = expectedIdentity; + Plan = plan; + Manifest = manifest; + Authority = authority; + } + + public string ArtifactRoot { get; } + + public string ArtifactPath { get; } + + public EvidencePolicy Policy { get; } + + public EvidencePullRequestRunIdentity RunIdentity { get; } + + public EvidencePullRequestGateExpectedIdentity ExpectedIdentity { get; } + + public EvidencePlan Plan { get; } + + public EvidenceManifest Manifest { get; } + + public EvidencePullRequestGateAuthoritySnapshot Authority { get; } + + public static async Task CreateAsync( + bool documentationOnly = false, + bool includeRequiredAssertion = true, + bool includeArtifact = true) + { + var repositoryPath = Path.Join(Path.GetTempPath(), $"appsurface-pr-gate-{Guid.NewGuid():N}"); + Directory.CreateDirectory(repositoryPath); + RunGit(repositoryPath, "init", "-q"); + var sourcePath = documentationOnly ? "docs/readme.md" : "src/project.cs"; + WriteFile(repositoryPath, sourcePath, "before\n"); + RunGit(repositoryPath, "add", sourcePath); + Commit(repositoryPath, "base"); + var baseRevision = RunGit(repositoryPath, "rev-parse", "HEAD").Trim(); + WriteFile(repositoryPath, sourcePath, "after\n"); + RunGit(repositoryPath, "add", sourcePath); + Commit(repositoryPath, "head"); + var headRevision = RunGit(repositoryPath, "rev-parse", "HEAD").Trim(); + + var targetProducer = new EvidenceProducerDeclaration( + "build", + "build", + "1", + [], + ["build/passed"], + [new EvidenceArtifactSlot("report", "reports", "text/plain", Required: false, MaximumBytes: 1024)], + TimeoutSeconds: 30); + var targeted = new EvidenceProfile( + "targeted", + EvidenceProfileScope.Targeted, + [], + [targetProducer], + [new EvidenceObligation("compile", "code", "Compile the changed source.", ["build"], "build/passed")]); + var docs = new EvidenceProfile("docs", EvidenceProfileScope.Targeted, [], [], []); + var policy = new EvidencePolicy( + "pr-gate", + "1", + "targeted", + [targeted, docs], + [new EvidencePolicyRule("source", "src/**", "targeted"), new EvidencePolicyRule("documentation", "docs/**", "docs")]); + + var runIdentity = new EvidencePullRequestRunIdentity(321, 321, 777, "main", 654321, 1); + var expectedIdentity = new EvidencePullRequestGateExpectedIdentity( + "forge-trust/AppSurface", + "pull_request_target", + "evidence-gate.yml", + "evidence-subject", + runIdentity); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repositoryPath, baseRevision, headRevision); + var planner = new EvidencePlanner(); + var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(planner, policy, snapshot, runIdentity); + + var artifactRoot = Path.Join(repositoryPath, "handoff"); + var producerArtifactRoot = Path.Join(artifactRoot, "build"); + Directory.CreateDirectory(producerArtifactRoot); + IReadOnlyList artifacts = []; + var artifactPath = Path.Join(producerArtifactRoot, "reports", "build.txt"); + if (includeArtifact) + { + var writer = new EvidenceArtifactWriter(targetProducer, producerArtifactRoot); + artifacts = [await writer.WriteAsync("report", "reports/build.txt", "trusted artifact bytes"u8.ToArray())]; + } + + var producerResult = new EvidenceProducerResult( + "build", + EvidenceProducerOutcome.Passed, + includeRequiredAssertion ? ["build/passed"] : [], + Artifacts: artifacts); + var manifest = EvidenceManifestBuilder.Build( + plan, + documentationOnly ? [] : [producerResult], + envelopeStatus: documentationOnly ? EvidenceEnvelopeStatus.NotRequired : EvidenceEnvelopeStatus.ValidatedNotAttested); + if (documentationOnly) + { + manifest = EvidenceManifestBuilder.Build(plan, []); + } + + var authority = new EvidencePullRequestGateAuthoritySnapshot( + expectedIdentity.Repository, + expectedIdentity.EventName, + baseRevision, + headRevision, + expectedIdentity.WorkflowId, + runIdentity, + expectedIdentity.SubjectJobId, + headRevision, + "success", + SubjectEnvelopeAttested: !documentationOnly); + return new GateFixture( + repositoryPath, + artifactRoot, + artifactPath, + policy, + runIdentity, + expectedIdentity, + plan, + manifest, + authority); + } + + public Task VerifyAsync( + EvidencePlan? plan = null, + EvidenceManifest? manifest = null, + EvidencePolicy? policy = null, + EvidencePullRequestGateExpectedIdentity? expectedIdentity = null, + EvidencePullRequestGateAuthoritySnapshot? authority = null, + IEvidencePullRequestGateAuthorityProvider? authorityProvider = null, + IEvidencePullRequestGateArtifactVerifier? artifactVerifier = null, + string? trustedArtifactHandoffRootPath = null, + bool omitArtifactRoot = false, + bool useFakeArtifactVerifier = true, + CancellationToken cancellationToken = default) + { + var planner = new EvidencePlanner(); + return EvidencePullRequestGateVerifier.VerifyAsync( + planner, + policy ?? Policy, + _repositoryPath, + expectedIdentity ?? ExpectedIdentity, + authorityProvider ?? new FakeAuthorityProvider(authority ?? Authority), + omitArtifactRoot ? null : trustedArtifactHandoffRootPath ?? ArtifactRoot, + artifactVerifier ?? (useFakeArtifactVerifier ? new FakeArtifactVerifier(true) : null), + plan ?? Plan, + manifest ?? Manifest, + cancellationToken); + } + + public async Task ResolvePlanAsync(EvidencePolicy policy) + { + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(_repositoryPath, Plan.BaseRevision!, Plan.HeadRevision!); + return EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot, RunIdentity); + } + + public ValueTask DisposeAsync() + { + Directory.Delete(_repositoryPath, recursive: true); + return ValueTask.CompletedTask; + } + + private static void WriteFile(string root, string relativePath, string contents) + { + var path = TestPathUtils.PathUnder(root, relativePath.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, contents); + } + + private static void Commit(string repository, string message) => RunGit( + repository, + "-c", "user.name=AppSurface Test", + "-c", "user.email=appsurface@example.invalid", + "commit", "-qm", message); + + private static string RunGit(string repository, params string[] arguments) + { + var start = new ProcessStartInfo("git") + { + WorkingDirectory = repository, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.True(process.ExitCode == 0, $"Git fixture command failed: {error}"); + return output; + } + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceRevisionPlanBuilderTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceRevisionPlanBuilderTests.cs new file mode 100644 index 000000000..11a949c03 --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceRevisionPlanBuilderTests.cs @@ -0,0 +1,50 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidenceRevisionPlanBuilderTests +{ + [Fact] + public async Task VerifyAsync_ShouldRejectPlansWithoutRevisionBoundV2FieldsBeforeReadingGit() + { + var planner = new EvidencePlanner(); + var policy = new EvidencePolicy( + "gate", + "1", + "targeted", + [new EvidenceProfile("targeted", EvidenceProfileScope.Targeted, [], [], [])], + []); + var plans = new[] + { + CreatePlan(contractVersion: "1.0"), + CreatePlan(baseRevision: null), + CreatePlan(headRevision: null), + }; + + foreach (var plan in plans) + { + var exception = await Assert.ThrowsAsync(() => + EvidenceRevisionPlanBuilder.VerifyAsync(planner, policy, string.Empty, plan)); + + Assert.Equal("ASEVD139", exception.Code); + Assert.Contains("not revision-bound v2 evidence", exception.Message, StringComparison.Ordinal); + } + } + + private static EvidencePlan CreatePlan( + string contractVersion = "2.0", + string? baseRevision = "base", + string? headRevision = "head") => + new( + ContractVersion: contractVersion, + PolicyId: "gate", + PolicyDigest: new string('a', 64), + DiffDigest: new string('b', 64), + Profile: new EvidenceProfile("targeted", EvidenceProfileScope.Targeted, [], [], []), + ChangedPaths: [new NormalizedDiffPath("src/Feature.cs")], + MatchedRuleIds: [], + PlanDigest: new string('c', 64), + BaseRevision: baseRevision, + HeadRevision: headRevision); +} diff --git a/Cli/ForgeTrust.AppSurface.Cli/CoverageRunArtifactReader.cs b/Cli/ForgeTrust.AppSurface.Cli/CoverageRunArtifactReader.cs index 8e453f010..885e36239 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/CoverageRunArtifactReader.cs +++ b/Cli/ForgeTrust.AppSurface.Cli/CoverageRunArtifactReader.cs @@ -473,10 +473,14 @@ private static bool IsPathWithin(string root, string path, StringComparison comp private static int UnixOpenCloseOnExec => OperatingSystem.IsMacOS() ? 0x01000000 : 0x00080000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] - private static int UnixOpenDirectory => OperatingSystem.IsMacOS() ? 0x00100000 : 0x00010000; + private static int UnixOpenDirectory => OperatingSystem.IsMacOS() ? 0x00100000 + : RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? 0x00004000 + : 0x00010000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] - private static int UnixOpenNoFollow => OperatingSystem.IsMacOS() ? 0x00000100 : 0x00020000; + private static int UnixOpenNoFollow => OperatingSystem.IsMacOS() ? 0x00000100 + : RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? 0x00008000 + : 0x00020000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] private static int UnixOpenNonBlocking => OperatingSystem.IsMacOS() ? 0x00000004 : 0x00000800; diff --git a/Cli/ForgeTrust.AppSurface.Cli/CoverageRunOutputLease.cs b/Cli/ForgeTrust.AppSurface.Cli/CoverageRunOutputLease.cs index ff3777774..bcaf0ffa2 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/CoverageRunOutputLease.cs +++ b/Cli/ForgeTrust.AppSurface.Cli/CoverageRunOutputLease.cs @@ -1393,10 +1393,14 @@ private static IOException NativeIOException(string message) private static int UnixCloseOnExec => OperatingSystem.IsMacOS() ? 0x01000000 : 0x00080000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] - private static int UnixDirectory => OperatingSystem.IsMacOS() ? 0x00100000 : 0x00010000; + private static int UnixDirectory => OperatingSystem.IsMacOS() ? 0x00100000 + : RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? 0x00004000 + : 0x00010000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] - private static int UnixNoFollow => OperatingSystem.IsMacOS() ? 0x00000100 : 0x00020000; + private static int UnixNoFollow => OperatingSystem.IsMacOS() ? 0x00000100 + : RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? 0x00008000 + : 0x00020000; [ExcludeFromCodeCoverage(Justification = "The platform security lanes exercise the OS-specific native flag values.")] private static int UnixNonBlocking => OperatingSystem.IsMacOS() ? 0x00000004 : 0x00000800; diff --git a/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs b/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs index 6f82428da..c0c0be2a8 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs +++ b/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs @@ -188,12 +188,19 @@ public override async ValueTask ExecuteAsync(IConsole console) } } - var manifest = EvidenceManifestBuilder.Build(plan, results, ObservationOnly, resourceResults: resourceResults); + // The built-in CLI does not authenticate CI job provenance or isolate head-controlled execution. + // A revision-bound local run is useful evidence to inspect, but only the trusted host may promote it. + var manifest = EvidenceManifestBuilder.Build( + plan, + results, + ObservationOnly || string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal), + resourceResults: resourceResults); await Workflow.WriteManifestAsync(manifest, OutputDirectory, cancellationToken); await console.Output.WriteLineAsync(EvidenceCliWorkflow.FormatSummary(manifest)); await console.Output.WriteLineAsync($"Artifacts: {Path.Join(OutputDirectory, "evidence-plan.json")}, {Path.Join(OutputDirectory, "evidence-manifest.json")}, {Path.Join(OutputDirectory, "evidence-summary.json")}"); await WriteGitHubSummaryAsync(manifest, cancellationToken); - if (manifest.ClaimKind == EvidenceClaimKind.None) + if (manifest.ClaimKind == EvidenceClaimKind.None + || (GateMode && manifest.ClaimKind == EvidenceClaimKind.ObservationOnly)) { throw new CommandException("ASEVD211: Evidence is incomplete. Inspect evidence-summary.json and the producer output before allowing a gate to proceed."); } @@ -252,6 +259,14 @@ internal sealed partial class EvidenceVerifyCommand(EvidenceCliWorkflow workflow [CommandOption("plan", Description = "Generated evidence-plan.json path. Defaults next to the manifest.")] public string? PlanPath { get; set; } + /// Gets or sets the trusted base-owned policy required for v2 verification. + [CommandOption("policy", Description = "Trusted base-owned policy path required for revision-bound v2 verification.")] + public string? PolicyPath { get; set; } + + /// Gets or sets the trusted Git object store required for v2 verification. + [CommandOption("repository", Description = "Trusted Git object store containing both exact commits for v2 verification.")] + public string? RepositoryPath { get; set; } + /// public async ValueTask ExecuteAsync(IConsole console) { @@ -265,7 +280,7 @@ public async ValueTask ExecuteAsync(IConsole console) var planPath = string.IsNullOrWhiteSpace(PlanPath) ? Path.Join(Path.GetDirectoryName(Path.GetFullPath(ManifestPath))!, "evidence-plan.json") : PlanPath; - var (_, manifest) = await _workflow.VerifyAsync(planPath, ManifestPath, console.RegisterCancellationHandler()); + var (_, manifest) = await _workflow.VerifyAsync(planPath, ManifestPath, console.RegisterCancellationHandler(), PolicyPath, RepositoryPath); await console.Output.WriteLineAsync($"Evidence manifest verified: {manifest.ClaimKind} ({manifest.Eligibility})"); } catch (EvidenceCliException exception) @@ -303,5 +318,25 @@ internal abstract partial class EvidencePlanningCommandBase(EvidenceCliWorkflow /// /// Creates the explicit policy-and-diff input consumed by a planning operation. /// - protected EvidencePlanningRequest CreatePlanningRequest() => new(PolicyPath, Paths, DiffFile); + protected EvidencePlanningRequest CreatePlanningRequest() => new(PolicyPath, Paths, DiffFile, BaseRevision, HeadRevision, RepositoryPath, GateMode, PullRequestRunIdentityFile); + + /// Gets or sets the complete base commit ID for revision-bound planning. + [CommandOption("base-revision", Description = "Complete base Git commit ID. Requires --head-revision and --diff-file.")] + public string? BaseRevision { get; set; } + + /// Gets or sets the complete head commit ID for revision-bound planning. + [CommandOption("head-revision", Description = "Complete head Git commit ID. Requires --base-revision and --diff-file.")] + public string? HeadRevision { get; set; } + + /// Gets or sets the trusted Git object-store directory containing both exact commits. + [CommandOption("repository", Description = "Git object-store directory for revision capture. Defaults to the current directory.")] + public string? RepositoryPath { get; set; } + + /// Gets or sets whether path-only local planning must be rejected. + [CommandOption("gate-mode", Description = "Require revision-bound inputs; local path-only evidence is never gate eligible.")] + public bool GateMode { get; set; } + + /// Gets or sets the trusted controller's canonical PR/run identity JSON path. + [CommandOption("pr-run-identity", Description = "Canonical controller-captured PR/run identity JSON for a revision-bound CI plan.")] + public string? PullRequestRunIdentityFile { get; set; } } diff --git a/Cli/ForgeTrust.AppSurface.Cli/EvidencePolicyShadowCommand.cs b/Cli/ForgeTrust.AppSurface.Cli/EvidencePolicyShadowCommand.cs new file mode 100644 index 000000000..1b824e44b --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli/EvidencePolicyShadowCommand.cs @@ -0,0 +1,339 @@ +using System.Security; +using System.Text.Json; +using System.Text.Json.Serialization; +using CliFx; +using CliFx.Binding; +using CliFx.Infrastructure; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.Cli; + +/// +/// Compares protected-base policy and fixture inputs with candidate inputs without creating an Evidence claim. +/// +/// +/// Every input is read under a fixed byte limit and deserialized with the Evidence contract serializer. A missing +/// candidate fixture file is treated as an empty candidate set, while a missing base fixture file is an error. The +/// result is written to a new JSON file and is always marked claimEligible=false. +/// +[Command("evidence shadow-policy", Description = "Compare base and candidate evidence policies without making a claim.")] +internal sealed partial class EvidencePolicyShadowCommand : ICommand +{ + private const int MaximumInputBytes = 1_048_576; + private const int MaximumOutputBytes = 1_048_576; + private const string OutputFileName = "evidence-policy-shadow.json"; + + private static readonly JsonSerializerOptions OutputJsonOptions = new(JsonSerializerDefaults.Web) + { + WriteIndented = true, + Converters = { new JsonStringEnumConverter() }, + }; + + /// Gets or sets the policy from the protected base checkout. + [CommandOption("base-policy", Description = "Evidence policy loaded from the protected base checkout.")] + public string BasePolicyPath { get; set; } = string.Empty; + + /// Gets or sets the candidate policy under review. + [CommandOption("candidate-policy", Description = "Candidate Evidence policy JSON path.")] + public string CandidatePolicyPath { get; set; } = string.Empty; + + /// Gets or sets the base-owned fixture set from the protected base checkout. + [CommandOption("base-fixtures", Description = "Fixture array loaded from the protected base checkout.")] + public string BaseFixturesPath { get; set; } = string.Empty; + + /// Gets or sets the candidate fixture set; a specified but missing file means an empty candidate set. + [CommandOption("candidate-fixtures", Description = "Candidate fixture array path; a missing file is treated as empty.")] + public string CandidateFixturesPath { get; set; } = string.Empty; + + /// Gets or sets a new JSON file path or an output directory. + [CommandOption("output", Description = "New JSON file path or directory for the bounded shadow result.")] + public string OutputPath { get; set; } = string.Empty; + + /// + public async ValueTask ExecuteAsync(IConsole console) + { + ArgumentNullException.ThrowIfNull(console); + var cancellationToken = console.RegisterCancellationHandler(); + EvidencePolicyShadowResult result; + try + { + result = await CompareAsync(cancellationToken); + } + catch (ShadowInputException exception) + { + result = CreateFailureResult(exception.Code, exception.FixtureSource, exception.Message); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NullReferenceException) + { + result = CreateFailureResult( + "ASEPSCLI004", + EvidencePolicyShadowFixtureSource.Candidate, + "Policy-shadow input could not be validated; no comparison was performed."); + } + + byte[] outputBytes; + try + { + outputBytes = SerializeBounded(result); + } + catch (ShadowResultTooLargeException) + { + result = CreateFailureResult( + "ASEPSCLI005", + EvidencePolicyShadowFixtureSource.Candidate, + $"The shadow result exceeds the {MaximumOutputBytes}-byte output limit; the full result was omitted."); + outputBytes = SerializeBounded(result); + } + + try + { + await WriteNewOutputAsync(OutputPath, outputBytes, cancellationToken); + } + catch (Exception exception) when (exception is IOException + or UnauthorizedAccessException + or ArgumentException + or NotSupportedException + or SecurityException) + { + throw new CommandException("ASEPSCLI006: The bounded shadow result could not be written to a new output target."); + } + + if (!result.IsCompatible) + { + var codes = result.Diagnostics + .Select(static diagnostic => diagnostic.Code) + .Distinct(StringComparer.Ordinal) + .OrderBy(static code => code, StringComparer.Ordinal); + var codeList = string.Join(", ", codes); + throw new CommandException( + $"ASEPSCLI010: Evidence policy shadow is incompatible; claimEligible=false; diagnostics={codeList}. Inspect the bounded JSON result."); + } + + await console.Output.WriteLineAsync( + $"Evidence policy shadow compatible: {result.Selections.Count} selections; claimEligible=false."); + } + + private async Task CompareAsync(CancellationToken cancellationToken) + { + var basePolicyBytes = await ReadBoundedInputAsync( + BasePolicyPath, + "--base-policy", + EvidencePolicyShadowFixtureSource.Base, + allowMissing: false, + cancellationToken); + var candidatePolicyBytes = await ReadBoundedInputAsync( + CandidatePolicyPath, + "--candidate-policy", + EvidencePolicyShadowFixtureSource.Candidate, + allowMissing: false, + cancellationToken); + var baseFixtureBytes = await ReadBoundedInputAsync( + BaseFixturesPath, + "--base-fixtures", + EvidencePolicyShadowFixtureSource.Base, + allowMissing: false, + cancellationToken); + var candidateFixtureBytes = await ReadBoundedInputAsync( + CandidateFixturesPath, + "--candidate-fixtures", + EvidencePolicyShadowFixtureSource.Candidate, + allowMissing: true, + cancellationToken); + + var basePolicy = DeserializeInput( + basePolicyBytes!, + "--base-policy", + EvidencePolicyShadowFixtureSource.Base); + var candidatePolicy = DeserializeInput( + candidatePolicyBytes!, + "--candidate-policy", + EvidencePolicyShadowFixtureSource.Candidate); + var baseFixtures = DeserializeInput( + baseFixtureBytes!, + "--base-fixtures", + EvidencePolicyShadowFixtureSource.Base); + EvidencePolicyShadowFixture[] candidateFixtures = candidateFixtureBytes is null + ? [] + : DeserializeInput( + candidateFixtureBytes, + "--candidate-fixtures", + EvidencePolicyShadowFixtureSource.Candidate); + + return EvidencePolicyShadowValidator.Validate(basePolicy, candidatePolicy, baseFixtures, candidateFixtures); + } + + private static async Task ReadBoundedInputAsync( + string path, + string optionName, + EvidencePolicyShadowFixtureSource source, + bool allowMissing, + CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(path)) + { + throw new ShadowInputException( + "ASEPSCLI001", + source, + $"{optionName} must name an input file; no comparison was performed."); + } + + try + { + await using var input = new FileStream( + Path.GetFullPath(path), + FileMode.Open, + FileAccess.Read, + FileShare.Read, + bufferSize: 16 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan); + if (input.Length > MaximumInputBytes) + { + throw new ShadowInputException( + "ASEPSCLI003", + source, + $"{optionName} exceeds the {MaximumInputBytes}-byte input limit; no comparison was performed."); + } + + using var buffer = new MemoryStream((int)Math.Min(input.Length, MaximumInputBytes)); + var chunk = new byte[16 * 1024]; + while (true) + { + var count = await input.ReadAsync(chunk.AsMemory(), cancellationToken); + if (count == 0) + { + break; + } + + if (buffer.Length + count > MaximumInputBytes) + { + throw new ShadowInputException( + "ASEPSCLI003", + source, + $"{optionName} exceeds the {MaximumInputBytes}-byte input limit; no comparison was performed."); + } + + await buffer.WriteAsync(chunk.AsMemory(0, count), cancellationToken); + } + + return buffer.ToArray(); + } + catch (FileNotFoundException) when (allowMissing) + { + return null; + } + catch (DirectoryNotFoundException) when (allowMissing) + { + return null; + } + catch (ShadowInputException) + { + throw; + } + catch (Exception exception) when (exception is IOException + or UnauthorizedAccessException + or ArgumentException + or NotSupportedException + or SecurityException) + { + throw new ShadowInputException( + "ASEPSCLI001", + source, + $"{optionName} could not be read; no comparison was performed."); + } + } + + private static TValue DeserializeInput( + byte[] bytes, + string optionName, + EvidencePolicyShadowFixtureSource source) + { + try + { + return EvidenceCanonicalJson.Deserialize(bytes); + } + catch (Exception exception) when (exception is JsonException + or InvalidOperationException + or NotSupportedException + or ArgumentException) + { + throw new ShadowInputException( + "ASEPSCLI002", + source, + $"{optionName} is malformed Evidence JSON; no comparison was performed."); + } + } + + private static EvidencePolicyShadowResult CreateFailureResult( + string code, + EvidencePolicyShadowFixtureSource source, + string message) => + new( + IsCompatible: false, + Selections: [], + Diagnostics: [new EvidencePolicyShadowDiagnostic(code, source, null, null, null, message)], + DiagnosticsTruncated: false); + + private static byte[] SerializeBounded(EvidencePolicyShadowResult result) + { + var contents = JsonSerializer.SerializeToUtf8Bytes(new ShadowOutput(false, result), OutputJsonOptions); + if (contents.Length > MaximumOutputBytes) + { + throw new ShadowResultTooLargeException(); + } + + return contents; + } + + private static async Task WriteNewOutputAsync( + string outputPath, + byte[] contents, + CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(outputPath)) + { + throw new ArgumentException("The output target is required.", nameof(outputPath)); + } + + var fullPath = Path.GetFullPath(outputPath); + var resultPath = Directory.Exists(fullPath) + ? Path.Join(fullPath, OutputFileName) + : string.Equals(Path.GetExtension(fullPath), ".json", StringComparison.OrdinalIgnoreCase) + ? fullPath + : Path.Join(fullPath, OutputFileName); + var outputDirectory = Path.GetDirectoryName(resultPath); + if (string.IsNullOrWhiteSpace(outputDirectory)) + { + throw new ArgumentException("The output target has no parent directory.", nameof(outputPath)); + } + + Directory.CreateDirectory(outputDirectory); + await using var output = new FileStream( + resultPath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + bufferSize: 16 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan); + await output.WriteAsync(contents.AsMemory(), cancellationToken); + await output.FlushAsync(cancellationToken); + } + + private sealed record ShadowOutput(bool ClaimEligible, EvidencePolicyShadowResult Result); + + private sealed class ShadowInputException( + string code, + EvidencePolicyShadowFixtureSource fixtureSource, + string message) + : Exception(message) + { + public string Code { get; } = code; + + public EvidencePolicyShadowFixtureSource FixtureSource { get; } = fixtureSource; + } + + private sealed class ShadowResultTooLargeException : Exception + { + } + +} diff --git a/Cli/ForgeTrust.AppSurface.Cli/README.md b/Cli/ForgeTrust.AppSurface.Cli/README.md index 57900acd2..57fc1daf8 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/README.md +++ b/Cli/ForgeTrust.AppSurface.Cli/README.md @@ -627,10 +627,29 @@ appsurface evidence verify ./TestResults/evidence/evidence-manifest.json `init --sample` is safe to run in an existing repository: it creates a marked policy, host skeleton, and README and refuses to overwrite unmarked files. `doctor` does not start tests or resources; it reports whether the selected policy needs Docker, a browser runtime, or a protected release envelope. `explain` writes `evidence-plan.json` and a concise human summary before any producer runs. `run` writes the plan, `evidence-manifest.json`, and `evidence-summary.json`; it also appends a short claim summary to `$GITHUB_STEP_SUMMARY` when that CI-provided path exists. `verify` validates plan/manifest digest binding without rerunning producers. +For revision-bound PR planning, pass the complete `--base-revision`, complete `--head-revision`, and byte-exact `--diff-file` together. `--repository` identifies the Git object store (default: current directory for planning), and `--gate-mode` rejects path-only input. A trusted controller may also pass `--pr-run-identity` pointing at canonical JSON with numeric `repositoryId`, `headRepositoryId`, `pullRequestNumber`, `workflowRunId`, `workflowRunAttempt`, and a bounded `targetBranch`; partial or local-only input cannot use it. The [cookbook](../../guides/evidencehost-cookbook.md#revision-bound-pr-rehearsal) supplies the exact diff command and a complete `explain`/`run`/`verify` rehearsal. Version-2 plans bind the source diff and NUL status digests separately from the normalized path digest. `verify` requires `--policy` from a separately trusted base checkout and `--repository` for v2, then regenerates the plan from those inputs. The CLI still cannot authenticate GitHub PR freshness or job provenance: its v2 `run` is `ObservationOnly`, and `--gate-mode` exits nonzero for it. Version-1 path and diff commands remain local compatibility paths and cannot authorize the new required check. + The built-in producer reuses the private [`ForgeTrust.AppSurface.Evidence.Coverage`](../../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md) engine used by `coverage run` and `coverage gate`; it writes the normal gate and patch-target artifacts beside its coverage output. When a policy requires patch thresholds, `evidence run` measures the same bounded `--diff-file` snapshot used to plan the selected profile, rather than reopening that path after execution starts. Browser E2E and resource-backed evidence belong in the separate consumer-owned [`ForgeTrust.AppSurface.Evidence.Aspire`](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/README.md) lifecycle. An explicit policy-selected empty profile may claim `NoEvidenceRequired`; unavailable capability, filtered required tests, a failed producer, a missing assertion, an unready declared resource, or a failed declared coverage threshold produces `ClaimKind.None` and command failure. `--observation-only` records a diagnostic claim that is deliberately ineligible for a PR or release gate. The v1 workflow has no outbound telemetry, no automatic assembly/test discovery, no Docker sandbox, no independent artifact attestation, and no semantic classifier that silently labels arbitrary getters or constructors low value. Keep generated-code exclusions and the coverage thresholds in the reviewed Evidence policy explicit. See the [EvidenceHost cookbook](../../guides/evidencehost-cookbook.md) for policy, E2E, release-envelope, and incomplete-profile patterns. +#### `appsurface evidence shadow-policy` + +Use `shadow-policy` to compare a proposed policy with the protected base policy and its base-owned fixture set before proposing a policy change. The [planner policy-shadow documentation](../../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md) describes the comparison and its bounded diagnostics. + +```bash +appsurface evidence shadow-policy \ + --base-policy ../protected-base/.appsurface/evidence/evidence.policy.json \ + --candidate-policy .appsurface/evidence/evidence.policy.json \ + --base-fixtures ../protected-base/docs/fixtures/issue-777-policy-shadow/fixtures.json \ + --candidate-fixtures ./docs/fixtures/issue-777-policy-shadow/fixtures.json \ + --output ./TestResults/evidence-policy-shadow +``` + +All four input flags and the output flag are explicit. Each input and the serialized result are limited to 1 MiB; inputs are parsed with the Evidence contract serializer. Fixture inputs are JSON arrays of `EvidencePolicyShadowFixture` records; the camelCase form is `[{"id":"ordinary-code","kind":"Code","changedPath":{"path":"src/Feature.cs","kind":"modified","previousPath":null}}]`. A specified but missing candidate fixture file means an empty candidate set, so base-owned deletions are reported. A missing base fixture file, malformed input, or oversized input fails closed. The output directory receives a new `evidence-policy-shadow.json`; a `--output` path ending in `.json` selects a new file directly. Existing result files are never overwritten. + +The JSON result always sets `claimEligible` to `false` and contains no Evidence manifest claim. A compatible comparison exits zero; any validator finding or input failure exits nonzero. Human diagnostics report stable codes and do not echo candidate-controlled IDs, paths, policy text, or exception details. The caller must source both base inputs from the protected base checkout. This CLI cannot authenticate input provenance, select a trusted revision, authorize a gate, or establish Evidence claim authority; a protected workflow must independently enforce any result it chooses to use. + ### `appsurface coverage run` Run instrumented .NET test projects and merge private Cobertura artifacts. diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs index d161e8e06..342b24e4c 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs @@ -144,6 +144,42 @@ internal async Task ResolveAsync(EvidencePlanningReq ArgumentNullException.ThrowIfNull(request); cancellationToken.ThrowIfCancellationRequested(); var policy = await ReadPolicyAsync(request.PolicyPath, cancellationToken).ConfigureAwait(false); + var revisionRequested = request.BaseRevision is not null || request.HeadRevision is not null; + if (request.PullRequestRunIdentityFile is not null && !revisionRequested) + { + throw new EvidenceCliException("ASEVD233", "PR/run identity requires revision-bound planning.", "Supply complete --base-revision and --head-revision with the exact --diff-file."); + } + + if (revisionRequested) + { + if (request.BaseRevision is null || request.HeadRevision is null || request.DiffFile is null || request.Paths.Count != 0) + { + throw new EvidenceCliException("ASEVD230", "Revision-bound planning requires --base-revision, --head-revision and --diff-file, without --path.", "Supply complete Git commit IDs and a byte-exact diff captured from that pair."); + } + + var captured = await EvidenceGitChangeCapture.CaptureAsync( + request.RepositoryPath ?? Directory.GetCurrentDirectory(), + request.BaseRevision, + request.HeadRevision, + cancellationToken).ConfigureAwait(false); + var supplied = await ReadDiffSnapshotAsync(request.DiffFile, cancellationToken).ConfigureAwait(false); + if (!captured.SourceDiff.Span.SequenceEqual(supplied.Bytes.Span)) + { + throw new EvidenceCliException("ASEVD231", "The supplied diff bytes do not match the exact Git commit pair.", "Regenerate --diff-file from the complete --base-revision and --head-revision using the documented fixed Git options."); + } + + var runIdentity = request.PullRequestRunIdentityFile is null + ? null + : await ReadCanonicalAsync(request.PullRequestRunIdentityFile, cancellationToken).ConfigureAwait(false); + var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(_planner, policy, captured, runIdentity); + return new EvidencePlanningResolution(plan, supplied); + } + + if (request.GateMode) + { + throw new EvidenceCliException("ASEVD230", "Gate mode requires revision-bound planning.", "Supply --base-revision, --head-revision and --diff-file; path-only local plans cannot authorize a gate."); + } + var inputs = await ReadPathsAndSnapshotAsync(request, cancellationToken).ConfigureAwait(false); return new EvidencePlanningResolution(_planner.Resolve(policy, inputs.Paths), inputs.Snapshot); } @@ -190,7 +226,9 @@ await File.WriteAllTextAsync( public async Task<(EvidencePlan Plan, EvidenceManifest Manifest)> VerifyAsync( string planPath, string manifestPath, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + string? trustedPolicyPath = null, + string? repositoryPath = null) { var plan = await ReadCanonicalAsync(planPath, cancellationToken).ConfigureAwait(false); var manifest = await ReadCanonicalAsync(manifestPath, cancellationToken).ConfigureAwait(false); @@ -205,7 +243,22 @@ await File.WriteAllTextAsync( EvidencePlan resolvedPlan; try { - resolvedPlan = _planner.Resolve(plan.PolicySnapshot, plan.ChangedPaths); + if (string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal)) + { + if (trustedPolicyPath is null || repositoryPath is null) + { + throw new EvidenceCliException("ASEVD232", "Revision-bound verification requires a trusted policy and Git object store.", "Pass --policy from the trusted base and --repository containing both exact commits."); + } + + var trustedPolicy = await ReadPolicyAsync(trustedPolicyPath, cancellationToken).ConfigureAwait(false); + await EvidenceRevisionPlanBuilder.VerifyAsync( + _planner, trustedPolicy, repositoryPath, plan, cancellationToken).ConfigureAwait(false); + resolvedPlan = plan; + } + else + { + resolvedPlan = _planner.Resolve(plan.PolicySnapshot, plan.ChangedPaths); + } } catch (EvidencePlanningException exception) { @@ -236,13 +289,31 @@ public static string FormatSummary(EvidencePlan plan) return string.Join( Environment.NewLine, $"Evidence plan: {plan.Profile.Id} ({plan.Profile.Scope.ToString().ToLowerInvariant()})", + $"Plan digest: {plan.PlanDigest}", + string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + ? $"Revisions: {plan.BaseRevision![..12]}..{plan.HeadRevision![..12]} (source diff {plan.SourceDiffDigest})" + : "Revisions: local v1 input (not a CI gate authorization)", $"Why: {string.Join(", ", plan.MatchedRuleIds)}", - $"Changed paths: {string.Join(", ", plan.ChangedPaths.Select(static path => path.Path))}", + $"Changed paths ({plan.ChangedPaths.Count}): {FormatChangedPaths(plan.ChangedPaths)}", $"Obligations: {obligations}", $"Required producers: {FormatIds(plan.Profile.Producers.Select(static producer => producer.Id))}", $"Required resources: {FormatIds(plan.Profile.Resources.Select(static resource => resource.Id))}"); } + private static string FormatChangedPaths(IReadOnlyList paths) + { + const int maximumDisplayedPaths = 12; + const int maximumPathCharacters = 100; + var displayed = paths.Take(maximumDisplayedPaths) + .Select(path => path.Path.Length <= maximumPathCharacters + ? path.Path + : string.Concat(path.Path.AsSpan(0, maximumPathCharacters), "…")); + var result = string.Join(", ", displayed); + return paths.Count > maximumDisplayedPaths + ? $"{result}, … (+{paths.Count - maximumDisplayedPaths} more)" + : result; + } + /// /// Formats a deterministic, human-readable summary of an evidence claim and any remaining obligations. /// @@ -387,19 +458,45 @@ private static async Task WriteCanonicalAsync(string path, TValue value, private static async Task ReadCanonicalAsync(string path, CancellationToken cancellationToken) { - if (!File.Exists(path)) - { - throw new EvidenceCliException("ASEVD208", $"Evidence file '{path}' does not exist.", "Pass paths from the same generated evidence output directory."); - } - try { - return EvidenceCanonicalJson.Deserialize(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)); + const int maximumEvidenceBytes = 4 * 1024 * 1024; + await using var source = File.OpenRead(path); + await using var captured = new MemoryStream(); + var buffer = new byte[80 * 1024]; + while (true) + { + var count = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + if (count == 0) + { + break; + } + + if (captured.Length + count > maximumEvidenceBytes) + { + throw new EvidenceCliException("ASEVD209", "Evidence JSON exceeds the 4 MiB verification limit.", "Keep plans and manifests bounded; do not embed raw test output."); + } + + await captured.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + } + + var bytes = captured.ToArray(); + var value = EvidenceCanonicalJson.Deserialize(bytes); + if (!EvidenceCanonicalJson.Serialize(value).AsSpan().SequenceEqual(bytes)) + { + throw new EvidenceCliException("ASEVD209", "Evidence JSON is not canonical.", "Use unedited evidence-plan.json and evidence-manifest.json generated by AppSurface."); + } + + return value; } catch (JsonException exception) { throw new EvidenceCliException("ASEVD209", $"Evidence file '{path}' is not valid JSON: {exception.Message}", "Regenerate evidence instead of editing the output."); } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new EvidenceCliException("ASEVD208", $"Evidence file '{path}' could not be read.", "Pass readable plan and manifest files from the same generated evidence output directory."); + } } private static bool ContainsGeneratedMarker(string path) => File.ReadAllText(path).Contains(GeneratedMarker, StringComparison.Ordinal); @@ -517,7 +614,15 @@ An incomplete profile is not complete evidence. Keep normal AppHost composition /// /// Describes a policy and explicit changed-path input for an EvidenceHost planning operation. /// -internal sealed record EvidencePlanningRequest(string PolicyPath, IReadOnlyList Paths, string? DiffFile); +internal sealed record EvidencePlanningRequest( + string PolicyPath, + IReadOnlyList Paths, + string? DiffFile, + string? BaseRevision = null, + string? HeadRevision = null, + string? RepositoryPath = null, + bool GateMode = false, + string? PullRequestRunIdentityFile = null); /// /// Binds a resolved plan to the immutable diff bytes used to derive its changed paths. diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md index 908b2f93f..8d49ea7e1 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md @@ -2,7 +2,7 @@ `ForgeTrust.AppSurface.Evidence.Cli` supplies the internal workflow used by the public `appsurface evidence` commands. Most adopters install the [AppSurface CLI](../../Cli/ForgeTrust.AppSurface.Cli/README.md), not this package directly. -Start with the [EvidenceHost guide](../../start-here/evidencehost.md). The workflow reads only explicit policy and diff inputs; it does not scan consumer assemblies, discover tests, provision third-party services, or report outbound usage telemetry. +Start with the [EvidenceHost guide](../../start-here/evidencehost.md). The workflow reads explicit policy and diff inputs; revision-bound mode also invokes fixed-options Git against the supplied object store. It does not scan consumer assemblies, discover tests, provision third-party services, or report outbound usage telemetry. ## Release Guidance @@ -28,7 +28,9 @@ appsurface evidence verify TestResults/evidence/evidence-manifest.json | `doctor` | Resolves policy and reports policy, diff, Docker, browser, and release-envelope prerequisites without starting anything. | | `explain` | Writes the resolved plan and a human-readable summary without running producers. | | `run` | Runs selected built-in coverage evidence, writes a canonical plan/manifest/summary, and writes a GitHub step summary when available. Consumer-owned browser/E2E or resource-backed producers run through the separate Aspire EvidenceHost package. | -| `verify` | Recomputes binding and digest verification without running any producer. | +| `verify` | Reads at most 4 MiB per canonical plan or manifest, then recomputes binding and digests without running a producer. v2 also requires a separately trusted `--policy` and `--repository` to regenerate the exact Git change. | + +Revision-bound `doctor`, `explain`, and `run` require `--base-revision`, `--head-revision`, and `--diff-file` together, with no `--path`. `--repository` points at the trusted object store and defaults to the current directory for these planning commands. `--gate-mode` rejects local path-only planning. A trusted controller may add `--pr-run-identity` with canonical PR/run identity JSON; it is not accepted for a local-only plan. A mismatch between the supplied source diff and the fixed-options Git diff fails with `ASEVD231`; partial input fails with `ASEVD230`; identity without revisions fails with `ASEVD233`. The [cookbook rehearsal](../../guides/evidencehost-cookbook.md#revision-bound-pr-rehearsal) shows a copyable command sequence. Built-in `run` treats v2 results as `ObservationOnly` because the local CLI cannot authenticate CI job provenance or subject isolation; gate mode exits nonzero on that observation. External gate authorization requires the [base-owned verifier](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md) to check current PR identity and execution provenance. ## Incomplete profiles are not complete evidence diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs index 7ccf71fea..3ff1d6daf 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -306,6 +307,24 @@ public sealed record EvidencePolicy( IReadOnlyList Profiles, IReadOnlyList Rules); +/// +/// Records bounded pull-request and workflow identity captured by the trusted controller. +/// These fields are provenance to compare with an authoritative CI provider, not proof by themselves. +/// +/// GitHub repository's stable numeric identifier. +/// Head repository's stable numeric identifier; differs for forks. +/// Pull-request number in the target repository. +/// Target branch name at capture time. +/// GitHub Actions workflow-run identifier. +/// Positive attempt number for that run. +public sealed record EvidencePullRequestRunIdentity( + long RepositoryId, + long HeadRepositoryId, + int PullRequestNumber, + string TargetBranch, + long WorkflowRunId, + int WorkflowRunAttempt); + /// /// Captures the immutable result of policy resolution before resource or producer execution. /// @@ -318,6 +337,11 @@ public sealed record EvidencePolicy( /// Rules that explain selection. /// SHA-256 digest of canonical plan bytes excluding this digest field. /// Canonical checked-in policy snapshot used for resolution and later verification. +/// Complete base commit ID for a v2 revision-bound plan; absent for legacy local plans. +/// Complete head commit ID for a v2 revision-bound plan; absent for legacy local plans. +/// SHA-256 of the exact fixed-options Git diff bytes for a v2 plan. +/// SHA-256 of the exact NUL-delimited Git name-status bytes for a v2 plan. +/// Controller-captured PR/run identity for a CI v2 plan; absent in local rehearsal. public sealed record EvidencePlan( string ContractVersion, string PolicyId, @@ -327,7 +351,12 @@ public sealed record EvidencePlan( IReadOnlyList ChangedPaths, IReadOnlyList MatchedRuleIds, string PlanDigest, - EvidencePolicy? PolicySnapshot = null); + EvidencePolicy? PolicySnapshot = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? BaseRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? HeadRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SourceDiffDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? NameStatusDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] EvidencePullRequestRunIdentity? PullRequestRunIdentity = null); /// /// Captures a bounded producer result returned to the EvidenceHost. @@ -381,6 +410,11 @@ public sealed record EvidenceExecutionMetrics( /// Bounded producer terminal results. /// Secret-free lifecycle timing and cleanup state. /// SHA-256 digest of canonical manifest bytes excluding this digest field. +/// Complete base commit ID copied from a v2 plan. +/// Complete head commit ID copied from a v2 plan. +/// SHA-256 of the exact Git diff bytes copied from a v2 plan. +/// SHA-256 of the exact Git name-status bytes copied from a v2 plan. +/// Controller-captured PR/run identity copied from a v2 plan. public sealed record EvidenceManifest( string ContractVersion, string PlanDigest, @@ -394,7 +428,12 @@ public sealed record EvidenceManifest( IReadOnlyList UnmediatedObligationIds, IReadOnlyList ProducerResults, EvidenceExecutionMetrics Metrics, - string ManifestDigest); + string ManifestDigest, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? BaseRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? HeadRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SourceDiffDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? NameStatusDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] EvidencePullRequestRunIdentity? PullRequestRunIdentity = null); /// /// Supplies the immutable execution context exposed to a registered evidence producer. @@ -436,6 +475,8 @@ public sealed class EvidenceArtifactWriter /// Maximum total artifact bytes accepted by one v1 producer declaration. public const long MaximumTotalArtifactBytes = 256L * 1024 * 1024; + private const int StreamBufferSize = 81_920; + private readonly EvidenceProducerDeclaration _producer; private readonly string _rootPath; private readonly object _sync = new(); @@ -518,6 +559,110 @@ public async ValueTask WriteAsync( } } + /// + /// Copies one declared artifact from a readable stream while hashing it, without buffering the complete artifact. + /// The source stream remains owned by the caller and must yield exactly bytes. + /// + /// Declared artifact slot identifier. + /// Normalized artifact-root-relative destination path. + /// Readable source stream. The writer does not dispose it. + /// Exact expected byte count, checked against both slot and v1 producer limits before reading. + /// Cancellation requested by the EvidenceHost lifecycle. + /// Hash and metadata for the copied artifact. + /// + /// This method writes to a path beneath the controlled artifact root and does not provide no-follow or + /// descriptor-relative extraction guarantees. Use it only for separately validated trusted streams; it is not + /// a safe copier for paths or streams supplied directly by an untrusted extraction boundary. + /// + public async ValueTask WriteAsync( + string logicalName, + string relativePath, + Stream contents, + long declaredLengthBytes, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(contents); + if (!contents.CanRead) + { + throw new ArgumentException("Evidence artifact source streams must be readable.", nameof(contents)); + } + + if (declaredLengthBytes < 0) + { + throw new ArgumentOutOfRangeException(nameof(declaredLengthBytes)); + } + + if (_producer.ArtifactSlots.FirstOrDefault(slot => string.Equals(slot.LogicalName, logicalName, StringComparison.Ordinal)) is not { } slot) + { + throw new InvalidOperationException($"Artifact '{logicalName}' is not declared by producer '{_producer.Id}'."); + } + + var normalizedPath = EvidenceArtifactValidation.NormalizeRelativePath(relativePath); + EvidenceArtifactValidation.ValidatePathForSlot(slot, normalizedPath); + ReserveArtifact(logicalName, normalizedPath, declaredLengthBytes, slot.MaximumBytes); + + string? temporaryPath = null; + try + { + cancellationToken.ThrowIfCancellationRequested(); + var destination = EvidenceArtifactValidation.GetContainedPath(_rootPath, normalizedPath); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + temporaryPath = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; + + string digest; + long copiedLength; + await using (var destinationStream = new FileStream( + temporaryPath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + StreamBufferSize, + FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + var result = await CopyAndHashAsync(contents, destinationStream, declaredLengthBytes, cancellationToken).ConfigureAwait(false); + copiedLength = result.Length; + digest = result.Sha256; + await destinationStream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + if (copiedLength != declaredLengthBytes) + { + throw new InvalidDataException($"Artifact '{logicalName}' stream length did not match its declared length."); + } + + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temporaryPath, destination, overwrite: true); + var artifact = new EvidenceArtifactResult(logicalName, normalizedPath, slot.MediaType, copiedLength, digest); + lock (_sync) + { + _artifacts[logicalName] = artifact; + } + + return artifact; + } + catch + { + if (temporaryPath is not null) + { + try + { + File.Delete(temporaryPath); + } + catch (IOException) + { + // Preserve the original write, read, or cancellation failure. + } + catch (UnauthorizedAccessException) + { + // Preserve the original write, read, or cancellation failure. + } + } + + ReleaseArtifact(logicalName, normalizedPath, declaredLengthBytes); + throw; + } + } + /// /// Revalidates the final on-disk bytes for every artifact written through this writer. /// @@ -525,19 +670,42 @@ public async ValueTask WriteAsync( /// when every artifact still has its declared length and digest. public async Task VerifyWrittenArtifactsAsync(CancellationToken cancellationToken = default) { + long totalBytes = 0; foreach (var artifact in WrittenArtifacts) { string path; try { + var slot = _producer.ArtifactSlots.FirstOrDefault(candidate => + string.Equals(candidate.LogicalName, artifact.LogicalName, StringComparison.Ordinal)); + if (slot is null + || artifact.LengthBytes < 0 + || artifact.LengthBytes > slot.MaximumBytes + || artifact.LengthBytes > MaximumTotalArtifactBytes - totalBytes) + { + return false; + } + + totalBytes += artifact.LengthBytes; path = EvidenceArtifactValidation.GetContainedPath(_rootPath, artifact.RelativePath); - var bytes = await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false); - if (bytes.LongLength != artifact.LengthBytes - || !string.Equals(EvidenceDigest.Sha256(bytes), artifact.Sha256, StringComparison.Ordinal)) + await using var stream = new FileStream( + path, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + StreamBufferSize, + FileOptions.Asynchronous | FileOptions.SequentialScan); + var result = await CopyAndHashAsync(stream, null, artifact.LengthBytes, cancellationToken).ConfigureAwait(false); + if (result.Length != artifact.LengthBytes + || !string.Equals(result.Sha256, artifact.Sha256, StringComparison.Ordinal)) { return false; } } + catch (InvalidDataException) + { + return false; + } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException) { return false; @@ -547,7 +715,7 @@ public async Task VerifyWrittenArtifactsAsync(CancellationToken cancellati return true; } - private void ReserveArtifact(string logicalName, string normalizedPath, int lengthBytes, long maximumBytes) + private void ReserveArtifact(string logicalName, string normalizedPath, long lengthBytes, long maximumBytes) { lock (_sync) { @@ -574,7 +742,7 @@ private void ReserveArtifact(string logicalName, string normalizedPath, int leng } } - private void ReleaseArtifact(string logicalName, string normalizedPath, int lengthBytes) + private void ReleaseArtifact(string logicalName, string normalizedPath, long lengthBytes) { lock (_sync) { @@ -583,6 +751,52 @@ private void ReleaseArtifact(string logicalName, string normalizedPath, int leng _totalBytes -= lengthBytes; } } + + private static async Task<(long Length, string Sha256)> CopyAndHashAsync( + Stream source, + Stream? destination, + long maximumBytes, + CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = ArrayPool.Shared.Rent(StreamBufferSize); + long length = 0; + try + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + var remaining = maximumBytes - length; + var readSize = remaining > 0 + ? (int)Math.Min(StreamBufferSize, Math.Min(buffer.Length, remaining)) + : 1; + var bytesRead = await source.ReadAsync(buffer.AsMemory(0, readSize), cancellationToken).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + if (remaining == 0) + { + throw new InvalidDataException("Evidence artifact stream exceeds its declared or allowed length."); + } + + hash.AppendData(buffer, 0, bytesRead); + if (destination is not null) + { + await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + + length += bytesRead; + } + + return (length, Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant()); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } } /// @@ -920,7 +1134,12 @@ public static EvidenceManifest Build( UnmediatedObligationIds: unmediated.OrderBy(static id => id, StringComparer.Ordinal).ToArray(), ProducerResults: producerResults.OrderBy(static result => result.ProducerId, StringComparer.Ordinal).ToArray(), Metrics: metrics, - ManifestDigest: string.Empty); + ManifestDigest: string.Empty, + BaseRevision: plan.BaseRevision, + HeadRevision: plan.HeadRevision, + SourceDiffDigest: plan.SourceDiffDigest, + NameStatusDigest: plan.NameStatusDigest, + PullRequestRunIdentity: plan.PullRequestRunIdentity); return draft with { ManifestDigest = EvidenceDigest.CanonicalSha256(draft) }; } @@ -939,7 +1158,14 @@ public static bool Verify(EvidencePlan plan, EvidenceManifest manifest) ArgumentNullException.ThrowIfNull(manifest); var planWithoutDigest = plan with { PlanDigest = string.Empty }; - if (plan.PolicySnapshot is null + if (!HasValidRevisionBinding(plan) + || !string.Equals(plan.ContractVersion, manifest.ContractVersion, StringComparison.Ordinal) + || !string.Equals(plan.BaseRevision, manifest.BaseRevision, StringComparison.Ordinal) + || !string.Equals(plan.HeadRevision, manifest.HeadRevision, StringComparison.Ordinal) + || !string.Equals(plan.SourceDiffDigest, manifest.SourceDiffDigest, StringComparison.Ordinal) + || !string.Equals(plan.NameStatusDigest, manifest.NameStatusDigest, StringComparison.Ordinal) + || !Equals(plan.PullRequestRunIdentity, manifest.PullRequestRunIdentity) + || plan.PolicySnapshot is null || !string.Equals(plan.PolicyDigest, EvidenceDigest.CanonicalSha256(plan.PolicySnapshot), StringComparison.Ordinal) || !string.Equals(plan.DiffDigest, EvidenceDigest.CanonicalSha256(plan.ChangedPaths), StringComparison.Ordinal) || !string.Equals(plan.PlanDigest, EvidenceDigest.CanonicalSha256(planWithoutDigest), StringComparison.Ordinal) @@ -963,6 +1189,40 @@ public static bool Verify(EvidencePlan plan, EvidenceManifest manifest) manifest.Metrics); return string.Equals(manifest.ManifestDigest, expected.ManifestDigest, StringComparison.Ordinal); } + + private static bool HasValidRevisionBinding(EvidencePlan plan) + { + if (string.Equals(plan.ContractVersion, "1.0", StringComparison.Ordinal)) + { + return plan.BaseRevision is null + && plan.HeadRevision is null + && plan.SourceDiffDigest is null + && plan.NameStatusDigest is null + && plan.PullRequestRunIdentity is null; + } + + return string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + && IsLowerHex(plan.BaseRevision, 40, 64) + && plan.HeadRevision?.Length == plan.BaseRevision?.Length + && IsLowerHex(plan.HeadRevision, 40, 64) + && IsLowerHex(plan.SourceDiffDigest, 64) + && IsLowerHex(plan.NameStatusDigest, 64) + && (plan.PullRequestRunIdentity is null + || plan.PullRequestRunIdentity is + { + RepositoryId: > 0, + HeadRepositoryId: > 0, + PullRequestNumber: > 0, + TargetBranch.Length: > 0 and <= 128, + WorkflowRunId: > 0, + WorkflowRunAttempt: > 0, + }); + } + + private static bool IsLowerHex(string? value, params int[] allowedLengths) + => value is not null + && allowedLengths.Contains(value.Length) + && value.All(static character => character is >= '0' and <= '9' or >= 'a' and <= 'f'); } /// diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs new file mode 100644 index 000000000..4b8ee3d82 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs @@ -0,0 +1,767 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Win32.SafeHandles; + +[assembly: InternalsVisibleTo("ForgeTrust.AppSurface.Cli.Tests")] + +namespace ForgeTrust.AppSurface.Evidence.Contracts; + +/// +/// Identifies one untrusted scratch file and its declared evidence artifact destination. +/// +/// Declared logical artifact slot name. +/// Canonical slash-separated path relative to the trusted scratch directory. +/// Canonical slash-separated path beneath the evidence writer root and declared slot. +public sealed record EvidenceNoFollowArtifact( + string LogicalName, + string SourceRelativePath, + string DestinationRelativePath); + +/// +/// Lowers the extractor's built-in file, byte, and elapsed-time ceilings for one extraction call. +/// +/// +/// Limits may be reduced by the caller but cannot exceed 64 files, the evidence writer's 256 MiB +/// per-producer total, or two minutes. Each individual artifact is also bounded by its declared slot. +/// +public sealed record EvidenceNoFollowArtifactExtractionLimits +{ + /// The absolute maximum number of source files in one extraction call. + public const int MaximumAllowedFileCount = 64; + + /// The absolute maximum aggregate source size in one extraction call. + public const long MaximumAllowedTotalBytes = EvidenceArtifactWriter.MaximumTotalArtifactBytes; + + /// The absolute maximum wall-clock duration of one extraction call. + public static readonly TimeSpan MaximumAllowedDuration = TimeSpan.FromMinutes(2); + + /// Gets the maximum number of files accepted by one extraction call. + public int MaximumFileCount { get; init; } = MaximumAllowedFileCount; + + /// Gets the maximum aggregate source size accepted by one extraction call. + public long MaximumTotalBytes { get; init; } = MaximumAllowedTotalBytes; + + /// Gets the maximum wall-clock duration of one extraction call. + public TimeSpan MaximumDuration { get; init; } = MaximumAllowedDuration; +} + +/// +/// Copies explicitly selected scratch files into declared evidence artifact slots using Linux no-follow opens. +/// +/// +/// The caller must provide an already-open handle to the trusted scratch directory. The extractor requires Linux +/// x64 or arm64 with the openat2 syscall and statx; it fails closed when either facility or a required +/// resolution flag is unavailable. It never falls back to caller-path-based source reads. +/// +public static class EvidenceNoFollowArtifactExtractor +{ + private const int StreamBufferSize = 81_920; + private const int MaximumRelativePathBytes = 4_096; + private const int MaximumSegmentBytes = 255; + + private const long OpenAt2SyscallNumber = 437; + + private const ulong OpenReadOnly = 0; + private const ulong OpenCloseOnExec = 0x0008_0000; + private const ulong OpenNoFollowX64 = 0x0002_0000; + private const ulong OpenNoFollowArm64 = 0x0000_8000; + private static ulong OpenNoFollow => RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? OpenNoFollowArm64 : OpenNoFollowX64; + private const ulong OpenNonBlocking = 0x0000_0800; + private const ulong OpenNoControllingTerminal = 0x0000_0100; + private const ulong ResolveNoMagicLinks = 0x02; + private const ulong ResolveNoSymlinks = 0x04; + private const ulong ResolveBeneath = 0x08; + + private const int AtEmptyPath = 0x1000; + private const uint StatxBasicStats = 0x07ff; + private const uint StatxType = 1 << 0; + private const uint StatxMode = 1 << 1; + private const uint StatxLinkCount = 1 << 2; + private const uint StatxModifyTime = 1 << 6; + private const uint StatxChangeTime = 1 << 7; + private const uint StatxInode = 1 << 8; + private const uint StatxSize = 1 << 9; + private const uint StatxRequiredMask = StatxType | StatxMode | StatxLinkCount | StatxModifyTime | StatxChangeTime | StatxInode | StatxSize; + private const ushort FileTypeMask = 0xf000; + private const ushort RegularFileType = 0x8000; + private const ushort DirectoryFileType = 0x4000; + + private const int ErrorInvalidArgument = 22; + private const int ErrorNoSys = 38; + private const int ErrorTooLarge = 7; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// + /// Opens each listed source beneath without following symlinks and streams + /// its bytes through . + /// + /// Already-open handle to the trusted scratch directory. The extractor borrows it for this call. + /// Writer that owns the declared destination slots and artifact root. + /// Explicit source-to-destination mappings. Directories are never enumerated. + /// Optional stricter file-count, aggregate-byte, and duration limits. + /// Caller cancellation token. + /// The metadata for artifacts completed by this call, in input order. + /// The operating system, architecture, kernel, or libc lacks required enforcement. + /// A source or destination path is not canonical and root-relative, or the input contains duplicates. + /// A source is not a single-link regular file, changes while being copied, or exceeds the selected limits. + /// A source cannot be opened or inspected through the required Linux descriptor APIs. + /// The extraction exceeds its configured duration. + /// + /// Source paths must use forward slashes and contain no empty, dot, or parent segments. The extractor checks each + /// opened file's type, link count, identity, size, modification time, and change time. It also hashes a second + /// read through the same open descriptor and compares it with the bytes streamed to the writer before promotion. + /// A later failure does not roll back artifacts already completed earlier in the same call because the writer + /// exposes no batch transaction. + /// + public static Task> ExtractAsync( + SafeFileHandle trustedScratchRoot, + EvidenceArtifactWriter writer, + IReadOnlyList artifacts, + EvidenceNoFollowArtifactExtractionLimits? limits = null, + CancellationToken cancellationToken = default) => + ExtractCoreAsync( + trustedScratchRoot, + writer, + artifacts, + limits, + cancellationToken, + afterFirstPassBeforeSecondPass: null); + + /// + /// Runs extraction with a deterministic checkpoint for source-mutation verification tests. + /// + /// Already-open handle to the trusted scratch directory. The extractor borrows it for this call. + /// Writer that owns the declared destination slots and artifact root. + /// Explicit source-to-destination mappings. Directories are never enumerated. + /// Trusted test callback invoked after each source's streamed pass and initial metadata check, immediately before its verification pass. + /// Optional stricter file-count, aggregate-byte, and duration limits. + /// Caller cancellation token. + /// The metadata for artifacts completed by this call, in input order. + /// + /// This internal entry point exists only to make source-mutation tests deterministic. Production callers use + /// , + /// which does not accept a callback. + /// + internal static Task> ExtractAsyncForTesting( + SafeFileHandle trustedScratchRoot, + EvidenceArtifactWriter writer, + IReadOnlyList artifacts, + Action afterFirstPassBeforeSecondPass, + EvidenceNoFollowArtifactExtractionLimits? limits = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(afterFirstPassBeforeSecondPass); + return ExtractCoreAsync( + trustedScratchRoot, + writer, + artifacts, + limits, + cancellationToken, + afterFirstPassBeforeSecondPass); + } + + private static async Task> ExtractCoreAsync( + SafeFileHandle trustedScratchRoot, + EvidenceArtifactWriter writer, + IReadOnlyList artifacts, + EvidenceNoFollowArtifactExtractionLimits? limits, + CancellationToken cancellationToken, + Action? afterFirstPassBeforeSecondPass) + { + ArgumentNullException.ThrowIfNull(trustedScratchRoot); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(artifacts); + + var effectiveLimits = limits ?? new EvidenceNoFollowArtifactExtractionLimits(); + ValidateLimits(effectiveLimits); + + var requestedArtifacts = artifacts.ToArray(); + if (requestedArtifacts.Length > effectiveLimits.MaximumFileCount) + { + throw new InvalidDataException("The artifact list exceeds the configured file-count limit."); + } + + var requests = ValidateRequests(requestedArtifacts); + EnsureLinuxEnforcementAvailable(); + cancellationToken.ThrowIfCancellationRequested(); + + var startedTimestamp = Stopwatch.GetTimestamp(); + using var operationCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + operationCancellation.CancelAfter(effectiveLimits.MaximumDuration); + var operationToken = operationCancellation.Token; + + var rootHandleAdded = false; + var openedFiles = new List(requests.Count); + try + { + trustedScratchRoot.DangerousAddRef(ref rootHandleAdded); + if (!rootHandleAdded || trustedScratchRoot.IsInvalid || trustedScratchRoot.IsClosed) + { + throw new ArgumentException("The trusted scratch root must be an open directory handle.", nameof(trustedScratchRoot)); + } + + var rootSnapshot = ReadSnapshot(trustedScratchRoot); + if ((rootSnapshot.Mode & FileTypeMask) != DirectoryFileType) + { + throw new ArgumentException("The trusted scratch root handle must refer to a directory.", nameof(trustedScratchRoot)); + } + + var rootDescriptor = trustedScratchRoot.DangerousGetHandle().ToInt32(); + var identities = new HashSet(); + long totalBytes = 0; + foreach (var request in requests) + { + operationToken.ThrowIfCancellationRequested(); + var fileHandle = OpenRelativeRegularCandidate(rootDescriptor, request.SourceRelativePath); + try + { + var snapshot = ReadSnapshot(fileHandle); + if ((snapshot.Mode & FileTypeMask) != RegularFileType) + { + throw new InvalidDataException($"Source '{request.SourceRelativePath}' is not a regular file."); + } + + if (snapshot.LinkCount != 1) + { + throw new InvalidDataException($"Source '{request.SourceRelativePath}' has more than one hard link."); + } + + if (!identities.Add(snapshot.Identity)) + { + throw new InvalidDataException("The artifact list refers to the same underlying file more than once."); + } + + if (snapshot.Size > (ulong)effectiveLimits.MaximumTotalBytes + || snapshot.Size > long.MaxValue + || (ulong)totalBytes > (ulong)effectiveLimits.MaximumTotalBytes - snapshot.Size) + { + throw new InvalidDataException("The artifact sources exceed the configured aggregate byte limit."); + } + + totalBytes += (long)snapshot.Size; + openedFiles.Add(new OpenedArtifact(request, fileHandle, snapshot)); + fileHandle = null!; + } + finally + { + fileHandle?.Dispose(); + } + } + + var results = new List(openedFiles.Count); + foreach (var openedFile in openedFiles) + { + operationToken.ThrowIfCancellationRequested(); + EnsureWithinDuration(startedTimestamp, effectiveLimits.MaximumDuration); + + await using var source = new FileStream( + openedFile.Handle, + FileAccess.Read, + StreamBufferSize, + isAsync: false); + using var verifiedSource = new VerifiedSourceStream( + source, + openedFile.Handle, + openedFile.Snapshot, + checked((long)openedFile.Snapshot.Size), + startedTimestamp, + effectiveLimits.MaximumDuration, + afterFirstPassBeforeSecondPass is null + ? null + : () => afterFirstPassBeforeSecondPass(openedFile.Request.SourceRelativePath)); + + var result = await writer.WriteAsync( + openedFile.Request.LogicalName, + openedFile.Request.DestinationRelativePath, + verifiedSource, + checked((long)openedFile.Snapshot.Size), + operationToken).ConfigureAwait(false); + results.Add(result); + } + + return results; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new TimeoutException("The Linux no-follow artifact extraction exceeded its configured duration."); + } + finally + { + foreach (var openedFile in openedFiles) + { + openedFile.Handle.Dispose(); + } + + if (rootHandleAdded) + { + trustedScratchRoot.DangerousRelease(); + } + } + } + + private static IReadOnlyList ValidateRequests(IReadOnlyList artifacts) + { + var logicalNames = new HashSet(StringComparer.Ordinal); + var sourcePaths = new HashSet(StringComparer.Ordinal); + var destinationPaths = new HashSet(StringComparer.Ordinal); + var requests = new List(artifacts.Count); + + foreach (var artifact in artifacts) + { + ArgumentNullException.ThrowIfNull(artifact); + if (string.IsNullOrWhiteSpace(artifact.LogicalName)) + { + throw new ArgumentException("Artifact logical names cannot be empty.", nameof(artifacts)); + } + + var sourcePath = ValidateRelativePath(artifact.SourceRelativePath, nameof(artifacts)); + var destinationPath = ValidateRelativePath(artifact.DestinationRelativePath, nameof(artifacts)); + if (!logicalNames.Add(artifact.LogicalName) + || !sourcePaths.Add(sourcePath) + || !destinationPaths.Add(destinationPath)) + { + throw new ArgumentException("Artifact logical names, source paths, and destination paths must be unique.", nameof(artifacts)); + } + + requests.Add(new ValidatedRequest(artifact.LogicalName, sourcePath, destinationPath)); + } + + return requests; + } + + private static string ValidateRelativePath(string? path, string parameterName) + { + if (string.IsNullOrWhiteSpace(path) + || path[0] == '/' + || path.Contains('\\') + || path.Contains('\0')) + { + throw new ArgumentException("Artifact paths must be canonical, slash-separated relative paths.", parameterName); + } + + byte[] encoded; + try + { + encoded = StrictUtf8.GetBytes(path); + } + catch (EncoderFallbackException exception) + { + throw new ArgumentException("Artifact paths must contain valid UTF-8 characters.", parameterName, exception); + } + + if (encoded.Length > MaximumRelativePathBytes) + { + throw new ArgumentException("Artifact paths exceed the Linux relative-path byte limit.", parameterName); + } + + foreach (var segment in path.Split('/')) + { + if (segment.Length == 0 || segment is "." or "..") + { + throw new ArgumentException("Artifact paths cannot contain empty, dot, or parent segments.", parameterName); + } + + int segmentLength; + try + { + segmentLength = StrictUtf8.GetByteCount(segment); + } + catch (EncoderFallbackException exception) + { + throw new ArgumentException("Artifact paths must contain valid UTF-8 characters.", parameterName, exception); + } + + if (segmentLength > MaximumSegmentBytes || segment.Any(char.IsControl)) + { + throw new ArgumentException("Artifact path segments exceed Linux filename limits or contain control characters.", parameterName); + } + } + + return path; + } + + private static void ValidateLimits(EvidenceNoFollowArtifactExtractionLimits limits) + { + if (limits.MaximumFileCount is < 1 or > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The file-count limit must be between 1 and 64."); + } + + if (limits.MaximumTotalBytes is < 1 or > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedTotalBytes) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The aggregate byte limit must be between 1 byte and 256 MiB."); + } + + if (limits.MaximumDuration <= TimeSpan.Zero + || limits.MaximumDuration > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedDuration) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The duration limit must be positive and no greater than two minutes."); + } + } + + private static void EnsureLinuxEnforcementAvailable() + { + if (!OperatingSystem.IsLinux()) + { + throw new PlatformNotSupportedException("No-follow artifact extraction requires Linux openat2 and statx."); + } + + if (RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + throw new PlatformNotSupportedException("No-follow artifact extraction currently supports Linux x64 and arm64 only."); + } + } + + private static SafeFileHandle OpenRelativeRegularCandidate(int rootDescriptor, string relativePath) + { + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + + var descriptor = InvokeOpenAt2(rootDescriptor, relativePath, ref how); + return new SafeFileHandle(new IntPtr(descriptor), ownsHandle: true); + } + + private static int InvokeOpenAt2(int rootDescriptor, string relativePath, ref LinuxOpenHow how) + { + var pathPointer = Marshal.StringToCoTaskMemUTF8(relativePath); + try + { + var result = Syscall(OpenAt2SyscallNumber, rootDescriptor, pathPointer, ref how, (nuint)Marshal.SizeOf()); + if (result >= 0 && result <= int.MaxValue) + { + return (int)result; + } + + var error = Marshal.GetLastPInvokeError(); + if (error is ErrorNoSys or ErrorInvalidArgument or ErrorTooLarge) + { + throw new PlatformNotSupportedException( + "This Linux kernel does not enforce the required openat2 resolution flags; extraction was refused."); + } + + throw new IOException($"Linux openat2 refused the scratch artifact path (errno {error})."); + } + finally + { + Marshal.FreeCoTaskMem(pathPointer); + } + } + + private static FileSnapshot ReadSnapshot(SafeFileHandle handle) + { + LinuxStatx statx; + try + { + if (Statx( + handle.DangerousGetHandle().ToInt32(), + string.Empty, + AtEmptyPath, + StatxBasicStats, + out statx) != 0) + { + var error = Marshal.GetLastPInvokeError(); + if (error == ErrorNoSys) + { + throw new PlatformNotSupportedException("This Linux libc or kernel does not provide statx; extraction was refused."); + } + + throw new IOException($"Linux statx could not inspect the opened scratch entry (errno {error})."); + } + } + catch (EntryPointNotFoundException exception) + { + throw new PlatformNotSupportedException("This Linux libc does not export statx; extraction was refused.", exception); + } + + if ((statx.Mask & StatxRequiredMask) != StatxRequiredMask) + { + throw new PlatformNotSupportedException("Linux statx did not return the metadata required for safe extraction."); + } + + return new FileSnapshot( + statx.DeviceMajor, + statx.DeviceMinor, + statx.Inode, + statx.Mode, + statx.LinkCount, + statx.Size, + statx.ModifyTime.Seconds, + statx.ModifyTime.Nanoseconds, + statx.ChangeTime.Seconds, + statx.ChangeTime.Nanoseconds); + } + + private static void EnsureWithinDuration(long startedTimestamp, TimeSpan maximumDuration) + { + if (Stopwatch.GetElapsedTime(startedTimestamp) >= maximumDuration) + { + throw new TimeoutException("The Linux no-follow artifact extraction exceeded its configured duration."); + } + } + + private static void EnsureUnchanged(FileSnapshot before, FileSnapshot after) + { + if (before != after) + { + throw new InvalidDataException("A scratch artifact changed while it was being extracted."); + } + } + + private sealed class VerifiedSourceStream : Stream + { + private readonly FileStream _source; + private readonly SafeFileHandle _handle; + private readonly FileSnapshot _initialSnapshot; + private readonly long _expectedLength; + private readonly long _startedTimestamp; + private readonly TimeSpan _maximumDuration; + private readonly Action? _afterFirstPassBeforeSecondPass; + private readonly IncrementalHash _firstPassHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long _bytesRead; + private bool _validated; + + public VerifiedSourceStream( + FileStream source, + SafeFileHandle handle, + FileSnapshot initialSnapshot, + long expectedLength, + long startedTimestamp, + TimeSpan maximumDuration, + Action? afterFirstPassBeforeSecondPass) + { + _source = source; + _handle = handle; + _initialSnapshot = initialSnapshot; + _expectedLength = expectedLength; + _startedTimestamp = startedTimestamp; + _maximumDuration = maximumDuration; + _afterFirstPassBeforeSecondPass = afterFirstPassBeforeSecondPass; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => _expectedLength; + + public override long Position + { + get => _bytesRead; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + ArgumentNullException.ThrowIfNull(buffer); + _ = buffer.AsSpan(offset, count); + throw new NotSupportedException("No-follow artifact extraction reads source streams asynchronously."); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var bytesRead = await _source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + ProcessFirstPassBytes(buffer.Span[..bytesRead]); + if (bytesRead == 0) + { + await ValidateAtEndAsync(cancellationToken).ConfigureAwait(false); + } + + return bytesRead; + } + + public override void Flush() => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _firstPassHash.Dispose(); + } + + base.Dispose(disposing); + } + + private void ProcessFirstPassBytes(ReadOnlySpan bytes) + { + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + if (bytes.Length == 0) + { + return; + } + + if (_bytesRead > _expectedLength - bytes.Length) + { + return; + } + + _firstPassHash.AppendData(bytes); + _bytesRead += bytes.Length; + } + + private async Task ValidateAtEndAsync(CancellationToken cancellationToken) + { + if (_validated) + { + return; + } + + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + if (_bytesRead != _expectedLength) + { + throw new InvalidDataException("A scratch artifact ended before its opened descriptor size."); + } + + EnsureUnchanged(_initialSnapshot, ReadSnapshot(_handle)); + var firstDigest = _firstPassHash.GetHashAndReset(); + _afterFirstPassBeforeSecondPass?.Invoke(); + _source.Position = 0; + + using var secondPassHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[StreamBufferSize]; + long secondPassBytes = 0; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + var bytesRead = await _source.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + if (secondPassBytes > _expectedLength - bytesRead) + { + throw new InvalidDataException("A scratch artifact grew while its content was being verified."); + } + + secondPassHash.AppendData(buffer, 0, bytesRead); + secondPassBytes += bytesRead; + } + + var secondDigest = secondPassHash.GetHashAndReset(); + EnsureUnchanged(_initialSnapshot, ReadSnapshot(_handle)); + if (secondPassBytes != _expectedLength + || !CryptographicOperations.FixedTimeEquals(firstDigest, secondDigest)) + { + throw new InvalidDataException("A scratch artifact's content changed while it was being extracted."); + } + + _validated = true; + } + } + + private sealed class OpenedArtifact( + ValidatedRequest request, + SafeFileHandle handle, + FileSnapshot snapshot) : IDisposable + { + public ValidatedRequest Request { get; } = request; + + public SafeFileHandle Handle { get; } = handle; + + public FileSnapshot Snapshot { get; } = snapshot; + + public void Dispose() => Handle.Dispose(); + } + + private sealed record ValidatedRequest(string LogicalName, string SourceRelativePath, string DestinationRelativePath); + + private readonly record struct FileIdentity(uint DeviceMajor, uint DeviceMinor, ulong Inode); + + private readonly record struct FileSnapshot( + uint DeviceMajor, + uint DeviceMinor, + ulong Inode, + ushort Mode, + uint LinkCount, + ulong Size, + long ModifySeconds, + uint ModifyNanoseconds, + long ChangeSeconds, + uint ChangeNanoseconds) + { + public FileIdentity Identity => new(DeviceMajor, DeviceMinor, Inode); + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxOpenHow + { + public ulong Flags; + public ulong Mode; + public ulong Resolve; + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxStatxTimestamp + { + public long Seconds; + public uint Nanoseconds; + private int _reserved; + } + + [StructLayout(LayoutKind.Sequential, Size = 256)] + private struct LinuxStatx + { + public uint Mask; + private uint _blockSize; + private ulong _attributes; + public uint LinkCount; + private uint _userId; + private uint _groupId; + public ushort Mode; + private ushort _spare0; + public ulong Inode; + public ulong Size; + private ulong _blocks; + private ulong _attributesMask; + private LinuxStatxTimestamp _accessTime; + private LinuxStatxTimestamp _birthTime; + public LinuxStatxTimestamp ChangeTime; + public LinuxStatxTimestamp ModifyTime; + private uint _rdevMajor; + private uint _rdevMinor; + public uint DeviceMajor; + public uint DeviceMinor; + private ulong _mountId; + private uint _dioMemoryAlignment; + private uint _dioOffsetAlignment; + private ulong _spare1; + private ulong _spare2; + private ulong _spare3; + private ulong _spare4; + private ulong _spare5; + private ulong _spare6; + private ulong _spare7; + private ulong _spare8; + private ulong _spare9; + private ulong _spare10; + private ulong _spare11; + private ulong _spare12; + } + + [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] + private static extern long Syscall(long number, int directoryDescriptor, IntPtr path, ref LinuxOpenHow how, nuint size); + + [DllImport("libc", EntryPoint = "statx", SetLastError = true)] + private static extern int Statx( + int directoryDescriptor, + [MarshalAs(UnmanagedType.LPUTF8Str)] string path, + int flags, + uint mask, + out LinuxStatx statx); +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md index 6f7d0cd57..b0a501743 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md @@ -16,6 +16,10 @@ for current release risk, migration guidance, and readiness. An `EvidencePolicy` resolves into an immutable `EvidencePlan`. A run records declared `EvidenceProducerResult` values and then uses `EvidenceManifestBuilder.Build(...)` to produce an `EvidenceManifest`. Both plan and manifest have canonical JSON and SHA-256 digests, so a gate can verify a result without rerunning the test suite. +Local path or text-diff planning retains contract version `1.0`. Revision-bound pull-request planning emits version `2.0` only when supplied a complete base commit ID, complete head commit ID, and a source diff that byte-for-byte matches the fixed-options Git diff for that pair. The v2 plan and manifest carry `BaseRevision`, `HeadRevision`, `SourceDiffDigest`, and `NameStatusDigest`. `DiffDigest` continues to bind the normalized path inventory; it is distinct from the exact source-diff digest. A trusted controller can also record `EvidencePullRequestRunIdentity` in the plan and manifest: numeric repository/head repository IDs, PR number, target branch, run ID, and attempt. A local rehearsal omits it; the final verifier must compare it with authoritative GitHub data. Optional v2 fields are omitted from v1 canonical JSON, preserving existing v1 digests. A v1 local manifest may still describe its local claim, but the [AppSurface CI gate design](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md) does not accept v1 as authorization. + +`EvidenceRevisionPlanBuilder.ResolveForPullRequest(...)` requires the conservative mixed-profile policy and rejects a release-only profile on a PR. `EvidenceRevisionPlanBuilder.VerifyAsync(...)` independently regenerates the Git diff/status and policy selection from a trusted object store and trusted base-owned policy. `EvidenceManifestBuilder.Verify(...)` checks internal plan/manifest consistency, including v2 field shape and equality, but cannot authenticate the GitHub event, trusted policy source, or subject job. The final CI verifier must check those external facts and current PR base/head before issuing a gate verdict. + | Type family | Purpose | | --- | --- | | `EvidencePolicy`, `EvidenceProfile`, `EvidencePolicyRule` | Checked-in change-risk policy and explicitly selected profile. | @@ -23,6 +27,32 @@ An `EvidencePolicy` resolves into an immutable `EvidencePlan`. A run records dec | `EvidencePlan`, `NormalizedDiffPath` | Deterministic resolved input. The plan binds policy identity, diff, selected profile, and matched rules. | | `EvidenceProducerResult`, `EvidenceManifest` | Terminal producer outcomes and the resulting gate claim. | | `EvidenceCanonicalJson`, `EvidenceDigest`, `EvidenceManifestBuilder` | Canonical serialization, digesting, claim calculation, and manifest verification. | +| `EvidenceArtifactWriter`, `EvidenceArtifactValidation` | Bounded artifact copying, streamed integrity verification, and declaration/path validation. | +| `EvidenceNoFollowArtifactExtractor` | Linux descriptor-relative extraction of explicitly selected untrusted scratch files into declared artifact slots. | + +## Writing and verifying artifacts + +`EvidenceArtifactWriter.WriteAsync(logicalName, relativePath, ReadOnlyMemory, cancellationToken)` remains available for artifacts already held in memory. Producers handling larger artifacts should use the stream overload: + +```csharp +await using var input = File.OpenRead(sourcePath); +var artifact = await context.Artifacts!.WriteAsync( + "report", + "coverage/report.json", + input, + declaredLengthBytes, + cancellationToken); +``` + +The stream overload requires a readable stream and an explicit, non-negative declared length. It checks that length against the selected slot's `MaximumBytes` and the remaining per-producer v1 allowance before reading. The v1 producer allowance is 256 MiB total across all artifact slots. The stream must yield exactly the declared number of bytes: an early end or any extra byte fails with `InvalidDataException`; an over-limit declaration fails before the stream is consumed. SHA-256 is computed as bytes are copied through a fixed-size buffer, so memory use does not grow with artifact size. The writer does not seek or rewind the input, and it does not dispose it; callers should pass a stream positioned at the artifact's first byte. A short stream is read through EOF, while an overlong stream is read through at most one byte beyond the declaration before failing. Cancellation propagates and a failed or cancelled stream write releases its reservation and removes its partial destination when possible. + +After writing, `VerifyWrittenArtifactsAsync(cancellationToken)` opens each destination as a stream and recomputes its length and digest with the same bounded-buffer approach. It returns `false` if an artifact is missing, exceeds its slot or producer limit, or no longer matches the metadata; cancellation propagates. Verification detects later changes to the copied file, while the returned `EvidenceArtifactResult` contains only the declared name, normalized relative path, media type, byte length, and digest. + +The writer's destination handling is path-based beneath a controlled evidence root. Neither the stream overload nor `VerifyWrittenArtifactsAsync` is a no-follow, descriptor-relative extraction primitive. Pass only separately validated trusted streams and use a dedicated no-follow extraction boundary for untrusted scratch paths; a path that appears contained is not proof that symlinks or concurrent path changes were excluded. Prefer the stream overload when the artifact is not already in memory, and use the memory overload for small content that the producer already owns as a byte buffer. + +For untrusted scratch output on Linux x64 or arm64, use `EvidenceNoFollowArtifactExtractor.ExtractAsync` with an already-open handle to the trusted scratch directory, an `EvidenceArtifactWriter` configured for the declared producer, and an explicit list of `EvidenceNoFollowArtifact` source/destination mappings. The extractor selects the no-follow open flag for the running architecture, then opens each source relative to that handle with Linux `openat2` no-symlink and beneath-root constraints, verifies regular-file identity and a single hard link with `statx`, streams it into the declared slot, and checks for mutation. It does not discover files or accept a subject-provided artifact list as authority. Source and destination paths must be canonical slash-separated relative paths without empty, `.` or `..` components; duplicate mappings are rejected. + +By default one extraction accepts at most 64 files and 256 MiB in two minutes, in addition to each slot's own byte limit. `EvidenceNoFollowArtifactExtractionLimits` can lower those limits but cannot raise them. Unsupported operating systems, architectures, or kernels fail closed; there is no path-based fallback. Extraction is sequential, not transactional: an error on a later file does not undo already written artifacts, so a caller must treat the whole producer result as failed and clean its artifact root before any claim. This primitive validates scratch-to-writer copying; the [trusted PR verifier](../ForgeTrust.AppSurface.Evidence.Planner/README.md) must separately authenticate the final handoff artifact bytes and job provenance. `EvidenceClaimKind.TargetedComplete` is eligible for a pull-request gate; `ReleaseComplete` is eligible only for a release gate and requires `ValidatedNotAttested` envelope status. `ObservationOnly` is deliberately informative, never gate-eligible. `NoEvidenceRequired` is valid only when the selected profile declares no resources, producers, or obligations. @@ -44,5 +74,6 @@ An unavailable capability, timeout, skipped producer, incomplete test profile, o - Do not treat a coverage collection artifact as a gate pass unless its producer has closed the assertion declared by the selected policy. - Do not claim independent attestation in v1. An accepted envelope is represented as `ValidatedNotAttested`. - Do not edit generated plan or manifest JSON. `EvidenceManifestBuilder.Verify(...)` and `appsurface evidence verify` detect inconsistent or edited claim fields by recomputing internal digests; they do not authenticate their inputs. Gates must obtain the plan and manifest through a trusted CI channel. +- Do not interpret `2.0` as a runtime sandbox claim. Revision binding says which commit pair was planned; a trusted controller and verifier must still establish job provenance, isolation, cleanup, and current PR identity. The built-in `appsurface evidence run` emits `ObservationOnly` for v2 inputs because that local command cannot establish those conditions. Read next: the [planner README](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md), the [Aspire lifecycle README](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Aspire/README.md), and the [EvidenceHost cookbook](https://github.com/forge-trust/AppSurface/blob/main/guides/evidencehost-cookbook.md). diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md index e53d03b30..77223e0df 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md @@ -5,3 +5,5 @@ The assembly owns one in-process implementation of coverage discovery, execution, watchdog supervision, merge, gate evaluation, patch analysis, and controlled artifact writing. The CLI owns command parsing and presentation; Evidence owns policy and claim translation. This direction ensures Evidence produces coverage claims from the same execution engine as `appsurface coverage run` and `appsurface coverage gate`, without invoking a second process. Both surfaces use the fail-mode default. For VSTest test phases with at least 90 seconds remaining, the engine requests no-dump hang blame and reserves part of the current budget for sequence output and summary. Evidence's producer deadline remains authoritative and includes discovery/build time. The [CLI hang-diagnostics reference](../../Cli/ForgeTrust.AppSurface.Cli/README.md#coverage-run-hang-diagnostics) documents the timeout arithmetic, opt-outs, artifact statuses, and migration for healthy long-running tests. Evidence results never include test names or Sequence.xml contents. All coverage orchestration types are internal and visible only to first-party assemblies. Consumers should use the documented public [coverage commands](../../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-coverage-run) and [EvidenceHost workflow](../../start-here/evidencehost.md). + +Coverage output acquisition and collector-artifact reads use native no-follow directory opens. Linux arm64 has different `O_DIRECTORY` and `O_NOFOLLOW` values from Linux x64, so platform security tests must run on the architecture being validated; a macOS coverage run cannot exercise that native path. The [CLI output-path reference](../../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-coverage-run) explains the fail-closed `ASCOV109` and collector-artifact diagnostics. diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs new file mode 100644 index 000000000..16d17cf83 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs @@ -0,0 +1,426 @@ +using System.Diagnostics; +using System.Text; +using ForgeTrust.AppSurface.Evidence.Contracts; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Captures the two byte-exact Git representations used by a revision-bound evidence gate. +/// +/// +/// A source diff binds the plan to exact Git output; a separate NUL-delimited status stream +/// selects paths even when a binary, mode, symlink, or submodule change has no text hunk. +/// Neither representation authenticates the repository or a remote PR by itself. +/// +public sealed class EvidenceGitChangeSnapshot +{ + private readonly byte[] _sourceDiff; + private readonly byte[] _nameStatus; + + internal EvidenceGitChangeSnapshot( + string baseRevision, + string headRevision, + byte[] sourceDiff, + byte[] nameStatus, + IReadOnlyList changedPaths) + { + BaseRevision = baseRevision; + HeadRevision = headRevision; + _sourceDiff = sourceDiff; + _nameStatus = nameStatus; + SourceDiffDigest = EvidenceDigest.Sha256(sourceDiff); + NameStatusDigest = EvidenceDigest.Sha256(nameStatus); + ChangedPaths = Array.AsReadOnly(changedPaths.ToArray()); + } + + /// Gets the complete canonical base commit object ID. + public string BaseRevision { get; } + + /// Gets the complete canonical head commit object ID. + public string HeadRevision { get; } + + /// Gets the bounded source diff bytes. Callers must not treat them as executable instructions. + public ReadOnlyMemory SourceDiff => _sourceDiff; + + /// Gets the bounded NUL-delimited name-status bytes. + public ReadOnlyMemory NameStatus => _nameStatus; + + /// Gets the SHA-256 of the exact source diff bytes. + public string SourceDiffDigest { get; } + + /// Gets the SHA-256 of the exact name-status bytes. + public string NameStatusDigest { get; } + + /// Gets the normalized changed paths used for policy selection. + public IReadOnlyList ChangedPaths { get; } +} + +/// +/// Runs Git with fixed diff options against two complete commit IDs in a trusted object store. +/// +/// +/// Supply a trusted bare or object-only checkout containing both commits. The caller is responsible +/// for fetching the exact objects, pinning the Git version in CI, and independently checking current +/// PR or tag identity before a gate verdict. This type never reads the ambient checkout's HEAD +/// and disables Git replacement refs so those refs cannot reinterpret a supplied object ID. +/// +public static class EvidenceGitChangeCapture +{ + /// Maximum captured source diff size for the first AppSurface gate. + public const int MaximumSourceDiffBytes = 20 * 1024 * 1024; + + /// Maximum number of changed records accepted for policy selection. + public const int MaximumChangedRecords = 10_000; + + /// Maximum UTF-8 byte length of one changed repository path. + public const int MaximumPathBytes = 4 * 1024; + + /// Maximum wall-clock seconds for capture of both Git representations. + public const int MaximumCaptureSeconds = 120; + + private const int MaximumNameStatusBytes = 85 * 1024 * 1024; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + /// + /// Captures and validates a byte-exact diff and NUL status stream for the same commit pair. + /// + /// Trusted Git object store containing both commits. + /// Full 40- or 64-character lower-case commit ID. + /// Full commit ID in the same object format. + /// Cancellation for Git execution and bounded reads. + /// A bounded snapshot suitable for trusted policy planning. + public static async Task CaptureAsync( + string repositoryPath, + string baseRevision, + string headRevision, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(repositoryPath); + ValidateRevision(baseRevision); + ValidateRevision(headRevision); + if (baseRevision.Length != headRevision.Length) + { + throw new EvidencePlanningException("ASEVD130", "Git revisions use different object ID formats.", "Supply two complete commit IDs from the same repository."); + } + + var repository = Path.GetFullPath(repositoryPath); + if (!Directory.Exists(repository)) + { + throw new EvidencePlanningException("ASEVD131", "The trusted Git object store is unavailable.", "Fetch the exact base and head commits into a trusted object-only checkout."); + } + + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(MaximumCaptureSeconds)); + try + { + return await CaptureWithinDeadlineAsync(repository, baseRevision, headRevision, deadline.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new EvidencePlanningException("ASEVD137", "Exact Git change capture exceeded its deadline.", "Retry in the pinned runner or reduce the change before a reviewed deadline increase."); + } + } + + private static async Task CaptureWithinDeadlineAsync( + string repository, + string baseRevision, + string headRevision, + CancellationToken cancellationToken) + { + await RequireCommitAsync(repository, baseRevision, cancellationToken).ConfigureAwait(false); + await RequireCommitAsync(repository, headRevision, cancellationToken).ConfigureAwait(false); + + var sourceDiff = await RunGitAsync( + repository, + ["-c", "diff.external=", "-c", "diff.noprefix=false", "-c", "diff.mnemonicprefix=false", "-c", "diff.algorithm=myers", "diff", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", "--full-index", "--unified=3", "--find-renames=50%", "--find-copies=50%", "--submodule=short", "--ignore-submodules=none", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", baseRevision, headRevision, "--"], + MaximumSourceDiffBytes, + cancellationToken).ConfigureAwait(false); + var nameStatus = await RunGitAsync( + repository, + ["-c", "diff.external=", "-c", "diff.noprefix=false", "-c", "diff.mnemonicprefix=false", "-c", "diff.algorithm=myers", "diff", "--name-status", "-z", "--no-ext-diff", "--no-textconv", "--no-color", "--find-renames=50%", "--find-copies=50%", "--submodule=short", "--ignore-submodules=none", "--no-relative", baseRevision, headRevision, "--"], + MaximumNameStatusBytes, + cancellationToken).ConfigureAwait(false); + if (sourceDiff.Length == 0 && nameStatus.Length != 0) + { + throw new EvidencePlanningException("ASEVD133", "Git source diff is empty while changed paths are reported.", "Recapture both representations from the same exact commit pair."); + } + + var paths = ParseNameStatus(nameStatus); + if (paths.Count == 0) + { + throw new EvidencePlanningException("ASEVD132", "The exact Git revisions have no changed paths.", "Use a commit pair with an explicit policy-selected change; never infer a no-evidence claim from an empty diff."); + } + + return new EvidenceGitChangeSnapshot(baseRevision, headRevision, sourceDiff, nameStatus, paths); + } + + /// + /// Regenerates both Git representations and rejects a changed or substituted snapshot. + /// + /// The same trusted object store used for capture. + /// Snapshot whose exact bytes and normalized paths must still bind. + /// Cancellation for Git execution. + /// A task that completes only when both representations match. + public static async Task VerifyAsync( + string repositoryPath, + EvidenceGitChangeSnapshot snapshot, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(snapshot); + var regenerated = await CaptureAsync(repositoryPath, snapshot.BaseRevision, snapshot.HeadRevision, cancellationToken).ConfigureAwait(false); + if (!regenerated.SourceDiff.Span.SequenceEqual(snapshot.SourceDiff.Span) + || !regenerated.NameStatus.Span.SequenceEqual(snapshot.NameStatus.Span) + || !regenerated.ChangedPaths.SequenceEqual(snapshot.ChangedPaths)) + { + throw new EvidencePlanningException("ASEVD133", "Git change bytes or selected paths differ from the captured snapshot.", "Discard the stale plan and recapture both representations from the exact commit objects."); + } + } + + /// + /// Strictly parses git diff --name-status -z bytes, including both rename or copy paths. + /// + /// Complete NUL-delimited Git stdout. + /// Changed paths in Git's order. + public static IReadOnlyList ParseNameStatus(ReadOnlySpan bytes) + { + if (bytes.Length > MaximumNameStatusBytes) + { + throw MalformedStatus(); + } + + var changes = new List(); + var seen = new HashSet(StringComparer.Ordinal); + var offset = 0; + while (offset < bytes.Length) + { + if (changes.Count >= MaximumChangedRecords) + { + throw new EvidencePlanningException("ASEVD134", "Git reported too many changed records.", "Reduce the change or revise the reviewed gate limit and its tests."); + } + + var status = ReadField(bytes, ref offset); + var isPair = status.Length > 0 && (status[0] == 'R' || status[0] == 'C'); + if (!IsSupportedStatus(status)) + { + throw MalformedStatus(); + } + + var firstPath = ReadPath(bytes, ref offset); + var path = isPair ? ReadPath(bytes, ref offset) : firstPath; + if (!seen.Add(path)) + { + throw MalformedStatus(); + } + + changes.Add(new NormalizedDiffPath(path, StatusKind(status[0]), isPair ? firstPath : null)); + } + + return changes; + } + + private static string ReadPath(ReadOnlySpan bytes, ref int offset) + { + var field = ReadFieldBytes(bytes, ref offset); + if (field.Length is 0 or > MaximumPathBytes) + { + throw MalformedStatus(); + } + + string path; + try + { + path = StrictUtf8.GetString(field); + } + catch (DecoderFallbackException) + { + throw MalformedStatus(); + } + + if (path.StartsWith('/') + || path.EndsWith('/') + || path.Contains('\\') + || path.Any(char.IsControl) + || path.Split('/').Any(static segment => segment.Length == 0 || segment is "." or "..")) + { + throw MalformedStatus(); + } + + return path; + } + + private static string ReadField(ReadOnlySpan bytes, ref int offset) + { + var field = ReadFieldBytes(bytes, ref offset); + if (field.Length is 0 or > 4) + { + throw MalformedStatus(); + } + + try + { + return StrictUtf8.GetString(field); + } + catch (DecoderFallbackException) + { + throw MalformedStatus(); + } + } + + private static ReadOnlySpan ReadFieldBytes(ReadOnlySpan bytes, ref int offset) + { + var terminator = bytes[offset..].IndexOf((byte)0); + if (terminator < 0) + { + throw MalformedStatus(); + } + + var field = bytes.Slice(offset, terminator); + offset += terminator + 1; + return field; + } + + private static bool IsSupportedStatus(string status) + { + if (status is "A" or "D" or "M" or "T") + { + return true; + } + + return status.Length is >= 2 and <= 4 + && status[0] is 'R' or 'C' + && int.TryParse(status.AsSpan(1), out var score) + && score is >= 0 and <= 100; + } + + private static string StatusKind(char status) => status switch + { + 'A' => "added", + 'D' => "deleted", + 'M' => "modified", + 'T' => "typechanged", + 'R' => "renamed", + 'C' => "copied", + _ => throw MalformedStatus(), + }; + + private static EvidencePlanningException MalformedStatus() => + new("ASEVD135", "Git name-status output is malformed or contains an unsafe path.", "Recapture the exact commit pair with the pinned Git runner; do not fall back to text-hunk path selection."); + + private static void ValidateRevision(string revision) + { + if (string.IsNullOrWhiteSpace(revision) + || revision.Length is not (40 or 64) + || revision.Any(static character => character is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + { + throw new EvidencePlanningException("ASEVD130", "A Git revision is not a complete lower-case commit ID.", "Supply the complete base and head object IDs, not refs or abbreviated SHAs."); + } + } + + private static async Task RequireCommitAsync(string repository, string revision, CancellationToken cancellationToken) + { + var result = await RunGitAsync(repository, ["cat-file", "-t", revision], 32, cancellationToken).ConfigureAwait(false); + if (!result.AsSpan().SequenceEqual("commit\n"u8)) + { + throw new EvidencePlanningException("ASEVD131", "An exact Git revision is not a commit object.", "Fetch the complete base and head commits into the trusted object store."); + } + } + + private static async Task RunGitAsync( + string repository, + IReadOnlyList arguments, + int maximumBytes, + CancellationToken cancellationToken) + { + var start = new ProcessStartInfo("git") + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + start.ArgumentList.Add("--no-pager"); + start.ArgumentList.Add("-C"); + start.ArgumentList.Add(repository); + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + // A trusted object-store path must not be redirected by inherited Git environment + // variables such as GIT_DIR or GIT_ALTERNATE_OBJECT_DIRECTORIES. Keep only the + // fixed settings below, independent of the caller's ambient checkout. + foreach (var key in start.Environment.Keys.Where(static key => key.StartsWith("GIT_", StringComparison.OrdinalIgnoreCase)).ToArray()) + { + start.Environment.Remove(key); + } + + start.Environment["GIT_CONFIG_NOSYSTEM"] = "1"; + start.Environment["GIT_CONFIG_GLOBAL"] = OperatingSystem.IsWindows() ? "NUL" : "/dev/null"; + start.Environment["GIT_CONFIG_COUNT"] = "0"; + start.Environment["GIT_CONFIG_PARAMETERS"] = string.Empty; + start.Environment["GIT_NO_REPLACE_OBJECTS"] = "1"; + start.Environment["GIT_EXTERNAL_DIFF"] = string.Empty; + start.Environment["GIT_DIFF_OPTS"] = string.Empty; + start.Environment["GIT_PAGER"] = "cat"; + start.Environment["LC_ALL"] = "C"; + + using var process = new Process { StartInfo = start }; + try + { + if (!process.Start()) + { + throw new EvidencePlanningException("ASEVD136", "The trusted Git process did not start.", "Install the pinned Git version in the gate runner."); + } + + var stdoutTask = ReadBoundedAsync(process.StandardOutput.BaseStream, maximumBytes, cancellationToken); + var stderrTask = ReadBoundedAsync(process.StandardError.BaseStream, 4096, cancellationToken); + try + { + var stdout = await stdoutTask.ConfigureAwait(false); + await stderrTask.ConfigureAwait(false); + await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); + if (process.ExitCode != 0) + { + throw new EvidencePlanningException("ASEVD136", "Git could not read the exact commit pair.", "Fetch both complete commits into the trusted object store and recapture the change."); + } + + return stdout; + } + catch + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + + throw; + } + } + catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or IOException) + { + throw new EvidencePlanningException("ASEVD136", "The trusted Git process is unavailable.", "Install the pinned Git version and ensure its object store is readable."); + } + } + + private static async Task ReadBoundedAsync(Stream stream, int maximumBytes, CancellationToken cancellationToken) + { + await using var captured = new MemoryStream(); + var buffer = new byte[81920]; + while (true) + { + var request = (int)Math.Min(buffer.Length, maximumBytes - captured.Length + 1); + var count = await stream.ReadAsync(buffer.AsMemory(0, request), cancellationToken).ConfigureAwait(false); + if (count == 0) + { + return captured.ToArray(); + } + + if (captured.Length + count > maximumBytes) + { + throw new EvidencePlanningException("ASEVD134", "Git output exceeds the reviewed gate byte limit.", "Reduce the change or revise the reviewed gate limit and its tests."); + } + + await captured.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs index 892e3fe13..845dbd2a9 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs @@ -20,6 +20,32 @@ public EvidencePlan Resolve(EvidencePolicy policy, IReadOnlyList + /// Resolves a plan for a pull-request gate after verifying that mixed targeted profiles + /// cannot lose requirements when selection falls back to the conservative profile. + /// + /// Versioned consumer policy used by the trusted gate. + /// Explicit normalized changed paths, including both sides of renames. + /// A hash-bound evidence plan whose mixed-profile fallback is validated as a superset. + /// + /// This is an opt-in gate API. + /// and retain their local v1 behavior and do not + /// enforce cross-profile closure. + /// + public EvidencePlan ResolveForGate(EvidencePolicy policy, IReadOnlyList changedPaths) + { + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(changedPaths); + + ValidateGatePolicy(policy); + return ResolveValidated(policy, changedPaths); + } + + private static EvidencePlan ResolveValidated(EvidencePolicy policy, IReadOnlyList changedPaths) + { if (changedPaths.Count == 0) { throw new EvidencePlanningException( @@ -129,6 +155,233 @@ public static void ValidatePolicy(EvidencePolicy policy) } } + /// + /// Validates that a policy's conservative fallback preserves every requirement from each + /// rule-selected targeted profile that may participate in a mixed pull-request diff. + /// + /// Policy to validate before using it for a pull-request gate. + /// + /// The check includes resources and their readiness declarations, producers and their resource + /// wiring, assertions, artifact slots, and obligations. Additional conservative requirements + /// are allowed. Targeted profiles with no evidence requirements, such as an explicit docs-only + /// profile, are valid and contribute no requirements to the superset check. Release profiles + /// are outside this pull-request check and need their own event and eligibility validation. + /// Existing local v1 callers may continue to use . + /// + /// is . + /// The policy is invalid or its conservative profile + /// omits or weakens a targeted profile requirement. + public static void ValidateGatePolicy(EvidencePolicy policy) + { + ValidatePolicy(policy); + + var profiles = policy.Profiles.ToDictionary(static profile => profile.Id, StringComparer.Ordinal); + var conservativeProfile = profiles[policy.ConservativeProfileId]; + if (conservativeProfile.Scope != EvidenceProfileScope.Targeted) + { + throw new EvidencePlanningException( + "ASEVD129", + $"Conservative profile '{conservativeProfile.Id}' is not a targeted pull-request profile.", + "Use a targeted PR policy and validate release profiles only in the protected release context."); + } + + var releaseRule = policy.Rules.FirstOrDefault(rule => profiles[rule.ProfileId].Scope != EvidenceProfileScope.Targeted); + if (releaseRule is not null) + { + throw new EvidencePlanningException( + "ASEVD129", + $"Pull-request gate rule '{releaseRule.Id}' selects non-targeted profile '{releaseRule.ProfileId}'.", + "Map pull-request changes to targeted profiles; select release profiles only from the validated protected release context."); + } + + var targetedProfiles = policy.Rules + .Select(rule => profiles[rule.ProfileId]) + .DistinctBy(static profile => profile.Id, StringComparer.Ordinal) + .Where(profile => !string.Equals(profile.Id, conservativeProfile.Id, StringComparison.Ordinal)) + .OrderBy(static profile => profile.Id, StringComparer.Ordinal); + + foreach (var targetedProfile in targetedProfiles) + { + ValidateConservativeProfileSuperset(conservativeProfile, targetedProfile); + } + } + + private static void ValidateConservativeProfileSuperset(EvidenceProfile conservativeProfile, EvidenceProfile targetedProfile) + { + var difference = FindProfileSupersetDifference(conservativeProfile, targetedProfile); + if (difference is { } missing) + { + throw GatePolicyValidationFailure(conservativeProfile, targetedProfile, missing.Requirement, missing.Detail); + } + } + + /// + /// Finds the first selected requirement that a candidate profile does not preserve. + /// + /// Profile selected by the candidate policy. + /// Previously selected profile whose requirements must remain. + /// The first deterministic difference, or when every requirement is preserved. + /// + /// This comparison is shared by conservative gate-policy validation and the non-claiming policy-shadow + /// validator. It compares resource declarations, producer wiring and assertions, artifact slots, and obligations. + /// + internal static EvidenceProfileRequirementDifference? FindProfileSupersetDifference( + EvidenceProfile candidateProfile, + EvidenceProfile requiredProfile) + { + var candidateResources = candidateProfile.Resources.ToDictionary(static resource => resource.Id, StringComparer.Ordinal); + foreach (var requiredResource in requiredProfile.Resources.OrderBy(static resource => resource.Id, StringComparer.Ordinal)) + { + if (!candidateResources.TryGetValue(requiredResource.Id, out var candidateResource)) + { + return new EvidenceProfileRequirementDifference($"resource '{requiredResource.Id}'", "the declaration is missing"); + } + + if (!string.Equals(candidateResource.Readiness, requiredResource.Readiness, StringComparison.Ordinal) + || candidateResource.DeadlineSeconds > requiredResource.DeadlineSeconds) + { + return new EvidenceProfileRequirementDifference( + $"resource '{requiredResource.Id}'", + "the readiness mode or deadline is weaker than the required declaration"); + } + + var missingDependency = requiredResource.Requires + .Where(dependencyId => !candidateResource.Requires.Contains(dependencyId, StringComparer.Ordinal)) + .OrderBy(static dependencyId => dependencyId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingDependency is not null) + { + return new EvidenceProfileRequirementDifference( + $"resource dependency '{missingDependency}' for resource '{requiredResource.Id}'", + "the dependency is missing"); + } + } + + var candidateProducers = candidateProfile.Producers.ToDictionary(static producer => producer.Id, StringComparer.Ordinal); + foreach (var requiredProducer in requiredProfile.Producers.OrderBy(static producer => producer.Id, StringComparer.Ordinal)) + { + if (!candidateProducers.TryGetValue(requiredProducer.Id, out var candidateProducer)) + { + return new EvidenceProfileRequirementDifference($"producer '{requiredProducer.Id}'", "the declaration is missing"); + } + + if (!string.Equals(candidateProducer.Kind, requiredProducer.Kind, StringComparison.Ordinal) + || !string.Equals(candidateProducer.Version, requiredProducer.Version, StringComparison.Ordinal) + || candidateProducer.TimeoutSeconds > requiredProducer.TimeoutSeconds + || !PreservesCoverageGate(candidateProducer.CoverageGate, requiredProducer.CoverageGate)) + { + return new EvidenceProfileRequirementDifference( + $"producer '{requiredProducer.Id}'", + "the kind, version, deadline, or coverage gate does not preserve the required declaration"); + } + + var missingResource = requiredProducer.RequiredResources + .Where(resourceId => !candidateProducer.RequiredResources.Contains(resourceId, StringComparer.Ordinal)) + .OrderBy(static resourceId => resourceId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingResource is not null) + { + return new EvidenceProfileRequirementDifference( + $"resource '{missingResource}' required by producer '{requiredProducer.Id}'", + "the producer no longer requires it"); + } + + var missingAssertion = requiredProducer.AssertionIds + .Where(assertionId => !candidateProducer.AssertionIds.Contains(assertionId, StringComparer.Ordinal)) + .OrderBy(static assertionId => assertionId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingAssertion is not null) + { + return new EvidenceProfileRequirementDifference( + $"assertion '{missingAssertion}' on producer '{requiredProducer.Id}'", + "the assertion is missing"); + } + + var candidateArtifactSlots = candidateProducer.ArtifactSlots.ToDictionary(static slot => slot.LogicalName, StringComparer.Ordinal); + foreach (var requiredSlot in requiredProducer.ArtifactSlots.OrderBy(static slot => slot.LogicalName, StringComparer.Ordinal)) + { + if (!candidateArtifactSlots.TryGetValue(requiredSlot.LogicalName, out var candidateSlot)) + { + return new EvidenceProfileRequirementDifference( + $"artifact slot '{requiredProducer.Id}/{requiredSlot.LogicalName}'", + "the declaration is missing"); + } + + if (!string.Equals(candidateSlot.RelativeRoot, requiredSlot.RelativeRoot, StringComparison.Ordinal) + || !string.Equals(candidateSlot.MediaType, requiredSlot.MediaType, StringComparison.Ordinal) + || (requiredSlot.Required && !candidateSlot.Required) + || candidateSlot.MaximumBytes > requiredSlot.MaximumBytes) + { + return new EvidenceProfileRequirementDifference( + $"artifact slot '{requiredProducer.Id}/{requiredSlot.LogicalName}'", + "its root, media type, required flag, or byte limit weakens the required declaration"); + } + } + } + + var candidateObligations = candidateProfile.Obligations.ToDictionary(static obligation => obligation.Id, StringComparer.Ordinal); + foreach (var requiredObligation in requiredProfile.Obligations.OrderBy(static obligation => obligation.Id, StringComparer.Ordinal)) + { + if (!candidateObligations.TryGetValue(requiredObligation.Id, out var candidateObligation)) + { + return new EvidenceProfileRequirementDifference($"obligation '{requiredObligation.Id}'", "the declaration is missing"); + } + + if (!string.Equals(candidateObligation.RiskClass, requiredObligation.RiskClass, StringComparison.Ordinal) + || !string.Equals(candidateObligation.Rationale, requiredObligation.Rationale, StringComparison.Ordinal) + || !string.Equals(candidateObligation.RequiredAssertionId, requiredObligation.RequiredAssertionId, StringComparison.Ordinal)) + { + return new EvidenceProfileRequirementDifference( + $"obligation '{requiredObligation.Id}'", + "its risk class, rationale, or required assertion does not preserve the required declaration"); + } + + var missingProducer = requiredObligation.RequiredProducerIds + .Where(producerId => !candidateObligation.RequiredProducerIds.Contains(producerId, StringComparer.Ordinal)) + .OrderBy(static producerId => producerId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingProducer is not null) + { + return new EvidenceProfileRequirementDifference( + $"producer '{missingProducer}' required by obligation '{requiredObligation.Id}'", + "the obligation no longer requires it"); + } + } + + return null; + } + + private static EvidencePlanningException GatePolicyValidationFailure( + EvidenceProfile conservativeProfile, + EvidenceProfile targetedProfile, + string requirement, + string detail) => + new( + "ASEVD129", + $"Conservative profile '{conservativeProfile.Id}' does not preserve {requirement} required by targeted profile '{targetedProfile.Id}': {detail}.", + "Add the missing or equivalent requirement to the conservative profile, or use an explicit combined profile for the pull-request paths."); + + private static bool PreservesCoverageGate( + EvidenceCoverageGateRequirements? candidate, + EvidenceCoverageGateRequirements? required) + { + if (required is null) + { + return true; + } + + return candidate is not null + && candidate.MinLinePercent >= required.MinLinePercent + && candidate.MinBranchPercent >= required.MinBranchPercent + && OptionalThresholdIsPreserved(candidate.MinPatchLinePercent, required.MinPatchLinePercent) + && OptionalThresholdIsPreserved(candidate.MinPatchBranchPercent, required.MinPatchBranchPercent) + && string.Equals(candidate.PatchLineMode, required.PatchLineMode, StringComparison.OrdinalIgnoreCase) + && candidate.TolerancePercent <= required.TolerancePercent; + } + + private static bool OptionalThresholdIsPreserved(decimal? candidate, decimal? required) => + required is null || (candidate is { } candidateValue && candidateValue >= required.Value); + private static void ValidateProfile(EvidenceProfile profile) { if (profile.Resources.Count > EvidenceProfileLimits.MaximumResources @@ -359,6 +612,8 @@ private static void ValidateCoverageGate(string producerId, EvidenceCoverageGate private sealed record RuleCandidate(EvidencePolicyRule Rule, int Specificity); } +internal readonly record struct EvidenceProfileRequirementDifference(string Requirement, string Detail); + /// /// Reads explicit changed paths from a unified diff without depending on a local Git checkout. /// diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePolicyShadowValidator.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePolicyShadowValidator.cs new file mode 100644 index 000000000..c56def73d --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePolicyShadowValidator.cs @@ -0,0 +1,473 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Labels a base-owned path case by its expected repository role. The label is supplied by the +/// fixture owner; it is not inferred from candidate policy rules. +/// +public enum EvidencePolicyShadowFixtureKind +{ + /// Narrative documentation explicitly intended to be documentation-only. + Documentation, + + /// Ordinary executable product or test code. + Code, + + /// A path whose evidence profile requires a disposable or otherwise declared resource. + Resource, + + /// Policy, workflow, runner, gate, or other control-plane material. + ControlPlane, + + /// A path intentionally absent from the policy's recognized path classes. + Unknown, +} + +/// +/// Identifies whether a finding or selection row is associated with trusted base input or candidate-controlled input. +/// +public enum EvidencePolicyShadowFixtureSource +{ + /// The case came from the trusted base-owned fixture set. + Base, + + /// The case was added or changed in candidate fixture data. + Candidate, +} + +/// +/// Describes one expected path selection used by the policy-shadow comparison. +/// +/// Stable fixture identifier, unique within its fixture set. +/// Base-owned classification independent of candidate policy rules. +/// Repository-relative path input, including a previous path for a rename. +public sealed record EvidencePolicyShadowFixture( + string Id, + EvidencePolicyShadowFixtureKind Kind, + NormalizedDiffPath ChangedPath); + +/// +/// Reports the selected profile IDs for one fixture under both policy versions. +/// +/// Whether the fixture is trusted base input or supplemental candidate input. +/// Stable fixture identifier. +/// Fixture classification. +/// The path input resolved under both policies. +/// Profile selected by the trusted base policy. +/// Profile selected by the proposed candidate policy. +public sealed record EvidencePolicyShadowSelection( + EvidencePolicyShadowFixtureSource FixtureSource, + string FixtureId, + EvidencePolicyShadowFixtureKind Kind, + NormalizedDiffPath ChangedPath, + string BaseProfileId, + string CandidateProfileId); + +/// +/// Describes one bounded, non-claiming policy-shadow finding. +/// +/// Stable diagnostic code. +/// Base or candidate side associated with the finding; weakened selections are attributed to the candidate. +/// Stable fixture identifier, if the finding concerns a fixture. +/// Fixture classification, if the finding concerns a fixture. +/// Bounded repository-relative path, if the finding concerns a path. +/// Stable explanatory text without policy claims or exception details. +public sealed record EvidencePolicyShadowDiagnostic( + string Code, + EvidencePolicyShadowFixtureSource FixtureSource, + string? FixtureId, + EvidencePolicyShadowFixtureKind? Kind, + string? Path, + string Message); + +/// +/// Contains a deterministic comparison of base-owned and candidate evidence-policy selections. +/// This result is a shadow-analysis outcome only; it is not a gate verdict or evidence claim. +/// +/// Whether the bounded comparison found no policy or fixture incompatibility. +/// Resolved profile pairs, ordered deterministically and bounded by fixture limits. +/// Stable findings, ordered deterministically and capped at the validator limit. +/// Whether additional findings were omitted after reaching the diagnostic cap. +public sealed record EvidencePolicyShadowResult( + bool IsCompatible, + IReadOnlyList Selections, + IReadOnlyList Diagnostics, + bool DiagnosticsTruncated); + +/// +/// Compares a trusted base gate policy with an untrusted candidate without issuing an EvidenceHost claim. +/// +/// +/// The caller must load the base policy and fixture set from the protected base revision. The validator cannot +/// authenticate input provenance, select a trusted revision, run a workflow, or establish T7 authority. Until +/// a base-owned workflow invokes this API with protected-base inputs and independently enforces its result, the +/// output must not be treated as gate authority. Candidate fixture data is audit-only: an edited or removed +/// candidate case never replaces a base-owned case, while candidate +/// additions and edited variants are checked as supplemental inputs. Both policies must independently pass +/// . Each case is then resolved under both +/// policies and the candidate selection is compared with the base selection, including resource, producer, +/// assertion, artifact-slot, and obligation requirements. +/// +public static class EvidencePolicyShadowValidator +{ + /// Maximum number of base or candidate fixture cases accepted in one input set. + public const int MaximumFixtures = 64; + + /// Maximum number of findings returned by one comparison. + public const int MaximumDiagnostics = 32; + + private const int MaximumProfiles = 64; + private const int MaximumRules = 256; + private const int MaximumFixtureIdentifierLength = 128; + private const int MaximumPathLength = 512; + private const int MaximumChangeKindLength = 32; + + /// + /// Validates old and candidate gate policies against the trusted base fixture set and candidate fixture data. + /// + /// Gate policy loaded from the protected base revision. + /// Proposed policy, treated as untrusted data. + /// Authoritative expected cases loaded from the protected base revision. + /// Candidate case data. It may add checks, but cannot replace base cases. + /// A bounded, deterministic shadow result with no evidence claim or gate verdict. + /// + /// The fixture classifications are supplied by the base-owned case set. A control-plane case must match + /// an explicit rule under both policies; conservative fallback alone is reported so new control-plane + /// paths cannot silently become indistinguishable from unknown paths. Candidate fixture deletions and + /// edits are reported, and the original base case remains in the comparison. + /// + /// An input argument is . + public static EvidencePolicyShadowResult Validate( + EvidencePolicy trustedBasePolicy, + EvidencePolicy candidatePolicy, + IReadOnlyList trustedBaseFixtures, + IReadOnlyList candidateFixtures) + { + ArgumentNullException.ThrowIfNull(trustedBasePolicy); + ArgumentNullException.ThrowIfNull(candidatePolicy); + ArgumentNullException.ThrowIfNull(trustedBaseFixtures); + ArgumentNullException.ThrowIfNull(candidateFixtures); + + var diagnostics = new List(); + var selections = new List(); + + var basePolicyValid = ValidateGatePolicy(trustedBasePolicy, EvidencePolicyShadowFixtureSource.Base, diagnostics); + var candidatePolicyValid = ValidateGatePolicy(candidatePolicy, EvidencePolicyShadowFixtureSource.Candidate, diagnostics); + if (!basePolicyValid || !candidatePolicyValid) + { + return CreateResult(selections, diagnostics); + } + + if (trustedBaseFixtures.Count == 0) + { + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + "ASEPS003", + EvidencePolicyShadowFixtureSource.Base, + null, + null, + null, + "The trusted base fixture set is empty; no policy-shadow comparison was performed.")); + return CreateResult(selections, diagnostics); + } + + if (!TryIndexFixtures(trustedBaseFixtures, EvidencePolicyShadowFixtureSource.Base, diagnostics, out var baseById)) + { + return CreateResult(selections, diagnostics); + } + + var candidateById = new Dictionary(StringComparer.Ordinal); + var candidateFixturesValid = false; + if (candidateFixtures.Count > MaximumFixtures) + { + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + "ASEPS003", + EvidencePolicyShadowFixtureSource.Candidate, + null, + null, + null, + $"Candidate fixture input exceeds the {MaximumFixtures}-case limit; authoritative base cases remain active.")); + candidateById = new Dictionary(StringComparer.Ordinal); + } + else + { + candidateFixturesValid = TryIndexFixtures(candidateFixtures, EvidencePolicyShadowFixtureSource.Candidate, diagnostics, out candidateById); + } + + var cases = new List<(EvidencePolicyShadowFixture Fixture, EvidencePolicyShadowFixtureSource Source)>(); + foreach (var baseFixture in baseById.Values.OrderBy(static fixture => fixture.Id, StringComparer.Ordinal)) + { + cases.Add((baseFixture, EvidencePolicyShadowFixtureSource.Base)); + + if (!candidateFixturesValid) + { + continue; + } + + if (!candidateById.TryGetValue(baseFixture.Id, out var candidateFixture)) + { + diagnostics.Add(CreateFixtureDiagnostic( + "ASEPS004", + EvidencePolicyShadowFixtureSource.Candidate, + baseFixture, + "Candidate fixture data removed this base-owned case; the base case remains authoritative.")); + continue; + } + + if (candidateFixture != baseFixture) + { + diagnostics.Add(CreateFixtureDiagnostic( + "ASEPS004", + EvidencePolicyShadowFixtureSource.Candidate, + candidateFixture, + "Candidate fixture data edited this base-owned case; both the original base case and candidate variant are checked.")); + cases.Add((candidateFixture, EvidencePolicyShadowFixtureSource.Candidate)); + } + } + + if (candidateFixturesValid) + { + foreach (var candidateFixture in candidateById.Values + .Where(fixture => !baseById.ContainsKey(fixture.Id)) + .OrderBy(static fixture => fixture.Id, StringComparer.Ordinal)) + { + cases.Add((candidateFixture, EvidencePolicyShadowFixtureSource.Candidate)); + } + } + + foreach (var (fixture, source) in cases) + { + var basePlan = TryResolve(trustedBasePolicy, fixture, EvidencePolicyShadowFixtureSource.Base, diagnostics); + var candidatePlan = TryResolve(candidatePolicy, fixture, EvidencePolicyShadowFixtureSource.Candidate, diagnostics); + if (basePlan is null || candidatePlan is null) + { + continue; + } + + selections.Add(new EvidencePolicyShadowSelection( + source, + fixture.Id, + fixture.Kind, + basePlan.ChangedPaths[0], + basePlan.Profile.Id, + candidatePlan.Profile.Id)); + + var difference = EvidencePlanner.FindProfileSupersetDifference(candidatePlan.Profile, basePlan.Profile); + if (difference is { } missing) + { + diagnostics.Add(CreateFixtureDiagnostic( + "ASEPS007", + EvidencePolicyShadowFixtureSource.Candidate, + fixture, + $"Candidate selection does not preserve {missing.Requirement}: {missing.Detail}.")); + } + + if (fixture.Kind == EvidencePolicyShadowFixtureKind.ControlPlane) + { + AddUnrecognizedControlPlanePaths(trustedBasePolicy, fixture, EvidencePolicyShadowFixtureSource.Base, diagnostics); + AddUnrecognizedControlPlanePaths(candidatePolicy, fixture, EvidencePolicyShadowFixtureSource.Candidate, diagnostics); + } + } + + return CreateResult(selections, diagnostics); + } + + private static bool ValidateGatePolicy( + EvidencePolicy policy, + EvidencePolicyShadowFixtureSource source, + ICollection diagnostics) + { + if (policy.Profiles is null || policy.Rules is null || policy.Profiles.Count > MaximumProfiles || policy.Rules.Count > MaximumRules) + { + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + source == EvidencePolicyShadowFixtureSource.Base ? "ASEPS001" : "ASEPS002", + source, + null, + null, + null, + $"The {(source == EvidencePolicyShadowFixtureSource.Base ? "base" : "candidate")} gate policy exceeds the bounded policy shape or is incomplete.")); + return false; + } + + try + { + EvidencePlanner.ValidateGatePolicy(policy); + return true; + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NullReferenceException) + { + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + source == EvidencePolicyShadowFixtureSource.Base ? "ASEPS001" : "ASEPS002", + source, + null, + null, + null, + $"The {(source == EvidencePolicyShadowFixtureSource.Base ? "base" : "candidate")} gate policy is invalid; no policy-shadow comparison was performed.")); + return false; + } + } + + private static bool TryIndexFixtures( + IReadOnlyList fixtures, + EvidencePolicyShadowFixtureSource source, + ICollection diagnostics, + out Dictionary fixturesById) + { + fixturesById = new Dictionary(StringComparer.Ordinal); + if (fixtures.Count > MaximumFixtures) + { + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + "ASEPS003", + source, + null, + null, + null, + $"The {(source == EvidencePolicyShadowFixtureSource.Base ? "base" : "candidate")} fixture set exceeds the {MaximumFixtures}-case limit.")); + return false; + } + + var valid = true; + foreach (var fixture in fixtures) + { + if (fixture is null + || string.IsNullOrWhiteSpace(fixture.Id) + || fixture.Id.Length > MaximumFixtureIdentifierLength + || !Enum.IsDefined(fixture.Kind) + || fixture.ChangedPath is null + || !HasBoundedPath(fixture.ChangedPath.Path) + || (fixture.ChangedPath.Kind is not null && fixture.ChangedPath.Kind.Length > MaximumChangeKindLength) + || (fixture.ChangedPath.PreviousPath is not null && !HasBoundedPath(fixture.ChangedPath.PreviousPath))) + { + diagnostics.Add(CreateFixtureDiagnostic( + "ASEPS003", + source, + fixture, + "Fixture data is incomplete or exceeds the bounded identifier/path limits.")); + valid = false; + continue; + } + + if (!fixturesById.TryAdd(fixture.Id, fixture)) + { + diagnostics.Add(CreateFixtureDiagnostic( + "ASEPS003", + source, + fixture, + "Fixture identifiers must be unique within each input set.")); + valid = false; + } + } + + return valid; + } + + private static EvidencePlan? TryResolve( + EvidencePolicy policy, + EvidencePolicyShadowFixture fixture, + EvidencePolicyShadowFixtureSource policySource, + ICollection diagnostics) + { + try + { + return new EvidencePlanner().ResolveForGate(policy, [fixture.ChangedPath]); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NullReferenceException) + { + var side = policySource == EvidencePolicyShadowFixtureSource.Base ? "base" : "candidate"; + diagnostics.Add(CreateFixtureDiagnostic( + policySource == EvidencePolicyShadowFixtureSource.Base ? "ASEPS005" : "ASEPS006", + policySource, + fixture, + $"The {side} policy could not resolve this fixture; no selection comparison was made.")); + return null; + } + } + + private static void AddUnrecognizedControlPlanePaths( + EvidencePolicy policy, + EvidencePolicyShadowFixture fixture, + EvidencePolicyShadowFixtureSource policySource, + ICollection diagnostics) + { + foreach (var path in EnumeratePaths(fixture.ChangedPath)) + { + EvidencePlan? plan; + try + { + plan = new EvidencePlanner().ResolveForGate(policy, [new NormalizedDiffPath(path)]); + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NullReferenceException) + { + continue; + } + + if (!policy.Rules.Any(rule => PathPattern.TryMatch(rule.Pattern, path, out _))) + { + var side = policySource == EvidencePolicyShadowFixtureSource.Base ? "base" : "candidate"; + diagnostics.Add(new EvidencePolicyShadowDiagnostic( + "ASEPS008", + policySource, + Bound(fixture.Id, MaximumFixtureIdentifierLength), + fixture.Kind, + Bound(path, MaximumPathLength), + $"The {side} policy does not explicitly recognize this control-plane path; conservative fallback alone is not a control-plane mapping.")); + } + } + } + + private static IEnumerable EnumeratePaths(NormalizedDiffPath changedPath) + { + yield return changedPath.Path; + if (!string.IsNullOrWhiteSpace(changedPath.PreviousPath)) + { + yield return changedPath.PreviousPath; + } + } + + private static EvidencePolicyShadowDiagnostic CreateFixtureDiagnostic( + string code, + EvidencePolicyShadowFixtureSource source, + EvidencePolicyShadowFixture? fixture, + string message) => + new( + code, + source, + fixture is null ? null : Bound(fixture.Id, MaximumFixtureIdentifierLength), + fixture is null || !Enum.IsDefined(fixture.Kind) ? null : fixture.Kind, + fixture?.ChangedPath is null ? null : Bound(fixture.ChangedPath.Path, MaximumPathLength), + message); + + private static bool HasBoundedPath(string? path) => + !string.IsNullOrWhiteSpace(path) && path.Length <= MaximumPathLength; + + private static string Bound(string? value, int maximumLength) => + string.IsNullOrEmpty(value) || value.Length <= maximumLength + ? value ?? string.Empty + : string.Concat(value.AsSpan(0, maximumLength - 1), "…"); + + private static EvidencePolicyShadowResult CreateResult( + IReadOnlyCollection selections, + IReadOnlyCollection diagnostics) + { + var orderedSelections = selections + .OrderBy(static selection => selection.FixtureSource) + .ThenBy(static selection => selection.FixtureId, StringComparer.Ordinal) + .ThenBy(static selection => selection.ChangedPath.Path, StringComparer.Ordinal) + .ThenBy(static selection => selection.ChangedPath.PreviousPath, StringComparer.Ordinal) + .ToArray(); + var orderedDiagnostics = diagnostics + .OrderBy(static diagnostic => diagnostic.Code, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.FixtureSource) + .ThenBy(static diagnostic => diagnostic.FixtureId, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.Path, StringComparer.Ordinal) + .ThenBy(static diagnostic => diagnostic.Message, StringComparer.Ordinal) + .ToArray(); + var truncated = orderedDiagnostics.Length > MaximumDiagnostics; + var boundedDiagnostics = orderedDiagnostics.Take(MaximumDiagnostics).ToArray(); + return new EvidencePolicyShadowResult( + IsCompatible: orderedDiagnostics.Length == 0, + Selections: orderedSelections, + Diagnostics: boundedDiagnostics, + DiagnosticsTruncated: truncated); + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs new file mode 100644 index 000000000..c40529be8 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs @@ -0,0 +1,1132 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ForgeTrust.AppSurface.Evidence.Contracts; +using Microsoft.Win32.SafeHandles; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Identifies the pull request and subject job expected by the trusted controller. +/// +/// Canonical base repository in owner/name form. +/// Validated workflow event name. +/// Controller-owned workflow identity. +/// Controller-owned subject job identity. +/// Controller-owned numeric repository, PR, run, and attempt identity. +public sealed record EvidencePullRequestGateExpectedIdentity( + string Repository, + string EventName, + string WorkflowId, + string SubjectJobId, + EvidencePullRequestRunIdentity RunIdentity); + +/// +/// Reports one fresh PR view and the authoritative provenance of its subject job. +/// +/// Base repository containing the pull request. +/// Event that created the workflow run. +/// Current target-branch commit ID. +/// Current pull request head commit ID. +/// Workflow associated with the subject job. +/// Authoritative PR, repository, run, and attempt identity. +/// Subject job identity. +/// Commit independently attested as the subject job checkout, or an empty string when no checkout was attested. Only an explicitly empty profile may be eligible in the latter case. +/// Authoritative terminal job conclusion. +/// Whether an independent trusted observation confirmed the subject job's isolation envelope. +public sealed record EvidencePullRequestGateAuthoritySnapshot( + string Repository, + string EventName, + string BaseRevision, + string HeadRevision, + string WorkflowId, + EvidencePullRequestRunIdentity RunIdentity, + string SubjectJobId, + string SubjectJobHeadRevision, + string SubjectJobConclusion, + bool SubjectEnvelopeAttested = false); + +/// Describes one matched trusted policy rule in a bounded gate result. +/// Trusted policy rule identifier, or the bounded conservative-fallback identifier. +/// Trusted policy pattern, or a fixed conservative-fallback description. +/// Trusted profile selected by the rule. +public sealed record EvidencePullRequestGateRuleSummary(string Id, string Pattern, string ProfileId); + +/// Describes why one trusted obligation was selected. +/// Trusted obligation identifier. +/// Trusted obligation risk class. +/// Trusted policy rationale, bounded for rendering. +public sealed record EvidencePullRequestGateObligationRationale(string Id, string RiskClass, string Rationale); + +/// +/// Bounded rendering data derived from the plan independently verified against trusted policy and Git. +/// +/// Selected profile identifier from the verified plan. +/// Fixed explanation of direct-rule or conservative-fallback selection. +/// Bounded matched-rule details from trusted policy. +/// Bounded identifiers selected by the verified profile. +/// Bounded verified closure identifiers that are also selected by the verified profile. +/// Bounded selected identifiers not independently closed by validated producer assertions. +/// Bounded trusted rationale for selected obligations. +/// First 12 characters of the verified base object ID. +/// First 12 characters of the verified head object ID. +/// Number of matched rules omitted from this rendering summary. +/// Number of selected obligation IDs omitted from this summary. +/// Number of closed obligation IDs omitted from this summary. +/// Number of missing obligation IDs omitted from this summary. +/// Number of obligation rationales omitted from this summary. +/// Whether the verified profile selects a resource, producer, or obligation. +public sealed record EvidencePullRequestGateSummary( + string ProfileId, + string SelectionRationale, + IReadOnlyList MatchedRules, + IReadOnlyList SelectedObligationIds, + IReadOnlyList ClosedObligationIds, + IReadOnlyList MissingObligationIds, + IReadOnlyList ObligationRationales, + string BaseRevisionShort, + string HeadRevisionShort, + int OmittedMatchedRuleCount, + int OmittedSelectedObligationCount, + int OmittedClosedObligationCount, + int OmittedMissingObligationCount, + int OmittedObligationRationaleCount, + bool ProfileHasEvidence); + +/// +/// Provides an authoritative, fresh PR revision and subject-job provenance observation. +/// +public interface IEvidencePullRequestGateAuthorityProvider +{ + /// + /// Reads the current PR target/head and the run/job association for the expected controller context. + /// + /// Identity captured by the trusted controller. + /// Cancellation for the authority lookup. + /// A fresh observation, or when it is unavailable. + Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default); +} + +/// +/// Verifies the bytes behind manifest artifact metadata using the trusted extracted-artifact root. +/// +/// +/// Implementations must open artifacts without following links, enforce the declared artifact roots, +/// and hash the bytes actually read. Returning asserts that every artifact +/// record in the manifest matches its declared logical slot, media type, length, and digest. The gate +/// never treats manifest metadata alone as byte proof. +/// +public interface IEvidencePullRequestGateArtifactVerifier +{ + /// Verifies artifact bytes associated with one independently verified plan. + /// Controller-owned extracted-artifact handoff directory. + /// Plan already recreated from trusted policy and exact Git objects. + /// Bounded manifest whose artifact bytes must be checked. + /// Cancellation for bounded no-follow reads. + /// only when all artifact records are confirmed from bytes. + Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default); +} + +/// +/// Verifies declared artifact bytes by opening every path beneath a trusted handoff root without following links. +/// +/// +/// This implementation requires Linux x64 or arm64 with openat2 and statx. It fails closed on other +/// platforms or when those kernel facilities are unavailable. The supplied root must be a controller-owned +/// directory containing one subdirectory per producer, matching the EvidenceHost artifact layout. +/// +public sealed class EvidencePullRequestGateNoFollowArtifactVerifier : IEvidencePullRequestGateArtifactVerifier +{ + private const long OpenAt2SyscallNumber = 437; + private const ulong OpenReadOnly = 0; + private const ulong OpenCloseOnExec = 0x0008_0000; + private const ulong OpenNoFollowX64 = 0x0002_0000; + private const ulong OpenNoFollowArm64 = 0x0000_8000; + private const ulong OpenNonBlocking = 0x0000_0800; + private const ulong OpenNoControllingTerminal = 0x0000_0100; + private const ulong OpenDirectoryX64 = 0x0001_0000; + private const ulong OpenDirectoryArm64 = 0x0000_4000; + private static ulong OpenNoFollow => RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? OpenNoFollowArm64 : OpenNoFollowX64; + private static ulong OpenDirectory => RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? OpenDirectoryArm64 : OpenDirectoryX64; + private const ulong ResolveNoMagicLinks = 0x02; + private const ulong ResolveNoSymlinks = 0x04; + private const ulong ResolveBeneath = 0x08; + private const int AtEmptyPath = 0x1000; + private const uint StatxBasicStats = 0x07ff; + private const uint StatxRequiredMask = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9); + private const ushort FileTypeMask = 0xf000; + private const ushort RegularFileType = 0x8000; + private const ushort DirectoryFileType = 0x4000; + private const int MaximumFiles = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount; + private const long MaximumTotalBytes = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedTotalBytes; + private const int StreamBufferSize = 81_920; + + /// + public async Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(trustedArtifactHandoffRootPath); + ArgumentNullException.ThrowIfNull(verifiedPlan); + ArgumentNullException.ThrowIfNull(candidateManifest); + cancellationToken.ThrowIfCancellationRequested(); + + if (!OperatingSystem.IsLinux() || RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + return false; + } + + try + { + using var rootHandle = OpenTrustedRoot(trustedArtifactHandoffRootPath); + var rootSnapshot = ReadSnapshot(rootHandle); + if ((rootSnapshot.Mode & FileTypeMask) != DirectoryFileType) + { + return false; + } + + var producerResults = candidateManifest.ProducerResults + .GroupBy(static result => result.ProducerId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (producerResults.Count != candidateManifest.ProducerResults.Count) + { + return false; + } + + var verifiedFiles = 0; + long totalBytes = 0; + var identities = new HashSet(); + foreach (var producer in verifiedPlan.Profile.Producers) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!producerResults.TryGetValue(producer.Id, out var result) + || !EvidenceArtifactValidation.AreValid(producer, result.Artifacts)) + { + return false; + } + + foreach (var artifact in result.Artifacts ?? []) + { + cancellationToken.ThrowIfCancellationRequested(); + if (++verifiedFiles > MaximumFiles + || !TryGetDeclaredSlot(producer, artifact, out var slot) + || !TryGetCanonicalArtifactPath(producer.Id, artifact.RelativePath, out var relativePath)) + { + return false; + } + + using var fileHandle = OpenRelative(rootHandle, relativePath); + var before = ReadSnapshot(fileHandle); + if ((before.Mode & FileTypeMask) != RegularFileType + || before.LinkCount != 1 + || before.Size > long.MaxValue + || (long)before.Size != artifact.LengthBytes + || artifact.LengthBytes > slot.MaximumBytes + || !identities.Add(before.Identity) + || artifact.LengthBytes > MaximumTotalBytes - totalBytes) + { + return false; + } + + totalBytes += artifact.LengthBytes; + var actualDigest = await HashExactBytesAsync(fileHandle, artifact.LengthBytes, cancellationToken).ConfigureAwait(false); + var after = ReadSnapshot(fileHandle); + if (!before.Equals(after) + || !string.Equals(actualDigest, artifact.Sha256, StringComparison.Ordinal)) + { + return false; + } + } + } + + return producerResults.Keys.All(producerId => verifiedPlan.Profile.Producers.Any(producer => producer.Id == producerId)); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception) + { + return false; + } + } + + private static bool TryGetDeclaredSlot( + EvidenceProducerDeclaration producer, + EvidenceArtifactResult artifact, + out EvidenceArtifactSlot slot) + { + slot = producer.ArtifactSlots.FirstOrDefault(candidate => candidate.LogicalName == artifact.LogicalName)!; + if (slot is null + || artifact.LengthBytes < 0 + || artifact.LengthBytes > slot.MaximumBytes + || !string.Equals(artifact.MediaType, slot.MediaType, StringComparison.Ordinal)) + { + return false; + } + + try + { + EvidenceArtifactValidation.ValidatePathForSlot(slot, artifact.RelativePath); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + private static bool TryGetCanonicalArtifactPath(string producerId, string relativePath, out string artifactPath) + { + artifactPath = string.Empty; + if (producerId.Length == 0 + || relativePath.Length == 0 + || producerId.Contains('\\') + || relativePath.Contains('\\') + || producerId.Any(char.IsControl) + || relativePath.Any(char.IsControl)) + { + return false; + } + + try + { + artifactPath = $"{producerId}/{relativePath}"; + var normalized = EvidenceArtifactValidation.NormalizeRelativePath(artifactPath); + return string.Equals(normalized, artifactPath, StringComparison.Ordinal) + && System.Text.Encoding.UTF8.GetByteCount(artifactPath) <= EvidenceGitChangeCapture.MaximumPathBytes; + } + catch (ArgumentException) + { + return false; + } + } + + private static async Task HashExactBytesAsync( + SafeFileHandle fileHandle, + long expectedLength, + CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[StreamBufferSize]; + long total = 0; + while (true) + { + var read = await RandomAccess.ReadAsync(fileHandle, buffer.AsMemory(), total, cancellationToken).ConfigureAwait(false); + if (read == 0) + { + break; + } + + if (read > expectedLength - total) + { + throw new InvalidDataException("Artifact bytes exceed the declared length."); + } + + total += read; + hash.AppendData(buffer, 0, read); + } + + if (total != expectedLength) + { + throw new InvalidDataException("Artifact bytes do not match the declared length."); + } + + return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + } + + private static SafeFileHandle OpenTrustedRoot(string rootPath) + { + var fullPath = Path.GetFullPath(rootPath); + if (!Path.IsPathFullyQualified(fullPath) || !fullPath.StartsWith(Path.DirectorySeparatorChar)) + { + throw new ArgumentException("The artifact handoff root must be an absolute Linux path.", nameof(rootPath)); + } + + var anchorDescriptor = OpenDirectoryPath("/"); + using var anchor = new SafeFileHandle(new IntPtr(anchorDescriptor), ownsHandle: true); + var relativeRoot = fullPath[1..]; + if (relativeRoot.Length == 0) + { + return OpenDirectoryPathHandle("/"); + } + + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal | OpenDirectory, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + return new SafeFileHandle(new IntPtr(InvokeOpenAt2(anchor.DangerousGetHandle().ToInt32(), relativeRoot, ref how)), ownsHandle: true); + } + + private static SafeFileHandle OpenRelative(SafeFileHandle rootHandle, string relativePath) + { + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + return new SafeFileHandle(new IntPtr(InvokeOpenAt2(rootHandle.DangerousGetHandle().ToInt32(), relativePath, ref how)), ownsHandle: true); + } + + private static int OpenDirectoryPath(string path) + { + var descriptor = OpenDirectoryNative(path, OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenDirectory); + if (descriptor < 0) + { + throw new IOException("The trusted artifact root could not be opened."); + } + + return descriptor; + } + + private static SafeFileHandle OpenDirectoryPathHandle(string path) => + new(new IntPtr(OpenDirectoryPath(path)), ownsHandle: true); + + private static int InvokeOpenAt2(int rootDescriptor, string relativePath, ref LinuxOpenHow how) + { + var pathPointer = Marshal.StringToCoTaskMemUTF8(relativePath); + try + { + var result = Syscall(OpenAt2SyscallNumber, rootDescriptor, pathPointer, ref how, (nuint)Marshal.SizeOf()); + if (result >= 0 && result <= int.MaxValue) + { + return (int)result; + } + + throw new IOException("Linux refused the no-follow artifact path."); + } + finally + { + Marshal.FreeCoTaskMem(pathPointer); + } + } + + private static FileSnapshot ReadSnapshot(SafeFileHandle handle) + { + if (Statx(handle.DangerousGetHandle().ToInt32(), string.Empty, AtEmptyPath, StatxBasicStats, out var statx) != 0 + || (statx.Mask & StatxRequiredMask) != StatxRequiredMask) + { + throw new IOException("Linux could not inspect the opened artifact safely."); + } + + return new FileSnapshot( + statx.DeviceMajor, + statx.DeviceMinor, + statx.Inode, + statx.Mode, + statx.LinkCount, + statx.Size, + statx.ModifyTime.Seconds, + statx.ModifyTime.Nanoseconds, + statx.ChangeTime.Seconds, + statx.ChangeTime.Nanoseconds); + } + + private static int OpenDirectoryNative(string path, ulong flags) => OpenNative(path, checked((int)flags)); + + [DllImport("libc", EntryPoint = "open", SetLastError = true)] + private static extern int OpenNative([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags); + + [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] + private static extern long Syscall(long number, int directoryDescriptor, IntPtr path, ref LinuxOpenHow how, nuint size); + + [DllImport("libc", EntryPoint = "statx", SetLastError = true)] + private static extern int Statx( + int directoryDescriptor, + [MarshalAs(UnmanagedType.LPUTF8Str)] string path, + int flags, + uint mask, + out LinuxStatx statx); + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxOpenHow + { + public ulong Flags; + public ulong Mode; + public ulong Resolve; + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxStatxTimestamp + { + public long Seconds; + public uint Nanoseconds; + private int _reserved; + } + + [StructLayout(LayoutKind.Sequential, Size = 256)] + private struct LinuxStatx + { + public uint Mask; + private uint _blockSize; + private ulong _attributes; + public uint LinkCount; + private uint _userId; + private uint _groupId; + public ushort Mode; + private ushort _spare0; + public ulong Inode; + public ulong Size; + private ulong _blocks; + private ulong _attributesMask; + private LinuxStatxTimestamp _accessTime; + private LinuxStatxTimestamp _birthTime; + public LinuxStatxTimestamp ChangeTime; + public LinuxStatxTimestamp ModifyTime; + private uint _rdevMajor; + private uint _rdevMinor; + public uint DeviceMajor; + public uint DeviceMinor; + private ulong _mountId; + private uint _dioMemoryAlignment; + private uint _dioOffsetAlignment; + private ulong _spare1; + private ulong _spare2; + private ulong _spare3; + private ulong _spare4; + private ulong _spare5; + private ulong _spare6; + private ulong _spare7; + private ulong _spare8; + private ulong _spare9; + private ulong _spare10; + private ulong _spare11; + private ulong _spare12; + } + + private readonly record struct FileIdentity(uint DeviceMajor, uint DeviceMinor, ulong Inode); + + private readonly record struct FileSnapshot( + uint DeviceMajor, + uint DeviceMinor, + ulong Inode, + ushort Mode, + uint LinkCount, + ulong Size, + long ModifySeconds, + uint ModifyNanoseconds, + long ChangeSeconds, + uint ChangeNanoseconds) + { + public FileIdentity Identity => new(DeviceMajor, DeviceMinor, Inode); + } +} + +/// +/// Returns a bounded PR-gate result without including untrusted manifest or provider diagnostics. +/// +/// Whether the current PR may consume the evidence as a passing gate. +/// Stable diagnostic code. +/// Fixed, secret-safe diagnostic text. +/// Bounded summary after independent plan verification; absent on pre-plan failures. +public sealed record EvidencePullRequestGateVerificationResult( + bool IsEligible, + string Code, + string Diagnostic, + EvidencePullRequestGateSummary? Summary = null); + +/// +/// Independently verifies revision-bound PR evidence at the trusted controller boundary. +/// +/// +/// The policy and Git object store are trusted inputs supplied separately from the untrusted plan +/// and manifest. The verifier recreates the v2 plan from exact Git objects, checks manifest +/// self-consistency and every selected obligation, then reads authoritative PR and job state just +/// before returning. It never uses the plan's policy snapshot or revision values as authority. +/// +public static class EvidencePullRequestGateVerifier +{ + /// Maximum canonical plan or manifest size accepted by this verifier. + public const int MaximumContractBytes = 4 * 1024 * 1024; + + /// Maximum aggregate UTF-16 text units traversed in an input contract. + public const int MaximumContractTextUnits = 1 * 1024 * 1024; + + /// Maximum time allowed for the final authoritative provider lookup. + public const int MaximumAuthorityReadSeconds = 10; + + /// Maximum time allowed for trusted no-follow artifact byte verification. + public const int MaximumArtifactVerificationSeconds = 120; + + /// Maximum number of identifiers or rationale entries returned in a rendering summary. + public const int MaximumSummaryItems = 64; + + private static readonly EvidencePullRequestGateVerificationResult InvalidIdentity = + Failure("ASEVG001", "The trusted controller identity is invalid."); + private static readonly EvidencePullRequestGateVerificationResult InvalidPlan = + Failure("ASEVG002", "The supplied plan is missing, oversized, or is not revision-bound v2 evidence."); + private static readonly EvidencePullRequestGateVerificationResult PlanMismatch = + Failure("ASEVG003", "The plan does not match the trusted policy and exact Git change."); + private static readonly EvidencePullRequestGateVerificationResult InvalidManifest = + Failure("ASEVG004", "The manifest is invalid, incomplete, or does not close every selected obligation and cleanup requirement."); + private static readonly EvidencePullRequestGateVerificationResult NotGateEligible = + Failure("ASEVG005", "The evidence claim is observational, out of scope, or not eligible for a pull-request gate."); + private static readonly EvidencePullRequestGateVerificationResult AuthorityUnavailable = + Failure("ASEVG006", "Fresh pull-request or subject-job authority could not be verified."); + private static readonly EvidencePullRequestGateVerificationResult AuthorityMismatch = + Failure("ASEVG007", "The current pull request or subject-job provenance does not match this evidence run."); + private static readonly EvidencePullRequestGateVerificationResult Cancelled = + Failure("ASEVG008", "Pull-request evidence verification was cancelled."); + private static readonly EvidencePullRequestGateVerificationResult ArtifactVerifierUnavailable = + Failure("ASEVG009", "Trusted artifact byte verification is unavailable for this nonempty evidence profile."); + private static readonly EvidencePullRequestGateVerificationResult ArtifactVerificationFailed = + Failure("ASEVG010", "One or more extracted evidence artifacts could not be verified from bytes."); + private static readonly EvidencePullRequestGateVerificationResult Eligible = + new(true, "ASEVG000", "The current pull request has complete, revision-bound, gate-eligible evidence."); + + /// + /// Verifies untrusted plan and manifest values against controller-owned policy, Git objects, + /// and a final authoritative observation of the pull request and subject job. + /// + /// Trusted evidence planner. + /// Policy loaded from the protected base revision. + /// Trusted object store containing the exact PR commits. + /// PR, workflow run, and subject-job identity captured by the controller. + /// Provider for fresh current PR revisions and job provenance. + /// Trusted extracted-artifact root, or only for an empty profile. + /// Trusted no-follow artifact verifier; required for nonempty profiles. + /// Plan received through the subject-job handoff. + /// Manifest received through the subject-job handoff. + /// Cancellation for Git and authority operations. + /// A bounded result with fixed diagnostics and no raw untrusted output. + public static async Task VerifyAsync( + EvidencePlanner planner, + EvidencePolicy trustedBaseOwnedPolicy, + string trustedGitObjectStorePath, + EvidencePullRequestGateExpectedIdentity expectedIdentity, + IEvidencePullRequestGateAuthorityProvider authorityProvider, + string? trustedArtifactHandoffRootPath, + IEvidencePullRequestGateArtifactVerifier? artifactVerifier, + EvidencePlan untrustedPlan, + EvidenceManifest untrustedManifest, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(trustedBaseOwnedPolicy); + ArgumentException.ThrowIfNullOrWhiteSpace(trustedGitObjectStorePath); + ArgumentNullException.ThrowIfNull(expectedIdentity); + ArgumentNullException.ThrowIfNull(authorityProvider); + + if (!HasValidExpectedIdentity(expectedIdentity)) + { + return InvalidIdentity; + } + + try + { + if (untrustedPlan is null + || untrustedManifest is null + || !string.Equals(untrustedPlan.ContractVersion, "2.0", StringComparison.Ordinal) + || !HasValidRevision(untrustedPlan.BaseRevision) + || !HasValidRevision(untrustedPlan.HeadRevision) + || untrustedPlan.BaseRevision!.Length != untrustedPlan.HeadRevision!.Length + || !IsBoundedPlan(untrustedPlan) + || !IsBoundedManifest(untrustedManifest)) + { + return InvalidPlan; + } + } + catch (Exception) + { + return InvalidPlan; + } + + if (!Equals(untrustedPlan.PullRequestRunIdentity, expectedIdentity.RunIdentity)) + { + return AuthorityMismatch; + } + + if (!Equals(untrustedManifest.PullRequestRunIdentity, expectedIdentity.RunIdentity)) + { + return InvalidManifest; + } + + try + { + await EvidenceRevisionPlanBuilder.VerifyAsync( + planner, + trustedBaseOwnedPolicy, + trustedGitObjectStorePath, + untrustedPlan, + cancellationToken, + expectedIdentity.RunIdentity).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Cancelled; + } + catch (Exception) + { + return PlanMismatch; + } + + bool manifestIsConsistent; + try + { + manifestIsConsistent = EvidenceManifestBuilder.Verify(untrustedPlan, untrustedManifest); + } + catch (Exception) + { + return InvalidManifest; + } + + if (!manifestIsConsistent) + { + return WithSummary(InvalidManifest, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, false, false); + } + + if (untrustedManifest.ClaimKind == EvidenceClaimKind.ObservationOnly) + { + return WithSummary(NotGateEligible, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + var hasEmptyProfile = IsEmptyProfile(untrustedPlan.Profile); + var artifactsVerified = hasEmptyProfile; + if (!hasEmptyProfile) + { + if (string.IsNullOrWhiteSpace(trustedArtifactHandoffRootPath)) + { + return WithSummary(ArtifactVerifierUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + if (artifactVerifier is null) + { + return WithSummary(ArtifactVerifierUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + using var artifactDeadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + artifactDeadline.CancelAfter(TimeSpan.FromSeconds(MaximumArtifactVerificationSeconds)); + try + { + artifactsVerified = await artifactVerifier.VerifyArtifactsAsync( + trustedArtifactHandoffRootPath, + untrustedPlan, + untrustedManifest, + artifactDeadline.Token) + .WaitAsync(TimeSpan.FromSeconds(MaximumArtifactVerificationSeconds), cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return WithSummary(Cancelled, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + catch (Exception) + { + return WithSummary(ArtifactVerificationFailed, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + if (!artifactsVerified) + { + return WithSummary(ArtifactVerificationFailed, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + } + + if (!HasCompleteGateEvidence(untrustedPlan, untrustedManifest)) + { + return WithSummary(InvalidManifest, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + + EvidencePullRequestGateAuthoritySnapshot? authority; + using (var authorityDeadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + authorityDeadline.CancelAfter(TimeSpan.FromSeconds(MaximumAuthorityReadSeconds)); + try + { + authority = await authorityProvider.ReadFreshAsync(expectedIdentity, authorityDeadline.Token) + .WaitAsync(TimeSpan.FromSeconds(MaximumAuthorityReadSeconds), cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Cancelled; + } + catch (Exception) + { + return WithSummary(AuthorityUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + } + + if (authority is null) + { + return WithSummary(AuthorityUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + + return WithSummary( + MatchesCurrentAuthority(expectedIdentity, authority, untrustedPlan, untrustedManifest) ? Eligible : AuthorityMismatch, + untrustedPlan, + trustedBaseOwnedPolicy, + untrustedManifest, + true, + artifactsVerified); + } + + private static EvidencePullRequestGateVerificationResult WithSummary( + EvidencePullRequestGateVerificationResult result, + EvidencePlan verifiedPlan, + EvidencePolicy trustedPolicy, + EvidenceManifest candidateManifest, + bool manifestIsConsistent, + bool artifactsVerified) => + result with + { + Summary = CreateSummary(verifiedPlan, trustedPolicy, candidateManifest, manifestIsConsistent, artifactsVerified), + }; + + private static EvidencePullRequestGateSummary CreateSummary( + EvidencePlan verifiedPlan, + EvidencePolicy trustedPolicy, + EvidenceManifest candidateManifest, + bool manifestIsConsistent, + bool artifactsVerified) + { + var selected = verifiedPlan.Profile.Obligations + .Select(static obligation => obligation.Id) + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray(); + var closed = manifestIsConsistent && artifactsVerified + ? verifiedPlan.Profile.Obligations + .Where(obligation => obligation.RequiredProducerIds.All(producerId => + candidateManifest.ProducerResults.Any(result => result.ProducerId == producerId + && result.Outcome == EvidenceProducerOutcome.Passed + && result.SatisfiedAssertionIds.Contains(obligation.RequiredAssertionId, StringComparer.Ordinal)))) + .Select(static obligation => obligation.Id) + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray() + : []; + var missing = selected.Except(closed, StringComparer.Ordinal).OrderBy(static id => id, StringComparer.Ordinal).ToArray(); + + var matchedRules = verifiedPlan.MatchedRuleIds + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .Select(id => CreateRuleSummary(id, trustedPolicy)) + .Where(static rule => rule is not null) + .Select(static rule => rule!) + .ToArray(); + var rationales = verifiedPlan.Profile.Obligations + .OrderBy(static obligation => obligation.Id, StringComparer.Ordinal) + .Select(static obligation => new EvidencePullRequestGateObligationRationale( + obligation.Id, + obligation.RiskClass, + Truncate(obligation.Rationale, 256))) + .ToArray(); + + var fallbackId = $"conservative:{trustedPolicy.ConservativeProfileId}"; + return new EvidencePullRequestGateSummary( + verifiedPlan.Profile.Id, + verifiedPlan.MatchedRuleIds.Contains(fallbackId, StringComparer.Ordinal) ? "conservative-fallback" : "matched-policy-rules", + TakeBounded(matchedRules, out var omittedRules), + TakeBounded(selected, out var omittedSelected), + TakeBounded(closed, out var omittedClosed), + TakeBounded(missing, out var omittedMissing), + TakeBounded(rationales, out var omittedRationales), + verifiedPlan.BaseRevision![..12], + verifiedPlan.HeadRevision![..12], + omittedRules, + omittedSelected, + omittedClosed, + omittedMissing, + omittedRationales, + !IsEmptyProfile(verifiedPlan.Profile)); + } + + private static EvidencePullRequestGateRuleSummary? CreateRuleSummary(string ruleId, EvidencePolicy trustedPolicy) + { + var rule = trustedPolicy.Rules.FirstOrDefault(candidate => string.Equals(candidate.Id, ruleId, StringComparison.Ordinal)); + if (rule is not null) + { + return new EvidencePullRequestGateRuleSummary(rule.Id, Truncate(rule.Pattern, 256), rule.ProfileId); + } + + var fallbackId = $"conservative:{trustedPolicy.ConservativeProfileId}"; + return string.Equals(ruleId, fallbackId, StringComparison.Ordinal) + ? new EvidencePullRequestGateRuleSummary(ruleId, "conservative fallback", trustedPolicy.ConservativeProfileId) + : null; + } + + private static IReadOnlyList TakeBounded(IReadOnlyList values, out int omittedCount) + { + omittedCount = Math.Max(0, values.Count - MaximumSummaryItems); + return Array.AsReadOnly(values.Take(MaximumSummaryItems).ToArray()); + } + + private static string Truncate(string value, int maximumLength) => value.Length <= maximumLength + ? value + : value[..maximumLength]; + + private static bool IsEmptyProfile(EvidenceProfile profile) => + profile.Resources.Count == 0 && profile.Producers.Count == 0 && profile.Obligations.Count == 0; + + private static bool HasCompleteGateEvidence(EvidencePlan plan, EvidenceManifest manifest) + { + if (plan.Profile.Scope != EvidenceProfileScope.Targeted + || manifest.ContractVersion != "2.0" + || manifest.ExecutionVerdict != EvidenceExecutionVerdict.Passed + || manifest.Eligibility != EvidenceClaimEligibility.PullRequestGate + || manifest.EnvelopeStatus is EvidenceEnvelopeStatus.Unavailable or EvidenceEnvelopeStatus.Invalid + || !manifest.Metrics.CleanupCompleted + || manifest.Metrics.PlanningMilliseconds < 0 + || manifest.Metrics.ResourceReadinessMilliseconds < 0 + || manifest.Metrics.ProducerMilliseconds < 0 + || manifest.Metrics.CleanupMilliseconds < 0 + || manifest.Metrics.TotalMilliseconds < 0) + { + return false; + } + + var noEvidenceRequired = plan.Profile.Resources.Count == 0 + && plan.Profile.Producers.Count == 0 + && plan.Profile.Obligations.Count == 0; + if (manifest.EnvelopeStatus != (noEvidenceRequired + ? EvidenceEnvelopeStatus.NotRequired + : EvidenceEnvelopeStatus.ValidatedNotAttested)) + { + return false; + } + + var requiredClaim = noEvidenceRequired ? EvidenceClaimKind.NoEvidenceRequired : EvidenceClaimKind.TargetedComplete; + if (manifest.ClaimKind != requiredClaim) + { + return false; + } + + var expectedObligations = plan.Profile.Obligations + .Select(static obligation => obligation.Id) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray(); + if (!manifest.SelectedObligationIds.SequenceEqual(expectedObligations, StringComparer.Ordinal) + || !manifest.ClosedObligationIds.SequenceEqual(expectedObligations, StringComparer.Ordinal) + || manifest.UnmediatedObligationIds.Count != 0) + { + return false; + } + + var resourceResults = manifest.ResourceResults + .GroupBy(static result => result.ResourceId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (resourceResults.Count != plan.Profile.Resources.Count + || plan.Profile.Resources.Any(resource => + !resourceResults.TryGetValue(resource.Id, out var result) + || result.Outcome != EvidenceResourceOutcome.Ready + || result.ElapsedMilliseconds < 0)) + { + return false; + } + + var producerResults = manifest.ProducerResults + .GroupBy(static result => result.ProducerId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (producerResults.Count != plan.Profile.Producers.Count + || plan.Profile.Producers.Any(producer => + !producerResults.TryGetValue(producer.Id, out var result) + || result.Outcome != EvidenceProducerOutcome.Passed + || result.ElapsedMilliseconds < 0 + || !EvidenceArtifactValidation.AreValid(producer, result.Artifacts))) + { + return false; + } + + return plan.Profile.Obligations.All(obligation => obligation.RequiredProducerIds.All(producerId => + producerResults.TryGetValue(producerId, out var result) + && result.Outcome == EvidenceProducerOutcome.Passed + && result.SatisfiedAssertionIds.Contains(obligation.RequiredAssertionId, StringComparer.Ordinal))); + } + + private static bool MatchesCurrentAuthority( + EvidencePullRequestGateExpectedIdentity expected, + EvidencePullRequestGateAuthoritySnapshot current, + EvidencePlan plan, + EvidenceManifest manifest) => + current.RunIdentity is not null + && current.RunIdentity.HeadRepositoryId == current.RunIdentity.RepositoryId + && string.Equals(current.Repository, expected.Repository, StringComparison.OrdinalIgnoreCase) + && string.Equals(current.EventName, expected.EventName, StringComparison.Ordinal) + && Equals(current.RunIdentity, expected.RunIdentity) + && Equals(plan.PullRequestRunIdentity, current.RunIdentity) + && Equals(plan.PullRequestRunIdentity, expected.RunIdentity) + && current.BaseRevision == plan.BaseRevision + && current.HeadRevision == plan.HeadRevision + && string.Equals(current.WorkflowId, expected.WorkflowId, StringComparison.Ordinal) + && string.Equals(current.SubjectJobId, expected.SubjectJobId, StringComparison.Ordinal) + && (IsEmptyProfile(plan.Profile) + || (current.SubjectJobHeadRevision == plan.HeadRevision && current.SubjectEnvelopeAttested)) + && string.Equals(current.SubjectJobConclusion, "success", StringComparison.OrdinalIgnoreCase); + + private static bool HasValidExpectedIdentity(EvidencePullRequestGateExpectedIdentity identity) => + identity.RunIdentity is not null + && identity.RunIdentity.RepositoryId > 0 + && identity.RunIdentity.HeadRepositoryId > 0 + && identity.RunIdentity.PullRequestNumber > 0 + && identity.RunIdentity.WorkflowRunId > 0 + && identity.RunIdentity.WorkflowRunAttempt > 0 + && IsSafeIdentityText(identity.RunIdentity.TargetBranch, 128) + && IsSafeIdentityText(identity.Repository, 255) + && identity.Repository.Count(static character => character == '/') == 1 + && (identity.EventName is "pull_request" or "pull_request_target") + && IsSafeIdentityText(identity.WorkflowId, 256) + && IsSafeIdentityText(identity.SubjectJobId, 128); + + private static bool IsSafeIdentityText(string? value, int maximumLength) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= maximumLength + && !value.Any(char.IsControl); + + private static bool HasValidRevision(string? revision) => + revision is { Length: 40 or 64 } + && revision.All(static character => character is >= '0' and <= '9' or >= 'a' and <= 'f'); + + private static bool IsBoundedPlan(EvidencePlan plan) + { + var budget = new TextBudget(); + return plan.Profile is not null + && plan.PullRequestRunIdentity is not null + && IsBoundedRunIdentity(plan.PullRequestRunIdentity, budget) + && plan.PolicySnapshot is not null + && plan.ChangedPaths is { Count: <= EvidenceGitChangeCapture.MaximumChangedRecords } + && plan.MatchedRuleIds is { Count: <= EvidenceGitChangeCapture.MaximumChangedRecords * 2 } + && IsBoundedPolicy(plan.PolicySnapshot, budget) + && AddText(budget, plan.ContractVersion, plan.PolicyId, plan.PolicyDigest, plan.DiffDigest, plan.PlanDigest, + plan.BaseRevision, plan.HeadRevision, plan.SourceDiffDigest, plan.NameStatusDigest) + && AddMany(budget, plan.MatchedRuleIds, 128) + && plan.ChangedPaths.All(path => path is not null + && AddText(budget, path.Path, path.Kind, path.PreviousPath) + && path.Path.Length <= EvidenceGitChangeCapture.MaximumPathBytes + && (path.PreviousPath is null || path.PreviousPath.Length <= EvidenceGitChangeCapture.MaximumPathBytes)) + && IsBoundedProfile(plan.Profile, budget) + && EvidenceCanonicalJson.Serialize(plan).Length <= MaximumContractBytes; + } + + private static bool IsBoundedManifest(EvidenceManifest manifest) + { + var budget = new TextBudget(); + if (manifest.PullRequestRunIdentity is null + || !IsBoundedRunIdentity(manifest.PullRequestRunIdentity, budget) + || manifest.ResourceResults is not { Count: <= EvidenceProfileLimits.MaximumResources } + || manifest.SelectedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.ClosedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.UnmediatedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.ProducerResults is not { Count: <= EvidenceProfileLimits.MaximumProducers } + || manifest.Metrics is null) + { + return false; + } + + return AddText(budget, manifest.ContractVersion, manifest.PlanDigest, manifest.ManifestDigest, + manifest.BaseRevision, manifest.HeadRevision, manifest.SourceDiffDigest, manifest.NameStatusDigest, + manifest.Metrics.CleanupDiagnostic) + && manifest.ResourceResults.All(result => result is not null + && AddText(budget, result.ResourceId, result.Diagnostic) + && result.Diagnostic is null or { Length: <= 512 }) + && AddMany(budget, manifest.SelectedObligationIds, 128) + && AddMany(budget, manifest.ClosedObligationIds, 128) + && AddMany(budget, manifest.UnmediatedObligationIds, 128) + && manifest.ProducerResults.All(result => result is not null + && AddText(budget, result.ProducerId, result.Diagnostic) + && result.Diagnostic is null or { Length: <= 512 } + && result.SatisfiedAssertionIds is { Count: <= 256 } + && result.Artifacts is { Count: <= 128 } + && AddMany(budget, result.SatisfiedAssertionIds, 128) + && result.Artifacts.All(artifact => artifact is not null + && AddText(budget, artifact.LogicalName, artifact.RelativePath, artifact.MediaType, artifact.Sha256))) + && EvidenceCanonicalJson.Serialize(manifest).Length <= MaximumContractBytes; + } + + private static bool IsBoundedPolicy(EvidencePolicy policy, TextBudget budget) => + policy.Profiles is { Count: > 0 and <= 128 } + && policy.Rules is { Count: <= 10_000 } + && AddText(budget, policy.Id, policy.Version, policy.ConservativeProfileId) + && policy.Profiles.All(profile => profile is not null && IsBoundedProfile(profile, budget)) + && policy.Rules.All(rule => rule is not null && AddText(budget, rule.Id, rule.Pattern, rule.ProfileId)); + + private static bool IsBoundedRunIdentity(EvidencePullRequestRunIdentity identity, TextBudget budget) => + identity.RepositoryId > 0 + && identity.HeadRepositoryId > 0 + && identity.PullRequestNumber > 0 + && identity.WorkflowRunId > 0 + && identity.WorkflowRunAttempt > 0 + && identity.TargetBranch is { Length: > 0 and <= 128 } + && !identity.TargetBranch.Any(char.IsControl) + && budget.TryAdd(identity.TargetBranch); + + private static bool IsBoundedProfile(EvidenceProfile profile, TextBudget budget) => + profile is not null + && profile.Resources is { Count: <= EvidenceProfileLimits.MaximumResources } + && profile.Producers is { Count: <= EvidenceProfileLimits.MaximumProducers } + && profile.Obligations is { Count: <= EvidenceProfileLimits.MaximumObligations } + && AddText(budget, profile.Id) + && profile.Resources.All(resource => resource is not null + && resource.Requires is { Count: <= EvidenceProfileLimits.MaximumResources } + && AddText(budget, resource.Id, resource.Readiness) + && AddMany(budget, resource.Requires, 128)) + && profile.Producers.All(producer => producer is not null + && producer.RequiredResources is { Count: <= EvidenceProfileLimits.MaximumResources } + && producer.AssertionIds is { Count: <= 256 } + && producer.ArtifactSlots is { Count: <= 128 } + && AddText(budget, producer.Id, producer.Kind, producer.Version) + && AddMany(budget, producer.RequiredResources, 128) + && AddMany(budget, producer.AssertionIds, 128) + && producer.ArtifactSlots.All(slot => slot is not null && AddText(budget, slot.LogicalName, slot.RelativeRoot, slot.MediaType))) + && profile.Obligations.All(obligation => obligation is not null + && obligation.RequiredProducerIds is { Count: <= EvidenceProfileLimits.MaximumProducers } + && AddText(budget, obligation.Id, obligation.RiskClass, obligation.Rationale, obligation.RequiredAssertionId) + && AddMany(budget, obligation.RequiredProducerIds, 128)); + + private static bool AddMany(TextBudget budget, IEnumerable? values, int maximumItemLength) + { + if (values is null) + { + return false; + } + + foreach (var value in values) + { + if (value is null || value.Length > maximumItemLength || !budget.TryAdd(value)) + { + return false; + } + } + + return true; + } + + private static bool AddText(TextBudget budget, params string?[] values) + { + foreach (var value in values) + { + if (value is not null && (value.Length > EvidenceGitChangeCapture.MaximumPathBytes || !budget.TryAdd(value))) + { + return false; + } + } + + return true; + } + + private static EvidencePullRequestGateVerificationResult Failure(string code, string diagnostic) => + new(false, code, diagnostic); + + private sealed class TextBudget + { + private int _used; + + public bool TryAdd(string value) + { + if (value.Length > MaximumContractTextUnits - _used) + { + return false; + } + + _used += value.Length; + return true; + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs new file mode 100644 index 000000000..a912bce3c --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs @@ -0,0 +1,112 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Binds an independently captured Git change to the closed pull-request policy selection. +/// +/// +/// A v2 plan proves internal consistency only. A gate must supply its own trusted policy and Git +/// object store to , and must separately check the current PR identity +/// and the subject job's provenance immediately before issuing a verdict. +/// +public static class EvidenceRevisionPlanBuilder +{ + /// + /// Resolves a v2 plan from exact, full commit IDs and fixed-options Git diff/status bytes. + /// + /// The policy resolver. + /// Trusted, base-owned pull-request policy. + /// Captured exact Git change. + /// Optional trusted controller-captured PR/run identity; local rehearsal omits it. + /// A canonical digest-bound v2 plan. + public static EvidencePlan ResolveForPullRequest( + EvidencePlanner planner, + EvidencePolicy policy, + EvidenceGitChangeSnapshot snapshot, + EvidencePullRequestRunIdentity? runIdentity = null) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(snapshot); + if (runIdentity is not null && (runIdentity.RepositoryId <= 0 + || runIdentity.HeadRepositoryId <= 0 + || runIdentity.PullRequestNumber <= 0 + || string.IsNullOrWhiteSpace(runIdentity.TargetBranch) + || runIdentity.TargetBranch.Length > 128 + || runIdentity.WorkflowRunId <= 0 + || runIdentity.WorkflowRunAttempt <= 0)) + { + throw new EvidencePlanningException( + "ASEVD140", + "The controller PR/run identity is incomplete or malformed.", + "Capture numeric repository, PR, run, and attempt IDs and a bounded target branch from the trusted event."); + } + + var local = planner.ResolveForGate(policy, snapshot.ChangedPaths); + var draft = local with + { + ContractVersion = "2.0", + BaseRevision = snapshot.BaseRevision, + HeadRevision = snapshot.HeadRevision, + SourceDiffDigest = snapshot.SourceDiffDigest, + NameStatusDigest = snapshot.NameStatusDigest, + PullRequestRunIdentity = runIdentity, + PlanDigest = string.Empty, + }; + return draft with { PlanDigest = EvidenceDigest.CanonicalSha256(draft) }; + } + + /// + /// Recreates a v2 pull-request plan using a trusted policy and exact Git objects, rejecting + /// a modified policy, revision pair, diff, status inventory, profile, or canonical plan digest. + /// This method does not authenticate the external PR event or job that supplied the plan. + /// + /// The policy resolver. + /// Policy read from the trusted base revision. + /// Trusted Git object store containing both commits. + /// Untrusted plan to compare with the independently resolved one. + /// Cancellation for bounded Git operations. + /// Separately trusted PR/run identity for a CI gate; omit only for local rehearsal. + /// A task that completes only when the plan matches the trusted inputs. + public static async Task VerifyAsync( + EvidencePlanner planner, + EvidencePolicy trustedPolicy, + string repositoryPath, + EvidencePlan plan, + CancellationToken cancellationToken = default, + EvidencePullRequestRunIdentity? expectedRunIdentity = null) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(trustedPolicy); + ArgumentNullException.ThrowIfNull(plan); + if (!string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + || plan.BaseRevision is null + || plan.HeadRevision is null) + { + throw new EvidencePlanningException( + "ASEVD139", + "The supplied plan is not revision-bound v2 evidence.", + "Regenerate the plan from complete base/head commit IDs and a trusted base-owned policy."); + } + + if (expectedRunIdentity is not null && !Equals(plan.PullRequestRunIdentity, expectedRunIdentity)) + { + throw new EvidencePlanningException( + "ASEVD139", + "The plan PR/run identity differs from the trusted controller identity.", + "Discard the supplied plan and capture a new one for the authoritative PR, run, and attempt."); + } + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync( + repositoryPath, plan.BaseRevision, plan.HeadRevision, cancellationToken).ConfigureAwait(false); + var expected = ResolveForPullRequest(planner, trustedPolicy, snapshot, expectedRunIdentity ?? plan.PullRequestRunIdentity); + if (!EvidenceCanonicalJson.Serialize(expected).AsSpan().SequenceEqual(EvidenceCanonicalJson.Serialize(plan))) + { + throw new EvidencePlanningException( + "ASEVD139", + "The revision-bound plan does not match the trusted policy or exact Git change.", + "Discard the supplied plan and rerun planning from the base-owned policy and fetched commit objects."); + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md index 1d11cd206..1e0d0aad6 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md @@ -2,7 +2,7 @@ `ForgeTrust.AppSurface.Evidence.Planner` turns an explicit diff and a checked-in `EvidencePolicy` into one deterministic `EvidencePlan`. It is the boundary that makes a coverage or E2E gate explainable before work begins. -Begin with the [EvidenceHost guide](https://github.com/forge-trust/AppSurface/blob/main/start-here/evidencehost.md). This package owns planning only: it does not invoke Git, start Aspire, run tests, create containers, or decide that missing evidence is acceptable. +Begin with the [EvidenceHost guide](https://github.com/forge-trust/AppSurface/blob/main/start-here/evidencehost.md). The policy resolver owns planning only: it does not invoke Git, start Aspire, run tests, create containers, or decide that missing evidence is acceptable. The separate `EvidenceGitChangeCapture` API does invoke Git to capture and verify exact commit-pair changes. ## Release Guidance @@ -24,6 +24,61 @@ var plan = planner.Resolve(policy, [new NormalizedDiffPath("src/Orders/SubmitOrd `Resolve` normalizes and sorts paths, applies the most-specific matching rules, and falls back to `ConservativeProfileId` for a path that has no rule. If equally specific rules choose different profiles, it throws `EvidencePlanningException` instead of silently taking a lower-risk route. `EvidenceUnifiedDiffReader.Read(...)` accepts a CI-provided Git-formatted unified diff when callers do not want to depend on a local Git checkout. Hunked diffs must include `diff --git` file headers; use explicit paths when only a non-Git diff is available. +## Pull-request gate planning + +Use `ResolveForGate` to build a plan for a PR gate. It opts into stricter validation before selecting paths: + +```csharp +var plan = new EvidencePlanner().ResolveForGate(policy, changedPaths); +``` + +In addition to the ordinary v1 policy checks, the gate path checks that the conservative profile includes every requirement from every rule-selected targeted profile that could be combined in one diff. It preserves resource declarations and producer resource dependencies; producer kind, version, assertions, and coverage requirements; artifact-slot roots, media types, required status, and byte bounds; and obligation identity, risk class, rationale, required assertion, and required producers. The conservative profile may add resources, producers, assertions, artifact slots, and obligations. Resource readiness modes must match, and resource or producer deadlines may be shortened. Coverage thresholds may be strengthened. A required artifact slot cannot become optional, and its byte limit may stay the same or become smaller. + +An empty targeted profile is valid for an explicit docs-only rule: it contributes no requirements to the superset check and can still resolve to `NoEvidenceRequired`. PR rules and their conservative profile must use `Targeted` scope. Release profiles require separate validation in their trusted release context. + +`ValidateGatePolicy(policy)` exposes the same check for policy preflight. `Resolve` and `ValidatePolicy` deliberately retain local v1 behavior and do not perform cross-profile validation. Local planning therefore remains compatible, but its result alone does not prove that a policy is safe for a PR gate. Gate callers should use `ResolveForGate` with the same base-owned policy snapshot used for the run. A failed superset check reports `ASEVD129` before a plan is produced. + +## Non-claiming policy-shadow comparison + +[`EvidencePolicyShadowValidator.Validate`](EvidencePolicyShadowValidator.cs) compares a proposed policy with the protected base policy using an authoritative base-owned fixture set. Each fixture names a stable ID, a repository-relative changed path (optionally with its previous rename path), and one of five base-owned classifications: documentation, code, resource, control plane, or unknown. The validator resolves every case under both policies and rejects candidate selections that omit or weaken any base-selected resource, producer, assertion, artifact slot, or obligation. A control-plane fixture requires an explicit policy rule in both the protected base and candidate policies; conservative fallback on either side is reported as an unrecognized control-plane path. Candidate fixture additions and edits can provide supplemental cases, but deleting or editing a base fixture is reported and does not remove the original case from evaluation. + +The caller must obtain the base policy, base fixtures, and path classifier from the protected base revision; passing candidate-controlled copies as those inputs would defeat the comparison. This library authenticates none of its inputs and returns only a bounded shadow result, never a manifest or required-check verdict. It accepts at most 64 fixtures per input set, 64 profiles, and 256 rules, and returns at most 32 deterministic diagnostics with an explicit truncation flag. A candidate policy must still pass `ValidateGatePolicy`; a passing shadow comparison does not establish subject isolation, producer evidence, or current GitHub revision freshness. See the [issue #777 rollout record](../../docs/evidence-gate-rollout.md) for the separate live control-plane pilot and required-check activation criteria. + +## Revision-bound Git change capture + +For a revision-bound gate, [EvidenceGitChangeCapture](EvidenceGitChangeCapture.cs) captures the source diff and the path-selection stream from an explicit commit pair: + +```csharp +var snapshot = await EvidenceGitChangeCapture.CaptureAsync( + trustedObjectStorePath, + baseCommitId, + headCommitId, + cancellationToken); +var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot); +// Run the evidence producers for `plan` here. +await EvidenceRevisionPlanBuilder.VerifyAsync( + new EvidencePlanner(), trustedBaseOwnedPolicy, trustedObjectStorePath, plan, cancellationToken); +// Separately recheck the PR's live base/head before issuing the verdict. +``` + +`baseCommitId` and `headCommitId` must be complete lower-case commit object IDs, either 40 or 64 hexadecimal characters, in the same object format. They must resolve to commit objects in a trusted bare or object-only Git checkout. The capture implementation invokes Git with fixed diff options, neutralized ambient Git configuration, and replacement refs disabled (`GIT_NO_REPLACE_OBJECTS=1`); an untrusted replacement ref cannot redefine either exact commit ID. The gate runner remains responsible for supplying that trusted object store, pinning the Git version, fetching the exact commits, and checking its trust boundary. + +The snapshot keeps two representations for different purposes. `SourceDiff` contains the exact bounded `git diff --binary` bytes and `SourceDiffDigest` binds those bytes. `NameStatus` contains the separate `git diff --name-status -z` byte stream; its NUL-delimited records are parsed into `ChangedPaths`, including both old and new paths for renames and copies. Policy selection uses those parsed status paths, so binary, mode, symlink, and submodule changes are not lost just because they have no text hunk. `NameStatusDigest` binds the exact status bytes. Do not parse paths from source-diff text as a substitute for the status stream. + +The initial gate bounds are a 20 MiB source diff, 10,000 changed records, 4 KiB of UTF-8 bytes per path, and 120 seconds for the complete capture operation (`MaximumCaptureSeconds`). A separate bounded read protects the status stream before parsing. Exceeding a bound or receiving malformed, truncated, unsafe, or invalid-UTF-8 status data fails closed; callers must not fall back to an empty or text-hunk-only path list. + +`EvidenceRevisionPlanBuilder.ResolveForPullRequest` emits contract version `2.0` and binds both revisions plus source/status digests to the normalized path selection and policy. Its `VerifyAsync` independently regenerates both Git representations and resolves the plan from a separately trusted policy. It rejects a substituted policy or plan but does not query GitHub or prove current-base/head freshness. The trusted controller must independently recheck the remote PR's current base and head immediately before issuing a gate verdict, as described in the [issue #777 gate design](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md). + +## Trusted PR verdict boundary + +For a nonempty profile, the manifest must declare `ValidatedNotAttested`, and the fresh authority snapshot must separately provide both the independently attested subject checkout revision and `SubjectEnvelopeAttested` after trusted isolation inspection. The manifest's enum is a structural claim, not proof of the runner envelope; a missing independent attestation returns `ASEVG007`. An explicitly empty profile instead requires `NotRequired` and may use a fresh PR/run/job authority snapshot whose subject checkout revision is empty, because it executes no subject code. A nonempty profile cannot use that unknown checkout as a shortcut. + +[`EvidencePullRequestGateVerifier.VerifyAsync`](EvidencePullRequestGateVerifier.cs) is the final library seam for a PR verdict. Supply the base-owned policy and trusted Git object store separately from the candidate v2 plan and manifest. `EvidencePullRequestGateExpectedIdentity` must come from controller-owned workflow context: repository, event, workflow and subject-job IDs, plus numeric repository, head-repository, PR, run and attempt IDs and target branch in `EvidencePullRequestRunIdentity`. Do not copy expected identity from the plan itself. The verifier recreates the plan from Git, checks the manifest and every selected obligation, then calls an `IEvidencePullRequestGateAuthorityProvider` to reread current PR base/head and subject-job provenance immediately before it returns. A missing, stale, fork, wrong-job, or observational result is ineligible. + +For a nonempty profile, also pass a controller-owned extracted-artifact handoff root and an `IEvidencePullRequestGateArtifactVerifier`. The supplied [`EvidencePullRequestGateNoFollowArtifactVerifier`](EvidencePullRequestGateVerifier.cs) requires Linux x64 or arm64 with `openat2` and `statx`; it opens each declared file beneath that root without following links and verifies type, single-link identity, length, slot, and SHA-256 from the bytes read. Directory and no-follow open flags are selected for the running Linux architecture, so an arm64 runner uses the same fail-closed path checks as x64. It rejects missing, moved, duplicate or forged artifacts. A missing verifier or root returns `ASEVG009`; a byte mismatch returns `ASEVG010`. An explicit empty targeted profile has no artifact handoff to verify and may yield `NoEvidenceRequired` after the same revision and authority checks. The host's own success is not a substitute for this final verification. + +`EvidencePullRequestGateVerificationResult` exposes a fixed diagnostic code and bounded `Summary` for terminal, GitHub summary, and machine rendering. The summary carries profile/rule rationale, short revisions, and selected, closed, and missing obligation IDs; it does not carry producer logs or arbitrary artifact contents. A calling CI command may issue a passing check only for `IsEligible == true` (`ASEVG000`). `ASEVG001`–`ASEVG008` cover invalid trusted identity, v2 plan or manifest mismatch, out-of-scope claim, unavailable or mismatched fresh authority, and cancellation. A verifier implementation alone does not provide a GitHub API authority provider or isolate the subject job; those remain requirements of the [AppSurface rollout](../../docs/evidence-gate-rollout.md). + ## Policy design Keep the policy small and explicit: @@ -45,5 +100,9 @@ The planner does not classify C# semantics or infer that a getter, constructor, | `ASEVD121` | An identifier is empty or exceeds 128 characters. | Use a stable identifier up to 128 characters. | | `ASEVD111`, `ASEVD124` | A producer or resource requires an undeclared resource. | Declare every required resource in the same profile. | | `ASEVD128` | A hunked unified diff does not include Git file headers. | Supply a Git-formatted diff or explicit changed paths. | +| `ASEVD129` | A PR gate selects a release-only profile or its conservative profile does not preserve a targeted profile requirement. | Map PR paths to targeted profiles and add any missing conservative requirements, or use an explicit combined profile. | +| `ASEVD130`–`ASEVD136` | Exact Git revisions, object-store reads, bounded status parsing, or capture verification failed. | Fetch full commit objects into the trusted object store and recapture with the pinned Git runner; do not downgrade to path-only selection. | +| `ASEVD137` | Exact Git change capture exceeded its 120-second deadline. | Retry in the pinned runner or reduce the change before a reviewed deadline increase. | +| `ASEVD139` | A v2 plan did not match the trusted policy and exact Git commit pair. | Discard it and replan from the trusted base-owned policy and fetched objects. | Read next: [contracts](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md), [CLI workflow](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md), and the [policy cookbook](https://github.com/forge-trust/AppSurface/blob/main/guides/evidencehost-cookbook.md). diff --git a/ForgeTrust.AppSurface.slnx b/ForgeTrust.AppSurface.slnx index ba1fa0a5a..2a4a5e984 100644 --- a/ForgeTrust.AppSurface.slnx +++ b/ForgeTrust.AppSurface.slnx @@ -153,6 +153,8 @@ + + diff --git a/TODOS.md b/TODOS.md index 61c3bef9d..6e26a579d 100644 --- a/TODOS.md +++ b/TODOS.md @@ -108,3 +108,71 @@ - **What:** Add a source analyzer and optional codemod for legacy dotted AppSurface configuration-key call sites. **Why:** Runtime diagnostics can identify executed paths, but they cannot prove that every attribute, direct read, audit registration, provider mapping, and dormant branch has migrated. **Pros:** Gives maintainers a compile-time inventory and automates safe `.` to `:` replacements. **Cons:** The analyzer would freeze grammar and API assumptions too early if built before the typed key and migration diagnostics stabilize. **Context:** The logical-key contract deliberately keeps only one permanent colon syntax and uses bounded compatibility input; the analyzer should consume the final parser rules rather than reimplementing them. **Effort estimate:** L (human team) -> M with CC+gstack. **Priority:** P2. **Depends on / blocked by:** Stable `AppSurfaceConfigKey`, application-boundary parser, diagnostic codes, and release-train policy. - **What:** Add a credentialed Google Secret Manager contract proof for explicit mappings, convention ids, versions, and exact provenance. **Why:** The fake transport proves AppSurface behavior but cannot prove deployed IAM, API resource validation, or response-name behavior. **Pros:** Catches provider drift before a release and validates the exact native-resource contract. **Cons:** Requires a dedicated project, credential rotation, cleanup, cost controls, and a trust-boundary design for CI. **Context:** Keep the default provider suite deterministic and value-safe; run the live proof as a separate protected release verification rather than enumerating unclaimed secrets. **Effort estimate:** M (human team) -> S with CC+gstack. **Priority:** P2. **Depends on / blocked by:** Stable Google codec/resource-claim contract and approved CI credential design. + +## EvidenceHost follow-ups (#777) + +### Reusable EvidenceHost workflow for another repository + +**What:** Design a versioned consumer input/output and reusable GitHub workflow after AppSurface's required gate has a second adopter. +**Why:** The first reference should prove the trust boundary before it becomes a compatibility promise. +**Pros:** Easier adoption and one maintained workflow contract. +**Cons:** Public versioning, support and security obligations may outgrow the first adopter's needs. +**Context:** [The #777 design](docs/designs/issue-777-policy-driven-ci-evidence-gate.md) deliberately keeps the runner AppSurface-owned; start from its validated policy/producer matrix, pilot results and [implementation plan](docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md). +**Effort:** L +**Priority:** P3 +**Depends on:** #777 shipped and a real second adopter. + +### Fork check publisher without same-repository promotion + +**What:** Evaluate a base-owned PR-eligible check publisher for fork contributions if the measured exact-SHA promotion cost is too high. +**Why:** #777's fork observation is intentionally ineligible for its required gate. +**Pros:** Could reduce maintainer promotion work while retaining a verified head-attached check. +**Cons:** Adds a new authenticated publication and provenance boundary. +**Context:** Use the #777 pilot's fork frequency, turnaround and failure records; never turn a manual dispatch or label into an eligible claim. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 fork pilot and a measured maintainer burden. + +### Self-hosted EvidenceHost runner support + +**What:** Add an external reaper and runner isolation proof for persistent or self-hosted EvidenceHost runners. +**Why:** #777 relies on ephemeral VM destruction when its local-only resources lose their runner. +**Pros:** Broader deployment options for repositories with a self-hosted compute need. +**Cons:** A persistent runner needs a new cleanup lifetime, network boundary and operations owner. +**Context:** Keep GitHub-hosted ephemeral PR jobs as the #777 reference; use a concrete adopter and failure model before changing that guarantee. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 rollout and a self-hosted runner adopter. + +### Merge-queue EvidenceHost event support + +**What:** Add `merge_group` event handling and revalidate required-check identity when AppSurface adopts merge queue. +**Why:** A PR-head check cannot automatically authorize a synthetic merge-group revision. +**Pros:** EvidenceHost can stay a required gate when queueing is enabled. +**Cons:** New event identity, source-diff and freshness semantics require live proof. +**Context:** #777 gates ordinary PRs with strict freshness. Reuse its capture/verify boundary for a separately defined merge-group identity. +**Effort:** M +**Priority:** P3 +**Depends on:** #777 rollout and a merge-queue adoption decision. + +### Evidence-backed release publication + +**What:** Design a publisher that consumes only object-bound, digest-matching `ReleaseComplete` artifacts under a verified immutable tag rule. +**Why:** #777's release invocation is non-mutating; a claim alone cannot close a moving-tag check/use window. +**Pros:** Publication could inherit the same verified evidence identity. +**Cons:** Introduces an irreversible release side effect and a new authorization boundary. +**Context:** Start with #777's V2 tag binding and protected release pilot. Revalidate remote tag immutability and artifact bytes immediately before and throughout publication use. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 release proof, immutable tag policy and separate publisher approval. + +### Hosted EvidenceHost dashboard + +**What:** Consider a hosted view only if maintainers cannot diagnose real gate failures from the bounded GitHub summary, manifest and runbook. +**Why:** A dashboard would add hosting and retention before the first adopter proves a need. +**Pros:** Could centralize long-term evidence trends for multiple adopters. +**Cons:** Adds cost, permissions, sensitive-data handling and another source of truth. +**Context:** #777 records local and GitHub artifacts only. Collect actual diagnostic failures before proposing a service. +**Effort:** XL +**Priority:** P4 +**Depends on:** Measured multi-adopter diagnostic need after #777. diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs b/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs index f95437a38..31607b919 100644 --- a/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs +++ b/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs @@ -667,7 +667,7 @@ await page.WaitForFunctionAsync( null, new PageWaitForFunctionOptions { Timeout = 15_000 }); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); var scrollState = await page.EvaluateAsync( """ () => { @@ -720,7 +720,7 @@ await AppSurfaceDocsRouteHelper.GotoFirstAvailableAsync( "() => getComputedStyle(document.getElementById('main-content')).overflowAnchor"); Assert.Equal("none", overflowAnchor); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); await page.EvaluateAsync( """ () => { @@ -765,7 +765,7 @@ await page.WaitForFunctionAsync( null, new PageWaitForFunctionOptions { Timeout = 15_000 }); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); var scrollState = await page.EvaluateAsync( """ () => { @@ -1699,6 +1699,20 @@ private static async Task AssertSectionCopyPreservedNavigationAsync(IPage page, await AssertSectionCopyDidNotMutateHistoryAsync(page); } + private static async Task ScrollMainContentToBottomAsync(IPage page) + { + await page.EvaluateAsync(ScrollMainContentToBottomScript); + await page.WaitForFunctionAsync( + """ + () => { + const main = document.getElementById('main-content'); + return main && Math.max(0, main.scrollHeight - main.clientHeight) - main.scrollTop <= 8; + } + """, + null, + new PageWaitForFunctionOptions { Timeout = 15_000 }); + } + private const string ScrollMainContentToBottomScript = """ () => { @@ -1708,7 +1722,8 @@ private static async Task AssertSectionCopyPreservedNavigationAsync(IPage page, } main.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true })); - main.scrollTo(0, main.scrollHeight); + // Cancel any in-flight smooth outline navigation before checking the bottom. + main.scrollTo({ top: main.scrollHeight, behavior: 'instant' }); } """; } diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png index 8d65e6654..1b9324bac 100644 Binary files a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png and b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png differ diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-light-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-light-1440x1000.png index 4d7adc4c7..534c3cbd1 100644 Binary files a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-light-1440x1000.png and b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-light-1440x1000.png differ diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-dark-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-dark-1440x1000.png index 64e130056..85f3e579f 100644 Binary files a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-dark-1440x1000.png and b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-dark-1440x1000.png differ diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-light-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-light-1440x1000.png index 7fa435771..0e4e2a9f5 100644 Binary files a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-light-1440x1000.png and b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-system-light-1440x1000.png differ diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsLight/release-desktop-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsLight/release-desktop-1440x1000.png index 0aac77bd5..3edf639cb 100644 Binary files a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsLight/release-desktop-1440x1000.png and b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsLight/release-desktop-1440x1000.png differ diff --git a/docs/designs/issue-777-policy-driven-ci-evidence-gate.md b/docs/designs/issue-777-policy-driven-ci-evidence-gate.md new file mode 100644 index 000000000..926b9cf86 --- /dev/null +++ b/docs/designs/issue-777-policy-driven-ci-evidence-gate.md @@ -0,0 +1,158 @@ +# Design: AppSurface policy-driven CI evidence gate + +- Generated by /office-hours on 2026-09-30 +- Branch: `main` +- Repo: `forge-trust/AppSurface` +- Status: APPROVED (office-hours, 2026-09-30) +- Mode: Builder +- Issue: [#777](https://github.com/forge-trust/AppSurface/issues/777) +Builds on: [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) and completed [#775](https://github.com/forge-trust/AppSurface/issues/775) + +## Problem Statement + +AppSurface has an [Evidence planner, CLI, and host contract](../../start-here/evidencehost.md), but no AppSurface CI workflow calls `appsurface evidence`. A maintainer cannot point at a live, safe reference run that proves a checked-in policy selected the work for an exact change and that the resulting manifest supports the CI verdict. Current independent workflows still decide what to run in YAML. The AppSurface repository also has no required status check in its active default-branch ruleset, so publishing a green example alone would not create a merge gate. + +The first adopter is AppSurface's own maintainers. The intended outcome is a working required PR check plus a release invocation of the same evidence runner. It should be possible to copy the documented pattern later, but this issue does not promise a general reusable workflow interface for other repositories. + +## What Makes This Cool + +The workflow says *which revisions and policy were evaluated, why a profile was selected, what every obligation required, and whether the evidence actually closed it*. A docs-only change receives an explicit `NoEvidenceRequired` claim. A code change whose selected producer or disposable resource fails cannot become green because some other CI job passed. The console, GitHub summary, and machine manifest render one verdict from one plan. A fork can still be inspected, but it cannot borrow a trusted claim. + +## Constraints + +- [#777](https://github.com/forge-trust/AppSurface/issues/777) is an AppSurface-owned reference path, not a new CI scheduler, deployment system, generic plugin loader, or cross-job aggregation format. +- The [existing EvidenceHost design](appsurface-evidencehost-contract-first.md) owns the contract boundary: base-owned policy and explicit host registrations; separate trusted-tool and subject checkouts; [coverage core](evidence-coverage-core-extraction.md) reuse; typed producer/resource/obligation closure; bounded cleanup; observation-only execution for untrusted inputs. +- The current [planning CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) accepts policy and path/diff inputs but has no authoritative base/head arguments. Its run command can execute the built-in coverage producer; it cannot yet execute every resource-backed AppSurface profile. The [plan contract](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) records a normalized diff digest but not base/head or the exact source diff bytes. These are implementation gaps, not values YAML can invent. +- Required-check behavior depends on GitHub event and ruleset semantics. The current default-branch ruleset requires reviews but no CI status. A planned gate must be proven on an actual PR before that ruleset changes. +- No production credentials, mutable release operations, or head-controlled workflow/host/policy instructions enter the evidence run. The reference release profile remains non-mutating. + +## Premises + +1. **Selection is policy-owned and revision-bound.** The authoritative plan includes full base and head Git object IDs, SHA-256 of the exact captured source diff bytes, normalized change digest, policy digest, profile, and plan digest. CI regenerates and verifies the source diff from those objects with fixed Git options before `explain` and `run`; both commands consume the same immutable snapshot. A self-consistent manifest without this external revision check is insufficient. +2. **Only the manifest decides the gate.** A PR passes only for a verified, current-base-and-head, gate-eligible `TargetedComplete` or explicit `NoEvidenceRequired` claim. `NoEvidenceRequired` is not a synonym for a skipped job. Missing producer, resource, obligation, required artifact, cleanup, or envelope state produces no complete claim and a failed gate. A release pipeline requires `ReleaseComplete` with release eligibility; a PR check cannot reinterpret a targeted claim as release complete. Policy selects the candidate profile from the diff; trusted event context separately determines whether that profile may issue a PR or release claim. +3. **The trusted control plane is base-owned.** The workflow, policy, host registrations, runner, and envelope verifier come from the protected base/trusted-tool revision. The head is only the subject under test. No subject file can choose a command, image, mount, token, network capability, producer, or artifact root. +4. **Fork and other untrusted inputs remain observational.** They receive no privileged capability or complete claim. The required check fails until reviewed content is promoted to a trusted same-repository branch and a new PR-eligible run evaluates that exact promoted head. A manual `workflow_dispatch` report alone cannot satisfy the PR's required check. +5. **The reference proves all AppSurface-selected profiles.** The host must actually run every producer/resource required by the checked-in AppSurface policy, including its non-mutating release profile. Unsupported profile or missing registration fails closed; YAML never silently downgrades the profile. + +## Cross-Model Perspective + +A fresh `combo/sub` review supported a base-owned evidence path but challenged the original claim that a policy, diff, and plan digest alone identify the tested change. It observed that two revision pairs can yield the same normalized paths and that a GitHub event's merge checkout can differ from the requested head. We accepted the challenge: exact base/head identities and the captured diff-byte digest belong in the plan and manifest contract, and CI must independently regenerate the diff before execution. The reviewer also suggested a trusted manual rerun for forks; GitHub's required-check rules make that insufficient as a PR gate, so promotion to a same-repository branch is the explicit path. + +## Approaches Considered + +- **A — Narrow live PR gate (M; about 2–4 human days / 4–8 agent hours).** Gets coverage and no-evidence cases live sooner, but leaves resource-backed and release-profile completeness unproved. Rejected because the selected reference would still demonstrate only the easy branch of EvidenceHost. +- **B — Complete AppSurface EvidenceHost gate (L; about 1–2 human weeks / 1–2 agent days). Selected.** Builds one revision-bound runner and explicit AppSurface host registrations, exercises every policy-selected profile, then makes the PR check required after live proof. The extra work is concentrated in real host execution and trust isolation. +- **C — Versioned reusable workflow (XL; about 2–3 human weeks / 3–5 agent days).** Adds a public consumer input/output and compatibility surface before the first live adopter. Deferred until AppSurface's own path is stable. + +## Recommended Approach + +### 1. Capture and bind the exact change + +The PR controller reads the event's target-base tip and head SHA as data, validates full commit IDs, fetches both objects by SHA, and computes a fixed-options `git diff` between them. It records the source bytes once in a bounded file, independently regenerates the same bytes from the fetched objects, and fails if they differ. The comparison is deliberately the explicit pair rather than an implicit checkout, merge commit, or ambient Git state. This may select extra work when the base advances; that is a conservative cost, never a missing-evidence shortcut. The ordinary build workflow remains responsible for merge-commit compatibility. The plan also records the PR number, target-base tip, workflow/run identity, and head SHA as bounded provenance fields, but these are not substitutes for Git object verification. Immediately before the final verdict, the controller rereads the PR's current target-base tip and head via the GitHub API and rejects either mismatch as stale; a completed run is never retroactively reinterpreted for a new pair. + +Extend the versioned Evidence contracts and the [CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) with authoritative `--base-revision`, `--head-revision`, and `--diff-file` inputs. A new schema version records `SourceDiffDigest` separately from the existing normalized `DiffDigest`; plan and manifest digests cover both revisions and both digests. `explain`, `run`, and `verify` use the same canonical plan identity. Gate mode rejects path-only input, abbreviated SHAs, missing Git objects, a mismatched source diff, stale policy, or a head changed since the event. Local non-gate CLI use can keep its existing path/diff ergonomics and must not imply gate eligibility. Publish the schema migration and compatibility rules in the [Evidence contract reference](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md) and [EvidenceHost guide](../../guides/evidencehost-cookbook.md). + +### 2. Execute a closed AppSurface policy in one host + +Check in an AppSurface policy whose every repository path is accounted for by an explicit rule or conservative fallback. It distinguishes docs-only `NoEvidenceRequired` from code/coverage, resource-backed integration, and non-mutating release profiles. Renames evaluate both sides; deletions and mixed docs/code changes cannot collapse to docs-only. Policy selects only named, base-registered resources, producers, obligations, assertions, and artifact slots. A release profile runs only in a protected release context; selecting it in a PR context fails as an event/profile mismatch rather than issuing a release claim. + +A dedicated AppSurface host runner composes the [EvidenceHost bootstrap](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) with explicit first-party registrations. It invokes the extracted coverage core through its existing seam, provisions disposable required resources through Aspire adapters, and runs the selected AppSurface integration and package/release evidence as typed producers with bounded readiness, execution, artifact, and cleanup behavior. It does not treat existing separate workflow job conclusions as producer results. The host owns one manifest even on producer failure where the contract permits one. A missing registration or resource returns an incomplete/invalid manifest and nonzero gate exit. Any capability that AppSurface cannot run safely stays outside the policy until a concrete, tested producer exists; the conservative fallback cannot declare it satisfied. + +For the protected release invocation, the subject is the peeled commit of a protected annotated release tag, not the workflow's ambient checkout or a user-supplied branch name. The trusted release verifier reads the tag object and commit from Git, checks the tag/version against the existing protected release-publish validation, and records the tag object ID, peeled commit, comparison-base commit, and SHA-256 of each policy-declared release package or archive in the plan and manifest. A package producer hashes the exact output it verified; publishing may consume only those digest-matching artifacts if the claim is used to authorize publication. A changed tag, rebuilt artifact with different bytes, missing declared artifact, or mismatched release event invalidates `ReleaseComplete`. Release policy still selects the candidate profile from the explicit comparison-base/tag-commit diff; the protected event and artifact checks grant release eligibility separately. + +### 3. Separate trusted control and subject execution + +The PR workflow uses a base-owned, PR-eligible trigger such as `pull_request_target` only after a live pilot verifies event availability, check association with the PR's current head, and repository event policy. It uses pinned actions, minimal read permissions, `persist-credentials: false`, no secrets, and separate read-only trusted-tool and subject checkouts. The supported runner is an ephemeral GitHub-hosted VM. The trusted controller runs outside a rootless OCI subject container pinned by image digest. The container receives only a read-only subject source mount and a dedicated writable scratch mount. It has a non-root UID, read-only root filesystem, dropped capabilities, no-new-privileges, bounded CPU/memory/PIDs, and no token, Docker/Podman socket, host home, trusted-tool mount, or runner credential files. For a profile without dependencies it has no network; a resource-backed profile uses a per-run internal network with only its declared disposable services and explicit egress denial, including denial of the host gateway and cloud metadata endpoint. Trusted code starts the container with argument arrays, validates its exit status and declared artifacts copied out of scratch, and treats all subject output as untrusted data. The base-owned envelope verifier checks this exact mount/network/capability configuration, runner class, root identities, subject/trusted revisions, and capability evidence immediately before resource provisioning. Inputs from PR titles, paths, or head files are never interpolated into shell commands. If the runner cannot enforce these properties, trusted claims are disabled. + +The controller owns resource labels and an external supervisor process, independent of the EvidenceHost process, with a per-run 10-minute cleanup deadline. Normal `finally` cleanup and an `if: always()` CI step ask the supervisor to stop containers/services, remove the per-run network and scratch data, and attest completion; failed or timed-out cleanup prevents a complete claim. A forced EvidenceHost-process kill is tested with the supervisor still alive and must converge within the declared deadline. If the entire VM is lost, no final manifest/check success can be issued, and its local-only resources die with the ephemeral VM; provider VM-destruction latency is outside the 10-minute claim. Persistent/self-hosted runners and external shared resources are unsupported until they have a separately demonstrated external reaper. + +For fork or otherwise untrusted heads, the workflow may emit a bounded observation report from a dependency-free safe subset; it always records `ObservationOnly` and exits the required gate nonzero. Maintainers can review and promote an exact commit to a same-repository branch, then run the normal PR path on a replacement or updated PR. The fork PR's observation does not become green by approval label or manual dispatch. If GitHub's policy prevents the intended PR trigger or attaches its check to the wrong revision, rollout stops before ruleset activation; use a separately designed base-owned PR-eligible check publisher rather than weakening the trust boundary. + +### 4. Derive one bounded output and turn it into a gate + +After host completion, verify the manifest against the captured plan, source diff, policy, selected profile, artifact hashes, trust envelope, and current PR head. One renderer produces the terminal verdict, GitHub step summary, and machine JSON from that verified result. It prints claim kind, eligible gate, profile/rule rationale, base/head short IDs, selected/closed/missing obligation IDs, and stable diagnostic codes; it never prints secret values, raw producer logs, arbitrary file contents, or unbounded changed-path lists. It truncates and counts long collections deterministically and stays below GitHub's [1 MiB step-summary limit](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands). Artifact upload and summary writing are presentation steps, not verdict sources; an upload failure cannot turn an incomplete run green. A pre-plan validation failure emits a bounded diagnostic and failed status without inventing a manifest. + +The gate job has a stable name, runs on PR `opened`, `synchronize`, `reopened`, `ready_for_review`, and base-target `edited` events without path filters or job-level skipping, and explicitly exits nonzero for `None`, `ObservationOnly`, invalid, incomplete, stale, cancelled, or wrong-scope claims. This avoids GitHub's [skipped-job success semantics](https://docs.github.com/en/pull-requests/reference/status-checks). Keep the existing build/test checks while the new gate runs in observation mode. After successful same-repository, docs-only, failing, and fork PR pilots prove the check attaches to the current PR head, add that exact check to the default-branch ruleset with [strict required-check freshness](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets). When the target base advances after a run, GitHub must block merging until the PR branch is updated; that head update emits `synchronize` and a new base/head-bound check. The live pilot must prove this behavior, including a base update while the head is unchanged, before enforcement. If merge queue is adopted, add `merge_group` support and revalidate before queue activation. A manual release invocation uses the same runner and release-specific verifier but is never counted as the PR's required check. + +## Open Questions + +- Which concrete AppSurface integration and package/release assertions can be safely executed inside the first host? The implementer must inventory the current [build](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml), [package gate](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/package-gate.yml), and [release contract](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/release-contract.yml) workflows and name each policy obligation before wiring the host. Missing capability blocks that profile's promotion; it does not become an empty success. +- Does the live GitHub event policy permit the selected base-owned PR trigger, and does its named check satisfy the current-head required-check rule in this repository? This is a rollout experiment, not an assumed platform guarantee. + +## Success Criteria + +1. On a live AppSurface PR, `explain` and `run` report the same plan digest for verified base/head/diff/policy inputs; altering any one makes the gate fail before a complete claim. A new head causes a new run; a base update makes the strict required check stale until the head is updated and rerun. The final verifier checks both current SHAs, so an old manifest cannot satisfy either new revision. +2. Docs-only, code, mixed/renamed/deleted, resource-backed, and release fixtures select their candidate profiles solely from policy; trusted PR or protected release context separately determines claim eligibility. Docs-only produces explicit `NoEvidenceRequired`; unrecognized paths select the conservative profile or fail. +3. Positive host runs yield verified `TargetedComplete` or `ReleaseComplete` claims as appropriate. Injected missing producer, unavailable resource, failed assertion, absent required artifact, cleanup failure, or envelope mismatch yields no complete claim and a failed gate. Release fixtures also prove tag-object/peeled-commit and package-digest binding against the protected release invocation. Fork/untrusted runs yield `ObservationOnly` and a failed required check. +4. Terminal, GitHub summary, and manifest agree on the claim and missing obligations. Secret canaries and oversized/malicious paths do not leak or exceed output limits. Normal cancellation and a forced host-process kill clean up the disposable topology within the in-VM 10-minute bound; entire-VM loss yields no complete claim and leaves no shared resource. +5. A real PR demonstrates the stable evidence check on the current head, a base-advance freshness block, and the default-branch ruleset requires it with strict freshness. The repository can merge a qualifying trusted PR and blocks an incomplete or fork-observation PR. Existing checks remain green, formatting and changed-code branch tests pass, and solution coverage is run when practical. + +## Distribution Plan + +Deliver the reference as a checked-in AppSurface workflow, policy, explicit host runner, versioned Evidence contract/CLI changes, and an [EvidenceHost adoption guide](../../start-here/evidencehost.md). A consumer starts by copying the documented checkout/policy/runner pattern and replacing the explicit host registrations; it must prove completeness of every selected test profile before enforcing its own required check. The existing AppSurface package release pipeline publishes the contract and CLI changes. The CI workflow runs on PRs; the protected release pipeline invokes its release profile. No deployment or automatic release is introduced here. + +## Dependencies + +[#775](https://github.com/forge-trust/AppSurface/issues/775) supplies the current contract and coverage seam. The GitHub required-check rollout depends on a live PR pilot and a repository administrator updating the active default-branch ruleset. An AppSurface resource-backed and release producer inventory is needed before those profiles can become required. The older [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) remains the architecture source for consumer-owned hosts and trust-envelope semantics. + +## The Assignment + +Take one real AppSurface PR that changes code and record its exact target-base tip, head SHA, and selected policy profile. Use it as the pilot fixture for verifying that the planned base-owned check reports against the current head before asking an administrator to make the check required. + +## Next Steps + +1. Inventory existing AppSurface CI evidence and write the complete checked-in policy/registration matrix; identify any selected profile that lacks a safe producer. +2. Add revision/source-diff binding to contracts, CLI, planner, verifier, and documentation; test deterministic identity and tampering/compatibility cases. +3. Implement the explicit AppSurface host runner and typed producers, then prove complete and failure branches including resource, cleanup, and release envelope behavior. +4. Add the base-owned PR workflow and protected release invocation, bounded renderer, fork observation path, and trust-isolation tests. +5. Pilot real PR check association and event policy; only then enable the exact required check in the ruleset and document the consumer adoption path. + +## What I noticed about how you think + +- You answered “AppSurface CI gates” when asked for the first proof. That makes this a real repository behavior, with branch protection as the finish line. +- You chose the stricter fork outcome: observation can inform review, but it cannot silently satisfy a required evidence check. +- You accepted the second opinion's revision-binding challenge and chose the complete EvidenceHost path. The design now has to prove the exact tested change and the harder resource/release branches, not just produce a polished YAML example. + + +## Reviewer Concerns + +Disposition: CONCERNS_RECORDED + +Stop: CONVERGENCE + +### R2-1 — completeness + +**Problem** + +> The release plan records a comparison-base commit, but the design does not define which trusted revision supplies that base or how the release event binds to it. Since policy selects the release profile from the tag-commit diff, different baselines can select different obligations while still producing a revision-bound manifest. + +**Remedy** + +> Define a deterministic, trusted source and selection rule for the release comparison base, bind that base to the protected release event, and test missing, changed, and mismatched baseline cases before allowing a ReleaseComplete claim. + +### R2-2 — completeness + +**Problem** + +> The design says a changed tag invalidates ReleaseComplete, but it does not specify a final check of the tag ref/object (or an enforced immutability guarantee) between evidence capture, verdict issuance, and publication use. A tag that moves after capture could leave a claim authorizing artifacts for a commit the release tag no longer identifies. + +**Remedy** + +> Require the trusted verifier to recheck the protected tag ref, tag object ID, and peeled commit immediately before issuing ReleaseComplete and before any publication consumes the claim, or specify and verify an equivalent immutable-tag guarantee; include a retagging race test. + +### R2-3 — feasibility + +**Problem** + +> The subject can write arbitrary content to scratch, and trusted code copies declared artifacts out, but the copy-out boundary has no path-containment, file-type, or size rules. A malicious subject could use symlinks or special files to make the trusted copier escape scratch or process unbounded data, undermining the stated isolation boundary. + +**Remedy** + +> Specify a no-follow extraction protocol that accepts only normalized relative paths resolving inside scratch and regular files, enforces per-file and aggregate count/size limits, and tests traversal, symlink, special-file, and oversized-artifact cases. + +### Prior finding evidence + +**R1-3 → R2-3 (persisting)** + +> Recommended Approach 3 specifies the ephemeral VM, rootless OCI container, mounts, credential/socket exclusions, resource network and egress limits, and envelope checks, but only says declared artifacts are copied from subject-writable scratch; it does not constrain that transfer so it cannot follow paths outside scratch or expose trusted host data. See R2-3. + diff --git a/docs/evidence-gate-diagnostics.md b/docs/evidence-gate-diagnostics.md new file mode 100644 index 000000000..d9723d27c --- /dev/null +++ b/docs/evidence-gate-diagnostics.md @@ -0,0 +1,160 @@ +# AppSurface evidence-gate diagnostics + +This guide maps the stable `ASEGC`, `ASEGG`, `ASEGO`, `ASEHB`, `ASEGH`, `ASEGS`, `ASESE`, `ASEPS`, `ASEPSCLI`, and `ASEVC` diagnostics emitted by the trusted cleanup checker, verifier I/O layer, [subject observation builder](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#trusted-subject-observation), private handoff, host, subject launcher, fixed offline entrypoint, policy-shadow validator and CLI, trusted verifier context resolver, and checked-in pilot workflow. `ASEGC` identifies downloaded cleanup-record verification, `ASEGG` identifies `verify-gate` command processing, `ASEGO` identifies the bounded non-claiming observation, `ASEHB` identifies the controller-to-subject handoff, `ASEGH` identifies host execution and a missing or inconsistent workflow verdict, `ASEGS` identifies the subject launcher, `ASESE` identifies the fixed offline entrypoint, `ASEPS` and `ASEPSCLI` identify non-claiming policy-shadow comparison and its CLI input/output layer, and `ASEVC` identifies attempt-specific verifier identity resolution. The controller capture script reports bounded plain-language errors; it does not currently emit these code families. + +These codes report a failed or incomplete operation, except `ASEHB010`, which reports completed subject execution without a gate claim. None turns an observation into a gate pass. The separate `ASEVG` codes are final library-verdict results, documented in the planner's [trusted PR verdict reference](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#trusted-pr-verdict-boundary). + +## Read the current result correctly + +`run` can exit `0` when the trusted policy explicitly selects an empty targeted profile and the host emits `NoEvidenceRequired`. That is a successful host result for that profile; it does not run a producer or publish a final CI verdict. Other profiles remain incomplete while their producer and resource registrations are absent. + +The checked-in `pull_request_target` workflow is a separate pilot. Its controller resolves the captured diff through the base-owned policy, and its credentialless job validates the bounded handoff. An explicitly empty documentation profile needs no OCI run; a supported code profile can start only with a reviewed digest-pinned image and offline dependencies. Both subject results say `claimEligible: false`. A completed code-coverage result also exports three fixed, bounded files to a separate attempt-scoped artifact; the trusted verifier compares their bytes with the receipt index after fresh PR recapture. Matching bytes prove transport integrity only, not producer truth or checkout/isolation authority. The verifier recaptures current PR revisions, checks the downloaded handoff and bounded subject result against that capture, requires the [same-run cleanup completion record](evidence-gate-subject-supervisor.md#attestation) for code coverage, resolves the attempt-specific subject job, and runs `verify-gate` against a trusted host manifest when both upstream jobs succeed. The [finalizer](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-finalize.py) publishes the independent verifier's bounded result only when the controller and subject jobs and verifier step succeeded and the machine, JSON summary, and Markdown outputs agree. A fully empty profile can therefore yield `ASEVG000` and a passing pilot job from fresh PR/run/job API authority without a subject checkout attestor. Missing, inconsistent, or unavailable outputs yield `ASEGH003` and fail; nonempty profiles still lack the required checkout and isolation proof and remain ineligible. The branch-owned shadow job checks contracts only. Keep the pilot non-required until the [rollout record](evidence-gate-rollout.md) proves every selected profile and current-head association; see also the [policy and producer matrix](evidence-gate-policy-matrix.md). + +## `ASEGC`: trusted cleanup-record handoff + +The [trusted cleanup verifier](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-verify-cleanup.py) runs after the handoff has been rebound to the fresh Git tree. It requires a canonical, complete 4 KiB or smaller cleanup record for `code-coverage`; `documentation-only` must have no cleanup record. The verifier also requires the credentialless subject job to have succeeded before this step runs. These checks establish a completed bounded cleanup handoff, not independent checkout, isolation, or producer authority. + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEGC001` | The trusted verified plan is missing, unsafe, oversized, or malformed. | Recreate the plan from the fresh base/head capture; do not use the downloaded plan as authority. | +| `ASEGC002` | The coverage cleanup artifact is missing, unsafe, malformed, noncanonical, or over 4 KiB. | Inspect the subject cleanup and artifact-upload steps; rerun with a fresh attempt-scoped artifact. | +| `ASEGC003` | The record does not report completed container, mount, and scratch cleanup within the 600-second deadline. | Keep the gate failed, diagnose the independent supervisor, and rerun after cleanup is proved. | +| `ASEGC004` | The profile is unsupported or an empty documentation profile unexpectedly has a cleanup artifact. | Preserve policy selection and the profile-specific artifact contract; do not reinterpret another profile as documentation-only. | + +## `ASEPS`: non-claiming policy-shadow comparison + +These findings come from the [policy-shadow validator](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#non-claiming-policy-shadow-comparison). They compare candidate policy and fixture data with a protected base policy and fixture set supplied by the caller. The library cannot establish that provenance or issue a required-check claim. + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEPS001` | The trusted base policy is invalid or exceeds the bounded policy shape. | Repair the protected base policy in a separately reviewed change; do not substitute candidate policy as the baseline. | +| `ASEPS002` | The candidate policy is invalid or exceeds the bounded policy shape. | Repair the proposed policy and rerun the non-claiming comparison. | +| `ASEPS003` | The base fixture set is empty, malformed, duplicated, or over limit, or candidate fixture input is malformed or over limit. | Restore bounded, unique fixture IDs and valid paths; preserve the base-owned fixture source. | +| `ASEPS004` | Candidate fixture data removed or edited a base-owned case. | Restore that case unchanged; add supplemental candidate cases under new IDs. The base case remains active during comparison. | +| `ASEPS005` | The base policy could not resolve a fixture. | Fix the protected base policy or fixture through a reviewed control-plane update. | +| `ASEPS006` | The candidate policy could not resolve a fixture. | Fix the candidate rule/profile mapping without dropping the fixture. | +| `ASEPS007` | A candidate selection omits or weakens a base-selected requirement. | Preserve the resource, producer, assertion, artifact, and obligation requirements selected by the base policy. | +| `ASEPS008` | A control-plane fixture path has no explicit matching rule; conservative fallback alone selected it. | Add an explicit reviewed control-plane mapping while retaining at least the base-selected obligations. | + +The [`appsurface evidence shadow-policy` command](../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-evidence-shadow-policy) wraps those findings without issuing a claim. Its I/O failures use these codes: + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEPSCLI001` | A required input path is missing or unreadable. | Supply the protected base policy and fixture files plus the candidate policy; a missing candidate fixture file alone is treated as an empty candidate set. | +| `ASEPSCLI002` | An input is malformed Evidence JSON. | Repair the source file rather than editing the emitted result. | +| `ASEPSCLI003` | An input exceeds its 1 MiB bound. | Keep the complete case set under the reviewed limit or make a reviewed limit change; do not truncate inputs. | +| `ASEPSCLI004` | Input validation could not complete safely. | Keep the result incompatible and inspect the protected input sources. | +| `ASEPSCLI005` | The serialized comparison exceeds its 1 MiB output bound. | Preserve failure and reduce unexpectedly large policy/fixture text through a reviewed change. | +| `ASEPSCLI006` | A new bounded result file cannot be created. | Use a new writable output path; existing files are not replaced. | +| `ASEPSCLI010` | The comparison has one or more incompatibility findings. | Read the bounded JSON result and repair the named `ASEPS` or input finding; do not treat this shadow result as a gate claim. | + +## `ASEVC`: trusted verifier context resolution + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEVC001` | The fresh controller identity, trusted workflow environment, attempt-specific GitHub run or subject job, API response, or create-new output is unavailable, malformed, stale, or ambiguous. | Keep the pilot failed. Recapture the current PR from the base-owned verifier job, confirm the run attempt and unique successful subject job through the [workflow run](https://docs.github.com/en/rest/actions/workflow-runs#get-a-workflow-run-attempt) and [workflow job](https://docs.github.com/en/rest/actions/workflow-jobs#list-jobs-for-a-workflow-run-attempt) APIs, then rerun with a new output path. Do not infer the job ID from a downloaded artifact or `head_sha`. | + +## `ASEGO`: bounded trusted subject observation + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEGO001` | A verified plan, canonical verifier identity, completed subject result, required coverage cleanup/artifact/preflight input, or create-new output is missing, unsafe, inconsistent, or over its fixed limit. | Keep the pilot failed. Repeat the [trusted verifier handoff](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#trusted-subject-observation) from the same current run attempt with fresh output paths; investigate a mismatched fixed artifact or image digest rather than editing the observation or granting a claim. | + +## `ASEGG`: verifier command and handoff processing + +| Code | Cause | Safe fix | Start here / reference | +| --- | --- | --- | --- | +| `ASEGG001` | `verify-gate` arguments are missing, duplicated, unknown, or malformed. | Run `--help`; provide each required option once and use a new output directory. | [Runner command and verifier boundary](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#verify-gate-and-current-pilot) | +| `ASEGG102` | A required trusted input is unavailable, or trusted input/output I/O could not be processed safely. | Check the trusted paths, permissions, and object store; regenerate missing handoffs from the base-owned controller. | [Runner command and verifier boundary](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#verify-gate-and-current-pilot) | +| `ASEGG103` | A plan, manifest, or identity is malformed or noncanonical JSON, or the trusted policy is malformed JSON. | Regenerate the handoff with the contract serializer; repair the reviewed base-owned policy at its source. Do not hand-edit a plan, manifest, or identity. | [Revision-bound verifier](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#trusted-pr-verdict-boundary) | +| `ASEGG106` | The verification result or summary exceeds its output bound. | Preserve the complete verdict; inspect the bounded inputs and summary-producing identifiers, and report a reproducible limit issue rather than truncating evidence. | [Runner command and verifier boundary](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#verify-gate-and-current-pilot) | +| `ASEGG107` | A plan, manifest, policy, or identity handoff exceeds its configured input byte limit. | Regenerate valid bounded handoffs. Do not truncate plans, manifests, policy, or identity to fit. | [Revision-bound verifier](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#trusted-pr-verdict-boundary) | +| `ASEGG108` | A verification result file already exists in the output directory; outputs are create-new. | Choose a fresh output directory and preserve the earlier result for diagnosis. | [Runner command and verifier boundary](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#verify-gate-and-current-pilot) | +| `ASEGG199` | An unexpected non-fatal verifier failure occurred. | Keep the run ineligible; inspect trusted runner diagnostics and the input handoffs, without exposing raw untrusted content or converting the result to success. | [Trusted PR verdict reference](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#trusted-pr-verdict-boundary) | + +## `ASEHB`: private controller-to-subject handoff + +These codes come from the `create`, `execute`, and `verify` modes of [`evidence-gate-handoff.py`](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-handoff.py) or the workflow's fixed result fallback. The trusted `verify` mode also rejects a downloaded archive or plan that differs from a fresh capture of the current Git tree. A successful handoff or subject run is still non-claiming; the trusted verifier must independently authorize the final PR check. + +| Code | Cause | Safe fix | +| --- | --- | --- | +| `ASEHB001` | A captured/downloaded identity, v2 plan, diff, digest, run attempt, bounded file set, or completed subject artifact index is missing or mismatched. | Recreate the handoff from the same base-owned policy, exact captured Git objects, and current workflow attempt. Do not edit the artifact. | +| `ASEHB002` | The controller cannot safely create or publish a private handoff directory. | Use a new physical output path under the ephemeral runner's private temporary root. | +| `ASEHB003` | Bounded Git tree inventory or archive creation failed or exceeded its deadline or byte limit. | Inspect the trusted Git store and limits; recapture the exact revision pair rather than substituting a working-tree snapshot. | +| `ASEHB004` | The archived tree contains an unsafe entry, omits a Git blob, changes a blob or mode, or exceeds a fixed bound. | Correct the head tree or its export attributes; do not skip the entry or trust the transformed archive. | +| `ASEHB005` | The downloaded snapshot could not be materialized as a bounded regular-file tree. | Retire the failed subject attempt and regenerate the exact private artifact. | +| `ASEHB006` | The bounded subject result could not be written safely. | Preserve failure and rerun with a new private result path. | +| `ASEHB007` | A fork capture is observation-only. | Review and promote the exact commit to a same-repository branch before requesting a gate-eligible PR run. | +| `ASEHB008` | The selected profile is unsupported, the reviewed digest-pinned offline image is unavailable, or the trusted launcher cannot load. | Implement the declared profile and image supply; do not substitute `code-coverage` for another profile. | +| `ASEHB009` | The selected subject process exited unsuccessfully. | Read its bounded diagnostic, fix the declared producer, and rerun a fresh attempt. | +| `ASEHB010` | The selected subject execution completed, but no trusted verifier has authorized a claim. | Continue to the base-owned verifier; do not use this result as a required-check verdict. | +| `ASEHB011` | An unexpected handoff failure or missing result triggered the fixed fallback. | Keep the run failed and inspect the trusted controller/subject job logs without exposing raw subject output. | +| `ASEHB012` | The fixed coverage artifact export is missing, linked, changed, oversized, contains unexpected files, or differs from the completed receipt index. | Keep the run non-claiming; recreate the same-run artifact export and verify its three fixed files against a fresh receipt. | +| `ASEHB013` | The host-side OCI envelope observation is absent, malformed, replayed from another run, or names a different image than the trusted preflight selected. | Keep the run non-claiming; inspect the base-owned launcher and preflight output, then rerun the exact head with a new attempt. Do not edit or re-sign the downloaded receipt. | + +## `ASEGH`: host and pilot workflow + +| Code | Cause | Safe fix | Start here / reference | +| --- | --- | --- | --- | +| `ASEGH001` | `run` arguments are missing, duplicated, unknown, or malformed. | Run `--help`; provide the required plan, policy, repository, and new output-directory options. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH003` | The finalizer cannot read a complete, consistent independent verifier result, or an upstream job/step failed after an otherwise eligible result. | Inspect the controller, subject, and verifier outcomes plus the bounded result files. Preserve fail-closed behavior; keep the pilot non-required until every selected profile is complete. | [Rollout record](evidence-gate-rollout.md) | +| `ASEGH102` | A required host input is unavailable, or host input/output I/O could not be processed safely. | Check the base-owned policy, plan, Git object store, paths, and permissions; recapture missing inputs in the trusted controller. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH103` | A plan is malformed or noncanonical, the trusted policy is malformed JSON, or the plan has no bounded identity from which a manifest can safely be formed. | Recreate the canonical plan and repair the reviewed base-owned policy source. If identity is not trustworthy, the host correctly emits no manifest. | [Revision-bound planning](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#revision-bound-git-change-capture) | +| `ASEGH104` | The plan fails trusted revision/policy verification, including the planner's exact-plan mismatch. | Discard the handoff and rebuild it from the protected policy and exact base/head objects in the trusted object store. | [Revision-bound planning](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#revision-bound-git-change-capture) | +| `ASEGH105` | Trusted host-input processing failed, or the host could not verify its produced manifest against the plan. | Keep the result invalid; inspect trusted input provenance and host diagnostics, then regenerate from the same reviewed policy and revisions. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH106` | Serialized plan, manifest, or summary exceeds the host output bound. | Retain all obligations and evidence; inspect the input profile and bounded output fields. Do not truncate the manifest or summary. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH107` | A host input exceeds the 4 MiB input bound. | Recreate the expected bounded input at its source. Do not trim changed paths or policy requirements to pass the limit. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH108` | A host result file already exists; outputs are create-new. | Select a fresh output directory and retain the existing result. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH130` | Host execution was cancelled before a complete host result was issued. | Keep the run incomplete; rerun only after the trusted controller confirms the same revisions and run identity are still current. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH199` | An unexpected non-fatal host failure occurred. | Treat the run as failed with no successful claim; inspect trusted runner diagnostics and retry only from validated inputs. | [Host run behavior](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#host-run-behavior) | +| `ASEGH201` | The selected profile names a producer or resource with no explicit first-party host registration. | Keep the profile's obligations. Implement and review the missing registration before claiming support; otherwise expect an incomplete manifest. | [Policy and producer matrix](evidence-gate-policy-matrix.md) | +| `ASEGH202` | The plan is not an explicitly rule-selected empty targeted profile supported by this runner. | Use an empty profile only for reviewed low-risk paths. For any evidence-bearing profile, wait for its producer/resource registrations; do not remove obligations to obtain a pass. | [Policy and producer matrix](evidence-gate-policy-matrix.md) | + +## `ASEGS`: standalone subject launcher + +These diagnostics come from the OCI execution primitive, which the pilot can invoke only for a supported selected profile with a configured image. Its successful subject-process exit is still not a gate claim. Keep controller-owned paths, image digest, profile, and limits authoritative; never relax an isolation check to make the launcher proceed. + +| Code | Cause | Safe fix | Start here / reference | +| --- | --- | --- | --- | +| `ASEGS001` | A controller-owned resource limit is missing, malformed, or outside approved bounds. | Supply timeout, memory, CPU, PID, and output limits from the approved profile and supported increments. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS002` | A checkout or scratch path is unavailable, noncanonical, linked, overlapping, or outside the required path boundary. | Use a real canonical checkout and a new direct child of `RUNNER_TEMP` for scratch; keep the two disjoint. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS003` | The runner is not the required Linux, non-root, ephemeral GitHub-hosted context, or its trusted run/directory identity is incomplete or unsafe. | Run only on the expected hosted runner with its intact environment and private rootless runtime directory. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS004` | The image reference is malformed or is not a canonical SHA-256 digest reference. | Supply the exact controller-pinned immutable digest; a tag is not sufficient. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS005` | The profile ID is malformed or is not in the launcher's controller-owned offline profile registry. | Use only a registered supported profile. Resource-backed profiles are unsupported by this launcher; do not relabel them as offline. | [Policy and producer matrix](evidence-gate-policy-matrix.md) | +| `ASEGS006` | The required rootless Podman executable is missing, unsafe, or not protected by the runner image. | Use a reviewed runner image with the expected protected executable; do not install or fetch an engine from the subject job. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS007` | The OCI engine returned malformed inspection or command JSON. | Use a compatible trusted runner engine and investigate its bounded response; do not skip inspection. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS008` | A trusted OCI process could not start or failed during a launcher stage. | Check the trusted engine and runner setup for that stage; preserve the failure and do not treat a subject exit as a claim. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS009` | Rootless OCI, cgroup v2, or CPU, memory, or PID enforcement is unavailable. | Use a runner that enforces every declared resource bound; do not run without cgroup enforcement. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS010` | The exact pinned image is not already present in local engine storage. | Stop: the launcher intentionally does not pull images. The repository currently supplies no pinned image, so image provisioning must be implemented and reviewed before this primitive can run. | [Policy and producer matrix](evidence-gate-policy-matrix.md) | +| `ASEGS011` | Image inspection is ambiguous, does not prove the exact pinned digest, or reports writable/anonymous volumes. | Provision exactly one locally available digest-matching image with no declared volumes; keep the inspection gate enabled. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS012` | The created container differs from the fixed command, identity, environment, limits, mounts, or isolation contract. | Investigate runner/engine behavior and restore the exact read-only, credentialless, no-network configuration; never waive the check. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS013` | Subject execution was cancelled. | Keep the result non-claiming and let trusted cleanup finish; rerun only as a new controller-authorized attempt. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS014` | A bounded launcher stage exceeded its deadline. | Diagnose the runner or process first; change a timeout only through reviewed controller-owned profile limits. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS015` | A bounded launcher stage exceeded its output-byte limit. | Reduce unexpected process output at its trusted source. Change a limit only through reviewed controller-owned bounds; do not discard output and call the run complete. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS016` | The trusted process could not be stopped safely after cancellation, timeout, or another failure. | Abandon the run and retire the ephemeral runner after trusted cleanup; never issue a claim from a process that may still be running. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS017` | Subject container removal or host tmpfs unmount failed. | Keep the result non-claiming and retire the ephemeral runner; do not retry in the same contaminated environment. An independent supervisor is still required before eligible claims. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS018` | The subject's exported result record is missing, malformed, noncanonical, mismatched to its exit status, or cannot be saved safely. | Inspect the fixed entrypoint and the bounded attached-output transport; do not infer success from the container exit code alone. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS019` | The quota-limited host scratch tmpfs could not be mounted or its live options, identity, or limits could not be verified. | Keep the result non-claiming and repair the trusted runner mount boundary; do not skip byte or inode verification. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS020` | The controller source diff is malformed, outside the subject checkout/scratch boundary, outside its byte bound, or does not match its captured SHA-256. | Recreate the same-run handoff from the exact controller capture; do not substitute a subject-provided diff. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASEGS021` | The completed artifact index is missing or malformed, or a fixed coverage artifact cannot be copied safely from the stopped container's scratch mount, exceeds its bound, or disagrees with that index. | Keep the run non-claiming; inspect the fixed output and private export path, then rerun a new attempt without weakening file or digest checks. | [Subject launcher contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | + +## `ASESE`: fixed offline subject entrypoint + +The [entrypoint](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-entrypoint.py) is a non-claiming primitive intended for a reviewed subject image. The pilot launcher can call it when that image is supplied, but no image or locked feed has been approved for the repository. The current solution's container-dependent tests produce `ASESE010`. The mounted controller diff is checked against its captured SHA-256 and used for patch thresholds; a successful toy-fixture execution record still says `claimEligible: false` and is not a manifest claim. + +| Code | Cause | Safe fix | Start here / reference | +| --- | --- | --- | --- | +| `ASESE001` | A fixed mount, root path, user-owned scratch directory, or container mount table is missing or unsafe. | Restore the exact read-only subject and dependency roots and private writable scratch mount; do not relax path or ownership checks. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE002` | The offline package feed, fixed solution, project path, or selected dependency lock is missing, ambiguous, or malformed. | Supply the reviewed image feed and the project's existing lock file, including a declared Linux RID lock; keep restore in locked mode. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE003` | A fixed command or no-follow source staging step cannot run safely, or the source tree changes, exceeds bounds, or contains unsupported links/types. | Recreate the exact clean subject snapshot and runner environment, then retry a new run. Do not skip source entries to make staging pass. | [Trusted handoff design](plans/issue-777-policy-driven-ci-evidence-gate-implementation.md) | +| `ASESE004` | The required .NET 10 SDK or runtime is unavailable. | Build and pin an image containing the reviewed .NET 10 toolchain; do not fetch tools from the subject checkout. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE005` | A fixed execution or source-staging deadline expired. | Inspect the trusted runner and profile budget; keep the run failed until a reviewed bound can accommodate it. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE006` | A fixed subject command exceeded its aggregate output-byte limit. | Diagnose unexpected output in the isolated run; do not discard it and declare success. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE008` | Locked restore, coverage collection, or the aggregate/patch coverage gate returned a nonzero exit. | Read the bounded step status and resolve the failing fixed command; no claim is issued. | [Coverage core reference](../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md) | +| `ASESE009` | The canonical bounded subject result could not be written, read, or streamed before container scratch disappears, or it exceeded its byte cap. | Preserve the failed execution state and use a fresh private scratch directory; do not treat a missing transport record as a completed run. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE010` | The full solution contains container-dependent tests but the offline profile has no declared service or network envelope. | Implement a reviewed disposable resource envelope and complete producer integration; do not exclude these tests or call the offline run complete. | [Policy and producer matrix](evidence-gate-policy-matrix.md) | +| `ASESE011` | A fixed subject process group could not be stopped or reaped after failure or timeout. | Keep the run failed and retire the ephemeral runner through trusted cleanup; never reuse a runner that may retain a child process. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE012` | The fixed source diff mount or digest is missing, unsafe, outside its byte bound, or mismatched. | Regenerate the controller handoff for the exact revision pair and keep the patch coverage run failed. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | +| `ASESE013` | A required coverage output is missing, linked, changing, oversized, or absent from the fixed artifact index after the gate command succeeds. | Inspect the isolated coverage outputs and restore the exact bounded regular files; do not infer success from the command exit alone. | [Subject entrypoint contract](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#subject-launcher) | + +For the first-time EvidenceHost concepts and consumer workflow, start at [EvidenceHost: start here](../start-here/evidencehost.md). For gate readiness and current implementation gaps, use the [rollout record](evidence-gate-rollout.md) and [policy and producer matrix](evidence-gate-policy-matrix.md). diff --git a/docs/evidence-gate-policy-matrix.md b/docs/evidence-gate-policy-matrix.md new file mode 100644 index 000000000..df52dc468 --- /dev/null +++ b/docs/evidence-gate-policy-matrix.md @@ -0,0 +1,34 @@ +# AppSurface evidence gate policy and producer matrix + +This is the implementation inventory for [issue #777](plans/issue-777-policy-driven-ci-evidence-gate-implementation.md). A selected profile may become a required claim only after every producer, resource, assertion, artifact slot, deadline, and cleanup action in its row has an explicit registration and a passing failure-path proof. Existing workflow success is not an EvidenceHost producer result. The reference gate remains non-required until the [rollout pilot](evidence-gate-rollout.md) proves current-head association and strict freshness. + +| Proposed path class | Canonical existing seam | Selected obligation and required resource | Artifact and cleanup | Current promotion state | +|---|---|---|---|---| +| Reviewed docs-only paths | [Evidence planner](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md) with an explicit empty targeted profile | Explicit `NoEvidenceRequired`; no producer or resource | Revision-bound plan and independent final verdict; credentialless handoff job still runs without OCI | Local positive and negative verifier/finalizer paths pass; **not promoted** until the [base-owned live pilot](evidence-gate-rollout.md) proves current-head association and old-base control-plane behavior | +| Code and coverage | [Solution coverage script](https://github.com/forge-trust/AppSurface/blob/main/scripts/coverage-solution.sh) and [coverage core](../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md) | Coverage thresholds: 95% overall line, 85% overall branch, 95% patch line, 85% patch branch; locked .NET 10 input | Cobertura, gate report and bounded diagnostics; isolated scratch cleanup | **Blocked**: the [offline image candidate](../scripts/evidence-gate-subject-image/README.md) has no published feed/digest; the existing [CLI coverage producer](../Evidence/ForgeTrust.AppSurface.Evidence.Cli/CoverageEvidenceProducer.cs) does not split container-backed test projects inside the subject boundary | +| Package artifacts and release-preparation PRs | [Package gate workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/package-gate.yml), [PackageIndex command](../tools/ForgeTrust.AppSurface.PackageIndex/README.md), and [release preparation verifier](../tools/ForgeTrust.AppSurface.Release/README.md) | Locked restore, build and package contract assertions; Node/pnpm and .NET 10 dependencies | Package manifest, validation report and exact `.nupkg` digests; remove per-run package/proof scratch | **Blocked**: controlled immutable package supply and a credentialless package producer are not registered | +| Durable PostgreSQL integration | [PostgreSQL verification script](https://github.com/forge-trust/AppSurface/blob/main/Durable/verify-postgresql.sh) and [local proof](../examples/durable-postgresql/README.md) | Disposable PostgreSQL 16.5 readiness and real database assertions | Per-scenario JSON and `run.json`; independent supervisor must remove database/container/network | **Blocked**: current scripts use Docker/Testcontainers directly, while the subject job cannot receive the Docker socket | +| Keycloak theme integration | [Build workflow theme proof](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) | Pinned Keycloak image, local service readiness and served-stylesheet assertion | Theme JSON/Markdown/log metadata; independent supervisor removes runtime and Buildx resources | **Blocked**: proof is an inline shell block with Docker/Buildx access, not a registered isolated producer | +| Protected release invocation | [Release inspect](../tools/ForgeTrust.AppSurface.Release/README.md), [release publish workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/release-publish.yml) and [release contract workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/release-contract.yml) | Validated V2 preparation base, annotated tag object and peeled commit, package/archive digest assertions | Read-only machine projection and digest-bound artifacts; no draft creation, upload, Pages deployment or publication in the evidence runner | **Blocked**: the producer now rereads the fixed AppSurface HTTPS tag ref after local inspection and rejects missing, lightweight, or moved tag identities before writing evidence. It still cannot issue a release claim: the production invocation provider is unavailable, the remote must be reread immediately before verdict and publication use, and exact isolated package/archive production and digest binding remain unimplemented | + +The existing [build workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml), [package gate](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/package-gate.yml), and [release checks](https://github.com/forge-trust/AppSurface/tree/main/.github/workflows) remain independently necessary. No job is removed with #777. During the pilot, record each existing job's assertion overlap, outcome, and added runtime. A later migration can assign steady-state ownership only after equivalent success and failure behavior is observed and separately reviewed. + +The [Release Publish workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/release-publish.yml) now rejects non-`main` dispatches when this protected workflow version runs. It checks that the workflow file ref is the expected `main` workflow and that the checkout running release tooling equals that workflow commit, with checkout credentials disabled. It also requires a configured `release-publish` environment with an independent reviewer, no administrator bypass, and exactly one custom deployment branch policy for `main`; all `contents: write` jobs reference it. The [Release publish guide](../tools/ForgeTrust.AppSurface.Release/README.md#publish) explains the ordering and administrator setup. A branch-edited workflow cannot be authenticated by checks inside itself, so administrator-controlled workflow policy remains necessary for publication. This closes a prerequisite for a trusted release invocation; the EvidenceGate release row remains blocked because its production invocation provider, final remote-tag reread, and exact built package/archive digest binding are still absent. + +The branch-owned release-publish change now calls the read-only [Docs archive tuple verifier](../tools/ForgeTrust.AppSurface.Release/README.md#docs-publication) from the protected workflow checkout before creating a draft release. It hashes the selected archive bytes and compares the versioned filename, publication-plan digest, and `.sha256` sidecar. This checks one generated archive at the publication boundary; it does not authenticate the protected tag for its entire publication lifetime, cover NuGet package bytes, or feed a complete EvidenceGate release producer. The `release-publish` environment and live protected pilot remain prerequisites. + +The AppSurface-specific policy must put unknown paths and mixed changes into a conservative profile containing the union of every targeted PR obligation. The [planner](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md) validates this property before a trusted gate run. Release-preparation PRs use a targeted PR profile; only the protected release invocation may select `ReleaseComplete` from the validated V2 preparation-base/tag diff. A missing safe producer keeps its profile fail-closed and prevents ruleset activation; deleting its obligation to get a green check is not a valid fallback. + +The policy uses the same conservative union for package project and lock files inside the PostgreSQL and Keycloak resource trees. Those paths change both dependency supply and an integration surface; the more specific project/lock rules carry explicit precedence so the resource rule cannot silently drop the package obligation. Non-.NET executable assets without a dedicated producer also select the conservative profile and remain incomplete. + +The [checked-in policy](https://github.com/forge-trust/AppSurface/blob/main/.appsurface/evidence/evidence.policy.json) also maps the gate runner, release and package tooling, workflows, gate documentation, and [shadow fixtures](fixtures/issue-777-policy-shadow/README.md) explicitly to the conservative control-plane profile. These files can change the authority or evidence inventory itself, so a narrow package-only or documentation-only selection would be insufficient. The [non-claiming shadow comparison](../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-evidence-shadow-policy) checks the proposed selection against base-owned fixture cases. Its workflow wiring is currently present only on the implementation branch; protected-base authority requires merge and a live smoke run. + +Resource provisioning belongs to the base-owned supervisor, with only declared service endpoints exposed to the credentialless subject VM. Restore, build hooks, and all head-controlled execution stay in that VM with pinned SDK/OCI images and locked dependencies. Exact per-profile deadlines and an overall workflow budget will be fixed from the cold-cache pilot before the check becomes required. The trusted verifier checks the current PR base/head or protected tag after the subject result, so an earlier successful producer cannot authorize a changed revision. + +The current [rollout record](evidence-gate-rollout.md#current-state) identifies a concrete budget mismatch: the conservative policy's serial resource and producer maxima total 107 minutes, but the subject job times out after 40 minutes. Resource-backed and package profiles also exceed that job budget. Their timeout declarations are ceilings rather than observed duration; none may be promoted until measured pilots support limits that fit the workflow's execution and cleanup windows. + +For the fixed `code-coverage` subject, the [host launcher](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject.py) now emits a bounded OCI `envelopeReceipt` only after checking the local image, live scratch tmpfs, and Podman isolation configuration and receiving supervisor cleanup. Its fields distinguish settings checked in Podman inspect from a live scratch-quota check; configured cgroup limits are not proof of effective enforcement. The [handoff verifier](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-handoff.py) binds it to the current run and the digest selected by trusted image preflight. This cross-job consistency check does not authenticate the actual consumed checkout or make an incomplete producer claim complete; the code/coverage row remains blocked pending those independent proofs and the missing service envelope. + +After the fresh Git recapture and bounded artifact transfer, the [trusted verifier workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) also reruns the existing [coverage gate](https://github.com/forge-trust/AppSurface/blob/main/Cli/ForgeTrust.AppSurface.Cli/CoverageGate.cs) on the downloaded Cobertura XML and the freshly captured source diff. The verifier uses an empty `/subject` directory only to normalize the fixed entrypoint's absolute Cobertura paths; it never executes files from that tree. This catches a subject report whose transferred coverage data fails the base-owned threshold calculation. The fixed replay thresholds must change with the trusted `code-coverage` policy declaration. Replaying subject-supplied XML cannot prove that tests ran or that its hit counts are truthful, so this step remains non-claiming until an independent subject measurement and producer registration are available. + +The verifier also emits a [bounded subject observation](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#trusted-subject-observation) after the handoff, cleanup, replay, and attempt-specific job checks. Its hashes identify the downloaded bytes that passed these checks and prepare an authenticated verifier handoff. `claimEligible: false` is fixed; this artifact does not supply the missing checkout, effective isolation, or producer proof and does not change any row's promotion state. diff --git a/docs/evidence-gate-rollout.md b/docs/evidence-gate-rollout.md new file mode 100644 index 000000000..1b5c8f560 --- /dev/null +++ b/docs/evidence-gate-rollout.md @@ -0,0 +1,154 @@ +# AppSurface evidence gate rollout record + +This runbook tracks the live proof required by [issue #777](plans/issue-777-policy-driven-ci-evidence-gate-implementation.md). The [policy matrix](evidence-gate-policy-matrix.md) identifies which profile obligations have safe first-party producers. A successful local plan, manifest, or shadow check is not proof that GitHub associates a base-owned check with the PR's current head. + +## Current state + +The active `Default` ruleset (GitHub ruleset ID `7295365`) has no required status-check rule as of 2026-10-01. Its 2026-10-02 API response also permits `OrganizationAdmin` bypass and neither dismisses stale reviews nor requires approval after the last push. The [protected-main image publisher](../scripts/evidence-gate-subject-image/README.md#protected-main-publisher-future-non-claiming) now rejects those settings; the repository administrator must remove the bypass and require a fresh review of the final PR revision before that publisher can run. Existing [build](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) and [package gate](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/package-gate.yml) workflows remain active. The #777 implementation branch is a self-change PR candidate: its new `pull_request_target` controller cannot become the base-owned authority until that code reaches the default branch. The [branch-owned shadow workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate-shadow.yml) validates contracts with a distinct, non-claiming name. The proposed [base-owned event pilot](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) now publishes the independent verifier result for a fully empty documentation profile when every upstream step succeeds; missing or incomplete evidence fails. This conditional behavior has local tests but no live base-owned proof. Keep the job non-required until the subject image and offline dependencies, isolation attestation, complete subject-result and producer verification, all selected producer registrations, and current-head check association have been proved. + +The publisher also needs the environment-scoped [ruleset-inspection credential](../scripts/evidence-gate-subject-image/README.md#protected-main-publisher-future-non-claiming). Its read-only workflow token cannot see bypass actors in GitHub's ruleset API, so a missing credential leaves publication blocked even after the ruleset settings are corrected. + +The [Release Publish workflow](../tools/ForgeTrust.AppSurface.Release/README.md#publish) now requires a separate `release-publish` environment before any write-capable release job. The current repository environment inventory has no such environment. A repository administrator must configure an exact `main` custom deployment branch policy, at least one independent reviewer with self-review disabled, and administrator bypass disabled. The validation job checks that configuration before release commands; an absent or weakened environment fails closed. This does not replace an organization or repository workflow policy, because branch-edited workflow files can remove in-workflow checks. + +The release workflow now rereads both the annotated tag object ID and peeled commit before draft asset upload and final promotion. These reads still have a check/use window: a writer allowed to replace a release tag can change it after the last read. The repository ruleset API currently exposes no tag-targeting ruleset to this token. Before publication relies on this workflow, an administrator must verify the effective repository and organization rules, then enforce update and deletion restrictions for release tags without a publication-capable bypass. Record that live rule and a same-commit retag rejection in the protected release pilot; the in-workflow rereads alone do not establish tag immutability. + +The proposed release workflow also runs a read-only [Docs archive tuple check](../tools/ForgeTrust.AppSurface.Release/README.md#docs-publication) from its protected workflow checkout before creating a draft release. That check compares the generated archive bytes with the publication plan and `.sha256` sidecar for the requested version. It is a local byte-consistency check; until the `release-publish` environment exists and a protected pilot runs, it has no live proof. It does not cover NuGet packages or issue a `ReleaseComplete` EvidenceGate claim. + +GitHub's [default `pull_request_target` event policy](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target#default-policy-for-pull_request_target) is currently in evaluation mode for affected public repositories and is scheduled for enforcement on November 2, 2026. GitHub says a repository with an applicable explicit Actions event policy is exempt from that default. The repository Actions-policy API returned no repository policy on 2026-10-03; the current token cannot read organization policies, so the effective policy and pilot event availability remain unverified. Before merging or requiring this check, a repository or organization administrator must inspect the effective policy and insights, then explicitly allow this workflow's `pull_request_target` event only if the isolation pilot supports it. If the event is blocked, stop rollout and use the separately designed base-owned check publisher described in the [approved plan](plans/issue-777-policy-driven-ci-evidence-gate-implementation.md); a skipped or missing check is not evidence success. + +This ordering requires a staged rollout. First, validate and merge the implementation while the evidence check remains non-required; the branch-owned shadow cannot certify its own proposed controller. Next, run the base-owned live pilot from `main` and record the outcomes below. Only then may an administrator add the observed verifier context to the ruleset. A draft implementation PR cannot itself supply the base-owned pilot evidence or safely activate its own required check. + +The checked-in [policy](https://github.com/forge-trust/AppSurface/blob/main/.appsurface/evidence/evidence.policy.json) and [subject workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) also disagree on a worst-case deadline. The host runs declared resources and producers serially. The `pr-conservative` profile permits 720 seconds of resource readiness plus 5,700 seconds of producer execution (107 minutes), while the credentialless subject job has a 40-minute timeout. PostgreSQL, Keycloak, and package profiles likewise permit 60–73 minutes before cleanup. These are declaration maxima, not measured pilot durations; a fast run could finish, but the current job cannot honor the declared budgets on their slow paths. Before any nonempty profile is promoted, inventory its actual producer and cleanup times in the live pilot, choose reviewed per-stage and total limits that fit the job budget, and reject a policy whose serial maximum exceeds that budget. Do not shorten an obligation or treat a job timeout as successful evidence. + +The [GitHub Actions job API](https://docs.github.com/en/rest/actions/workflow-jobs) reports run and job metadata but has no independent measurement of the worktree a job actually consumed. For [`pull_request_target`](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request_target), run `head_sha` can identify the base-side workflow commit even when a trusted step explicitly supplies a PR head. The implementation therefore cannot infer checkout provenance from API `head_sha`; its production authority provider leaves the subject checkout unknown. An explicit empty profile needs no subject checkout, but any nonempty profile remains ineligible until the approved trusted handoff and isolation checks are implemented. The controller-owned source snapshot and any [GitHub artifact attestation](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations/using-artifact-attestations-to-establish-provenance-for-builds) can authenticate the handed-off bytes, but the base-owned workflow and runner still have to guarantee that the subject job consumes those bytes. + +The [approved implementation plan](plans/issue-777-policy-driven-ci-evidence-gate-implementation.md) selects a base-owned handoff across separate ephemeral GitHub-hosted jobs. The [workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) uses the trusted base checkout to resolve the exact captured base/head diff and checked-in policy into a v2 plan. The [handoff implementation](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-handoff.py) inventories the exact head tree, rejects Git archive substitutions or omissions, and transports a bounded snapshot and selected plan in a [same-run artifact](https://docs.github.com/en/actions/concepts/workflows-and-actions/workflow-artifacts). The credentialless subject job validates that bundle and can invoke the fixed OCI launcher only when a digest-pinned image is supplied; its result is always non-claiming. The trusted verifier independently recaptures current PR revisions, checks the downloaded handoff's identity, diff, archive blobs, and file modes against the fresh Git tree, checks that the bounded subject result reports a successful execution for the same run, revision, profile, and snapshot, resolves the unique successful subject job from the attempt-specific GitHub APIs through the [verifier-context resolver](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-verifier-context.py), recomputes a host manifest, and runs `verify-gate`. The finalizer checks the three verifier outputs and upstream step outcomes before issuing the pilot check result. A fully empty profile can pass after fresh PR/run/job verification; the current implementation cannot authenticate a nonempty subject checkout, isolation envelope, or producer artifact bytes, so those profiles remain ineligible. + +For `code-coverage`, the controller exports only the bounded profile ID after planning. A separate trusted job requires `EVIDENCE_GATE_SUBJECT_IMAGE_DIGEST` to name `ghcr.io/forge-trust/appsurface-subject-native-validation@sha256:<64 lowercase hex digits>`, checks its GitHub artifact attestation against this repository, the protected-main publisher workflow, and `refs/heads/main`, and passes the same digest to the subject job. The subject job keeps `permissions: {}` and pulls that digest with an explicitly empty registry auth file before the launcher enforces its local `RepoDigest` check. A missing image variable, invalid provenance, private package, or failed anonymous pull leaves the pilot failed. The separate `EVIDENCE_GATE_SUBJECT_IMAGE` variable names the publisher's package without a digest. This branch-owned workflow wiring has no published protected-base image to use yet and remains non-claiming; a verified image does not establish subject checkout, isolation, cleanup, or producer evidence. The [subject image guide](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-image/README.md) describes publication and the first-package visibility step. + +For `code-coverage`, the subject result carries the bounded [fixed entrypoint record](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-entrypoint.py) in a versioned `executionReceipt`. The launcher and verifier require the five declared step names in order, with zero exit codes, and bind the record to the captured base/head revisions, workflow run and attempt, profile, and snapshot digest. A completed record also requires an ordered, bounded SHA-256 index for the generated Cobertura XML, gate Markdown, and gate JSON; failed records cannot include it. Gate JSON is required by this fixed profile even though the policy's diagnostics slot is optional. The [independent cleanup supervisor](evidence-gate-subject-supervisor.md) has a separate private state directory and a bounded non-claiming attestation; the subject job waits for complete cleanup and uploads that record on the coverage path. The trusted verifier now requires that downloaded attempt-scoped record to be canonical, bounded, and complete before host verification; the empty documentation profile must have no cleanup artifact. The receipt's canonical SHA-256 is a self-consistency check only: an artifact editor can recompute it, so neither the receipt nor cleanup-record validation authenticates execution, the consumed checkout, isolation, or producer artifact bytes. On a completed fixed run, the launcher copies only those three files from stopped-container scratch into a separate private runner-temp directory before supervisor cleanup. The subject job uploads that directory as a separate attempt-scoped artifact; the trusted verifier rehashes the three fixed downloaded names against the completed receipt after fresh PR recapture. Missing, extra, linked, oversized, changed, or digest-mismatched files fail closed. This proves transfer integrity, not that the PR-controlled coverage command produced truthful results or that the subject consumed the attested checkout under a verified isolation envelope. Keep the EvidenceGate host and workflow non-claiming until those proofs and a registered producer exist. + +The coverage subject now includes a separate version-1 `envelopeReceipt` from the [base-owned launcher](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject.py). It records the live scratch-quota check and fixed host-observed Podman configuration after OCI inspection and independent supervisor cleanup. The namespace and resource-limit fields describe inspected configuration, not proven runtime enforcement of every cgroup limit. The [handoff verifier](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-handoff.py) requires its exact run/revision/profile/snapshot binding and the immutable image digest from the trusted preflight job; an absent or inconsistent record fails with `ASEHB013`. Recomputing its SHA-256 is possible, so the receipt is not an independent job or checkout attestation and cannot set `SubjectEnvelopeAttested`. It does not change the non-claiming rollout state. + +The verifier now has a conditional, non-claiming [coverage replay step](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) after fresh revision capture and artifact-index validation. It reruns the base-owned coverage evaluator on the downloaded Cobertura XML and the recaptured `source.diff` with the policy's current 95% line, 85% branch, 95% patch-line, 85% patch-branch, `codecov` mode and 0.5-point tolerance settings. The step first rejects a selected plan whose coverage declaration differs from those fixed values; a reviewed policy and workflow update must keep them together. `/subject` is an empty verifier-side path-normalization root, not a second subject checkout. A failed replay fails the pilot job; a passing replay is still only a consistency check on subject-supplied coverage bytes and does not authenticate test execution, checkout consumption or OCI enforcement. The verifier job has a ten-minute budget for recapture, replay and final verdict. No code-profile pilot has reached this step yet because image publication and nonempty producer requirements remain open. + +After those checks, the trusted verifier resolves the unique subject job from the attempt-specific GitHub API and writes a bounded [subject observation](../tools/ForgeTrust.AppSurface.EvidenceGate/README.md#trusted-subject-observation). It binds the verified plan, fresh workflow/job identity, and exact downloaded subject-result bytes; `code-coverage` additionally binds the cleanup record, the three fixed artifact exports, and the digest chosen by trusted image preflight. The observation is uploaded as a one-day, run-and-attempt-scoped workflow artifact so a later authenticated handoff can refer to these exact bytes. It always says `claimEligible: false`. Neither a workflow artifact nor a future signature over this observation would prove the subject consumed the intended checkout, that runtime isolation was enforced, or that PR-controlled coverage data is truthful. The host and final verdict remain independent of the observation, and nonempty profiles remain incomplete. + +The fixed subject profile now receives the controller's captured `source.diff` through a separate read-only mount. The launcher compares its bytes with the handoff SHA-256 before creating the container, verifies the mount in OCI inspection, and passes the expected digest to the entrypoint, which checks the mounted file again before running aggregate and patch coverage. The patch gate uses 95% lines, 85% branches, and `codecov` line mode, matching the repository's [coverage gate](https://github.com/forge-trust/AppSurface/blob/main/scripts/coverage-solution.sh). This closes the missing patch-input path only; the current solution's container-backed test projects still cause the offline entrypoint to fail before coverage execution, and no complete producer artifact or checkout/isolation attestation is yet available. + +For same-repository PRs, the controller now invokes the [bounded policy-shadow preparer](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-policy-shadow.py) after capturing the exact head. It reads only the candidate policy and fixture blobs at that Git object ID, then passes them as data to the [base-owned shadow command](../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-evidence-shadow-policy) alongside the protected policy and fixtures. A missing candidate policy, unsafe Git mode, or incompatible comparison fails before handoff creation; deleted candidate fixtures remain absent so the old fixture obligations cannot be replaced by the PR. This wiring is branch-owned until merged into the protected base and exercised in a live pilot. The shadow result remains nonclaiming and does not supply producer, isolation, or current-head evidence. + +Do not add a required check until the pilot below has observed the exact check name, app identity, commit association, and base-update freshness behavior. No row below is a claimed pass until it has a run URL, captured base/head IDs, and an observed outcome. + +## Local pre-pilot validation + +On the issue #777 implementation branch, the frozen [docs-only fixture](fixtures/issue-777-docs-only/README.md) passed the copyable `explain` → host `run` → local `verify` rehearsal with `--no-restore`. The explained and hosted plans had the same digest (`a935646d382eb5dde80ff23161d499bfdf5506d13236354429dcd751bd2e2a54`); the local manifest reported `NoEvidenceRequired` with `PullRequestGate` eligibility. This is a contract rehearsal, not the trusted GitHub PR verdict or a live pilot row. + +The [copyable quickstart](fixtures/issue-777-docs-only/README.md) was rerun literally at `682c2145` from this checkout with a warm .NET toolchain. Its `explain`, host `run`, and local `verify` commands all exited zero in 12 seconds; both plans had digest `a935646d382eb5dde80ff23161d499bfdf5506d13236354429dcd751bd2e2a54`, and the manifest said `NoEvidenceRequired` with `PullRequestGate`. Two preceding attempts stopped before planning with local `CS0016` Debug XML output access errors; after `dotnet build-server shutdown`, the unchanged quickstart passed. This measures the local rehearsal, not cold installation, a subject producer, or GitHub check association. + +Focused local checks passed for the controller, subject launcher, and fixed offline entrypoint (47 Python tests), the CLI Evidence path (179 tests), the Aspire host bootstrap (28 tests), and the read-only release inspect suite (630 tests). The focused host/verifier project later passed 87 tests, and the no-follow PR verifier and artifact extractor passed 23 and 15 tests respectively on Linux arm64 after architecture-correct native flags were applied. + +The handoff tests pass valid plan-bound bundle creation, mismatched revision/run/profile rejection, fork observation, unsupported-profile failure, `export-ignore`, `export-subst`, case collisions, .NET canonical string escaping, and verifier-side rejection of stale identity, changed diff, or forged subject results. The complete evidence-gate Python suite passes 78 tests when its process-group cleanup test runs with the signal permissions required by the runner; nine cover the new verifier-context resolver. The focused PR gate and no-follow extractor tests pass 49/49 on macOS; their Linux-specific extraction branches still need a Linux run. A real v2 docs-only plan generated by the built CLI was handed from a bare Git object store to the subject runner: execution returned `0` for `documentation-only` with `claimEligible: false` and no OCI image. A second real CLI plan with `+`, a backtick, and a quote in its changed path passed the handoff's canonical parser. The trusted GitHub API authority project now passes 105 focused tests after accepting the documented attempt-specific job response without a per-job `run_attempt` field and the reviewed formatted policy source. A local `explain` → host `run` → `verify-gate` rehearsal with the checked-in policy and a synthetic expected job identity reached `ASEVG006`: the host emitted `NoEvidenceRequired`, and the verifier correctly stopped only at unavailable live GitHub authority. These prove bounded local behavior only; the GitHub verifier rehearsal itself has not run on a live PR. The protected release-inspection producer's focused tests pass 20/20 and the read-only machine-inspect tests pass 12/12. The release producer intentionally reports `Unavailable` without a trusted protected event, fresh remote tag verification, and exact built package/archive checks; the default host cannot issue `ReleaseComplete`. + +The exact `./scripts/coverage-solution.sh` run at `2cca334a` completed all 55 test projects but exited 1 at the coverage gate. Aggregate line coverage was 94.5538% (effective minimum 94.5%) and branch coverage was 87.9813% (effective minimum 84.5%); patch line coverage was 63.7755% (effective minimum 94.5%) and patch branch coverage was 57.5375% (effective minimum 84.5%) against `origin/main`. The detailed targets are in `TestResults/coverage-merged/coverage-patch-targets.json`. Later focused tests and native fixes are not included in that exact run, so these percentages are diagnostic, not a current green result. A Linux arm64 rerun of the unchanged script was interrupted after the solution build and two passing test projects when local free disk space dropped below the validation floor; it produced no gate result. Keep the [coverage gate](https://github.com/forge-trust/AppSurface/blob/main/scripts/coverage-solution.sh) open until a fresh exact run passes on the final committed code with sufficient runner capacity. + +For an implementation branch without a pull request, manually dispatch the [build workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) at that branch. Its build job fetches the full Git history and supplies `origin/main` as the patch-coverage base; ordinary PR runs continue to use `HEAD^1`. Record the branch commit and downloaded `coverage-gate-reports` artifact before treating the remote result as coverage evidence. A manual build still cannot substitute for the final gate rerun on the code that ships. + +The first [manual hosted run](https://github.com/forge-trust/AppSurface/actions/runs/36871797772) at `7e9f636e` stopped before coverage: locked solution restore reported `NU1004` for the EvidenceGate and EvidenceGate.Tests project references to Release. Their tracked locks have since been regenerated with `--force-evaluate`, and a full local `dotnet restore ForgeTrust.AppSurface.slnx --locked-mode --verbosity quiet` passed. That run supplied no coverage report and must not be counted as a gate pass. + +The second [manual hosted run](https://github.com/forge-trust/AppSurface/actions/runs/36873147394) at `e53cfac6` passed locked restore but the coverage script stopped during solution build with `CS0234`: unqualified `Console` in the EvidenceGate entrypoint resolved to the AppSurface namespace. The entrypoint now uses `System.Console`; a local Release build of the full solution passed with zero warnings/errors, its CLI help path ran, and the EvidenceGate Release test project passed 105/105. That hosted run had no coverage artifact either; rerun the hosted gate on the fixed commit. + +The third [manual hosted run](https://github.com/forge-trust/AppSurface/actions/runs/36874888011) at `39cfb898` built the solution and collected 95.87% aggregate line and 88.09% aggregate branch coverage, but exited `ASCOV120` before the patch gate. Its sole test failure was `CoverageSolutionScriptTests.BuildWorkflow_ShouldUseCoverageSolutionScriptForDefaultLane`, whose literal workflow assertion still expected the old empty manual diff base. The test now checks the full-history manual checkout and `origin/main` diff base alongside the PR behavior. The uploaded test-result artifact confirms 1 failed and 1,756 passed CLI tests; there was no coverage-gate artifact, so the aggregate percentages are diagnostic only. + +The fourth [manual hosted run](https://github.com/forge-trust/AppSurface/actions/runs/36966808783) at `536ec34a` reached the full test suite and reported 95.87% aggregate line and 88.09% aggregate branch coverage, but again exited `ASCOV120` before patch evaluation. The sole failure was the repository's [test-fixture path policy](https://github.com/forge-trust/AppSurface/blob/main/tests/ForgeTrust.AppSurface.Testing/README.md#policy-failures): two release-producer test reads joined a dynamic artifact-relative path with `Path.Join`. The tests now use the shared `TestPathUtils.PathUnder` helper and reference its test-support project. The focused path-policy test and EvidenceGate project (105 tests) pass locally. The exact local gate on the pre-fix tree likewise stopped at this one test, with 95.64% aggregate line and 87.91% aggregate branch coverage; neither run produced a patch report. Rerun the exact gate after the fix before making any coverage claim. + +The next local exact-script attempt after that fix reached 95.04% aggregate line and 87.30% aggregate branch coverage, then stopped at `ASCOV120`. A browser scroll test failed once, and PackageIndex tests compared assemblies built before a concurrent branch commit with the new Git revision. A separate gate invocation against the merged coverage file is **diagnostic only**: its patch line and branch results were 71.80% and 67.57%, below the effective 94.5% and 84.5% floors. The macOS run cannot exercise the Linux-only no-follow extractor, which accounts for 223 of its uncovered patch lines, so the hosted Linux report is needed before prioritizing coverage work. No exact-script pass or patch-coverage claim exists for this attempt. + +The fifth [hosted Linux run](https://github.com/forge-trust/AppSurface/actions/runs/36969341000) at `806194ca` passed the 55-project test run with no failed tests, then reached the exact patch gate. Aggregate coverage passed at 95.86% line and 88.09% branch. Patch coverage failed `ASCOV020`: 82.92% line (2,088/2,518) and 74.70% branch (2,598/3,478), against effective 94.5% and 84.5% floors. The generated [patch target report](https://github.com/forge-trust/AppSurface/actions/runs/36969341000) is the baseline for focused regression tests, led by the no-follow artifact verifier and extractor, host runner, and release inspection authority. The later local PackageIndex rerun at a fixed commit passed 1,081 tests with three skipped, confirming the previous revision mismatch came from changing HEAD during coverage collection. The focused browser regression passed after waiting for its delayed scroll callback before asserting frame reset. Neither focused pass replaces a complete final-code gate run. + +The sixth [hosted exact-script run](https://github.com/forge-trust/AppSurface/actions/runs/36973947580) at `2dfbc712` stopped at `ASCOV120` before producing gate reports. `TestFixturePathPolicyTests` rejected two `Path.Combine` calls in the new release-inspection authority test fixture. Both now use the repository's `TestPathUtils.PathUnder` helper; the focused path-policy suite passed 15/15 and the authority suite passed 14/14. + +The seventh [hosted exact-script run](https://github.com/forge-trust/AppSurface/actions/runs/36976025855) at `6fe67ce5` completed the tests and reached `ASCOV020`. Overall line coverage was 95.9907% (112,263/116,952), overall branch 88.4440% (46,036/52,051), and patch branch 85.3364% (2,968/3,478): all passed their effective 94.5%, 84.5%, and 84.5% floors. Patch line coverage was 89.9364% (2,261/2,514), below the effective 94.5% floor. The [patch target report](https://github.com/forge-trust/AppSurface/actions/runs/36976025855) points chiefly to no-follow artifact extraction and PR verification, with smaller host-runner and Git-capture gaps. Later shadow, native, and targeted regression-test changes were not in this run; the exact gate must be rerun on the final commit. + +Five solution projects that appeared to lack default `packages.lock.json` files instead use the tracked `packages.osx-arm64.lock.json` and `packages.linux-x64.lock.json` variants selected by `NuGetLockFilePath`. All ten existing lock files passed full-graph locked-mode restore with isolated temporary caches. No new lock files are needed for those projects. This verifies those lock graphs separately from the offline feed assembly below; neither check provides a published pinned subject image or a complete isolated CI producer. + +The [subject-image candidate](../scripts/evidence-gate-subject-image/README.md) first built locally from the pinned multi-platform .NET 10 SDK base with a synthetic package feed. The [offline feed builder](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-build-offline-feed.py) then succeeded in a network-disabled Linux .NET 10 container with this implementation-branch checkout and the existing NuGet cache mounted read-only: it verified 279 unique package archives selected from 157 solution-project lock files, totaling 610,312,849 bytes. After adding cleanup and bounded subprocess regression tests, its 23 synthetic builder tests and the complete 101-test evidence-gate Python suite passed locally. A second disposable build context containing those 279 real archives produced a `linux/amd64` Docker image (local image ID `sha256:6d427dbee6c96e9a75737cb66381b72b33bc1181c9269c6f10741cb1883323a4`, 2.54 GB). The same count and byte total were confirmed inside the image. Its fixed entrypoint returned its help contract under UID 65532 with a read-only root filesystem and no network. The temporary feed/context were removed; the local image remains for further testing. These checks prove this branch's locked inputs can be assembled into an image whose entrypoint starts; they do not authenticate a protected-base checkout. Rootless Podman execution on GitHub-hosted Linux, a published **registry** digest, a cold-cache restore, and a complete Evidence producer remain unverified. + +A local cold-cache `dotnet restore --locked-mode` attempt used that `linux/amd64` image with no network, a read-only root, UID 65532, an empty private NuGet cache, and a config with only the embedded feed. It did not reach package resolution: the arm64 Docker host's x64 emulation aborted the .NET SDK with `System.AccessViolationException`/`qemu: uncaught target signal 6` during MSBuild project loading; a serialized solution retry had the same result. This is an environment limit, not evidence of a missing package or a passing restore. Run the cold-cache proof on native x64 Linux before promotion. + +A focused review of the image candidate found that selecting every RID lock would make a clean Linux cache depend on macOS-only archives. The builder now resolves each solution project's exact `linux-x64` lock, matching the fixed subject entrypoint. A network-disabled Linux builder verified 277 package archives from 150 selected locks, totaling 557,811,468 bytes, and produced only those flat `.nupkg` files. The excluded packages are `Aspire.Dashboard.Sdk.osx-arm64` and `Aspire.Hosting.Orchestration.osx-arm64`. The 25 builder tests and full 103-test evidence-gate Python suite pass. The prior 279-package image is stale for this revised recipe; a new image build and cold-cache restore are pending. The opt-in [native x64 validation lane](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) invokes the [image validation script](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-image/validate-native.sh) to check both on a GitHub-hosted runner. The same review found that the subject's writable host scratch mount had no disk or inode quota, so isolation remains incomplete while that boundary is being corrected. + +The launcher requests a private 4 GiB, 262,144-inode tmpfs for `/scratch` and verifies the Podman configuration before starting the container. The fixed entrypoint sends only its bounded nonclaiming result record over attached output; the launcher validates and saves that record with exclusive no-follow creation. The full 108-test evidence-gate Python suite passed locally. The direct rootless Podman mount form later proved incompatible with the host's Podman 4.9. The branch launcher now follows the trusted-host mount and rootless bind approach that passed the native image recipe pilot; its own live execution, independent forced-kill cleanup, and claim attestation remain unproved. + +The first [native x64 image validation run](https://github.com/forge-trust/AppSurface/actions/runs/36970849396) built the revised image after verifying the feed, then stopped before the cold restore because Docker rejected `rw=true` in its bind-mount option. The option was removed; the cold-cache result and rootless Podman boundary are still unverified. + +The second [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36971728957) passed the host locked restore, verified the feed, and built the image, but the cold in-image restore reported `NU1004` for Aspire AppHost projects. The runner selected .NET SDK 10.0.401 while the image contained 10.0.102; the older SDK interpreted AppHost package and project references differently from the tracked Linux lock files. The image base is now pinned to the multi-platform .NET 10.0.401 manifest digest, the opt-in host lane requires that exact SDK, and the [non-claiming gate workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) pins its trusted planner and verifier jobs to the same SDK. No lock files were regenerated from this failed comparison. + +The third [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36972672718) used SDK 10.0.401 on the host and in the pinned image. It again verified 277 packages from 150 Linux-selected locks (557,811,468 bytes) and built the image. The cold no-network restore then failed `NU1004` only for `ForgeTrust.AppSurface.Auth.Aspire.Keycloak.Tests.csproj`: its selected lock omits the `AuthAspireKeycloakWeb` reference under `net10.0`. The host locked restore had succeeded, so the host's selected runtime identifier/lock path and the image's evaluated project graph are under comparison before any tracked lock is updated. No cold-cache success is claimed from this run. + +The fourth [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36976843978) at `f589c7b8` confirmed the host `NETCoreSdkRuntimeIdentifier=linux-x64` and selected tracked `packages.linux-x64.lock.json` in a serial locked preflight. It assembled the same 277-package feed and built the image, then stopped before container creation: Docker displayed the transferred image ID with a `sha256:` prefix while Podman displayed the same hex ID without it, and the smoke compared the strings literally. The non-claiming result reported `transferred-image-identity-mismatch`; the cold restore was not reached. The comparison now validates and compares the 64-hex IDs after removing only an optional display prefix. A new native run must still prove the Podman mount and cold restore; this presentation mismatch does not resolve the earlier `NU1004`. + +The fifth [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36978125169) at `07043e79` confirmed the tracked Linux lock selection, assembled 278 packages including the pinned project SDK, and matched Docker and Podman image IDs. Rootless Podman 4.9.3 then rejected `noswap` on `/scratch` at container creation because that option requires a rootful mount. No live mount check or cold restore ran. The fixed rootless launch contract now omits `noswap` while retaining the byte/inode quotas and other sandbox controls; no no-swap property is claimed. A new native run must verify the live mount and cold restore. + +The sixth [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36979113498) at `8ad98c57` again assembled the 278-package feed, but rootless Podman 4.9.3 rejected `nr_inodes=262144` as an unknown `--tmpfs` option. The live mount and cold restore were not reached. Rather than drop the approved inode quota, the next nonclaiming native probe mounts a bounded tmpfs from the trusted host and bind-mounts that filesystem into a rootless Podman container. This requires a separately reviewed production launcher and cleanup path before any isolation attestation can become eligible. + +The seventh [native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36980230101) at `276f23df` successfully mounted trusted-host quota-limited tmpfs, transferred the 278-package image into rootless Podman, and created the container. Its pre-start inspection then failed only the `HostConfig.CapDrop == ["ALL"]` presentation check; network denial, read-only root, fixed non-root user, and no-new-privileges checks passed. Podman computes `CapDrop` from its OCI spec, so the probe now checks its reported empty effective and bounding sets and the live process's five zero capability masks instead. The failed run removed the container and unmounted scratch. It neither started the container nor reached cold restore, and remains nonclaiming. + +The [eighth native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36983171273) at `6d647faf` showed that rootless Podman 4.9.3 omits `EffectiveCaps` and `BoundingCaps` from its pre-start inspect JSON. It reported `CapAdd=[]` and a `CapDrop` list containing all eleven default capabilities. Network denial, read-only root, fixed non-root user, and no-new-privileges checks passed again, but the missing fields made the provisional capability check fail before container start. Cleanup removed the container and unmounted scratch. The next nonclaiming probe accepts this reported drop request only as a pre-start configuration check and still requires all five live capability masks to be zero; neither run proves those masks or the cold restore yet. + +The [ninth native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36984743411) at `bae252b2` started the transferred image under rootless Podman. The live process reported zero inherited, permitted, effective, bounding, and ambient capability masks; read-only root and the private 4 GiB/262,144-inode tmpfs scratch checks passed, and cleanup removed the container and unmounted scratch. Podman inspect reported private PID/IPC/UTS/user namespaces and the requested 64-PID, 256 MiB, half-CPU limits; enforcement of those limits remains unverified. The subsequent Docker cold-cache restore still failed `NU1004` in several Aspire AppHost projects. The container emitted a warning while querying `nuget.org` for project SDK resolution even though the ordinary restore command specified the offline `--configfile` and feed. The next pilot supplies that same closed config in the disposable subject user's NuGet home before project evaluation; a passing locked restore is still required. + +The [tenth native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36985943666) at `955827f0` again passed the rootless Podman live checks and then restored every solution project from the embedded offline feed without `NU1004` or a `nuget.org` warning. The validation script nevertheless exited 2 after restore because its unprivileged host-side `find` could not traverse the UID-65532-owned private cache and treated the empty command-substitution output as an empty cache. The next pilot uses bounded `sudo -n find` and distinguishes inspection failure from an actually empty cache. This run proves locked restore reached successful per-project results; the whole native lane has not yet passed its final check. + +The [eleventh native x64 run](https://github.com/forge-trust/AppSurface/actions/runs/36986822043/job/110773641763) at `d1b78987` passed the complete non-claiming validation job, including the rootless Podman live smoke, empty-cache locked restore from the embedded feed, and bounded privileged inspection of the resulting private package cache. This closes the earlier inspection failure and demonstrates a successful cold restore on native x64 Linux. It remains a branch-owned recipe probe: it does not publish a protected-base image digest or attest production subject checkout, resource limits, cleanup supervision, producer artifacts, or a complete EvidenceHost claim. The [separate build job](https://github.com/forge-trust/AppSurface/actions/runs/36986822043/job/110773641743) passed the test collection and aggregate coverage thresholds but failed `ASCOV020`: patch line coverage was 90.3681% (2,627/2,907) against the effective 94.5% minimum. Patch branch coverage was 86.0117% against 84.5%. Focused tests added after this commit require a fresh exact-script run before any coverage pass can be claimed. + +The later [hosted build run](https://github.com/forge-trust/AppSurface/actions/runs/36994240641/job/110797186819) at `cb24c309` passed its test collection and aggregate coverage, then failed only `ASCOV020` patch lines: 92.47% (2,688/2,907) against the effective 94.5% floor. Aggregate lines were 96.03%, aggregate branches 88.51%, and patch branches 87.40%; all three passed. The [patch target report](https://github.com/forge-trust/AppSurface/actions/runs/36994240641) identifies the no-follow extractor and PR verifier as the largest remaining uncovered groups. The newer host-tmpfs launcher adaptation and any further tests are outside this run, so this is not a final-code gate result. + +The [hosted build run at `2b53b721`](https://github.com/forge-trust/AppSurface/actions/runs/37007024003/job/110837605371) completed all 55 .NET test assemblies (15,376 passed, two skipped, zero failed). Aggregate lines (96.05%), aggregate branches (88.54%), and patch branches (87.61%) passed, but the unchanged solution gate still failed `ASCOV020`: patch lines were 92.71% (2,696/2,908) against the effective 94.5% floor. The [native subject-image validation](https://github.com/forge-trust/AppSurface/actions/runs/37007024003/job/110837605151) passed separately, including rootless Podman checks and a cold locked restore. The changed-line target report identifies the Linux no-follow extractor and PR verifier as the largest uncovered groups. Focused coverage work after this SHA is not included in those measurements; no final-code coverage pass can be claimed yet. + +The next [hosted run at `75546a8b`](https://github.com/forge-trust/AppSurface/actions/runs/37013638706) again passed all solution tests, aggregate coverage, patch branches, and the separate native image validation. Patch lines improved to 93.45% (2,726/2,917), still below the effective 94.5% floor; the unchanged script exited 1. Its fresh target report is the basis for another focused pass. Neither run authorizes a draft-PR coverage claim or activation of the non-claiming evidence pilot. + +The [hosted run at `bd4ffef6`](https://github.com/forge-trust/AppSurface/actions/runs/37019088813) passed all 55 test projects and the native subject-image validation, but the unchanged coverage gate exited 1 at `ASCOV020`. Aggregate lines were 96.05% (113,169/117,819), aggregate branches 88.76% (46,458/52,340), and patch branches 93.64% (3,564/3,806); all passed. Patch lines reached 94.45% (2,756/2,918), just below the effective 94.5% floor. The [uploaded gate report](https://github.com/forge-trust/AppSurface/actions/runs/37019088813/artifacts/11233632224) is diagnostic for that commit only. The local macOS exact-script attempt on the same tree stopped at `ASCOV120` after one `CoverageRunWatchdogTests` timeout; its generated patch report undercounted Linux-only extractor paths and is not a substitute for the hosted result. The release machine-result and API-address fixes made afterward require a fresh full gate run. + +The [twelfth native x64 validation](https://github.com/forge-trust/AppSurface/actions/runs/36998581269/job/110810851386) at `5c7d9ea7` passed with the production-shaped trusted-host tmpfs bind launcher. Rootless Podman 4.9.3 reported a private 4 GiB, 262,144-inode scratch filesystem and the live process had zero capability masks; the script removed the container and unmounted scratch. The same job completed a cold locked restore from the embedded feed. This is still a non-claiming recipe validation: the workflow has no published immutable registry image digest, trusted subject checkout attestation, producer artifact verification, or complete manifest claim. The [separate build job](https://github.com/forge-trust/AppSurface/actions/runs/36998581269/job/110810851430) passed its tests and aggregate coverage but failed `ASCOV020` patch lines: 92.50% (2,689/2,907), below the effective 94.5% floor. Patch branches passed at 87.51%. The newer Git-capture, extractor, PR-verifier, and host-runner tests are outside that commit; the gate remains open. + +An isolated diagnosis of the earlier `NU1004` reproduced the changed Keycloak project graph when Aspire's restore-time targets were disabled. The tracked AppHost declares `Aspire.AppHost.Sdk` 13.4.4 as a project SDK, but that SDK is absent from ordinary `packages.lock.json` entries and therefore from the 277-package feed. The repository's cached archive passed `dotnet nuget verify --all` with NuGet content hash `yYcwwYub6sFzgtrnYJHrq6Q3F+fQYQd1r7aRCDShQHqNAYO8/ObfW/jXv0eTcbwlag7Oz33RRYbMnW8QMVi5qg==`. The feed builder now pins this archive separately and includes it only when a selected project declares that exact SDK. This is a supported explanation, not yet a passing cold-cache result; the next native run must show that the resolver actually consumes the embedded SDK package and retains the existing Linux lock graph. + +The fixed [offline subject entrypoint](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-entrypoint.py) scans every entry in its image-mounted dependency feed, including entries after the first package, and rejects links and special files before restore. It then uses only that feed with `--locked-mode`; a package absent from the feed or inconsistent with a project lock fails restore. This check protects the feed shape but does not authenticate the image or supply its missing packages; the digest-pinned image and cold-cache pilot remain required. + +The [hosted run at `952046c5`](https://github.com/forge-trust/AppSurface/actions/runs/37024148418) passed the unchanged solution coverage gate on native Linux: aggregate lines 96.0573% (113,168/117,813), aggregate branches 88.7649% (46,456/52,336), patch lines 94.6772% (2,757/2,912), and patch branches 93.7862% (3,562/3,798), each above its effective floor of 94.5% for lines or 84.5% for branches. All 55 test projects and the separate native image validation passed. The workflow as a whole failed strict docs export on 42 unresolved links to source-tree files. Those links were converted to source-hosted URLs, and the exact strict export passed locally. + +The [next hosted run at `2c70532b`](https://github.com/forge-trust/AppSurface/actions/runs/37029055717) again passed the unchanged solution coverage gate (96.06% aggregate lines, 88.76% aggregate branches, 94.68% patch lines, 93.79% patch branches), all eight preceding jobs, and the native image validation with 278 verified packages from 150 lock files and a cold offline restore. Its strict docs export failed on one remaining relative link to the fixed entrypoint; that link is now source-hosted in the current branch. A fresh strict export is required after the documentation edit. Neither run is a live base-owned PR pilot or a complete evidence claim. + +The [native Linux verification at `0d51d5a9`](https://github.com/forge-trust/AppSurface/actions/runs/37095402505) passed the unchanged `BUILD_CONFIGURATION=Release COVERAGE_PARALLELISM=2 ./scripts/coverage-solution.sh` gate: all 56 test projects completed with 16,275 passed, two skipped, and zero failed. Aggregate line and branch coverage were 96.09% (115,921/120,638) and 88.77% (47,998/54,068); patch line and branch coverage were 94.52% (2,895/3,063) and 93.59% (3,708/3,962), above the unchanged effective floors. Strict Docs export also passed. This establishes the repository coverage gate for that exact implementation commit, but it does not establish a complete EvidenceHost claim or a live base-owned PR check. The separate Codecov patch status for that commit reported 93.32% against its 95% target; it is advisory under the current ruleset and uses a different patch measurement. Re-run the exact gate after any code or test change that can affect coverage before updating the draft PR. + +The [native Linux verification at `ba50e49a`](https://github.com/forge-trust/AppSurface/actions/runs/37103062157) passed the same unchanged solution coverage gate and strict Docs export after the fixed offline subject command added the external-activation test project to its exclusive execution list. The uploaded gate report records aggregate lines 96.0891% (115,920/120,638), aggregate branches 88.7549% (47,988/54,068), patch lines 94.5152% (2,895/3,063), and patch branches 93.5891% (3,708/3,962), all above the effective floors. The [PR-head build at `a0835fac`](https://github.com/forge-trust/AppSurface/actions/runs/37102114771) also passed the exact gate and strict Docs export. These runs validate their committed revisions only; neither is a base-owned live evidence-gate pilot or a complete producer claim. The separate Codecov patch status remains advisory under the current ruleset. + +The [native Linux verification at `0600c63b`](https://github.com/forge-trust/AppSurface/actions/runs/37105726646) passed the unchanged solution coverage gate and strict Docs export after adding the fixed subject artifact index. Its uploaded report records aggregate lines 96.09% (115,922/120,638), aggregate branches 88.76% (47,989/54,068), patch lines 94.52% (2,895/3,063), and patch branches 93.59% (3,708/3,962), all above the effective floors. The same exact gate on local macOS passed all 56 test projects and aggregate and patch-branch thresholds but failed `ASCOV020` at 84.23% patch lines; 232 uncovered patch targets were in the Linux-only no-follow extractor and 169 in the verifier. The native Linux result is the coverage proof for that commit, not for later source changes or a completed evidence claim. + +The [native Linux validation at `3708f5b0`](https://github.com/forge-trust/AppSurface/actions/runs/37166598908) passed the unchanged solution gate and strict Docs export after release publication gained a protected-environment prerequisite and the Pages-write dependency check. Its uploaded gate report records aggregate lines 96.09% (115,924/120,640), aggregate branches 88.76% (47,990/54,068), patch lines 94.52% (2,897/3,065), and patch branches 93.59% (3,708/3,962), above the unchanged effective floors. The native subject-image validation passed. This validates that committed revision only; it is not a protected-base PR pilot or evidence that any nonempty profile can claim completion. The exact local macOS command stopped before tests with `ASCOV116` because this workspace has a sandbox marker, so the native GitHub run supplies the coverage result. + +## Pilot evidence to record + +| Scenario | Expected result | Run/PR URL | Base/head IDs | Observed check conclusion and commit | Full-gate latency | Status | +| --- | --- | --- | --- | --- | --- | --- | +| Same-repository docs-only PR | Explicit `NoEvidenceRequired` from an exact v2 plan; final verifier rechecks current base/head | — | — | — | — | Unverified | +| Same-repository code PR | Every declared code obligation and trusted subject result closes; otherwise fail | — | — | — | — | Unverified | +| Mixed/renamed/deleted control-plane change | Conservative superset or a stronger explicit targeted profile; never docs-only | — | — | — | — | Unverified | +| Resource-backed profile | Disposable readiness, producer, artifact, and supervisor cleanup succeed within reviewed bounds | — | — | — | — | Unverified | +| Deliberately failing producer or unavailable dependency | Stable check fails with missing obligation/diagnostic, even when artifact upload fails | — | — | — | — | Unverified | +| Fork PR | `ObservationOnly` may report a safe subset; required gate stays failed | — | — | — | — | Unverified | +| Base advances while PR head is unchanged | Previous result becomes stale; branch update and `synchronize` rerun are required | — | — | — | — | Unverified | +| Protected annotated release invocation | Read-only tag inspection and exact artifact digests; never counted as the PR check | — | — | — | — | Unverified | +| Cold cache and dependency-changing PR | Locked dependency restore stays inside the subject boundary; cache miss/mismatch fails closed | — | — | — | — | Unverified | +| Forced host-process kill | Independent in-VM supervisor removes the per-run topology within 10 minutes; no complete claim | — | — | — | — | Unverified | + +For each run, record first-result time separately from full-gate time, the duplicate cost beside the existing build/package checks, the exact profile/rule/plan digest, and any fork promotion effort. Preserve the terminal, step-summary, machine-JSON, and manifest outputs together; compare their claim and missing-obligation lists. Capture a secret canary and oversized path test without publishing their raw values. + +## Activation and rollback + +After all positive and negative pilot rows pass, identify the stable verifier job's exact status-check context and GitHub App/integration identity from a live PR. Add only that context to the active default-branch ruleset with strict required-check freshness. Verify a qualifying same-repository PR can merge and an incomplete or fork-observation PR cannot. Keep existing checks required or advisory according to their current separate policy; #777 does not remove them. + +If the check attaches to a merge ref rather than the PR's current head, the event is unavailable under repository policy, an external resource escapes the ephemeral VM, or dependency supply cannot remain isolated, stop before activation. Fix the base-owned workflow and rerun the affected pilot. If an activated gate later produces an incorrect green or blocks safe changes, remove the new required-status-check rule while preserving the workflow and evidence artifacts for diagnosis. A rollback of enforcement does not turn an invalid manifest into a valid one. + +When a merge queue is introduced, add and pilot `merge_group` handling before requiring the check in that queue. The checked-in [gate design](designs/issue-777-policy-driven-ci-evidence-gate.md) remains the source for trust and isolation requirements; this record holds observed rollout evidence only. diff --git a/docs/evidence-gate-subject-supervisor.md b/docs/evidence-gate-subject-supervisor.md new file mode 100644 index 000000000..a0b7f2cc3 --- /dev/null +++ b/docs/evidence-gate-subject-supervisor.md @@ -0,0 +1,49 @@ +# Evidence subject cleanup supervisor + +[`scripts/evidence-gate-subject-supervisor.py`](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-supervisor.py) is a private, non-claiming cleanup helper for the rootless Podman subject launcher. It owns one per-run container identity and one quota-limited host tmpfs mountpoint. It does not evaluate subject output, establish the execution envelope, or authorize an Evidence claim. + +## Launcher contract + +The launcher must create a new scratch directory directly under `RUNNER_TEMP`, then create the mountpoint as its direct child. Both directories must be owned by the runner user and have mode `0700`. The mountpoint name must be `quota-limited-scratch-` followed by 16 lowercase hexadecimal characters. The container name must be `ase-subject---<12 lowercase hexadecimal characters>`, using the positive decimal run and attempt IDs. + +Start the supervisor with a fixed argv and `shell=False`, as a direct child of the launcher: + +```text +python3 scripts/evidence-gate-subject-supervisor.py start \ + --container-name \ + --scratch-directory \ + --mountpoint \ + --parent-pid \ + --parent-start-time +``` + +Provide only `RUNNER_TEMP`, `HOME`, and `XDG_RUNTIME_DIR` plus a fixed `PATH` to the helper. The `start` operation validates the host directories and the launcher's Linux `/proc` start identity, creates a mode-`0700` per-run state directory and mode-`0600` manifest, then starts a new-session supervisor process. It waits for a bounded ready handshake before returning. Its single JSON response includes `schemaVersion`, `claimEligible: false`, `ownerToken`, `ownerLabel`, `manifestPath`, `stateDirectory`, `supervisorPid`, `supervisorStartTime`, and `supervisorReady: true`. The launcher checks the returned paths and process identity before container setup. The state directory and manifest are outside the mounted tmpfs. + +The launcher must add this exact label to the container at creation time, including when container creation can fail after making the object: + +```text +--label== +``` + +The supervisor only removes the exact container name when Podman inventory and inspect identify that one container, its owner label equals the returned token, and its `/scratch` bind source equals the manifest mountpoint. It inspects the container ID and removes that immutable ID, so a same-name replacement cannot be removed in the inspect/remove gap. + +After the launcher has finished consuming the result record and no longer needs the mount, request normal cleanup: + +```text +python3 scripts/evidence-gate-subject-supervisor.py request \ + --manifest --owner-token +``` + +The supervisor also starts cleanup when the launcher process exits or its PID is reused. The launcher should wait for `cleanup-attestation.json` in the returned state directory for no more than 600 seconds. Treat any missing, malformed, or incomplete record as cleanup failure. The supervisor removes the container first. It unmounts only when container removal is verified and the live mount at the exact target is a tmpfs with the fixed 4 GiB, 262,144-inode, owner, and mode settings. After unmount, it removes only the identity-checked mountpoint directory and the exact bounded `evidence-subject-result.json` export, then removes the empty scratch directory with `rmdir`. It never recursively removes files; unexpected entries or a result file with the wrong type, owner, mode, link count, or size leave scratch in place and make the attestation incomplete. A normal cleanup request must therefore come after the launcher has consumed the result. + +## Attestation + +The JSON record is limited to 4 KiB and has schema version 1. It always includes `claimEligible: false` and `published: false`. `status` is `complete` only when `containerStatus` is `removed` or `absent`, `mountStatus` is `unmounted` or `absent`, and `scratchStatus` is `removed` or `absent`. Other statuses fail closed; in particular, an unverified container preserves the mount so a possibly running process is not detached from its scratch filesystem. Diagnostics are stable codes, not raw Podman, sudo, or subject output. + +The [subject workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate.yml) runs the trusted [cleanup attestation checker](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-cleanup-attestation-check.py) after execution, including a launcher failure. The checker accepts exactly one runner-owned supervisor state directory, requires a private complete record, and copies at most 4 KiB to an attempt-scoped artifact. The runner's `RUNNER_TEMP` need only be owned by the runner; the supervisor state itself must be mode `0700`. A missing, ambiguous, unsafe, or incomplete record fails the subject job. After the fresh Git handoff is verified, the [trusted cleanup-record verifier](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-verify-cleanup.py) checks the downloaded attempt-scoped artifact for the `code-coverage` profile and rejects an unexpected record for `documentation-only`. It accepts only the supervisor's canonical complete schema. This binds the cleanup completion check into the verifier job's step sequence; it does not independently authenticate checkout, isolation, or producer evidence, and the workflow stays non-claiming. + +## Bounds and limitations + +The parent watcher has a fixed 30-minute lease, enough for the launcher's existing 20-minute maximum subject duration and setup overhead. If the parent remains verifiably alive at lease expiry, the helper does not clean up beneath it; it records an incomplete attestation with cleanup marked not attempted. If the parent identity cannot be verified, the helper also leaves resources in place and records an incomplete attestation. Once cleanup starts, it has a fixed 10-minute deadline; each trusted command has a 30-second timeout and combined output is capped at 256 KiB. The helper only supports Linux `/proc`, the fixed rootless Podman executable, and noninteractive `/usr/bin/sudo umount`. + +Starting a new session lets the supervisor survive a launcher `SIGKILL`; it cannot survive runner VM destruction or an external mechanism that kills the whole job cgroup. It is not a substitute for a post-job runner cleanup hook. The forced-parent-kill test uses injected proc, Podman, and mount behavior and needs no privileged Podman or real mount. A live rootless Podman integration pilot is still required before relying on the cleanup contract in a workflow. diff --git a/docs/fixtures/issue-777-docs-only/README.md b/docs/fixtures/issue-777-docs-only/README.md new file mode 100644 index 000000000..2bc6f5b3d --- /dev/null +++ b/docs/fixtures/issue-777-docs-only/README.md @@ -0,0 +1,34 @@ +# Immutable docs-only gate fixture + +This fixture contains a tiny Git bundle, its exact fixed-options source diff, a frozen canonical [AppSurface policy snapshot](https://github.com/forge-trust/AppSurface/blob/main/docs/fixtures/issue-777-docs-only/policy.json), and full commit IDs in [`fixture.json`](https://github.com/forge-trust/AppSurface/blob/main/docs/fixtures/issue-777-docs-only/fixture.json). It supports a copyable, local rehearsal of the [revision-bound Evidence CLI](../../../Cli/ForgeTrust.AppSurface.Cli/README.md). It is a **planning and host** fixture, not a PR check: the final [trusted verifier](../../../tools/ForgeTrust.AppSurface.EvidenceGate/README.md) still needs live current-head and subject-job authority. The frozen policy is rehearsal input only; a real gate must load policy from its protected base revision. + +From a normal AppSurface checkout, run: + +```bash +tmp_dir="$(mktemp -d)" +git clone -q docs/fixtures/issue-777-docs-only/repository.bundle "$tmp_dir/repository" +base_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["baseRevision"])')" +head_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["headRevision"])')" +dotnet run --project Cli/ForgeTrust.AppSurface.Cli -- evidence explain \ + --policy docs/fixtures/issue-777-docs-only/policy.json \ + --repository "$tmp_dir/repository" \ + --base-revision "$base_revision" \ + --head-revision "$head_revision" \ + --diff-file docs/fixtures/issue-777-docs-only/source.diff \ + --gate-mode \ + --output "$tmp_dir/explain" +dotnet run --project tools/ForgeTrust.AppSurface.EvidenceGate -- run \ + --plan "$tmp_dir/explain/evidence-plan.json" \ + --policy docs/fixtures/issue-777-docs-only/policy.json \ + --repository "$tmp_dir/repository" \ + --output-dir "$tmp_dir/host" +dotnet run --project Cli/ForgeTrust.AppSurface.Cli -- evidence verify \ + "$tmp_dir/host/evidence-manifest.json" \ + --plan "$tmp_dir/host/evidence-plan.json" \ + --policy docs/fixtures/issue-777-docs-only/policy.json \ + --repository "$tmp_dir/repository" +``` + +The expected selected profile is `documentation-only`, with `NoEvidenceRequired` and `PullRequestGate` on the host manifest. The `explain` and host plan digests must match. Reversing the commit IDs, changing a diff byte, or substituting the policy must fail before an eligible final verdict. This fixture uses no remote PR and therefore does not establish current-head check association or permit [ruleset activation](../../evidence-gate-rollout.md). + +The [non-claiming shadow workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate-shadow.yml) runs this same three-command rehearsal on a branch checkout and asserts matching plan digests and the explicit empty claim. The [fixture integrity test](https://github.com/forge-trust/AppSurface/blob/main/scripts/tests/test_evidence_gate_fixture.py) separately verifies the bundle, frozen policy and fixed-options Git diff against their recorded digests. diff --git a/docs/fixtures/issue-777-docs-only/fixture.json b/docs/fixtures/issue-777-docs-only/fixture.json new file mode 100644 index 000000000..f66caecbf --- /dev/null +++ b/docs/fixtures/issue-777-docs-only/fixture.json @@ -0,0 +1,8 @@ +{ + "baseRevision": "eff492202f8e7a858dcc1ba9af71bbedd7c012da", + "bundleSha256": "9680904e9aa22193b07f86dd1b78b016b0faf3922b4e4a45b8979413229f2554", + "changedPath": "docs/fixture-note.md", + "headRevision": "5251205a29db7c66a33b6a25cf2bc7b5b0481b2b", + "policySha256": "cb0bd61016adc9d0aef87efa84b4d777eedcb0d36c6fdf7314a1f4266d58facd", + "sourceDiffSha256": "639049c29cdd44e08c3eae50aa15a99d90aa83dea8c8496bd4b055f21f10362f" +} diff --git a/docs/fixtures/issue-777-docs-only/policy.json b/docs/fixtures/issue-777-docs-only/policy.json new file mode 100644 index 000000000..6dab4c6ce --- /dev/null +++ b/docs/fixtures/issue-777-docs-only/policy.json @@ -0,0 +1 @@ +{"ConservativeProfileId":"pr-conservative","Id":"appsurface-pr-evidence","Profiles":[{"Id":"documentation-only","Obligations":[],"Producers":[],"Resources":[],"Scope":"Targeted"},{"Id":"code-coverage","Obligations":[{"Id":"behavioral-coverage","Rationale":"Changed executable code must meet the AppSurface overall and patch coverage thresholds.","RequiredAssertionId":"appsurface/coverage/overall-and-patch-thresholds@1","RequiredProducerIds":["coverage"],"RiskClass":"behavioral-code"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"cobertura","MaximumBytes":20971520,"MediaType":"application/xml","RelativeRoot":"coverage/cobertura","Required":true},{"LogicalName":"gate-report","MaximumBytes":1048576,"MediaType":"text/markdown","RelativeRoot":"coverage/report","Required":true},{"LogicalName":"diagnostics","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"coverage/diagnostics","Required":false}],"AssertionIds":["appsurface/coverage/overall-and-patch-thresholds@1"],"CoverageGate":{"MinBranchPercent":85,"MinLinePercent":95,"MinPatchBranchPercent":85,"MinPatchLinePercent":95,"PatchLineMode":"codecov","TolerancePercent":0.5},"Id":"coverage","Kind":"coverage","RequiredResources":[],"TimeoutSeconds":1200,"Version":"1.0.0"}],"Resources":[],"Scope":"Targeted"},{"Id":"postgresql-integration","Obligations":[{"Id":"behavioral-coverage","Rationale":"Changed executable code must meet the AppSurface overall and patch coverage thresholds.","RequiredAssertionId":"appsurface/coverage/overall-and-patch-thresholds@1","RequiredProducerIds":["coverage"],"RiskClass":"behavioral-code"},{"Id":"postgresql-integration-contract","Rationale":"Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.","RequiredAssertionId":"appsurface/durable/postgresql-16.5-assertions@1","RequiredProducerIds":["postgresql-contract"],"RiskClass":"resource-backed-integration"},{"Id":"package-locked-build-and-artifacts","Rationale":"Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.","RequiredAssertionId":"appsurface/package/locked-restore-build@1","RequiredProducerIds":["package-contract"],"RiskClass":"package-artifacts"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"cobertura","MaximumBytes":20971520,"MediaType":"application/xml","RelativeRoot":"coverage/cobertura","Required":true},{"LogicalName":"gate-report","MaximumBytes":1048576,"MediaType":"text/markdown","RelativeRoot":"coverage/report","Required":true},{"LogicalName":"diagnostics","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"coverage/diagnostics","Required":false}],"AssertionIds":["appsurface/coverage/overall-and-patch-thresholds@1"],"CoverageGate":{"MinBranchPercent":85,"MinLinePercent":95,"MinPatchBranchPercent":85,"MinPatchLinePercent":95,"PatchLineMode":"codecov","TolerancePercent":0.5},"Id":"coverage","Kind":"coverage","RequiredResources":[],"TimeoutSeconds":1200,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"scenario-results","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"postgresql/scenarios","Required":true},{"LogicalName":"run-metadata","MaximumBytes":262144,"MediaType":"application/json","RelativeRoot":"postgresql/run","Required":true}],"AssertionIds":["appsurface/durable/postgresql-16.5-assertions@1"],"CoverageGate":null,"Id":"postgresql-contract","Kind":"postgresql-integration","RequiredResources":["postgresql-16-5"],"TimeoutSeconds":900,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"package-manifest","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"packages/manifest","Required":true},{"LogicalName":"validation-report","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/validation","Required":true},{"LogicalName":"nupkg-digest-index","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/digests","Required":true},{"LogicalName":"nupkg-bundle","MaximumBytes":268435456,"MediaType":"application/zip","RelativeRoot":"packages/nupkg","Required":true}],"AssertionIds":["appsurface/package/locked-restore-build@1","appsurface/package/artifact-manifest-and-digests@1"],"CoverageGate":null,"Id":"package-contract","Kind":"package-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":1800,"Version":"1.0.0"}],"Resources":[{"DeadlineSeconds":180,"Id":"postgresql-16-5","Readiness":"aspire_health","Requires":[]},{"DeadlineSeconds":300,"Id":"locked-package-inputs","Readiness":"completion","Requires":[]}],"Scope":"Targeted"},{"Id":"keycloak-theme-integration","Obligations":[{"Id":"behavioral-coverage","Rationale":"Changed executable code must meet the AppSurface overall and patch coverage thresholds.","RequiredAssertionId":"appsurface/coverage/overall-and-patch-thresholds@1","RequiredProducerIds":["coverage"],"RiskClass":"behavioral-code"},{"Id":"keycloak-theme-rendering","Rationale":"Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.","RequiredAssertionId":"appsurface/keycloak/served-theme-assets@1","RequiredProducerIds":["keycloak-theme-contract"],"RiskClass":"resource-backed-integration"},{"Id":"package-locked-build-and-artifacts","Rationale":"Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.","RequiredAssertionId":"appsurface/package/locked-restore-build@1","RequiredProducerIds":["package-contract"],"RiskClass":"package-artifacts"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"cobertura","MaximumBytes":20971520,"MediaType":"application/xml","RelativeRoot":"coverage/cobertura","Required":true},{"LogicalName":"gate-report","MaximumBytes":1048576,"MediaType":"text/markdown","RelativeRoot":"coverage/report","Required":true},{"LogicalName":"diagnostics","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"coverage/diagnostics","Required":false}],"AssertionIds":["appsurface/coverage/overall-and-patch-thresholds@1"],"CoverageGate":{"MinBranchPercent":85,"MinLinePercent":95,"MinPatchBranchPercent":85,"MinPatchLinePercent":95,"PatchLineMode":"codecov","TolerancePercent":0.5},"Id":"coverage","Kind":"coverage","RequiredResources":[],"TimeoutSeconds":1200,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"theme-proof","MaximumBytes":1048576,"MediaType":"application/json","RelativeRoot":"keycloak/theme","Required":true},{"LogicalName":"theme-summary","MaximumBytes":524288,"MediaType":"text/markdown","RelativeRoot":"keycloak/summary","Required":true},{"LogicalName":"runtime-metadata","MaximumBytes":262144,"MediaType":"application/json","RelativeRoot":"keycloak/runtime","Required":true}],"AssertionIds":["appsurface/keycloak/served-theme-assets@1"],"CoverageGate":null,"Id":"keycloak-theme-contract","Kind":"keycloak-theme-integration","RequiredResources":["keycloak-pinned-image"],"TimeoutSeconds":600,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"package-manifest","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"packages/manifest","Required":true},{"LogicalName":"validation-report","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/validation","Required":true},{"LogicalName":"nupkg-digest-index","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/digests","Required":true},{"LogicalName":"nupkg-bundle","MaximumBytes":268435456,"MediaType":"application/zip","RelativeRoot":"packages/nupkg","Required":true}],"AssertionIds":["appsurface/package/locked-restore-build@1","appsurface/package/artifact-manifest-and-digests@1"],"CoverageGate":null,"Id":"package-contract","Kind":"package-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":1800,"Version":"1.0.0"}],"Resources":[{"DeadlineSeconds":240,"Id":"keycloak-pinned-image","Readiness":"aspire_health","Requires":[]},{"DeadlineSeconds":300,"Id":"locked-package-inputs","Readiness":"completion","Requires":[]}],"Scope":"Targeted"},{"Id":"package-release-preparation","Obligations":[{"Id":"behavioral-coverage","Rationale":"Changed executable code must meet the AppSurface overall and patch coverage thresholds.","RequiredAssertionId":"appsurface/coverage/overall-and-patch-thresholds@1","RequiredProducerIds":["coverage"],"RiskClass":"behavioral-code"},{"Id":"package-locked-build-and-artifacts","Rationale":"Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.","RequiredAssertionId":"appsurface/package/locked-restore-build@1","RequiredProducerIds":["package-contract"],"RiskClass":"package-artifacts"},{"Id":"release-preparation-evidence","Rationale":"Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.","RequiredAssertionId":"appsurface/release/preparation-base-and-artifacts-verified@1","RequiredProducerIds":["release-preparation-contract"],"RiskClass":"release-preparation"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"cobertura","MaximumBytes":20971520,"MediaType":"application/xml","RelativeRoot":"coverage/cobertura","Required":true},{"LogicalName":"gate-report","MaximumBytes":1048576,"MediaType":"text/markdown","RelativeRoot":"coverage/report","Required":true},{"LogicalName":"diagnostics","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"coverage/diagnostics","Required":false}],"AssertionIds":["appsurface/coverage/overall-and-patch-thresholds@1"],"CoverageGate":{"MinBranchPercent":85,"MinLinePercent":95,"MinPatchBranchPercent":85,"MinPatchLinePercent":95,"PatchLineMode":"codecov","TolerancePercent":0.5},"Id":"coverage","Kind":"coverage","RequiredResources":[],"TimeoutSeconds":1200,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"package-manifest","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"packages/manifest","Required":true},{"LogicalName":"validation-report","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/validation","Required":true},{"LogicalName":"nupkg-digest-index","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/digests","Required":true},{"LogicalName":"nupkg-bundle","MaximumBytes":268435456,"MediaType":"application/zip","RelativeRoot":"packages/nupkg","Required":true}],"AssertionIds":["appsurface/package/locked-restore-build@1","appsurface/package/artifact-manifest-and-digests@1"],"CoverageGate":null,"Id":"package-contract","Kind":"package-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":1800,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"preparation-projection","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/preparation","Required":true},{"LogicalName":"prepared-artifact-digests","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/digests","Required":true}],"AssertionIds":["appsurface/release/preparation-base-and-artifacts-verified@1"],"CoverageGate":null,"Id":"release-preparation-contract","Kind":"release-preparation-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":900,"Version":"1.0.0"}],"Resources":[{"DeadlineSeconds":300,"Id":"locked-package-inputs","Readiness":"completion","Requires":[]}],"Scope":"Targeted"},{"Id":"pr-conservative","Obligations":[{"Id":"behavioral-coverage","Rationale":"Changed executable code must meet the AppSurface overall and patch coverage thresholds.","RequiredAssertionId":"appsurface/coverage/overall-and-patch-thresholds@1","RequiredProducerIds":["coverage"],"RiskClass":"behavioral-code"},{"Id":"control-plane-integrity","Rationale":"Workflow, policy, runner, host, and gate implementation changes require base-owned validation and cannot waive evidence.","RequiredAssertionId":"appsurface/control-plane/base-owned-validation@1","RequiredProducerIds":["control-plane-validation"],"RiskClass":"trusted-control-plane"},{"Id":"postgresql-integration-contract","Rationale":"Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.","RequiredAssertionId":"appsurface/durable/postgresql-16.5-assertions@1","RequiredProducerIds":["postgresql-contract"],"RiskClass":"resource-backed-integration"},{"Id":"keycloak-theme-rendering","Rationale":"Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.","RequiredAssertionId":"appsurface/keycloak/served-theme-assets@1","RequiredProducerIds":["keycloak-theme-contract"],"RiskClass":"resource-backed-integration"},{"Id":"package-locked-build-and-artifacts","Rationale":"Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.","RequiredAssertionId":"appsurface/package/locked-restore-build@1","RequiredProducerIds":["package-contract"],"RiskClass":"package-artifacts"},{"Id":"release-preparation-evidence","Rationale":"Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.","RequiredAssertionId":"appsurface/release/preparation-base-and-artifacts-verified@1","RequiredProducerIds":["release-preparation-contract"],"RiskClass":"release-preparation"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"cobertura","MaximumBytes":20971520,"MediaType":"application/xml","RelativeRoot":"coverage/cobertura","Required":true},{"LogicalName":"gate-report","MaximumBytes":1048576,"MediaType":"text/markdown","RelativeRoot":"coverage/report","Required":true},{"LogicalName":"diagnostics","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"coverage/diagnostics","Required":false}],"AssertionIds":["appsurface/coverage/overall-and-patch-thresholds@1"],"CoverageGate":{"MinBranchPercent":85,"MinLinePercent":95,"MinPatchBranchPercent":85,"MinPatchLinePercent":95,"PatchLineMode":"codecov","TolerancePercent":0.5},"Id":"coverage","Kind":"coverage","RequiredResources":[],"TimeoutSeconds":1200,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"validation-report","MaximumBytes":1048576,"MediaType":"application/json","RelativeRoot":"control-plane/report","Required":true}],"AssertionIds":["appsurface/control-plane/base-owned-validation@1"],"CoverageGate":null,"Id":"control-plane-validation","Kind":"control-plane-validation","RequiredResources":[],"TimeoutSeconds":300,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"scenario-results","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"postgresql/scenarios","Required":true},{"LogicalName":"run-metadata","MaximumBytes":262144,"MediaType":"application/json","RelativeRoot":"postgresql/run","Required":true}],"AssertionIds":["appsurface/durable/postgresql-16.5-assertions@1"],"CoverageGate":null,"Id":"postgresql-contract","Kind":"postgresql-integration","RequiredResources":["postgresql-16-5"],"TimeoutSeconds":900,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"theme-proof","MaximumBytes":1048576,"MediaType":"application/json","RelativeRoot":"keycloak/theme","Required":true},{"LogicalName":"theme-summary","MaximumBytes":524288,"MediaType":"text/markdown","RelativeRoot":"keycloak/summary","Required":true},{"LogicalName":"runtime-metadata","MaximumBytes":262144,"MediaType":"application/json","RelativeRoot":"keycloak/runtime","Required":true}],"AssertionIds":["appsurface/keycloak/served-theme-assets@1"],"CoverageGate":null,"Id":"keycloak-theme-contract","Kind":"keycloak-theme-integration","RequiredResources":["keycloak-pinned-image"],"TimeoutSeconds":600,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"package-manifest","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"packages/manifest","Required":true},{"LogicalName":"validation-report","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/validation","Required":true},{"LogicalName":"nupkg-digest-index","MaximumBytes":4194304,"MediaType":"application/json","RelativeRoot":"packages/digests","Required":true},{"LogicalName":"nupkg-bundle","MaximumBytes":268435456,"MediaType":"application/zip","RelativeRoot":"packages/nupkg","Required":true}],"AssertionIds":["appsurface/package/locked-restore-build@1","appsurface/package/artifact-manifest-and-digests@1"],"CoverageGate":null,"Id":"package-contract","Kind":"package-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":1800,"Version":"1.0.0"},{"ArtifactSlots":[{"LogicalName":"preparation-projection","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/preparation","Required":true},{"LogicalName":"prepared-artifact-digests","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/digests","Required":true}],"AssertionIds":["appsurface/release/preparation-base-and-artifacts-verified@1"],"CoverageGate":null,"Id":"release-preparation-contract","Kind":"release-preparation-contract","RequiredResources":["locked-package-inputs"],"TimeoutSeconds":900,"Version":"1.0.0"}],"Resources":[{"DeadlineSeconds":180,"Id":"postgresql-16-5","Readiness":"aspire_health","Requires":[]},{"DeadlineSeconds":240,"Id":"keycloak-pinned-image","Readiness":"aspire_health","Requires":[]},{"DeadlineSeconds":300,"Id":"locked-package-inputs","Readiness":"completion","Requires":[]}],"Scope":"Targeted"},{"Id":"protected-release","Obligations":[{"Id":"protected-release-subject","Rationale":"Only a protected release invocation may attest the tag object, peeled commit, validated preparation base, and exact package digests without publishing.","RequiredAssertionId":"appsurface/release/protected-tag-and-preparation-base@1","RequiredProducerIds":["release-inspection"],"RiskClass":"protected-release"}],"Producers":[{"ArtifactSlots":[{"LogicalName":"release-projection","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/projection","Required":true},{"LogicalName":"release-digest-index","MaximumBytes":2097152,"MediaType":"application/json","RelativeRoot":"release/digests","Required":true}],"AssertionIds":["appsurface/release/protected-tag-and-preparation-base@1"],"CoverageGate":null,"Id":"release-inspection","Kind":"release-inspection","RequiredResources":[],"TimeoutSeconds":600,"Version":"1.0.0"}],"Resources":[],"Scope":"Release"}],"Rules":[{"Id":"documentation-reference","Pattern":"docs/*.md","Precedence":0,"ProfileId":"documentation-only"},{"Id":"documentation-guides","Pattern":"guides/*.md","Precedence":0,"ProfileId":"documentation-only"},{"Id":"documentation-start-here","Pattern":"start-here/*.md","Precedence":0,"ProfileId":"documentation-only"},{"Id":"documentation-root-readme","Pattern":"README.md","Precedence":0,"ProfileId":"documentation-only"},{"Id":"documentation-contributor-guide","Pattern":"CONTRIBUTING.md","Precedence":0,"ProfileId":"documentation-only"},{"Id":"control-github","Pattern":".github/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-policy","Pattern":".appsurface/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-design-documents","Pattern":"docs/designs/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-issue-plans","Pattern":"docs/plans/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-policy-matrix","Pattern":"docs/evidence-gate-policy-matrix.md","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-rollout-guide","Pattern":"docs/evidence-gate-rollout.md","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-scripts","Pattern":"scripts/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-agent-guidance","Pattern":"AGENTS.md","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-nested-agent-guidance","Pattern":"**/AGENTS.md","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-evidence-implementation","Pattern":"Evidence/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-evidence-cli","Pattern":"Cli/ForgeTrust.AppSurface.Cli/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"control-evidence-cli-tests","Pattern":"Cli/ForgeTrust.AppSurface.Cli.Tests/**","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"coverage-csharp","Pattern":"**/*.cs","Precedence":0,"ProfileId":"code-coverage"},{"Id":"package-project-files","Pattern":"**/*.csproj","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"unknown-typescript","Pattern":"**/*.ts","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-tsx","Pattern":"**/*.tsx","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-javascript","Pattern":"**/*.js","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-css","Pattern":"**/*.css","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-scss","Pattern":"**/*.scss","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-razor","Pattern":"**/*.razor","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"unknown-sql","Pattern":"**/*.sql","Precedence":0,"ProfileId":"pr-conservative"},{"Id":"integration-durable-postgresql","Pattern":"Durable/**","Precedence":0,"ProfileId":"postgresql-integration"},{"Id":"integration-durable-package-projects","Pattern":"Durable/**/*.csproj","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-durable-package-locks","Pattern":"Durable/**/packages.lock.json","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-durable-postgresql-example","Pattern":"examples/durable-postgresql/**","Precedence":0,"ProfileId":"postgresql-integration"},{"Id":"integration-keycloak-theme","Pattern":"Web/ForgeTrust.AppSurface.Web.Tailwind/**","Precedence":0,"ProfileId":"keycloak-theme-integration"},{"Id":"integration-keycloak-theme-package-projects","Pattern":"Web/ForgeTrust.AppSurface.Web.Tailwind/**/*.csproj","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-keycloak-theme-package-locks","Pattern":"Web/ForgeTrust.AppSurface.Web.Tailwind/**/packages.lock.json","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-keycloak-library","Pattern":"Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**","Precedence":0,"ProfileId":"keycloak-theme-integration"},{"Id":"integration-keycloak-library-package-projects","Pattern":"Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/*.csproj","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-keycloak-library-package-locks","Pattern":"Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/packages.lock.json","Precedence":1,"ProfileId":"pr-conservative"},{"Id":"integration-keycloak-apphost","Pattern":"examples/auth-aspire-keycloak-apphost/**","Precedence":0,"ProfileId":"keycloak-theme-integration"},{"Id":"integration-keycloak-examples","Pattern":"examples/auth-aspire-keycloak-*/**","Precedence":0,"ProfileId":"keycloak-theme-integration"},{"Id":"packages-index","Pattern":"packages/**","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-tool","Pattern":"tools/ForgeTrust.AppSurface.PackageIndex/**","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-lockfiles","Pattern":"**/packages.lock.json","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-msbuild-files","Pattern":"**/*.props","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-msbuild-targets","Pattern":"**/*.targets","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-pnpm-lockfile","Pattern":"**/pnpm-lock.yaml","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-dotnet-build-config","Pattern":"Directory.Build.*","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-directory-package-config","Pattern":"Directory.Packages.props","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-sdk-config","Pattern":"global.json","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-nuget-config","Pattern":"NuGet.config","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"packages-gate-config","Pattern":"NuGet.package-gate.config","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"release-preparation-tool","Pattern":"tools/ForgeTrust.AppSurface.Release/**","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"release-preparation-documents","Pattern":"releases/**","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"release-preparation-version","Pattern":"VERSION","Precedence":0,"ProfileId":"package-release-preparation"},{"Id":"release-preparation-changelog","Pattern":"CHANGELOG.md","Precedence":0,"ProfileId":"package-release-preparation"}],"Version":"1"} \ No newline at end of file diff --git a/docs/fixtures/issue-777-docs-only/repository.bundle b/docs/fixtures/issue-777-docs-only/repository.bundle new file mode 100644 index 000000000..d89f1491b Binary files /dev/null and b/docs/fixtures/issue-777-docs-only/repository.bundle differ diff --git a/docs/fixtures/issue-777-docs-only/source.diff b/docs/fixtures/issue-777-docs-only/source.diff new file mode 100644 index 000000000..036c72ad9 --- /dev/null +++ b/docs/fixtures/issue-777-docs-only/source.diff @@ -0,0 +1,9 @@ +diff --git a/docs/fixture-note.md b/docs/fixture-note.md +index 906ee49cc1f28f6bc3ab25fddff22ac792773334..146b0a65bc9638d9ef8a0ec9502a8d410e1ed864 100644 +--- a/docs/fixture-note.md ++++ b/docs/fixture-note.md +@@ -1,3 +1,3 @@ + # Evidence fixture + +-The base revision has one documentation sentence. ++The head revision has one updated documentation sentence. diff --git a/docs/fixtures/issue-777-policy-shadow/README.md b/docs/fixtures/issue-777-policy-shadow/README.md new file mode 100644 index 000000000..38e5d9315 --- /dev/null +++ b/docs/fixtures/issue-777-policy-shadow/README.md @@ -0,0 +1,7 @@ +# AppSurface policy-shadow fixtures + +[`fixtures.json`](https://github.com/forge-trust/AppSurface/blob/main/docs/fixtures/issue-777-policy-shadow/fixtures.json) is the reviewed case set for the [non-claiming policy-shadow comparison](../../../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#non-claiming-policy-shadow-comparison). The file is a JSON array of `EvidencePolicyShadowFixture` records. Each record has a unique `id`, a base-owned `kind` (`Documentation`, `Code`, `Resource`, `ControlPlane`, or `Unknown`), and a `changedPath` object with a repository-relative `path`. A rename also supplies `kind: "renamed"` and `previousPath` inside `changedPath`. The canonical API shape and limits are in the [planner reference](../../../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#non-claiming-policy-shadow-comparison). + +The protected base revision must supply this file and the reviewed [AppSurface policy](https://github.com/forge-trust/AppSurface/blob/main/.appsurface/evidence/evidence.policy.json) to the trusted comparison. Candidate revisions may supply a copy as additional data, but removing or editing a base case is a finding and never removes the original case. The checked-in policy explicitly treats this fixture directory as control-plane material. The [rollout record](../../evidence-gate-rollout.md) tracks the separate live pilot and explains why a branch-owned shadow result is not a required-check verdict. + +The fixture set covers a docs-only path, ordinary code, PostgreSQL and Keycloak resources, package artifacts, workflows, the first-party runner, the release tool, this fixture file, an unknown extension, and a resource-to-code rename. The adjacent `AppSurfaceEvidencePolicyTests` resolve all cases under the checked-in policy. A base-owned workflow still needs to supply trusted input provenance and classify actual changed paths before this comparison can authorize any control-plane transition. diff --git a/docs/fixtures/issue-777-policy-shadow/fixtures.json b/docs/fixtures/issue-777-policy-shadow/fixtures.json new file mode 100644 index 000000000..c481788ec --- /dev/null +++ b/docs/fixtures/issue-777-policy-shadow/fixtures.json @@ -0,0 +1,61 @@ +[ + { + "id": "documentation-reference", + "kind": "Documentation", + "changedPath": { "path": "docs/overview.md" } + }, + { + "id": "ordinary-code", + "kind": "Code", + "changedPath": { "path": "src/Orders/SubmitOrder.cs" } + }, + { + "id": "postgresql-resource", + "kind": "Resource", + "changedPath": { "path": "Durable/ForgeTrust.AppSurface.Durable.PostgreSql/Store.cs" } + }, + { + "id": "keycloak-resource", + "kind": "Resource", + "changedPath": { "path": "Web/ForgeTrust.AppSurface.Web.Tailwind/theme.css" } + }, + { + "id": "package-artifact", + "kind": "Code", + "changedPath": { "path": "packages/package-index.yml" } + }, + { + "id": "workflow-control-plane", + "kind": "ControlPlane", + "changedPath": { "path": ".github/workflows/evidence-gate.yml" } + }, + { + "id": "runner-control-plane", + "kind": "ControlPlane", + "changedPath": { "path": "tools/ForgeTrust.AppSurface.EvidenceGate/Program.cs" } + }, + { + "id": "release-tool-control-plane", + "kind": "ControlPlane", + "changedPath": { "path": "tools/ForgeTrust.AppSurface.Release/ReleaseCommands.cs" } + }, + { + "id": "fixture-control-plane", + "kind": "ControlPlane", + "changedPath": { "path": "docs/fixtures/issue-777-policy-shadow/fixtures.json" } + }, + { + "id": "unrecognized-path", + "kind": "Unknown", + "changedPath": { "path": "new-surface/unclassified.bin" } + }, + { + "id": "resource-to-code-rename", + "kind": "Resource", + "changedPath": { + "path": "src/Orders/MovedStore.cs", + "kind": "renamed", + "previousPath": "Durable/ForgeTrust.AppSurface.Durable.PostgreSql/OldStore.cs" + } + } +] diff --git a/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md b/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md new file mode 100644 index 000000000..2a5e5ff85 --- /dev/null +++ b/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md @@ -0,0 +1,747 @@ +## Implementation plan +# Design: AppSurface policy-driven CI evidence gate + +- Generated by /office-hours on 2026-09-30 +- Branch: `main` +- Repo: `forge-trust/AppSurface` +- Status: APPROVED (office-hours, 2026-09-30) +- Mode: Builder +- Issue: [#777](https://github.com/forge-trust/AppSurface/issues/777) +Builds on: [EvidenceHost contract-first design](https://github.com/forge-trust/AppSurface/blob/main/docs/designs/appsurface-evidencehost-contract-first.md) and completed [#775](https://github.com/forge-trust/AppSurface/issues/775) + +## Problem Statement + +AppSurface has an [Evidence planner, CLI, and host contract](../../start-here/evidencehost.md), but no AppSurface CI workflow calls `appsurface evidence`. A maintainer cannot point at a live, safe reference run that proves a checked-in policy selected the work for an exact change and that the resulting manifest supports the CI verdict. Current independent workflows still decide what to run in YAML. The AppSurface repository also has no required status check in its active default-branch ruleset, so publishing a green example alone would not create a merge gate. + +The first adopter is AppSurface's own maintainers. The intended outcome is a working required PR check plus a release invocation of the same evidence runner. It should be possible to copy the documented pattern later, but this issue does not promise a general reusable workflow interface for other repositories. + +## What Makes This Cool + +The workflow says *which revisions and policy were evaluated, why a profile was selected, what every obligation required, and whether the evidence actually closed it*. A docs-only change receives an explicit `NoEvidenceRequired` claim. A code change whose selected producer or disposable resource fails cannot become green because some other CI job passed. The console, GitHub summary, and machine manifest render one verdict from one plan. A fork can still be inspected, but it cannot borrow a trusted claim. + +## Constraints + +- [#777](https://github.com/forge-trust/AppSurface/issues/777) is an AppSurface-owned reference path, not a new CI scheduler, deployment system, generic plugin loader, or cross-job aggregation format. +- The [existing EvidenceHost design](https://github.com/forge-trust/AppSurface/blob/main/docs/designs/appsurface-evidencehost-contract-first.md) owns the contract boundary: base-owned policy and explicit host registrations; separate trusted-tool and subject checkouts; [coverage core](https://github.com/forge-trust/AppSurface/blob/main/docs/designs/evidence-coverage-core-extraction.md) reuse; typed producer/resource/obligation closure; bounded cleanup; observation-only execution for untrusted inputs. +- The current [planning CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) accepts policy and path/diff inputs but has no authoritative base/head arguments. Its run command can execute the built-in coverage producer; it cannot yet execute every resource-backed AppSurface profile. The [plan contract](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) records a normalized diff digest but not base/head or the exact source diff bytes. These are implementation gaps, not values YAML can invent. +- Required-check behavior depends on GitHub event and ruleset semantics. The current default-branch ruleset requires reviews but no CI status. A planned gate must be proven on an actual PR before that ruleset changes. +- No production credentials, mutable release operations, or head-controlled workflow/host/policy instructions enter the evidence run. The reference release profile remains non-mutating. + +## Premises + +1. **Selection is policy-owned and revision-bound.** The authoritative plan includes full base and head Git object IDs, SHA-256 of the exact captured source diff bytes, normalized change digest, policy digest, profile, and plan digest. CI regenerates and verifies the source diff from those objects with fixed Git options before `explain` and `run`; both commands consume the same immutable snapshot. A self-consistent manifest without this external revision check is insufficient. +2. **Only the manifest decides the gate.** A PR passes only for a verified, current-base-and-head, gate-eligible `TargetedComplete` or explicit `NoEvidenceRequired` claim. `NoEvidenceRequired` is not a synonym for a skipped job. Missing producer, resource, obligation, required artifact, cleanup, or envelope state produces no complete claim and a failed gate. A release pipeline requires `ReleaseComplete` with release eligibility; a PR check cannot reinterpret a targeted claim as release complete. Policy selects the candidate profile from the diff; trusted event context separately determines whether that profile may issue a PR or release claim. +3. **The trusted control plane is base-owned.** The workflow, policy, host registrations, runner, and envelope verifier come from the protected base/trusted-tool revision. The head is only the subject under test. No subject file can choose a command, image, mount, token, network capability, producer, or artifact root. +4. **Fork and other untrusted inputs remain observational.** They receive no privileged capability or complete claim. The required check fails until reviewed content is promoted to a trusted same-repository branch and a new PR-eligible run evaluates that exact promoted head. A manual `workflow_dispatch` report alone cannot satisfy the PR's required check. +5. **The reference proves all AppSurface-selected profiles.** The host must actually run every producer/resource required by the checked-in AppSurface policy, including its non-mutating release profile. Unsupported profile or missing registration fails closed; YAML never silently downgrades the profile. + +## Cross-Model Perspective + +A fresh `combo/sub` review supported a base-owned evidence path but challenged the original claim that a policy, diff, and plan digest alone identify the tested change. It observed that two revision pairs can yield the same normalized paths and that a GitHub event's merge checkout can differ from the requested head. We accepted the challenge: exact base/head identities and the captured diff-byte digest belong in the plan and manifest contract, and CI must independently regenerate the diff before execution. The reviewer also suggested a trusted manual rerun for forks; GitHub's required-check rules make that insufficient as a PR gate, so promotion to a same-repository branch is the explicit path. + +## Approaches Considered + +- **A — Narrow live PR gate (M; about 2–4 human days / 4–8 agent hours).** Gets coverage and no-evidence cases live sooner, but leaves resource-backed and release-profile completeness unproved. Rejected because the selected reference would still demonstrate only the easy branch of EvidenceHost. +- **B — Complete AppSurface EvidenceHost gate (L; about 1–2 human weeks / 1–2 agent days). Selected.** Builds one revision-bound runner and explicit AppSurface host registrations, exercises every policy-selected profile, then makes the PR check required after live proof. The extra work is concentrated in real host execution and trust isolation. +- **C — Versioned reusable workflow (XL; about 2–3 human weeks / 3–5 agent days).** Adds a public consumer input/output and compatibility surface before the first live adopter. Deferred until AppSurface's own path is stable. + +## Recommended Approach + +### 1. Capture and bind the exact change + +The PR controller reads the event's target-base tip and head SHA as data, validates full commit IDs, fetches both objects by SHA, and computes a fixed-options `git diff` between them. It records the source bytes once in a bounded file, independently regenerates the same bytes from the fetched objects, and fails if they differ. The comparison is deliberately the explicit pair rather than an implicit checkout, merge commit, or ambient Git state. This may select extra work when the base advances; that is a conservative cost, never a missing-evidence shortcut. The ordinary build workflow remains responsible for merge-commit compatibility. The plan also records the PR number, target-base tip, workflow/run identity, and head SHA as bounded provenance fields, but these are not substitutes for Git object verification. Immediately before the final verdict, the controller rereads the PR's current target-base tip and head via the GitHub API and rejects either mismatch as stale; a completed run is never retroactively reinterpreted for a new pair. + +Extend the versioned Evidence contracts and the [CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) with authoritative `--base-revision`, `--head-revision`, and `--diff-file` inputs. A new schema version records `SourceDiffDigest` separately from the existing normalized `DiffDigest`; plan and manifest digests cover both revisions and both digests. `explain`, `run`, and `verify` use the same canonical plan identity. Gate mode rejects path-only input, abbreviated SHAs, missing Git objects, a mismatched source diff, stale policy, or a head changed since the event. Local non-gate CLI use can keep its existing path/diff ergonomics and must not imply gate eligibility. Publish the schema migration and compatibility rules in the [Evidence contract reference](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md) and [EvidenceHost guide](../../guides/evidencehost-cookbook.md). + +### 2. Execute a closed AppSurface policy in one host + +Check in an AppSurface policy whose every repository path is accounted for by an explicit rule or conservative fallback. It distinguishes docs-only `NoEvidenceRequired` from code/coverage, resource-backed integration, and non-mutating release profiles. Renames evaluate both sides; deletions and mixed docs/code changes cannot collapse to docs-only. Policy selects only named, base-registered resources, producers, obligations, assertions, and artifact slots. A release profile runs only in a protected release context; selecting it in a PR context fails as an event/profile mismatch rather than issuing a release claim. + +A dedicated AppSurface host runner composes the [EvidenceHost bootstrap](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) with explicit first-party registrations. It invokes the extracted coverage core through its existing seam, provisions disposable required resources through Aspire adapters, and runs the selected AppSurface integration and package/release evidence as typed producers with bounded readiness, execution, artifact, and cleanup behavior. It does not treat existing separate workflow job conclusions as producer results. The host owns one manifest even on producer failure where the contract permits one. A missing registration or resource returns an incomplete/invalid manifest and nonzero gate exit. Any capability that AppSurface cannot run safely stays outside the policy until a concrete, tested producer exists; the conservative fallback cannot declare it satisfied. + +For the protected release invocation, the subject is the peeled commit of a protected annotated release tag, not the workflow's ambient checkout or a user-supplied branch name. The trusted release verifier reads the tag object and commit from Git, checks the tag/version against the existing protected release-publish validation, and records the tag object ID, peeled commit, comparison-base commit, and SHA-256 of each policy-declared release package or archive in the plan and manifest. A package producer hashes the exact output it verified; publishing may consume only those digest-matching artifacts if the claim is used to authorize publication. A changed tag, rebuilt artifact with different bytes, missing declared artifact, or mismatched release event invalidates `ReleaseComplete`. Release policy still selects the candidate profile from the explicit comparison-base/tag-commit diff; the protected event and artifact checks grant release eligibility separately. + +### 3. Separate trusted control and subject execution + +The PR workflow uses a base-owned, PR-eligible trigger such as `pull_request_target` only after a live pilot verifies event availability, check association with the PR's current head, and repository event policy. It uses pinned actions, minimal read permissions, `persist-credentials: false`, no secrets, and separate read-only trusted-tool and subject checkouts. The supported runner is an ephemeral GitHub-hosted VM. The trusted controller runs outside a rootless OCI subject container pinned by image digest. The container receives only a read-only subject source mount and a dedicated writable scratch mount. It has a non-root UID, read-only root filesystem, dropped capabilities, no-new-privileges, bounded CPU/memory/PIDs, and no token, Docker/Podman socket, host home, trusted-tool mount, or runner credential files. For a profile without dependencies it has no network; a resource-backed profile uses a per-run internal network with only its declared disposable services and explicit egress denial, including denial of the host gateway and cloud metadata endpoint. Trusted code starts the container with argument arrays, validates its exit status and declared artifacts copied out of scratch, and treats all subject output as untrusted data. The base-owned envelope verifier checks this exact mount/network/capability configuration, runner class, root identities, subject/trusted revisions, and capability evidence immediately before resource provisioning. Inputs from PR titles, paths, or head files are never interpolated into shell commands. If the runner cannot enforce these properties, trusted claims are disabled. + +The controller owns resource labels and an external supervisor process, independent of the EvidenceHost process, with a per-run 10-minute cleanup deadline. Normal `finally` cleanup and an `if: always()` CI step ask the supervisor to stop containers/services, remove the per-run network and scratch data, and attest completion; failed or timed-out cleanup prevents a complete claim. A forced EvidenceHost-process kill is tested with the supervisor still alive and must converge within the declared deadline. If the entire VM is lost, no final manifest/check success can be issued, and its local-only resources die with the ephemeral VM; provider VM-destruction latency is outside the 10-minute claim. Persistent/self-hosted runners and external shared resources are unsupported until they have a separately demonstrated external reaper. + +For fork or otherwise untrusted heads, the workflow may emit a bounded observation report from a dependency-free safe subset; it always records `ObservationOnly` and exits the required gate nonzero. Maintainers can review and promote an exact commit to a same-repository branch, then run the normal PR path on a replacement or updated PR. The fork PR's observation does not become green by approval label or manual dispatch. If GitHub's policy prevents the intended PR trigger or attaches its check to the wrong revision, rollout stops before ruleset activation; use a separately designed base-owned PR-eligible check publisher rather than weakening the trust boundary. + +### 4. Derive one bounded output and turn it into a gate + +After host completion, verify the manifest against the captured plan, source diff, policy, selected profile, artifact hashes, trust envelope, and current PR head. One renderer produces the terminal verdict, GitHub step summary, and machine JSON from that verified result. It prints claim kind, eligible gate, profile/rule rationale, base/head short IDs, selected/closed/missing obligation IDs, and stable diagnostic codes; it never prints secret values, raw producer logs, arbitrary file contents, or unbounded changed-path lists. It truncates and counts long collections deterministically and stays below GitHub's [1 MiB step-summary limit](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands). Artifact upload and summary writing are presentation steps, not verdict sources; an upload failure cannot turn an incomplete run green. A pre-plan validation failure emits a bounded diagnostic and failed status without inventing a manifest. + +The gate job has a stable name, runs on PR `opened`, `synchronize`, `reopened`, `ready_for_review`, and base-target `edited` events without path filters or job-level skipping, and explicitly exits nonzero for `None`, `ObservationOnly`, invalid, incomplete, stale, cancelled, or wrong-scope claims. This avoids GitHub's [skipped-job success semantics](https://docs.github.com/en/pull-requests/reference/status-checks). Keep the existing build/test checks while the new gate runs in observation mode. After successful same-repository, docs-only, failing, and fork PR pilots prove the check attaches to the current PR head, add that exact check to the default-branch ruleset with [strict required-check freshness](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets). When the target base advances after a run, GitHub must block merging until the PR branch is updated; that head update emits `synchronize` and a new base/head-bound check. The live pilot must prove this behavior, including a base update while the head is unchanged, before enforcement. If merge queue is adopted, add `merge_group` support and revalidate before queue activation. A manual release invocation uses the same runner and release-specific verifier but is never counted as the PR's required check. + +## Open Questions + +- Which concrete AppSurface integration and package/release assertions can be safely executed inside the first host? The implementer must inventory the current [build](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml), [package gate](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/package-gate.yml), and [release contract](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/release-contract.yml) workflows and name each policy obligation before wiring the host. Missing capability blocks that profile's promotion; it does not become an empty success. +- Does the live GitHub event policy permit the selected base-owned PR trigger, and does its named check satisfy the current-head required-check rule in this repository? This is a rollout experiment, not an assumed platform guarantee. + +## Success Criteria + +1. On a live AppSurface PR, `explain` and `run` report the same plan digest for verified base/head/diff/policy inputs; altering any one makes the gate fail before a complete claim. A new head causes a new run; a base update makes the strict required check stale until the head is updated and rerun. The final verifier checks both current SHAs, so an old manifest cannot satisfy either new revision. +2. Docs-only, code, mixed/renamed/deleted, resource-backed, and release fixtures select their candidate profiles solely from policy; trusted PR or protected release context separately determines claim eligibility. Docs-only produces explicit `NoEvidenceRequired`; unrecognized paths select the conservative profile or fail. +3. Positive host runs yield verified `TargetedComplete` or `ReleaseComplete` claims as appropriate. Injected missing producer, unavailable resource, failed assertion, absent required artifact, cleanup failure, or envelope mismatch yields no complete claim and a failed gate. Release fixtures also prove tag-object/peeled-commit and package-digest binding against the protected release invocation. Fork/untrusted runs yield `ObservationOnly` and a failed required check. +4. Terminal, GitHub summary, and manifest agree on the claim and missing obligations. Secret canaries and oversized/malicious paths do not leak or exceed output limits. Normal cancellation and a forced host-process kill clean up the disposable topology within the in-VM 10-minute bound; entire-VM loss yields no complete claim and leaves no shared resource. +5. A real PR demonstrates the stable evidence check on the current head, a base-advance freshness block, and the default-branch ruleset requires it with strict freshness. The repository can merge a qualifying trusted PR and blocks an incomplete or fork-observation PR. Existing checks remain green, formatting and changed-code branch tests pass, and solution coverage is run when practical. + +## Distribution Plan + +Deliver the reference as a checked-in AppSurface workflow, policy, explicit host runner, versioned Evidence contract/CLI changes, and an [EvidenceHost adoption guide](../../start-here/evidencehost.md). A consumer starts by copying the documented checkout/policy/runner pattern and replacing the explicit host registrations; it must prove completeness of every selected test profile before enforcing its own required check. The existing AppSurface package release pipeline publishes the contract and CLI changes. The CI workflow runs on PRs; the protected release pipeline invokes its release profile. No deployment or automatic release is introduced here. + +## Dependencies + +[#775](https://github.com/forge-trust/AppSurface/issues/775) supplies the current contract and coverage seam. The GitHub required-check rollout depends on a live PR pilot and a repository administrator updating the active default-branch ruleset. An AppSurface resource-backed and release producer inventory is needed before those profiles can become required. The older [EvidenceHost contract-first design](https://github.com/forge-trust/AppSurface/blob/main/docs/designs/appsurface-evidencehost-contract-first.md) remains the architecture source for consumer-owned hosts and trust-envelope semantics. + +## The Assignment + +Take one real AppSurface PR that changes code and record its exact target-base tip, head SHA, and selected policy profile. Use it as the pilot fixture for verifying that the planned base-owned check reports against the current head before asking an administrator to make the check required. + +## Next Steps + +1. Inventory existing AppSurface CI evidence and write the complete checked-in policy/registration matrix; identify any selected profile that lacks a safe producer. +2. Add revision/source-diff binding to contracts, CLI, planner, verifier, and documentation; test deterministic identity and tampering/compatibility cases. +3. Implement the explicit AppSurface host runner and typed producers, then prove complete and failure branches including resource, cleanup, and release envelope behavior. +4. Add the base-owned PR workflow and protected release invocation, bounded renderer, fork observation path, and trust-isolation tests. +5. Pilot real PR check association and event policy; only then enable the exact required check in the ruleset and document the consumer adoption path. + +## What I noticed about how you think + +- You answered “AppSurface CI gates” when asked for the first proof. That makes this a real repository behavior, with branch protection as the finish line. +- You chose the stricter fork outcome: observation can inform review, but it cannot silently satisfy a required evidence check. +- You accepted the second opinion's revision-binding challenge and chose the complete EvidenceHost path. The design now has to prove the exact tested change and the harder resource/release branches, not just produce a polished YAML example. + + +## Reviewer Concerns + +Disposition: CONCERNS_RECORDED + +Stop: CONVERGENCE + +### R2-1 — completeness + +**Problem** + +> The release plan records a comparison-base commit, but the design does not define which trusted revision supplies that base or how the release event binds to it. Since policy selects the release profile from the tag-commit diff, different baselines can select different obligations while still producing a revision-bound manifest. + +**Remedy** + +> Define a deterministic, trusted source and selection rule for the release comparison base, bind that base to the protected release event, and test missing, changed, and mismatched baseline cases before allowing a ReleaseComplete claim. + +### R2-2 — completeness + +**Problem** + +> The design says a changed tag invalidates ReleaseComplete, but it does not specify a final check of the tag ref/object (or an enforced immutability guarantee) between evidence capture, verdict issuance, and publication use. A tag that moves after capture could leave a claim authorizing artifacts for a commit the release tag no longer identifies. + +**Remedy** + +> Require the trusted verifier to recheck the protected tag ref, tag object ID, and peeled commit immediately before issuing ReleaseComplete and before any publication consumes the claim, or specify and verify an equivalent immutable-tag guarantee; include a retagging race test. + +### R2-3 — feasibility + +**Problem** + +> The subject can write arbitrary content to scratch, and trusted code copies declared artifacts out, but the copy-out boundary has no path-containment, file-type, or size rules. A malicious subject could use symlinks or special files to make the trusted copier escape scratch or process unbounded data, undermining the stated isolation boundary. + +**Remedy** + +> Specify a no-follow extraction protocol that accepts only normalized relative paths resolving inside scratch and regular files, enforces per-file and aggregate count/size limits, and tests traversal, symlink, special-file, and oversized-artifact cases. + +### Prior finding evidence + +**R1-3 → R2-3 (persisting)** + +> Recommended Approach 3 specifies the ephemeral VM, rootless OCI container, mounts, credential/socket exclusions, resource network and egress limits, and envelope checks, but only says declared artifacts are copied from subject-writable scratch; it does not constrain that transfer so it cannot follow paths outside scratch or expose trusted host data. See R2-3. + + + +- Preserve the approved AppSurface-only EvidenceHost gate and its existing PR, fork, resource, release, documentation, and rollout requirements; no generic reusable workflow or deployment scope is added. +- For release policy selection, use the canonical V2 release-evidence `ContentSourceCommit` as the sole comparison-base commit. Read and validate it from the tag-bound prepared artifacts through `ReleaseTaggedProjectionResolver`; require a full canonical commit ID, existence in Git, ancestry to the peeled tag commit, and agreement with the protected release invocation's validated version, tag, and base branch. Bind the commit and source-diff digest into the release plan and manifest. Missing, invalid, non-ancestor, or changed preparation-base evidence fails before `ReleaseComplete`; test each case and a forged alternate base. +- The trusted verifier must reread the remote protected tag ref, annotated tag object ID, and peeled commit immediately before `ReleaseComplete` and again immediately before a publisher consumes that claim. Each must equal the plan's captured identity; a retag or missing tag fails closed. Test a tag move between capture and verdict and between verdict and publication. +- Copy subject artifacts from scratch with a no-follow, descriptor-relative extraction protocol. Allow only normalized relative declared paths resolving within scratch and regular files; reject symlinks, hardlink ambiguity, devices, FIFOs, sockets, traversal, duplicate/case-colliding names, and files changed during reading. Enforce documented file-count, per-file, aggregate-byte, and time limits before hashing/copying. Test traversal, symlink, special file, oversized file, count/aggregate overflow, and mutation races. Never use a shell `cp` or tar extraction as this trust-boundary operation. +- Before implementation, inventory each policy profile and prove its named producer, disposable resource, assertion, cleanup and artifact slot against the current workflows. A profile with a missing safe producer remains fail-closed and cannot be required or promoted. Keep the policy and registration matrix as a reviewable deliverable. +- Stage rollout so the new check first runs in non-required observation mode on same-repository, docs-only, failure, base-advance, and fork pilot PRs. Verify head association and event availability, then require the exact stable check with strict freshness. Preserve the existing checks. Document the ruleset activation, stop/rollback procedure, and admin owner. +- Set checked-in AppSurface extraction limits for the first runner: at most 64 declared regular artifacts, 256 MiB per file (also constrained by each slot's `MaximumBytes`), 512 MiB aggregate copied bytes, and 120 seconds total extraction time. Apply whichever per-slot or runner limit is lower. Reject before allocation when declared bounds already exceed a limit, and enforce streamed read-time bounds; changes to these limits require a reviewed policy/runner change and matching boundary tests. +- Rollback trigger: a claim attached to the wrong SHA, a false complete claim, subject isolation/credential exposure, cleanup failure, unavailable PR event, or a ruleset-induced block of otherwise qualifying PRs. For gate correctness or availability failures without suspected isolation or credential exposure, the repository administrator removes only the new exact check from the active ruleset to restore pre-gate merge eligibility for in-flight PRs after GitHub applies the ruleset; disable the workflow if continued execution is unsafe. For suspected isolation or credential exposure, follow the immediate contain/cancel sequence below before the ruleset change. Confirm existing checks still govern, document affected PRs/runs, fix root cause, rerun the full same-repository/docs/failure/fork/base-advance pilot, and re-enable the required check only after observed head association and freshness pass. +- Treat the office-hours 1–2 human-week / 1–2 agent-day effort line as a provisional comparison among approaches, not a delivery commitment. Re-estimate after the policy/producer inventory, with separate contract/CLI, host/isolation, release, live-pilot, and administrator-activation milestones; the latter two depend on GitHub event policy and administrator availability. +- For suspected subject isolation or credential exposure, disable/contain the new workflow so no new subject runs start, cancel active runs, then have the administrator remove the exact required check from the ruleset to restore prior merge behavior. For other gate correctness/availability failures, remove the required check promptly and disable the workflow if continued execution is unsafe. Record affected runs and preserve existing checks. Re-enable only after a root-cause fix, a trigger-specific regression proof (including envelope, resource, release, or cleanup branch as applicable), the full same-repository/docs/failure/fork/base-advance live pilot, and administrator verification of head association and strict freshness. +- Map every rollback trigger to re-enable proof: wrong-SHA attachment requires a controlled head/base update and current-head check-association assertion; false-complete claim requires injected missing obligation/failed assertion plus a nonzero gate assertion; isolation or credential exposure requires a hostile subject probe for mount, token, socket and network denial plus cancellation proof; cleanup failure requires supervisor kill/timeout injection and incomplete claim; unavailable PR event requires a live event-policy and check-attachment pilot; ruleset blocking a qualifying PR requires a live docs-only and code PR that pass the exact check under strict freshness. Release-related triggers additionally require retag/rebuilt-artifact regression. Record links to each proof in the rollout log before administrator re-enables the check. +- Treat changes to the base-owned workflow, policy, runner, envelope verifier, and host registrations as control-plane changes. The current trusted controller must classify these paths conservatively, require the old policy's obligations, and validate the proposed policy as data against old-versus-new selection fixtures for docs/code/rename/deletion/resource/release and unrecognized paths. A shadow run of the proposed controller/host in an unprivileged, non-claiming envelope must pass before merging; the proposed files cannot be trusted by their own PR run. Require explicit maintainer review of any reduced obligation or changed trust capability, a post-merge smoke run before continued enforcement, and a regression where deletion/weakening of a rule cannot let its own PR pass under the old gate. +- Use `ReleaseTaggedProjectionResolver`'s validated tagged projection and V2 evidence bundle as the sole source of the release preparation base. Verify the bundle's subject digest covers the V2 preparation-base commit, the V2 release manifest `PreparationBaseCommit` agrees, the annotated tag's `AppSurface-Release-Evidence-Subject-Sha256` trailer matches that digest, and the protected release invocation validates version/tag/base-branch reachability. Bind the validated bundle digest, tag object ID, peeled commit and preparation-base commit into the evidence plan. Reject a raw or alternate-ancestor field even if it is a valid Git ancestor; test forged prepared evidence, mismatched manifest source, and mismatched tag trailer. +- In the policy/registration matrix, name each existing workflow obligation's canonical command or implementation, whether EvidenceHost calls that exact seam, which old job remains necessary after activation, and expected steady-state ownership. During the pilot compare duplicate result and runtime; do not remove an existing required job until equivalent branch/failure behavior is proven and a separate migration is reviewed. +- Keep fork `ObservationOnly` and same-repository promotion as the approved gate behavior. The pilot records the number of fork PRs, maintainer promotion steps and elapsed turnaround, and the runbook documents the exact SHA promotion path. A base-owned external check publisher is a future separate design if that measured cost justifies it; it cannot silently upgrade the observation claim in #777. + + + + +- Put a revision-bound AppSurface gate quickstart on the [EvidenceHost start page](../../start-here/evidencehost.md), linked from the repository and CLI entry points. It must use a checked-in policy, one maintained fixture with two full commit IDs and exact diff bytes, and copyable `appsurface evidence explain` commands with expected profile, rationale, obligations, source-diff digest and plan digest. State prerequisites and distinguish the local `--path` sample from gate-eligible evidence. The chosen first-result clock runs from a normal checkout with the CLI installed to that verified explanation; target 2–5 minutes, measured in a fresh maintainer rehearsal. Report full producer/CI runtime separately. +- Define the gate input contract for `explain`, `run`, and `verify` in the CLI and contract references: both full `--base-revision` and `--head-revision` plus `--diff-file` are required together for a revision-bound PR candidate; missing/mixed/abbreviated inputs, absent Git objects, or bytes that fail independent diff regeneration are errors. A local path/diff plan remains usable but cannot claim gate eligibility. Document how the trusted controller supplies its immutable snapshot, how the host executes selected resource-backed producers, and which fields and plan digest the three commands must agree on. Show real command/output templates for a docs-only and a code fixture, with no implication that local `explain` alone can satisfy GitHub's required check. +- Give every gate diagnostic a stable code and a bounded human message with the observed identifier, what failed, likely cause, next action and a nearby link to its canonical reference or troubleshooting section. Demonstrate at least stale base/head, source-diff or plan mismatch, missing producer/resource, unsafe artifact, isolation-envelope failure, cleanup failure, and moved release tag. Keep terminal, summary and machine JSON codes consistent while never printing raw subject output or credentials. Test that the guidance is accurate for those injected branches and that long/malicious values remain bounded. +- Add one tested end-to-end AppSurface adoption walkthrough in the [cookbook](../../guides/evidencehost-cookbook.md): policy rule and explicit registration, local explain, host run, manifest verify, expected claim/verdict, then live check and strict-freshness pilot. Name which code is the reusable contract/CLI and which is AppSurface's reference runner. Include the exact-SHA same-repository promotion procedure for a fork and the fact that its original observation remains ineligible. Link the policy/producer matrix and the operator rollback guide. +- Publish a versioned v1-local to revision-bound gate migration table covering schema compatibility, plan/manifest identity changes, CLI input rules, and what old consumers must change or can keep. Separate consumer-tailorable policy/profile/registration/diagnostic display choices from fixed trust invariants: independent Git diff verification, base-owned authority, complete obligations, isolation, bounded extraction, cleanup attestation, and fresh PR/tag checks. Test the documented fixture and examples against the built CLI and host before enabling the required check. +- Measure and record the selected 2–5 minute first-result journey with a fresh maintainer starting at the documented start page; include discovery, commands, errors and reading the useful explanation. Separately record local full profile execution time, live PR gate latency, fork-promotion effort, and duplicate existing-CI time during the pilot. Treat these as rollout observations, not new telemetry infrastructure or an automatic release gate. + + + +- Preserve the complete AppSurface-only gate and non-mutating release reference, but place the base-owned controller/verifier and untrusted subject execution on separate ephemeral GitHub-hosted job VMs. The subject job has `permissions: {}`, no secrets or OIDC permission, no persisted checkout credential, and receives only the exact captured subject tree and bounded plan data; it never receives the trusted policy/runner as writable input. A private same-workflow artifact handoff carries bounded result bytes, not a generic cross-job aggregation API. The verifier treats every subject result and artifact as untrusted, independently recreates the plan from the base-owned policy and exact Git objects, validates run/job provenance, complete obligations, artifact hashes and cleanup, then performs fresh PR-head/base checks before its stable required-check verdict. No subject job or artifact can directly set that verdict. Pilot actual current-head association and event-policy availability before enforcement. Keep the OCI boundary inside the unprivileged subject VM and hostile-probe it; an inability to enforce it prevents a complete claim. +- Specify one versioned, byte-exact Git change protocol for the gate. Fetch and resolve full commit object IDs into a trusted bare/object-only checkout; invoke Git with argument arrays, pinned runner Git version, neutral trusted configuration, disabled external diff/textconv/color and fixed rename/submodule/binary options. Retain a bounded exact source diff for its digest, and derive selection paths separately from a NUL-delimited `git diff --name-status -z` representation of the same objects. Parse statuses and both rename/copy paths, including mode-only, symlink, binary and submodule changes; reject malformed/truncated/invalid-UTF-8/unrepresentable records rather than selecting an empty profile. Independently regenerate both representations before verdict. Enforce an initial 20 MiB source-diff cap, 10,000 changed records and 4 KiB path-byte cap, or revise these only through a reviewed policy/runner limit change. Test unusual names, zero diff, mixed changes, renames, deletions, type/mode-only and submodule records, oversized input and object/ref races. +- Do not let the v1 `EvidencePlanner` mixed-profile fallback erase a resource or producer obligation. For every trusted PR policy, validate that its conservative profile contains every producer, resource, assertion, artifact and obligation required by each targeted profile it may replace; an incompatible policy is invalid before any run. Test docs+code, docs+resource, resource+code, rename across classes, unknown path and control-plane changes for superset closure. Give legitimate release-preparation PRs a targeted PR profile while the protected release invocation selects its non-mutating release profile from its validated preparation-base/tag diff. If one policy cannot express both contexts without letting an event choose a profile in YAML, use a base-owned, versioned PR/release policy pair selected only by validated event kind; each policy still resolves its candidate profile from its exact diff and both digests enter the plan. An event/profile mismatch always fails. +- Treat the current self-consistency-only `EvidenceManifestBuilder.Verify` and CLI `verify` as necessary but insufficient for a CI authorization. Add a trusted gate verifier that checks the base-owned policy digest, independently regenerated Git diff and status set, immutable plan identity, subject-job provenance, execution envelope and external fresh GitHub/tag identity. Legacy v1 local claims retain documented compatibility but never authorize the new required check merely because their manifest says `PullRequestGate`. Test a fully recomputed forged plan/manifest, wrong policy source, wrong subject job, moved base/head/tag and a valid local-only manifest that the external gate rejects. +- Reuse `ReleaseTaggedProjectionResolver` as the sole release-evidence authority without copying its parser into the new host. Because it is currently internal to a non-packable release executable, expose a narrow, versioned, read-only machine result from the existing `inspect` path containing the validated V2 preparation base, evidence bundle digest, tag object ID and peeled commit, or extract that exact validation seam into a private shared assembly used by both callers. Prove identical success/failure behavior in the release tool and EvidenceHost. A release claim remains non-mutating; any future publisher that consumes it must verify tag immutability for the publication lifetime and use only artifacts bound to the captured object and digests. Without that protection, the claim cannot authorize publication. Test a tag move after the last pre-publication read as well as the two earlier race windows. +- Make dependency supply part of the subject envelope: use a pinned, base-owned SDK/OCI image and reviewed immutable package cache or controlled allowlisted mirror, with locked dependency integrity checks. Restore and all head-controlled build hooks run only inside the unprivileged subject boundary; cache misses, lock mismatches or mirror failure yield unavailable/incomplete evidence, never trusted-host restore or silent network expansion. Pilot a cold-cache run and a dependency-changing PR, and record the image/cache refresh path in the policy matrix. +- Give each policy-selected profile a checked-in, measurable maximum: capture/planning, resource readiness, producer execution, API retry, cleanup and total workflow deadlines. The total job deadline must leave room for the independent 10-minute cleanup and final verification; reject a policy whose declared worst-case work exceeds it. Cancel stale same-PR runs on a new head while allowing their supervisor cleanup to finish; do not cancel another PR's run or mark a cancelled run complete. Test overlapping pushes, a push during cleanup, unavailable/rate-limited GitHub API, each cancellation phase and a stuck producer. Set final numeric budgets after the producer inventory and before any required-check activation, using observed pilot duration rather than an arbitrary promise. +- Keep shadow control-plane validation entirely base-owned: the old trusted controller supplies the harness, path classifier, fixtures and expected outcomes. Subject changes to policy, workflow, runner, host registrations or test fixtures are data to that harness, never authority. Test deleted/weakened rules, edited/removed fixtures and an unrecognized control-plane path; each remains subject to the old obligations. New controller code runs only in an unprivileged non-claiming shadow and becomes authoritative after merge plus smoke proof. +- Preserve the already approved descriptor-relative extraction boundary, but do not route untrusted scratch paths through the current `EvidenceArtifactWriter`'s path-based write or `ReadAllBytes` verification. Stream no-follow copies into a private trusted root, hash bytes as copied, reject mutation and enforce both per-slot/per-producer v1 limits and the runner's 64-file/256 MiB per-file/512 MiB total/120-second caps. Extend the writer/verifier through a narrow streaming seam if necessary; document the lower applicable limit and test 256 MiB memory behavior without allocating entire artifacts. + +## Review record + + +- Preserve the approved AppSurface-only EvidenceHost gate and its existing PR, fork, resource, release, documentation, and rollout requirements; no generic reusable workflow or deployment scope is added. +- For release policy selection, use the canonical V2 release-evidence `ContentSourceCommit` as the sole comparison-base commit. Read and validate it from the tag-bound prepared artifacts through `ReleaseTaggedProjectionResolver`; require a full canonical commit ID, existence in Git, ancestry to the peeled tag commit, and agreement with the protected release invocation's validated version, tag, and base branch. Bind the commit and source-diff digest into the release plan and manifest. Missing, invalid, non-ancestor, or changed preparation-base evidence fails before `ReleaseComplete`; test each case and a forged alternate base. +- The trusted verifier must reread the remote protected tag ref, annotated tag object ID, and peeled commit immediately before `ReleaseComplete` and again immediately before a publisher consumes that claim. Each must equal the plan's captured identity; a retag or missing tag fails closed. Test a tag move between capture and verdict and between verdict and publication. +- Copy subject artifacts from scratch with a no-follow, descriptor-relative extraction protocol. Allow only normalized relative declared paths resolving within scratch and regular files; reject symlinks, hardlink ambiguity, devices, FIFOs, sockets, traversal, duplicate/case-colliding names, and files changed during reading. Enforce documented file-count, per-file, aggregate-byte, and time limits before hashing/copying. Test traversal, symlink, special file, oversized file, count/aggregate overflow, and mutation races. Never use a shell `cp` or tar extraction as this trust-boundary operation. +- Before implementation, inventory each policy profile and prove its named producer, disposable resource, assertion, cleanup and artifact slot against the current workflows. A profile with a missing safe producer remains fail-closed and cannot be required or promoted. Keep the policy and registration matrix as a reviewable deliverable. +- Stage rollout so the new check first runs in non-required observation mode on same-repository, docs-only, failure, base-advance, and fork pilot PRs. Verify head association and event availability, then require the exact stable check with strict freshness. Preserve the existing checks. Document the ruleset activation, stop/rollback procedure, and admin owner. +- Set checked-in AppSurface extraction limits for the first runner: at most 64 declared regular artifacts, 256 MiB per file (also constrained by each slot's `MaximumBytes`), 512 MiB aggregate copied bytes, and 120 seconds total extraction time. Apply whichever per-slot or runner limit is lower. Reject before allocation when declared bounds already exceed a limit, and enforce streamed read-time bounds; changes to these limits require a reviewed policy/runner change and matching boundary tests. +- Rollback trigger: a claim attached to the wrong SHA, a false complete claim, subject isolation/credential exposure, cleanup failure, unavailable PR event, or a ruleset-induced block of otherwise qualifying PRs. For gate correctness or availability failures without suspected isolation or credential exposure, the repository administrator removes only the new exact check from the active ruleset to restore pre-gate merge eligibility for in-flight PRs after GitHub applies the ruleset; disable the workflow if continued execution is unsafe. For suspected isolation or credential exposure, follow the immediate contain/cancel sequence below before the ruleset change. Confirm existing checks still govern, document affected PRs/runs, fix root cause, rerun the full same-repository/docs/failure/fork/base-advance pilot, and re-enable the required check only after observed head association and freshness pass. +- Treat the office-hours 1–2 human-week / 1–2 agent-day effort line as a provisional comparison among approaches, not a delivery commitment. Re-estimate after the policy/producer inventory, with separate contract/CLI, host/isolation, release, live-pilot, and administrator-activation milestones; the latter two depend on GitHub event policy and administrator availability. +- For suspected subject isolation or credential exposure, disable/contain the new workflow so no new subject runs start, cancel active runs, then have the administrator remove the exact required check from the ruleset to restore prior merge behavior. For other gate correctness/availability failures, remove the required check promptly and disable the workflow if continued execution is unsafe. Record affected runs and preserve existing checks. Re-enable only after a root-cause fix, a trigger-specific regression proof (including envelope, resource, release, or cleanup branch as applicable), the full same-repository/docs/failure/fork/base-advance live pilot, and administrator verification of head association and strict freshness. +- Map every rollback trigger to re-enable proof: wrong-SHA attachment requires a controlled head/base update and current-head check-association assertion; false-complete claim requires injected missing obligation/failed assertion plus a nonzero gate assertion; isolation or credential exposure requires a hostile subject probe for mount, token, socket and network denial plus cancellation proof; cleanup failure requires supervisor kill/timeout injection and incomplete claim; unavailable PR event requires a live event-policy and check-attachment pilot; ruleset blocking a qualifying PR requires a live docs-only and code PR that pass the exact check under strict freshness. Release-related triggers additionally require retag/rebuilt-artifact regression. Record links to each proof in the rollout log before administrator re-enables the check. +- Treat changes to the base-owned workflow, policy, runner, envelope verifier, and host registrations as control-plane changes. The current trusted controller must classify these paths conservatively, require the old policy's obligations, and validate the proposed policy as data against old-versus-new selection fixtures for docs/code/rename/deletion/resource/release and unrecognized paths. A shadow run of the proposed controller/host in an unprivileged, non-claiming envelope must pass before merging; the proposed files cannot be trusted by their own PR run. Require explicit maintainer review of any reduced obligation or changed trust capability, a post-merge smoke run before continued enforcement, and a regression where deletion/weakening of a rule cannot let its own PR pass under the old gate. +- Use `ReleaseTaggedProjectionResolver`'s validated tagged projection and V2 evidence bundle as the sole source of the release preparation base. Verify the bundle's subject digest covers the V2 preparation-base commit, the V2 release manifest `PreparationBaseCommit` agrees, the annotated tag's `AppSurface-Release-Evidence-Subject-Sha256` trailer matches that digest, and the protected release invocation validates version/tag/base-branch reachability. Bind the validated bundle digest, tag object ID, peeled commit and preparation-base commit into the evidence plan. Reject a raw or alternate-ancestor field even if it is a valid Git ancestor; test forged prepared evidence, mismatched manifest source, and mismatched tag trailer. +- In the policy/registration matrix, name each existing workflow obligation's canonical command or implementation, whether EvidenceHost calls that exact seam, which old job remains necessary after activation, and expected steady-state ownership. During the pilot compare duplicate result and runtime; do not remove an existing required job until equivalent branch/failure behavior is proven and a separate migration is reviewed. +- Keep fork `ObservationOnly` and same-repository promotion as the approved gate behavior. The pilot records the number of fork PRs, maintainer promotion steps and elapsed turnaround, and the runbook documents the exact SHA promotion path. A base-owned external check publisher is a future separate design if that measured cost justifies it; it cannot silently upgrade the observation claim in #777. + + + +### CEO Step 0 and decision ledger + +Mode: SELECTIVE EXPANSION, set by autoplan. The user selected option B, the complete AppSurface gate, in office hours. The scope challenge found no beneficial new capability within a one-day agent blast radius: the most important work is closing correctness holes in that approved scope. Generic reusable workflow, self-hosted runners, and automatic publication stay out of scope. The plan is already large; splitting into milestone proof points reduces risk without cutting the accepted outcome. + +Real problem: AppSurface has planning and manifest contracts but no live required check proving policy-selected evidence for exact revisions. A green example without a required check solves only a proxy. Do nothing leaves CI decisions in YAML and the trust claim unproven. + +Existing leverage: `EvidencePlanner` and contracts handle policy/profile selection and manifest identity; `EvidenceHostBootstrap` handles explicit registrations; the extracted coverage core is reusable; `ReleaseTaggedProjectionResolver` already validates annotated tags and V2 preparation-base ancestry; release-publish and package-gate workflows define candidate assertions. No new general scheduler is warranted. + +12-month path: local planner and ad hoc CI -> one versioned, revision-bound AppSurface runner with a required check -> copied, documented adopter pattern once this reference has shown real failure modes. This plan creates that path but does not promise compatibility to external consumers yet. + +Complexity check: the baseline spans contracts, CLI, host, policy, runner, workflows, tests and docs, well over eight files. The minimum correct path is still one canonical plan/verifier/renderer and explicit host registrations. Separate controller, untrusted subject and supervisor are necessary at the trust boundary; no additional service or generic plugin registry is proposed. + +Selective-expansion scan: CLI quickstart, sample diagnostics, copyable policy matrix, one-command local rehearsal, summary links, and troubleshooting examples were considered. Only the policy matrix, clear diagnostics and rehearsal guidance already follow from the approved API and adoption requirements; the other polish is deferred until the first pilot shows the actual friction. Platform potential is the versioned evidence identity and reference workflow, not a new public workflow interface. + +| ID and owner | Contract and evidence | Current | Proposed | Status | Exact authority and scope | +|---|---|---|---|---|---| +| C1 CEO | AppSurface-only required EvidenceHost gate; approved office-hours design and #777 | Complete option B | Generic reusable interface | declined | User chose B over C in office hours; preserve B. | +| C2 CEO | Release base must be deterministic; office-hours R2-1, V2 `ContentSourceCommit` | unspecified base | use canonical V2 preparation base | approved | Correctness detail within approved release binding; autoplan P2/P6. | +| C3 CEO | Tag must remain bound at verdict/publication; R2-2 | capture only | final and pre-publish remote ref checks | approved | Correctness detail within approved release eligibility; autoplan P2/P6. | +| C4 CEO | Subject artifact transfer is a trust boundary; R2-3 | copy declared scratch output | descriptor-relative no-follow bounded copy | approved | Security repair within approved isolation; autoplan P2/P6. | +| C5 CEO | Stable required check must be proven live; approved design | pilot then ruleset | retain with explicit rollback owner | approved | Operational detail of already approved rollout; autoplan P6. | + +### CEO scope summary + +10x ambition: a maintainer can see *why* a policy selected a profile, whether every obligation closed, and which exact change was tested, in one bounded verdict. The delight scan found no new feature that improves that proof more than closing the three recorded correctness gaps. + +Accepted scope: approved design plus C2-C5. Deferred: generic reusable workflow, self-hosted runner, automatic publication. Reviewer concerns are R2-1/R2-2/R2-3, now addressed as explicit implementation obligations, pending independent spec verification. + +### CEO review: temporal and strategic result + +The six-month regret would be a required check whose name is stable but whose evidence describes a different revision or a merely self-consistent manifest. The defense is the immutable base/head/source-diff identity, a fresh pre-verdict GitHub read, and live required-check association proof. In a future reusable-workflow phase, the AppSurface policy and host registrations should be replaceable without changing canonical plan identity. No current market comparison changes issue #777's concrete local goal; the risky alternative is shipping a demonstration that cannot block a bad merge. + +**NOT in scope.** A cross-repository reusable workflow, new scheduler, self-hosted runner, external resource reaper, merge-queue support before adoption, automatic publication, and deployment attestation are excluded. They would add contract and operational surface before the AppSurface reference is proven. Existing CI jobs remain independent; their conclusions cannot impersonate EvidenceHost producers. + +**What already exists.** `EvidencePlanner` provides policy selection and normalized path digestion; `EvidenceContracts` holds claim, producer, resource, artifact, plan, and manifest types; `EvidenceHostBootstrap` and Aspire adapters supply explicit host composition; `CoverageExecutionBoundary` is the coverage reuse seam; `ReleaseTaggedProjectionResolver` validates annotated tags and V2 preparation-base ancestry; `release-publish.yml`, `package-gate.yml`, and `release-contract.yml` provide assertion candidates and release context. The new work extends these surfaces rather than rebuilding their logic. + +#### 1. Architecture + +```text +PR event / protected release event + -> trusted base-owned controller -> verified revision pair + source diff + -> policy planner -> immutable plan -> explicit EvidenceHost registrations + -> isolated subject + disposable resources -> bounded artifact extractor + -> manifest verifier + fresh event/tag read -> one verdict renderer -> CI check + external supervisor -> cleanup attestation --^ +``` + +Four paths share that state machine: trusted PR `TargetedComplete`, docs-only PR `NoEvidenceRequired`, untrusted fork `ObservationOnly` with failed required gate, and protected release `ReleaseComplete` with tag and artifact rechecks. Missing event/revision/policy data fails before planning; an empty diff is allowed only when policy explicitly emits `NoEvidenceRequired` for a valid event and revision pair. Producer, resource, artifact, verifier, API, or cleanup failure leads to a bounded incomplete/invalid result and nonzero gate. The only legal progression is `Captured -> Planned -> Running -> CleanupVerified -> ManifestVerified -> FreshnessVerified -> EligibleVerdict`; any failure enters `Failed`, and a stale head/tag cannot transition back to eligible. Re-run from fresh capture. The principal coupling is the versioned plan identity shared by CLI, host, verifier and renderer; that is intentional. At 10x PR volume, disposable container startup and coverage dominate; at 100x, GitHub-hosted runner capacity and API rate limits dominate. No database, cache, or long-lived service is added. Rollback is removal of the required-check ruleset entry by the administrator, then disabling the workflow, while existing build/test checks remain active. + +#### 2. Error & Rescue Registry + +| Method/codepath | Failure / exception class | Rescue action | User sees | +|---|---|---|---| +| Capture revision / Git diff | missing object, malformed SHA, nonzero Git, oversized diff; validation/IO/process failure | fail closed; bounded diagnostic, never invent a manifest | `revision-invalid` / `diff-unavailable` and failed check | +| Policy parse / plan | malformed policy, unmapped path, hash mismatch; parse/contract failure | reject input or conservative policy rule; no silent fallback to docs-only | `policy-invalid` / `plan-mismatch` | +| Host registration / resource readiness | missing producer, startup timeout, unavailable dependency | mark unavailable/incomplete, run supervisor cleanup | named missing obligation and failed check | +| Subject execution | timeout, cancellation, assertion failure, invalid producer output | terminate subject, collect bounded diagnostics, cleanup | stable producer code and failed check | +| Artifact extraction | traversal, symlink, special file, mutation, size/count/time breach | reject artifact, stop extraction, cleanup | `artifact-invalid` and failed check | +| Manifest verification | digest/claim/envelope mismatch | reject claim; no alternate pass source | `manifest-invalid` and failed check | +| Freshness API / release ref read | timeout, 403/404, moved head/base/tag | bounded retry only for transient transport/rate limit, then fail closed; never reuse stale observation | `revision-stale` or `freshness-unavailable` | +| Cleanup supervisor | process loss, timeout, failed deletion | fail claim and invoke CI `always()` cleanup; local VM destruction is the final boundary | `cleanup-incomplete` and failed check | +| Summary/artifact upload | presentation IO/network error | preserve already computed failed verdict; upload cannot upgrade it | diagnostic in job log, gate status unchanged | + +Catch only specific expected process, IO, cancellation, contract and API failures. At every rescue, log run ID, stage, bounded IDs/digests and diagnostic code without raw subject output. Retry only transient API calls with bounded backoff; an invalid plan, unsafe artifact, failed assertion or stale revision is never retried into success. + +#### 3. Security and trust + +Threats are high-impact: untrusted head code escaping the subject container, reading runner credentials, reaching the host gateway, or tricking trusted extraction through a symlink. The base-owned workflow, pinned actions, minimal permissions, no subject token/socket/home, rootless pinned container, isolated network, envelope verification, and descriptor-relative no-follow copy are mandatory. PR title, path and head content are data, never shell or workflow instructions. A fork's observation cannot be promoted by label or manual dispatch. Log only bounded paths and diagnostics; secret canaries belong in tests. GitHub documents that `pull_request_target` uses a trusted base workflow but head checkout/execution is dangerous, so pilot its event/check association and enforce the container boundary before trusting it. No new secret is required. + +#### 4. Data flow and ordering + +```text +event identity -> full-SHA validation -> fetched Git objects -> fixed-options diff + -> source digest + policy digest -> canonical plan -> host result + -> no-follow copied artifacts -> manifest verification -> fresh API/ref read + -> eligible claim -> one bounded terminal/summary/JSON rendering +``` + +Nil/empty/wrong-type event fields, missing objects, invalid UTF-8 or overlong paths, policy conflicts and oversized streams fail at their first validator. Duplicate artifact names, partial writes and read-time mutation fail extraction. The shared invariant is: a successful claim names the exact currently eligible PR base/head or protected tag object and the exact copied artifact bytes. Test both orders of a head update versus final PR read, tag move versus verdict, tag move versus publisher consumption, artifact mutation versus hashing, and supervisor termination versus cleanup status. A fresh consumer must re-read identity; a prior successful manifest is not a reusable authorization token. The same PR event retried under identical inputs yields the same plan digest; a new run ID affects provenance only, not plan identity. + +#### 5. Code quality + +One canonical plan serializer/digest and one verifier should serve `explain`, `run`, and `verify`; no duplicated YAML eligibility rule or separate summary verdict path. Keep host registrations explicit and producer implementations cohesive. Avoid a generic plugin registry, reflection-driven policy binding, broad catch-all exception handling, and complex workflow shell interpolation. Favor typed diagnostics, narrow process wrappers and test seams exposed through internal APIs. + +#### 6. Test diagram + +| Boundary | Positive proof | Failure / edge proof | +|---|---|---| +| Revision and policy plan | same explain/run digest for fixed pair; docs-only and code profiles | changed head/base/source bytes/policy, rename/delete/mixed/unmapped/empty input | +| Host and manifest | selected resource/producer/assertion closes and complete claim | missing registration, unavailable resource, failed assertion, absent artifact, timeout/cancel | +| Isolation and extraction | declared regular artifact copied, hash matches | token/socket/network denial, traversal, symlink/special file, oversize, mutation race | +| Release | canonical V2 base, annotated tag, matching package digest | invalid/missing/non-ancestor/alternate base, retag at two windows, rebuilt artifact | +| Verdict and rollout | one renderer agrees across terminal/summary/JSON; live head-attached check | secret canary, oversized malicious path, fork fails gate, base advance blocks, wrong event/check association | +| Cleanup | normal and forced host-process kill complete within in-VM deadline | supervisor failure/time-out denies complete claim; VM loss issues no success | + +Unit tests should dominate plan parsing, digest, state transition, verifier, renderer and extraction; narrower integration tests cover host/resources, OCI boundary and cleanup; a few live PR pilots cover GitHub event and ruleset semantics. The 2am confidence test is a real code PR with one failed required producer that cannot merge. Hostile QA moves the head/tag after execution and swaps a symlink during extraction. Chaos kills EvidenceHost while the supervisor reaps resources. External GitHub timing is tested by controlled seams locally and observed in the pilot, not asserted through a flaky wall-clock test. + +#### 7. Performance + +Slow paths are coverage/test execution, disposable resource readiness and container startup, not plan hashing. Diff and artifacts require explicit byte/count/time limits and streamed processing; memory must not scale with raw logs or full artifact bodies. No ORM, database index, connection pool, or cache is in scope. Cache only immutable trusted-tool builds keyed by base commit and policy/tool version if a measured pilot warrants it; never cache a complete claim across revision or tag freshness boundaries. CI timeouts should exceed the host deadline plus cleanup and rendering, while bounding total job runtime. + +#### 8. Observability + +Log stage entry/exit, run ID, base/head or tag object short IDs, profile, obligation IDs, claim kind, diagnostic code and cleanup outcome. Never log raw subject stdout, secret values or arbitrary artifact contents. Machine JSON and GitHub summary share the verified verdict so a failed job can be reconstructed from retained bounded metadata. Track gate outcomes by profile and failure code, stale-revision frequency, resource readiness/cleanup duration, and summary truncation. The maintainer runbook maps codes to re-run, fix producer, promote fork commit, or disable required check; no dashboard service is needed for the first reference. + +#### 9. Rollout and rollback + +There is no database migration. First land versioned contracts and migration docs, then host/policy with all selected producers, then a non-required workflow, then pilot same-repo code/docs/failure/fork/base-advance cases. Only a repository administrator can activate the exact check in the ruleset after verifying source/check association and strict freshness. In the first five minutes, inspect one active PR's check name, attached SHA, claim and summary; within the first hour, confirm a base advance and failed/fork PR remain blocked. If wrong-head attachment, unavailable event, unexpected block or unsafe resource behavior occurs, remove the required-check entry immediately, disable the new workflow, and retain existing checks. The release path remains non-mutating and cannot publish merely because it produced evidence. + +#### 10. Long-term trajectory + +Reversibility is 4/5: versioned contracts need compatibility care, but the gate can be disabled without migrating data. The lasting debt is maintaining policy-to-registration parity and an OCI isolation runtime; the matrix, diagnostics and tests make that visible. External adopters may later copy the reference, but a reusable public workflow should wait for a second actual consumer. A new engineer should find the policy matrix, one local rehearsal, the versioned contract reference, and a runbook from the EvidenceHost start page. No accepted cherry-pick creates a new service or public API beyond the already planned contract revision. + +### CEO completion summary + +| Area | Result | Remaining proof | +|---|---|---| +| Premise / scope | AppSurface gate solves the named pain; option B retained | live pilot | +| Architecture / threat | explicit trusted/subject boundary; three prior concerns converted to requirements | OCI enforcement and extraction tests | +| Error / data | fail-closed state machine and rescue registry | implementation and race tests | +| Tests / performance | branch and failure coverage planned; bounded streams | profile inventory and runtime measurements | +| Rollout / trajectory | non-required pilot then admin ruleset; reversible | event/check association and strict freshness | + +### CEO independent spec review history + +First `combo/sub` spec review: 8/10, NOT PASS. It found (1) rollback triggers/actions and re-enable conditions underspecified, (2) extraction bounds lacked concrete values, and (3) the office-hours effort comparison lacked a workstream breakdown. The accepted CEO block now names each trigger and manual rollback, 64/256 MiB/512 MiB/120-second limits, and milestone-based re-estimation. The CEO scope summary and implementation input were refreshed for a second review. + +Second `combo/sub` spec review: 8/10, NOT PASS. It confirmed the numeric limits and provisional milestone estimate, but found that suspected isolation or credential exposure must stop/cancel unsafe runs before administrator ruleset removal, and that re-enabling must prove the triggering failure is fixed. The recorded requirements now distinguish unsafe-run containment from ordinary gate rollback and require a trigger-specific regression plus the full live pilot. A third review checked the corrected inputs and scored 8/10, leaving an auditable trigger-to-proof mapping gap. The mapping is now recorded as an accepted requirement, unconfirmed by another spec reviewer because the loop is capped at three launches. + +### Failure Modes Registry + +| Failure mode | Detection | Required result | Recovery owner | +|---|---|---|---| +| Wrong or stale PR revision | independent Git diff and final GitHub API read | failed check, no eligible claim | controller author | +| Policy/host drift | matrix and registration validation | invalid/incomplete manifest | policy/host maintainer | +| Producer/resource timeout | typed outcome and deadline | failed check and cleanup | producer owner | +| Isolation envelope mismatch | trusted pre-provision verifier | no subject execution/complete claim | runner maintainer | +| Unsafe artifact | descriptor-relative type/path/size/hash validation | reject artifact and complete claim | extractor maintainer | +| Retag or rebuilt release output | remote tag and artifact digest recheck | no `ReleaseComplete`/publication authorization | release maintainer | +| Cleanup failure | independent supervisor attestation | incomplete claim and failed check | CI maintainer | +| GitHub event/check misassociation | real PR pilot with head SHA and base advance | stop rollout before required ruleset | repository administrator | + +### Async order proof to implement + +```text +Controller/host Shared PR/tag identity GitHub/publisher +capture base/head/tag ---------> S0 +execute producers S0 head or tag moves -> S1 +verify manifest S0 +fresh-read ----------------------> S1 reject stale S0 + +Alternative order: move -> S1 before capture; capture S1, execute, then +fresh-read S1 may pass only if the manifest and every digest bind to S1. +Publisher repeats remote tag read immediately before consumption; a move +after verdict but before publication rejects the old claim. +``` + +The controlled regression pauses at final read and pre-publication consumption and releases a competing head/tag update in both orders. Cleanup attestation is a prerequisite for `ManifestVerified`; a supervisor failure before or after host completion cannot be masked by a prior producer success. + +### Decision Audit Trail + +| # | Phase | Decision | Classification | Principle | Rationale | Rejected | +|---|---|---|---|---|---|---| +| 1 | CEO | Retain complete AppSurface-only gate | prior user decision | P6 | Office-hours option B explicitly selected for #777 | narrow demo and generic reusable workflow | +| 2 | CEO | Use V2 preparation-base commit for release selection | auto-decided correction | P2/P6 | Existing release evidence gives a deterministic source and resolves R2-1 | arbitrary base ref or preceding tag heuristic | +| 3 | CEO | Recheck remote tag at verdict and publication | auto-decided correction | P2/P6 | Prevents a captured claim authorizing a moved tag | initial capture only | +| 4 | CEO | Descriptor-relative bounded artifact extraction | auto-decided safety repair | P2/P6 | Closes the subject-to-trusted copy boundary | ordinary file copy/tar | +| 5 | CEO | Fixed extraction limits and trigger-based rollback | auto-decided operational detail | P2/P6 | Makes the trust and rollout contracts testable | undocumented runtime defaults | +| 6 | CEO | Preserve provisional estimate and re-estimate after inventory | auto-decided clarification | P6 | Event feasibility and producer inventory are unknown | treating office-hours comparison as schedule commitment | +| 7 | CEO | Stop/cancel unsafe runs and map every rollback trigger to proof | auto-decided safety repair | P2/P6 | Third spec review required auditable re-enable evidence | generic re-pilot alone | + +### CEO voice reconciliation + +The native `combo/sub` reviewer completed against `INPUT: ceo 3100f9d5ae3d8808d9f68414c91ca49ff84f58b7886682e99b2ca6c63e28ef40` and raised four issues. Its two high findings, control-plane self-change validation and release baseline authority, are accepted as correctness obligations in the CEO block. Its medium duplicate-CI concern is accepted as a matrix and pilot comparison, without removing established checks prematurely. Its medium fork-cost concern is accepted as measurement and runbook detail; the user-selected observation-only fork gate remains unchanged. The Claude Code outside lane was unavailable at preflight, so no cross-provider consensus or User Challenge is claimed. + +| CEO dimension | Native voice | Outside voice | Consensus | +|---|---|---|---| +| Premises valid | conditional: release authority and control-plane lifecycle | unavailable | N/A | +| Right problem | yes: live required AppSurface gate | unavailable | N/A | +| Scope calibration | yes, with duplicate-CI and fork-cost measurement | unavailable | N/A | +| Alternatives explored | fork publisher worth later study | unavailable | N/A | +| Market risk | low for local gate | unavailable | N/A | +| Six-month trajectory | conditional on lifecycle and steady-state ownership | unavailable | N/A | + +The native review did not call for changing the user's chosen AppSurface-only scope or fork policy. No taste decision needs an interim question. The 0H CEO scope document matches the accepted obligations and was auto-approved for continuation under Autoplan's intermediate-decision rule; this is not implementation approval. + +### DX Step 0: developer and clock + +Primary product type: CLI-led developer tool with a GitHub Actions reference and a versioned .NET evidence contract. Primary developer: an AppSurface maintainer who has the repository and normal .NET toolchain, is adding or reviewing a PR, and needs to know whether the selected evidence will satisfy the required check. An external adopter is a later audience for the copyable guide, not the first-run clock. Mode: DX POLISH, selected by Autoplan for an enhancement to an existing tool. + +The current [EvidenceHost start page](../../start-here/evidencehost.md) gives a three-command sample (`init`, `doctor`, `explain`) and a visible plan. The [CLI package guide](../../Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md) documents `run` and `verify`; the [cookbook](../../guides/evidencehost-cookbook.md) covers docs-only, coverage, resource-backed and release examples. None currently gives a revision-bound AppSurface CI gate rehearsal because that workflow and those flags do not exist yet. Current time from checkout to a *revision-bound, gate-shaped* first result is therefore unavailable, not an observed 5-minute success. The local sample's `--path` result is a different endpoint. + +First-person developer perspective (inferred from inspected docs, not an observed user test): “I open the EvidenceHost page and quickly understand why `NoEvidenceRequired` differs from incomplete evidence. I can run the sample commands and see a profile and obligations. When I try to reproduce a failing PR check, the examples switch to `--path` or an arbitrary patch file. I cannot yet tell which base/head pair the CI gate used, where its checked-in policy lives, or whether my local result can satisfy the gate. I need one documented rehearsal from a real PR's two SHAs to the same plan digest, plus a diagnostic that tells me whether a failure is policy selection, missing producer, stale revision, unsafe artifact, or GitHub check wiring. I also need to know that a fork observation will stay red and how to promote its exact commit.” + +Clock: from an AppSurface maintainer's normal checkout and installed .NET/AppSurface CLI to a verified `explain` result for an actual base/head pair, including locating the guide, selecting a fixture pair, and reading the rationale. Current duration: unmeasured, estimated 8–12 minutes because the revision flags and gate guide are absent. Target: competitive 2–5 minutes, to be measured in a fresh maintainer rehearsal after implementation. This target does not claim a cold toolchain install, producer execution, or a live PR completes within five minutes. The useful “magical moment” is `explain` showing exact revisions, policy rule, profile, obligations, and one plan digest that `run` and `verify` reproduce. Delivery vehicle: the existing CLI plus one copyable AppSurface gate rehearsal in the start page, using the checked-in policy and two full SHAs; no hosted playground or new API. + +Comparable DX patterns are [Conftest's direct `test` command and explicit policy default](https://www.conftest.dev/options/), [Conftest's CI/JSON output choices](https://www.conftest.dev/output/), and [GitHub's required-check troubleshooting guidance](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks). These are interface patterns, not equivalent measured onboarding times; AppSurface's revision-bound evidence and required-check journey is longer. No peer timing is asserted. + +| Journey stage | Maintainer action | Evidenced or predicted friction | Planned disposition | +|---|---|---|---| +| Discover | Follow README link to EvidenceHost | Start page exists; CI reference not yet linked | Add AppSurface gate entry point | +| Evaluate | Read claim table and sample plan | Existing sample is local path mode | Label local vs gate mode clearly | +| Install | Use normal AppSurface CLI and .NET toolchain | Existing CLI install guide; cold timing unknown | Reuse existing instructions and state prerequisites | +| Hello world | Run `explain` for real base/head pair | Revision flags not yet implemented | Copyable rehearsal with expected summary | +| Integrate | Use checked-in policy and host matrix | Policy/registration matrix is planned | Link exact file and selected profile | +| Debug | Read code, summary, manifest | Existing diagnostics only cover v1 local flow | Problem + cause + fix + canonical doc link | +| CI adopt | Compare live PR check to local digest | Event/check association is unproven | Pilot checklist and exact SHA comparison | +| Upgrade | Move from v1 local to versioned gate contract | New schema/migration required | Version matrix and migration steps | +| Maintain | Change policy/control plane or rollback | Self-change and ruleset hazards | Shadow proof, runbook and rollback trigger map | + +First-time rehearsal roleplay, predicted rather than measured: T+0 opens the README EvidenceHost link; T+0:30 runs sample `init`/`doctor`; T+1 sees the local path-mode plan; T+2 tries to map it to a live PR but the current CLI has no authoritative revision flags; T+3 reads the cookbook and still lacks a gate-shaped command; T+5 must ask a maintainer for the PR's base/head and workflow details. The plan should remove that gap with a single end-to-end example, not with a new CLI mode that silently upgrades local output to a trusted claim. + + +- Put a revision-bound AppSurface gate quickstart on the [EvidenceHost start page](../../start-here/evidencehost.md), linked from the repository and CLI entry points. It must use a checked-in policy, one maintained fixture with two full commit IDs and exact diff bytes, and copyable `appsurface evidence explain` commands with expected profile, rationale, obligations, source-diff digest and plan digest. State prerequisites and distinguish the local `--path` sample from gate-eligible evidence. The chosen first-result clock runs from a normal checkout with the CLI installed to that verified explanation; target 2–5 minutes, measured in a fresh maintainer rehearsal. Report full producer/CI runtime separately. +- Define the gate input contract for `explain`, `run`, and `verify` in the CLI and contract references: both full `--base-revision` and `--head-revision` plus `--diff-file` are required together for a revision-bound PR candidate; missing/mixed/abbreviated inputs, absent Git objects, or bytes that fail independent diff regeneration are errors. A local path/diff plan remains usable but cannot claim gate eligibility. Document how the trusted controller supplies its immutable snapshot, how the host executes selected resource-backed producers, and which fields and plan digest the three commands must agree on. Show real command/output templates for a docs-only and a code fixture, with no implication that local `explain` alone can satisfy GitHub's required check. +- Give every gate diagnostic a stable code and a bounded human message with the observed identifier, what failed, likely cause, next action and a nearby link to its canonical reference or troubleshooting section. Demonstrate at least stale base/head, source-diff or plan mismatch, missing producer/resource, unsafe artifact, isolation-envelope failure, cleanup failure, and moved release tag. Keep terminal, summary and machine JSON codes consistent while never printing raw subject output or credentials. Test that the guidance is accurate for those injected branches and that long/malicious values remain bounded. +- Add one tested end-to-end AppSurface adoption walkthrough in the [cookbook](../../guides/evidencehost-cookbook.md): policy rule and explicit registration, local explain, host run, manifest verify, expected claim/verdict, then live check and strict-freshness pilot. Name which code is the reusable contract/CLI and which is AppSurface's reference runner. Include the exact-SHA same-repository promotion procedure for a fork and the fact that its original observation remains ineligible. Link the policy/producer matrix and the operator rollback guide. +- Publish a versioned v1-local to revision-bound gate migration table covering schema compatibility, plan/manifest identity changes, CLI input rules, and what old consumers must change or can keep. Separate consumer-tailorable policy/profile/registration/diagnostic display choices from fixed trust invariants: independent Git diff verification, base-owned authority, complete obligations, isolation, bounded extraction, cleanup attestation, and fresh PR/tag checks. Test the documented fixture and examples against the built CLI and host before enabling the required check. +- Measure and record the selected 2–5 minute first-result journey with a fresh maintainer starting at the documented start page; include discovery, commands, errors and reading the useful explanation. Separately record local full profile execution time, live PR gate latency, fork-promotion effort, and duplicate existing-CI time during the pilot. Treat these as rollout observations, not new telemetry infrastructure or an automatic release gate. + + +### DX pass review and scorecard + +These scores assess the *current plan before* and *planned experience after* the accepted follow-through. They do not assert an implemented or measured result. Mode remains DX POLISH; the approved AppSurface gate and existing CLI are the delivery vehicle. + +| Pass | Before → planned | Evidence, exact follow-through and residual proof | +|---|---:|---| +| 1. Getting started | 4 → 8 | [Start page](../../start-here/evidencehost.md) has a three-command local sample but no real revision-bound gate path. Add the checked-in fixture and three-step rehearsal: locate base/head and policy; run `explain` with immutable diff; read profile/rationale/obligations/digest. Target 2–5 minutes from normal checkout and installed CLI; fresh-user timing remains unmeasured. Cold install and full CI are separate clocks. | +| 2. CLI and API | 6 → 8 | The approved `--base-revision`, `--head-revision`, `--diff-file` interface needs a complete/invalid input matrix and same plan identity across `explain`, `run`, `verify`. Keep path mode local and non-eligible. The host, not a fake local CLI success, supplies resource-backed execution. Fixture tests must prove full-SHA and diff semantics. | +| 3. Errors and debugging | 5 → 8 | Existing local diagnostics do not cover all new gate failures. Stable codes plus problem/cause/action/link are required; test unsafe values and consistency across outputs. A failed claim must remain failed even if summary upload fails. | +| 4. Documentation | 6 → 8 | Existing start page, CLI reference and cookbook are useful but distributed. Add one start-here link chain, copyable expected output, tested adoption walkthrough, policy matrix and operator guide. Keep API reference and executable tutorial distinct and cross-linked. | +| 5. Upgrade and migration | 5 → 8 | Versioned revision-bound fields change plan/manifest identity. Publish compatibility matrix and examples for v1 local consumers; test old local behavior remains local and never inherits gate eligibility. No automatic codemod is justified for this additive reference. | +| 6. Environment and tooling | 6 → 8 | The planned reference fits .NET and GitHub Actions but host/resource and OCI availability need honest prerequisites and a local rehearsal. Retain noninteractive failure exits and immutable snapshots. Cross-platform claims require actual proof; GitHub-hosted Linux is the supported gate runner. | +| 7. Ecosystem and adoption | 5 → 7 | The first adopter is AppSurface; a copyable policy/host walkthrough is useful. External reusable workflow, public plugin ecosystem, support channel and hosted playground are outside #777. A second adopter would justify revisiting them. | +| 8. Measurement | 3 → 7 | Current first-result time is unmeasured. Time a fresh maintainer's full approved clock, record errors and completion, and separately log full gate, pilot and fork cost. This is a bounded rollout record, not ongoing telemetry or a new process. | + +Pass 1 gold-standard lesson is a single golden path and immediate meaningful output; no hosted playground is justified by the accepted scope. Pass 2 favors one guessable command grammar and consistent identity, without adding a generic endpoint. Pass 3 uses a structured code/message/help/link pattern. Pass 4 requires docs to ship with the contract. Pass 5 treats schema migration as a first-class task. Pass 6 emphasizes short local feedback; Pass 7 is intentionally limited to this repository's reference; Pass 8 measures the chosen first-result clock rather than a warmed command timer. No Hall of Fame example changes the approved behavior. + +#### Diagnostic trace for three concrete failure paths + +| Trigger | Current developer experience | Required developer experience | +|---|---|---| +| PR base or head changed after execution | The planned CLI has no revision inputs today, so it cannot explain a stale gate run. | `revision-stale`: show bounded captured/current short IDs, explain that the PR moved, tell the maintainer to update/rerun for the new pair, link the revision-input and strict-freshness guide; nonzero gate. | +| Captured diff differs from regenerated Git diff | Today's path/patch sample can explain a plan without authoritative base/head objects. | `diff-unavailable` or `plan-mismatch`: identify the expected/actual digest or missing object, reject the claim, advise fetching exact commits or recapturing the immutable snapshot, link the contract reference. | +| Subject declares a symlink/oversized artifact or cleanup fails | Neither branch is exercised by the current local sample, so the maintainer has no existing gate-specific explanation. | `artifact-invalid` names the declared slot and violated bound, or `cleanup-incomplete` names the failed stage; both point to the operator guide, preserve bounded data, and fail the gate. | + +The operator guide also covers envelope denial, missing registration/resource, failed assertion, unavailable GitHub freshness read, and moved release tag. Verbose debug may add bounded controller stage IDs but must not reveal raw subject logs, secrets or untrusted file contents. Exceptions and stack traces belong in trusted diagnostic artifacts only when safe; the required-check summary stays actionable and bounded. + +#### DX implementation and measurement checklist + +- [ ] A maintainer can follow the canonical start page from a normal checkout and reach a real revision-bound `explain` result in the accepted 2–5 minute target; capture observed timing and errors, not an estimate. +- [ ] CLI help and references specify required flag combinations, defaults, invalid cases, claim eligibility, schema versions, and the host-versus-CLI execution boundary; fixture commands and expected output pass against the built tool. +- [ ] The cookbook runs one complete policy/registration/host/manifest/verify example, links the policy matrix, and distinguishes AppSurface-owned reference files from package APIs. +- [ ] Every injected diagnostic branch gives code, problem, likely cause, corrective step and canonical link in terminal, summary and JSON without leaking unsafe output. +- [ ] The v1-local migration and compatibility matrix is accurate; old path mode cannot be mistaken for a gate claim. +- [ ] Pilot records full profile latency, duplicate-CI cost, fork promotion effort, and current-head/check association separately from first-result time; no unsupported platform or cross-platform claim appears in docs. + +#### DX prior learning, trend and decision audit + +Prior learning applied: `pr-evidence-required-check-freshness` (confidence 9/10, 2026-10-01) confirms that manual dispatch cannot satisfy the PR gate and that strict base freshness needs a live pilot. `appsurface-docs-source-file-links` (confidence 10/10, 2026-09-11) means docs should link workflow/source files through stable source URLs where the strict docs exporter does not emit those files. Previous AppSurface DX reviews have covered other products, with reported before scores from 5 to 8 and planned scores from 7 to 9.3; they are not a measured trend for this new gate. Current #777 DX score average is 5.0 before and 7.8 planned, with first-result time still unmeasured. + +| # | Decision | Classification | Authority and effect | +|---|---|---|---| +| 8 | Use existing CLI and checked-in fixture as the first-result vehicle | auto-decided within DX POLISH | Preserves approved revision-bound CLI and AppSurface-only scope; no hosted playground. | +| 9 | Keep local path mode ineligible and require the complete revision input set for a gate candidate | accepted-contract clarification | The approved design already distinguishes local planning from externally verified gate claims; prevents a misleading local green result. | +| 10 | Treat 2–5 minutes as a measured rehearsal target, with full CI timed separately | auto-decided measurement detail | Preserves the target's start and endpoint without claiming an observed result or adding telemetry infrastructure. | + +The native `combo/sub` reviewer completed against `INPUT: dx 60b157bb30d944971b115b35ffafebf1e80e1a145cb14f5b9a1e3457ebdcc3a1` and found four medium gaps: missing smallest tested local fixture, underspecified CLI gate input mode, diagnostics lacking actionable causes and links, and no complete adoption walkthrough. Each is accepted above. It also asked to separate adjustable consumer choices from fixed trust invariants; that is included in the migration/adoption reference. No critical DX blocker was reported. The Claude Code outside lane was unavailable at preflight; native review supplies no cross-provider consensus, so consensus is N/A. + +| DX voice dimension | Native `combo/sub` | Claude Code | Consensus | +|---|---|---|---| +| Getting started under five minutes | Conditional on tested fixture and measured clock | unavailable | N/A | +| CLI naming and input grammar | Needs explicit gate input matrix | unavailable | N/A | +| Error messages actionable | Needs cause/fix/link catalog | unavailable | N/A | +| Docs findable and complete | Needs end-to-end adoption path | unavailable | N/A | +| Upgrade path safe | No native objection; parent requires v1 compatibility matrix | unavailable | N/A | +| Environment friction | No native objection; parent retains supported GitHub-hosted Linux prerequisite | unavailable | N/A | + +## Implementation Tasks + +Synthesized from DX findings; each task is part of the approved AppSurface gate, not a separate product expansion. + +- [ ] **T1 (P1, human: ~4h / agent: ~1h)** — CLI and contracts — Define the complete revision-input, eligibility and identity contract for `explain`, `run` and `verify`. + - Surfaced by: Pass 2 and native DX finding 2; revision flags are planned but gate-mode combinations and the host boundary are not yet specified. + - Files: `Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs`, Evidence contracts/planner and their README files. + - Verify: CLI contract tests for valid full-SHA pairs and invalid/mixed/abbreviated/diff-mismatch inputs; explain/run/verify share plan digest. +- [ ] **T2 (P1, human: ~3h / agent: ~45min)** — Getting started — Check in a real immutable fixture and copyable three-step gate rehearsal with expected output. + - Surfaced by: Pass 1 and native DX finding 1; the present start page only reaches a local `--path` result. + - Files: `start-here/evidencehost.md`, checked-in AppSurface fixture/policy, CLI reference. + - Verify: run documented commands from a normal checkout; time a fresh maintainer from start page to revision-bound explanation. +- [ ] **T3 (P1, human: ~4h / agent: ~1h)** — Diagnostics — Make new gate failures actionable with stable codes, causes, fixes and canonical links. + - Surfaced by: Pass 3 and native DX finding 3; stale revisions, unsafe extraction and cleanup currently lack gate-specific guidance. + - Files: CLI/runner/verifier diagnostics, EvidenceHost troubleshooting reference, renderer tests. + - Verify: inject stale revision, mismatched diff, missing registration, unsafe artifact, envelope failure, cleanup failure and moved tag; compare terminal/summary/JSON codes and bound hostile values. +- [ ] **T4 (P1, human: ~4h / agent: ~1h)** — Adoption — Publish and execute the full AppSurface policy/registration/host/manifest/verify walkthrough. + - Surfaced by: Pass 4 and native DX finding 4; current cookbook lacks a live gate-shaped end-to-end path. + - Files: `guides/evidencehost-cookbook.md`, `start-here/evidencehost.md`, policy matrix and operator runbook. + - Verify: run the example end to end and pilot current-head check, docs/code, failure and exact-SHA fork promotion. +- [ ] **T5 (P2, human: ~2h / agent: ~30min)** — Migration and measurement — Document v1-local compatibility, fixed trust invariants and separate first-result/full-gate timing. + - Surfaced by: Passes 5 and 8; schema identity changes and the 2–5 minute target need an accurate migration path and actual clock. + - Files: Evidence contracts README, CLI README, start page and pilot log. + - Verify: old local examples remain ineligible; fresh maintainer timing uses the full approved start/end state and pilot log records distinct full-run/fork/duplicate-CI costs. + + +- Preserve the complete AppSurface-only gate and non-mutating release reference, but place the base-owned controller/verifier and untrusted subject execution on separate ephemeral GitHub-hosted job VMs. The subject job has `permissions: {}`, no secrets or OIDC permission, no persisted checkout credential, and receives only the exact captured subject tree and bounded plan data; it never receives the trusted policy/runner as writable input. A private same-workflow artifact handoff carries bounded result bytes, not a generic cross-job aggregation API. The verifier treats every subject result and artifact as untrusted, independently recreates the plan from the base-owned policy and exact Git objects, validates run/job provenance, complete obligations, artifact hashes and cleanup, then performs fresh PR-head/base checks before its stable required-check verdict. No subject job or artifact can directly set that verdict. Pilot actual current-head association and event-policy availability before enforcement. Keep the OCI boundary inside the unprivileged subject VM and hostile-probe it; an inability to enforce it prevents a complete claim. +- Specify one versioned, byte-exact Git change protocol for the gate. Fetch and resolve full commit object IDs into a trusted bare/object-only checkout; invoke Git with argument arrays, pinned runner Git version, neutral trusted configuration, disabled external diff/textconv/color and fixed rename/submodule/binary options. Retain a bounded exact source diff for its digest, and derive selection paths separately from a NUL-delimited `git diff --name-status -z` representation of the same objects. Parse statuses and both rename/copy paths, including mode-only, symlink, binary and submodule changes; reject malformed/truncated/invalid-UTF-8/unrepresentable records rather than selecting an empty profile. Independently regenerate both representations before verdict. Enforce an initial 20 MiB source-diff cap, 10,000 changed records and 4 KiB path-byte cap, or revise these only through a reviewed policy/runner limit change. Test unusual names, zero diff, mixed changes, renames, deletions, type/mode-only and submodule records, oversized input and object/ref races. +- Do not let the v1 `EvidencePlanner` mixed-profile fallback erase a resource or producer obligation. For every trusted PR policy, validate that its conservative profile contains every producer, resource, assertion, artifact and obligation required by each targeted profile it may replace; an incompatible policy is invalid before any run. Test docs+code, docs+resource, resource+code, rename across classes, unknown path and control-plane changes for superset closure. Give legitimate release-preparation PRs a targeted PR profile while the protected release invocation selects its non-mutating release profile from its validated preparation-base/tag diff. If one policy cannot express both contexts without letting an event choose a profile in YAML, use a base-owned, versioned PR/release policy pair selected only by validated event kind; each policy still resolves its candidate profile from its exact diff and both digests enter the plan. An event/profile mismatch always fails. +- Treat the current self-consistency-only `EvidenceManifestBuilder.Verify` and CLI `verify` as necessary but insufficient for a CI authorization. Add a trusted gate verifier that checks the base-owned policy digest, independently regenerated Git diff and status set, immutable plan identity, subject-job provenance, execution envelope and external fresh GitHub/tag identity. Legacy v1 local claims retain documented compatibility but never authorize the new required check merely because their manifest says `PullRequestGate`. Test a fully recomputed forged plan/manifest, wrong policy source, wrong subject job, moved base/head/tag and a valid local-only manifest that the external gate rejects. +- Reuse `ReleaseTaggedProjectionResolver` as the sole release-evidence authority without copying its parser into the new host. Because it is currently internal to a non-packable release executable, expose a narrow, versioned, read-only machine result from the existing `inspect` path containing the validated V2 preparation base, evidence bundle digest, tag object ID and peeled commit, or extract that exact validation seam into a private shared assembly used by both callers. Prove identical success/failure behavior in the release tool and EvidenceHost. A release claim remains non-mutating; any future publisher that consumes it must verify tag immutability for the publication lifetime and use only artifacts bound to the captured object and digests. Without that protection, the claim cannot authorize publication. Test a tag move after the last pre-publication read as well as the two earlier race windows. +- Make dependency supply part of the subject envelope: use a pinned, base-owned SDK/OCI image and reviewed immutable package cache or controlled allowlisted mirror, with locked dependency integrity checks. Restore and all head-controlled build hooks run only inside the unprivileged subject boundary; cache misses, lock mismatches or mirror failure yield unavailable/incomplete evidence, never trusted-host restore or silent network expansion. Pilot a cold-cache run and a dependency-changing PR, and record the image/cache refresh path in the policy matrix. +- Give each policy-selected profile a checked-in, measurable maximum: capture/planning, resource readiness, producer execution, API retry, cleanup and total workflow deadlines. The total job deadline must leave room for the independent 10-minute cleanup and final verification; reject a policy whose declared worst-case work exceeds it. Cancel stale same-PR runs on a new head while allowing their supervisor cleanup to finish; do not cancel another PR's run or mark a cancelled run complete. Test overlapping pushes, a push during cleanup, unavailable/rate-limited GitHub API, each cancellation phase and a stuck producer. Set final numeric budgets after the producer inventory and before any required-check activation, using observed pilot duration rather than an arbitrary promise. +- Keep shadow control-plane validation entirely base-owned: the old trusted controller supplies the harness, path classifier, fixtures and expected outcomes. Subject changes to policy, workflow, runner, host registrations or test fixtures are data to that harness, never authority. Test deleted/weakened rules, edited/removed fixtures and an unrecognized control-plane path; each remains subject to the old obligations. New controller code runs only in an unprivileged non-claiming shadow and becomes authoritative after merge plus smoke proof. +- Preserve the already approved descriptor-relative extraction boundary, but do not route untrusted scratch paths through the current `EvidenceArtifactWriter`'s path-based write or `ReadAllBytes` verification. Stream no-follow copies into a private trusted root, hash bytes as copied, reject mutation and enforce both per-slot/per-producer v1 limits and the runner's 64-file/256 MiB per-file/512 MiB total/120-second caps. Extend the writer/verifier through a narrow streaming seam if necessary; document the lower applicable limit and test 256 MiB memory behavior without allocating entire artifacts. + + +### Eng Step 0: scope challenge grounded in current code + +The reviewed target is the approved #777 implementation plan. The work touches at least the Evidence contracts, planner, CLI, Aspire host, private coverage core, release tool, tests, workflows, policy and documentation: more than eight files and at least the controller/verifier, subject runner and cleanup supervisor as distinct components. Scope is **accepted as-is** under the Autoplan no-reduction rule. The smaller arrangement keeps the complete behavior but uses one private base-owned controller/verifier implementation, one unprivileged subject job and one cleanup supervisor; no general scheduler, persistence layer or public workflow framework is added. This is a structural safety correction, not a feature cut. Re-estimate the provisional timeline after the producer inventory, now including the private cross-job handoff and live event pilot. + +What already exists: [`EvidencePlanner`](../../Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs) validates a policy and chooses a profile; [`EvidenceManifestBuilder`](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) closes typed obligations and verifies self-consistency; [`EvidenceHostBootstrap`](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) executes explicit registrations and lifecycle cleanup; the [coverage execution seam](../../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/CoverageExecutionBoundary.cs) is reusable; the [release inspect tool](../../tools/ForgeTrust.AppSurface.Release/README.md) already validates tag-bound V2 preparation evidence. The existing [build workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) and [release workflows](https://github.com/forge-trust/AppSurface/tree/main/.github/workflows) supply candidate assertions, not EvidenceHost producer results. The new work is trustworthy capture, isolation, extraction, external verification and live check wiring, not replacement of the typed core. + +Current-code findings and dispositions: + +| ID | Severity / confidence | Evidence | Consequence and accepted remedy | +|---|---|---|---| +| E1 | P1 / 9 | `EvidencePlanner.cs:49-52` uses `distinctProfiles.Length != 1` to select only `ConservativeProfileId`. | A docs+resource or resource+code change can drop obligations if the fallback is weaker. Validate conservative-profile superset or reject policy; test every mixed class. | +| E2 | P1 / 9 | `EvidencePlanner.cs:426-445` adds paths only from `---`/`+++` headers, apart from `rename from/to`. | Binary, mode-only, symlink or submodule changes can be absent from selection. Gate path inventory comes from NUL-delimited Git status records, with source diff separately bound. | +| E3 | P1 / 9 | `EvidenceCliWorkflow.cs:208` re-resolves `plan.PolicySnapshot` and `EvidenceContracts.cs:936-964` verifies internal digests; neither authenticates the GitHub event or base-owned policy source. | A self-consistent local manifest is not a required-check authorization. Add an external trusted verifier and negative forged/legacy tests. | +| E4 | P1 / 9 | `ReleaseTaggedProjectionResolver.cs:13,54` is internal and `ForgeTrust.AppSurface.Release.csproj:4,8` is a non-packable executable. | A new host cannot simply call the existing authority. Expose a read-only machine result or move the exact validator to a private shared seam; test parity. | +| E5 | P1 / 9 | `EvidenceContracts.cs:500,534` uses `WriteAllBytesAsync` and `ReadAllBytesAsync`; these are appropriate to current trusted bounded producer data, but not to the new 256 MiB untrusted scratch transfer. | Stream through no-follow descriptors and private trusted storage; retain lower per-slot/v1 limits and test memory as well as path races. | +| E6 | P1 / 8 | The approved plan places subject OCI execution on the `pull_request_target` controller VM; [GitHub's security guide](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target) says the event has elevated base trust and warns against fetching then executing untrusted PR code. | Separate subject and controller job VMs, remove subject job permissions/secrets/OIDC, treat handoff as untrusted, and retain OCI hostile probes. | +| E7 | P1 / 7 | The plan denies subject egress yet does not specify a package restore source for a clean runner. | Use locked packages from a pinned base-owned image/cache or controlled mirror, with restore only inside the subject boundary; prove cold cache and dependency PR behavior. | +| E8 | P2 / 7 | The plan has extraction/cleanup limits but leaves total run and GitHub API budgets unspecified; the current host executes resource and producer declarations sequentially (`EvidenceHostBootstrap.cs:338-387`). | Derive numeric policy and job budgets from inventory before enforcement; cancel stale same-PR runs and test overload/timeout branches. | +| E9 | P2 / 8 | The proposed control-plane shadow test does not explicitly own its fixtures at the base revision. | Old trusted harness and expected cases must be base-owned; subject fixture edits cannot approve their own policy weakening. | +| E10 | P1 / 7 | Tag rereads at verdict and pre-publication still leave a mutable-ref window after the last read. | A non-mutating claim is safe only for its captured identity; any publication consumer requires tag immutability for its use window and object/digest-bound artifacts. | + +No current implementation bug is claimed for #777's absent runner. E1-E5 quote existing code that the proposed gate must extend or avoid; E6-E10 identify plan risks, with observed platform guidance or explicit design text. The native review supplied E6-E10 and the broader form of E2. Its P1 issues are represented as mandatory pre-enforcement requirements, not dismissed because the current prototype works locally. Prior learning `appsurface-patch-gate-committed-source` (confidence 10/10, 2026-09-10) applies to final coverage proof: commit new changed code and tests before relying on `coverage-solution.sh` patch metrics. + +### Eng Section 1: architecture and data flow + +```text +PR event -> base-owned controller job VM -> full-SHA Git objects + | -> source-diff bytes + NUL status inventory + | -> checked-in PR policy + immutable plan + | | + +-- bounded snapshot artifact ----------+--> unprivileged subject job VM + -> OCI subject + declared resources + -> typed producer results + scratch + -> no-follow bounded extraction + -> independent cleanup supervisor + +<-- untrusted bounded results/artifacts --+ + -> base-owned verifier job VM -> rederive plan/diff/status/policy + -> verify provenance/manifest/artifacts/cleanup + -> fresh PR base/head API read + -> single renderer -> stable required check + +protected tag -> existing release inspect authority -> V2 preparation base + -> release policy + same subject/verify boundaries where applicable + -> final tag-object check -> non-mutating ReleaseComplete +``` + +The three-job private handoff is the important trust line: subject content can supply test data and artifacts but never the policy, expected selection fixture, job authority or final verdict. The verifier recomputes the plan instead of trusting a subject-supplied digest. The new runner should name its state transitions and one failure sink; every exception or cancellation lands in a bounded failed/incomplete verdict after cleanup. A live pilot is still needed because event policy and required-check association are GitHub behavior, not properties unit tests can establish. At 10x PR volume, container/resource startup and duplicate existing CI dominate; per-PR concurrency and stale-run cancellation bound work without a cache of complete claims. + +The PR/release profile conflict is explicit: a release-preparation PR must be able to pass a targeted PR gate, while its eventual protected tag must run release obligations. A base-owned PR/release policy pair is permitted only if a single policy cannot express both without letting YAML choose an event privilege. In either form, the validated event selects the policy scope and the exact diff selects the candidate profile. Plan identity binds that policy and revisions; no event can reinterpret a targeted claim as release complete. + +### Eng Section 2: code quality and error handling + +Keep one canonical planner/digest, one manifest verifier and one renderer. The public v1 `EvidenceManifestBuilder.Verify` has an explicit self-consistency contract; strengthen the external gate at a trusted boundary rather than silently redefining v1. The new Git status parser and source-diff capture may share a fixed Git invocation helper because they have the same revisions, configuration and error policy; do not extract a generic Git framework. Preserve `EvidenceCliWorkflow` local usage and publish a versioned gate contract. Reuse the release inspect authority through a narrow read-only result rather than duplicating V2 trailer parsing. Keep subject result diagnostics typed and bounded; do not catch an arbitrary failure and then emit `TargetedComplete` from a partially populated result. + +No new external package is required to implement the parsing, hashing, deadlines or renderer. Standard Git, .NET streams, `TimeProvider`/cancellation and existing xUnit infrastructure are the first reuse choices. The separate VM handoff uses the platform's existing job/artifact capability; it is private to this AppSurface workflow, not a public aggregation format. If the platform cannot deliver a provenance-safe handoff with the chosen event, rollout stops before the ruleset change; no `workflow_dispatch` success is substituted. + +### Eng Section 3: codepath and user-flow test diagram + +Current positive coverage exists for local docs/coverage selection, rename parsing, manifest self-consistency, host resource/producer timeouts and local cleanup in `EvidencePlannerTests.cs` and `EvidenceHostBootstrapTests.cs`. These do not exercise the proposed GitHub gate. `ReleaseToolTests.cs` covers tagged V2 validation, but not the new host/release handoff. The project uses xUnit and `dotnet test`; no LLM/prompt change or eval suite is in scope. + +```text +CODE PATHS MAINTAINER / CI FLOWS +Git capture Start page -> revision-bound explain + [GAP] full SHA/object fetch [GAP] fixture command + expected digest + [GAP] source diff exact bytes / 20 MiB cap [GAP] invalid or missing SHA guidance + [GAP] NUL status / rename / type / binary [GAP] local v1 result stays non-authoritative + [GAP] mismatch / malformed / empty -> fail PR gate +Policy resolution [GAP →E2E] docs-only explicit pass + [★★ TESTED] docs path -> no-evidence [GAP →E2E] code/resource complete pass + [★★ TESTED] unknown path -> conservative [GAP →E2E] failed obligation blocks merge + [GAP] mixed profile superset / reject [GAP →E2E] fork observation and promotion + [GAP] control-plane old-policy fixture [GAP →E2E] base advance and wrong-head block +Host / subject Protected release + [★★★ TESTED] local readiness/timeout/cleanup [GAP →E2E] V2 base/tag/package proof + [GAP] no-token separate VM / OCI denial [GAP] retag at each publication window + [GAP] cold-cache/missing dependency Operator + [GAP] no-follow extraction / 64,256,512,120 [GAP] cancellation, cleanup and rollback + [GAP] forced host kill / supervisor [GAP] actionable bounded diagnostics +Verification / output + [★★ TESTED] local self-consistency + [GAP] base-owned policy / job provenance / freshness + [GAP] one verdict across terminal/summary/JSON +``` + +Each `[GAP]` is a proposed codepath or flow, not an assertion about a shipped feature. For each critical path and edge case, verify an observable invariant, a credible regression, why existing coverage misses it, and the required test boundary. Add rows to current table-driven planner/host/release tests where they fit; create new runner/extractor/verifier tests at their actual boundaries, without reflection or test-only production hooks. No test is retired. Run focused xUnit suites for changed packages, hostile OCI integration on supported Linux, a live PR pilot for GitHub semantics, formatting and `./scripts/coverage-solution.sh` when practical. Live remote behavior remains a rollout dependency, not a simulated unit-test pass. + +### Eng Section 4: performance and operations + +There is no database query path or N+1 issue. The expensive stages are checkout/capture, locked restore, disposable resource readiness, test/coverage execution and artifact transfer. The 20 MiB source cap bounds in-memory diff handling; status records and artifact reads must be streamed or explicitly bounded. Avoid loading a 256 MiB artifact twice when hashing and verifying. Set the total deadline from the policy's worst-case sequential resource/producer durations plus cleanup and API/render reserve, then prove a normal full profile fits; the required check must fail closed rather than run indefinitely. Cache only immutable trusted image/package inputs keyed to lockfiles and base-owned tooling, never a manifest, complete claim or freshness result. Per-PR concurrency cancels stale work while the supervisor still cleans it up; unrelated PRs retain capacity. Log stage duration and failure code so the pilot can distinguish this gate's added cost from duplicate existing jobs. + +### Eng failure modes registry + +| Path | Realistic failure | Planned handling and proof | Critical gap after amendment? | +|---|---|---|---| +| Git capture/selection | Binary or mode-only change omitted, object missing, oversized diff | NUL status parser plus independent regeneration; malformed input fails with diagnostic and unit fixture | No | +| Policy/host | Mixed profile drops resource assertion or registration absent | Superset validation and negative matrix tests; incomplete/invalid manifest | No | +| Subject job/dependencies | Container escape attempt, cold cache or missing locked package | Separate unprivileged VM, OCI hostile probe, locked restore and fail-closed diagnostics | No; live isolation proof required | +| Artifact transfer | Symlink/race/special file or size overflow | Descriptor-relative no-follow stream copy with boundary/race tests; no complete claim | No | +| Freshness/provenance | Wrong job, moved head/base or GitHub 403/timeout | Base-owned independent verifier and bounded retry; failed check | No; live check association required | +| Release | Invalid V2 base, moved tag after last read, rebuilt package | Existing inspect authority, immutable publication precondition, retag and digest tests | No; external tag-rule proof required for publication use | +| Cleanup/concurrency | Host killed, stale run cancelled while cleanup active | Independent supervisor attestation, per-PR cancellation, kill/overlap tests | No | +| Control-plane PR | Head edits a rule and its expected fixture | Old base-owned harness/fixtures plus shadow proof and post-merge smoke | No | + +No failure is allowed to become a silent successful claim. Two platform behaviors remain measured dependencies: actual PR check association/event policy, and any future publication tag immutability. The new check stays non-required until the live pilot proves the former. This plan does not authorize a publisher from `ReleaseComplete` alone. + +### Eng workstreams and boundaries + +| Step | Modules touched | Depends on | +|---|---|---| +| A. Contract, Git identity and policy selection | Evidence Contracts, Planner, CLI | policy/producer inventory | +| B. Release inspect machine seam | Release tool and contracts | validated V2 authority already present | +| C. Host, isolation and streaming extraction | Evidence Aspire/Coverage, new AppSurface runner | A, producer inventory | +| D. Trusted controller/verifier and workflow jobs | new runner, GitHub workflows | A, B, C | +| E. Documentation and focused tests | start-here, guides, package docs, tests | alongside A-D, finalized after interfaces | +| F. Live pilot and ruleset activation | GitHub workflow/ruleset | A-E, repository administrator | + +Launch A and B in separate worktrees because their authored modules are disjoint. Integrate both, then C; D follows the runner boundary. Documentation/tests travel with each interface rather than waiting entirely until E. F is sequential and cannot be simulated. Shared new runner and workflow files are one lane to avoid ownership conflicts. No separate service or state store is needed. + +### Eng not in scope and deferred work + +Generic reusable workflow, self-hosted runner support, merge-queue event support before adoption, external check publisher for fork PRs, automatic package/release publication, deployment attestation and a hosted evidence dashboard remain outside #777. They add new trust or compatibility surfaces without helping AppSurface prove its first required gate. The private subject/verifier job handoff is part of this gate, not a generic aggregation API. These deferrals are recorded in `TODOS.md` with adoption or measurement triggers. Existing build/test checks remain until separate equivalence proof supports migration. + +### Eng decision audit and independent voice + +| # | Decision | Classification | Principle | Reason and rejected alternative | +|---|---|---|---|---| +| 11 | Separate privileged verifier and unprivileged subject VMs | safety correction within approved gate | P2/P5 | GitHub identifies `pull_request_target` head-code execution as elevated-risk; retain OCI but remove controller credentials from the subject VM. Rejected same privileged VM as the default. | +| 12 | Derive gate paths from NUL-delimited Git status, source bytes separately | verified correctness repair | P2/P5 | Existing unified-diff reader omits non-text header cases; rejected trusting the text parser for a gate. | +| 13 | Validate mixed-profile conservative superset | verified correctness repair | P2/P6 | Existing fallback replaces multiple profiles; rejected a weaker fallback that silently drops obligations. | +| 14 | Keep v1 digest verification, add external authority check | compatibility-preserving correction | P2/P5 | Existing verifier explicitly authenticates no source; rejected treating a local manifest as PR authorization. | +| 15 | Reuse release inspect authority and require immutable publication use | safety correction | P2/P5 | Internal executable seam needs a narrow bridge; rejected duplicate V2 parser or mutable-tag check/use gap. | +| 16 | Locked dependency supply, bounded deadlines and base-owned shadow fixtures | feasibility/operational correction | P2/P6 | Gives the complete profile a reproducible, bounded run; rejected trusted-host restore and subject-controlled expected fixtures. | + +The native `combo/sub` reviewer completed against `INPUT: eng 237a6770dc6da73691a9d243b6723d311d45e013ad4c48e404a4dddc484671de` with six findings: four P1 (same-VM privilege, Git selection completeness, tag use race, dependency restore) and two P2 (run budgets/concurrency, shadow fixture ownership). They are reconciled above. The Claude Code outside lane was unavailable at preflight; no cross-provider agreement is claimed. + +| Eng voice dimension | Native `combo/sub` | Claude Code | Consensus | +|---|---|---|---| +| Architecture sound | Conditional on VM separation and release seam | unavailable | N/A | +| Test coverage sufficient | Requires unusual Git, retag and hostile isolation branches | unavailable | N/A | +| Performance addressed | Needs whole-run and concurrency bounds | unavailable | N/A | +| Security threats covered | Same-VM and shadow-fixture risks require correction | unavailable | N/A | +| Error paths handled | Restore/cache and API failures need explicit outcomes | unavailable | N/A | +| Deployment risk manageable | Pilot before ruleset; tag immutability before publication use | unavailable | N/A | + +### Eng completion summary + +| Review area | Result | +|---|---| +| Scope challenge | Accepted as-is; safer three-job arrangement retains complete #777 outcome | +| Architecture | Four issue groups resolved into explicit trust, profile and release requirements | +| Code quality | Three seam issues mapped to reuse or narrow extension, no generic framework | +| Test review | Diagram and QA artifact complete; all proposed gate paths remain implementation gaps with named regression proofs | +| Performance | One bounded-runtime issue group, numeric profile/job budgets required before enforcement | +| Failure modes | Zero silent-success gaps after accepted requirements; live event and isolation proofs still pending | +| Parallelization | A/B parallel; C then D; live F last | +| Unresolved engineering decisions | None; administrator ruleset activation requires the completed pilot | +| Outside voice | Claude Code unavailable; native `combo/sub` completed, consensus N/A | + +Approval readiness for the *plan review*: PASS for decisions 11-16 under Autoplan's correctness/safety rules and the user's approved complete-gate scope. This does not claim an implemented gate or authorize a ruleset change before its pilot. + +## Implementation Tasks + +These engineering tasks derive from E1-E10 and the test diagram; effort assumes existing .NET/xUnit and GitHub Actions patterns are reused. Estimates exclude live-pilot waiting and administrator availability. + +- [ ] **T1 (P1, human: ~2 days / agent: ~5h)** — Git identity — Implement full-SHA capture, exact source-diff and NUL status inventory with bounded malformed-input handling. + - Surfaced by: E2 and native Git-selection finding; the current unified-diff parser omits non-text changes. + - Files: Evidence planner/CLI and new trusted runner; contract/CLI references. + - Verify: table-driven Git fixtures for binary, mode-only, symlink, submodule, rename/copy, deletion, invalid filename, empty and oversized diffs; repeat independently at verdict. +- [ ] **T2 (P1, human: ~1 day / agent: ~3h)** — Policy — Enforce mixed-profile superset and PR/release policy-context compatibility. + - Surfaced by: E1; the v1 planner replaces multiple selected profiles with one conservative profile. + - Files: Evidence policy/planner contracts and AppSurface checked-in policy/matrix. + - Verify: docs+resource, resource+code, release-preparation PR, protected release, rename/control-plane and missing-registration fixtures. +- [ ] **T3 (P1, human: ~3 days / agent: ~1 day)** — Isolation — Build separate credentialless subject job, private bounded handoff and trusted verifier job. + - Surfaced by: E3/E6 and native same-VM finding; local manifest digests do not authenticate source or job. + - Files: AppSurface runner and GitHub workflow, Evidence host integration. + - Verify: hostile OCI/credential/socket/network probe, forged manifest/wrong-job rejection, same-repo/fork/failed producer live pilots and head-association proof. +- [ ] **T4 (P1, human: ~2 days / agent: ~5h)** — Host and artifacts — Stream no-follow extraction with typed producer/resource and independent cleanup results. + - Surfaced by: E5 and existing path-based `ReadAllBytes` verification. + - Files: Evidence contracts/Aspire host and AppSurface runner. + - Verify: traversal, symlink, special file, hardlink ambiguity, collisions, mutation, every size/count/time cap and forced host kill; no complete claim on cleanup failure. +- [ ] **T5 (P1, human: ~1 day / agent: ~3h)** — Release — Bridge existing inspect authority to EvidenceHost and bind immutable tag/artifact use. + - Surfaced by: E4/E10 and native tag check/use finding. + - Files: Release tool/contract and AppSurface host release producer. + - Verify: tool/host parity; forged V2 base/trailer, retag at all windows, rebuilt/missing package and publication-ineligible mutable tag. +- [ ] **T6 (P1, human: ~1 day / agent: ~3h)** — Reproducibility — Supply locked dependencies inside the subject boundary and bound every phase/job. + - Surfaced by: E7/E8 and native restore/load findings. + - Files: pinned subject image/cache or mirror config, AppSurface policy/matrix and workflow. + - Verify: cold cache, cache/lock mismatch, mirror unavailable, dependency PR, cancellation at each phase, overlapping pushes and API timeout; record numeric budgets before enforcement. +- [ ] **T7 (P1, human: ~1 day / agent: ~3h)** — Control plane — Make old controller/fixtures authoritative for self-change PRs, with non-claiming shadow and post-merge smoke. + - Surfaced by: E9 and native shadow-fixture finding. + - Files: base-owned policy/runner tests and workflow. + - Verify: delete/weaken rule, change/remove expected fixture, unrecognized control-plane path, then live shadow/smoke proof. +- [ ] **T8 (P1, human: ~2 days plus pilot/admin wait / agent: ~4h plus wait)** — Rollout — Run the complete pilot and activate the exact required check only after observed proof. + - Surfaced by: E6/E8, original #777 finish line and GitHub event/check uncertainty. + - Files: GitHub workflow/ruleset runbook and pilot log. + - Verify: current-head association, strict base-advance freshness, docs/code/resource/failure/fork cases, release non-mutation, rollback trigger map, existing checks and `./scripts/coverage-solution.sh` when practical. + +## GSTACK REVIEW REPORT + +| Review | Trigger | Why | Runs | Status | Findings | +|---|---|---|---:|---|---| +| CEO Review | `/plan-ceo-review` via Autoplan | Scope and strategy | 19 including this review | ISSUES MAPPED | Complete AppSurface scope retained; one third-pass spec-review mapping was resolved by parent without a fourth reviewer. | +| Outside Review | Claude Code via Autoplan | Independent second opinion | 2 historical; current unavailable | UNAVAILABLE | CLI not installed at preflight; no cross-provider consensus is claimed for #777. | +| Eng Review | `/plan-eng-review` via Autoplan | Architecture and tests, required | 21 including this review | ISSUES MAPPED | 10 findings mapped to accepted requirements; zero silent-success critical gaps after amendment; live pilot remains. | +| Design Review | `/plan-design-review` | UI/UX gaps | 2 historical; skipped for #777 | SKIPPED | No UI scope in the #777 gate. | +| DX Review | `/plan-devex-review` via Autoplan | Developer experience gaps | 19 including this review | ISSUES MAPPED | Planned 5.0/10 → 7.8/10; first-result time unmeasured, target 2–5 minutes. | + +**OUTSIDE COVERAGE:** Claude Code was unavailable for CEO, DX and Eng phases. Native `combo/sub` reviews completed with 4, 4 and 6 issues respectively. Their findings were reconciled, but native review does not supply independent outside-provider coverage. + +**VERDICT:** APPROVED by the user at the final Autoplan gate on 2026-10-01 after CEO, DX and Eng review. The new required check must not be activated until the implementation, hostile isolation tests, live head/freshness pilot and administrator verification pass. Eng implementation review is required before ship because this plan review mapped issues rather than certifying code. + +NO UNRESOLVED DECISIONS diff --git a/examples/durable-postgresql.tests/DurablePostgreSqlLocalProofScriptTests.cs b/examples/durable-postgresql.tests/DurablePostgreSqlLocalProofScriptTests.cs index ce95873f3..482cbcfee 100644 --- a/examples/durable-postgresql.tests/DurablePostgreSqlLocalProofScriptTests.cs +++ b/examples/durable-postgresql.tests/DurablePostgreSqlLocalProofScriptTests.cs @@ -171,7 +171,7 @@ exit 0 using var process = Process.Start(startInfo)!; try { - await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(8)); + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(20)); } catch { @@ -310,7 +310,9 @@ exit 0 fakeBin, Environment.GetEnvironmentVariable("PATH") ?? string.Empty); startInfo.Environment["APPSURFACE_DURABLE_LOCAL_PORT"] = "54349"; - startInfo.Environment["APPSURFACE_DURABLE_LOCAL_PROOF_TIMEOUT_SECONDS"] = "2"; + // Leave time for all fake prerequisites to complete under the full coverage run. + // The deadline still expires while the fake verify-local child is running. + startInfo.Environment["APPSURFACE_DURABLE_LOCAL_PROOF_TIMEOUT_SECONDS"] = "10"; startInfo.Environment["APPSURFACE_TEST_CHILD_PID_FILE"] = childPidFile; startInfo.Environment["APPSURFACE_TEST_HEARTBEAT_FILE"] = heartbeatFile; startInfo.Environment["APPSURFACE_TEST_CLEANUP_HEARTBEAT_FILE"] = cleanupHeartbeatFile; @@ -320,7 +322,7 @@ exit 0 using var process = Process.Start(startInfo)!; try { - await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(8)); + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(20)); } catch { @@ -340,8 +342,8 @@ exit 0 Assert.True( process.ExitCode is 130 or 143, $"Expected an interrupted exit (130 or 143), but received {process.ExitCode}. stderr: {standardError}"); - Assert.Contains("exceeded its 2-second deadline", standardError, StringComparison.Ordinal); - Assert.InRange(stopwatch.Elapsed, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(7)); + Assert.Contains("exceeded its 10-second deadline", standardError, StringComparison.Ordinal); + Assert.InRange(stopwatch.Elapsed, TimeSpan.FromSeconds(9), TimeSpan.FromSeconds(19)); var childPid = await File.ReadAllTextAsync(childPidFile); Assert.Matches("^[0-9]+\\n?$", childPid); diff --git a/guides/evidencehost-cookbook.md b/guides/evidencehost-cookbook.md index 9a01bdab0..6b8088ef9 100644 --- a/guides/evidencehost-cookbook.md +++ b/guides/evidencehost-cookbook.md @@ -37,6 +37,21 @@ The selected coverage producer runs the existing `coverage gate` evaluator with If CI intentionally selects only part of the test suite, call that a targeted observation or create a policy profile whose declared obligations match that selection. Do not run a repository-wide threshold and call the outcome “full coverage.” +## Revision-bound PR rehearsal + +The [Git change capture reference](../Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md#revision-bound-git-change-capture) defines the fixed diff and NUL status inputs. For a local rehearsal with two complete commit IDs, capture the source diff using the same fixed options, then run: + +```bash +base=$(git rev-parse --verify HEAD~1^{commit}) +head=$(git rev-parse --verify HEAD^{commit}) +git -c diff.external= -c diff.noprefix=false -c diff.mnemonicprefix=false -c diff.algorithm=myers diff --no-ext-diff --no-textconv --no-color --binary --full-index --unified=3 --find-renames=50% --find-copies=50% --submodule=short --ignore-submodules=none --no-relative --src-prefix=a/ --dst-prefix=b/ "$base" "$head" -- > change.diff +appsurface evidence explain --gate-mode --policy .appsurface/evidence/evidence.policy.json --repository . --base-revision "$base" --head-revision "$head" --diff-file change.diff --output TestResults/evidence +appsurface evidence run --gate-mode --policy .appsurface/evidence/evidence.policy.json --repository . --base-revision "$base" --head-revision "$head" --diff-file change.diff --output TestResults/evidence +appsurface evidence verify TestResults/evidence/evidence-manifest.json --policy .appsurface/evidence/evidence.policy.json --repository . +``` + +The quoted `^{commit}` suffix is Git syntax for resolving a commit, including a peeled annotated tag; for PRs, use the event's full base and head commit IDs instead of ambient `HEAD`. The two planning commands produce the same v2 `PlanDigest` for identical inputs. A changed base/head, altered diff file, missing Git object, or policy mismatch fails. `--gate-mode` rejects path-only input, and `--path` cannot be combined with revision inputs. The built-in CLI's `run` emits `ObservationOnly` for v2 and exits nonzero in gate mode; it does not establish the trusted job and sandbox evidence needed for a required check. `verify` needs a separately trusted policy and Git object store for v2, but a successful local verification is still not a CI authorization. Keep the [policy matrix](../docs/evidence-gate-policy-matrix.md) alongside the base-owned controller and host registrations. + ## Resource-backed browser E2E Put the EvidenceHost in a test/CI project, separate from the application AppHost. Register each resource readiness probe and browser producer explicitly: diff --git a/releases/unreleased.entries/2026-10-02-evidence-gate-pilot.md b/releases/unreleased.entries/2026-10-02-evidence-gate-pilot.md new file mode 100644 index 000000000..d45a02787 --- /dev/null +++ b/releases/unreleased.entries/2026-10-02-evidence-gate-pilot.md @@ -0,0 +1,5 @@ + + +### Policy-driven CI evidence pilot + +AppSurface maintainers can rehearse a revision-bound [EvidenceHost plan](../../start-here/evidencehost.md) from a protected policy, an exact base/head diff, and a credentialless subject job. The [rollout record](../../docs/evidence-gate-rollout.md) explains the current non-claiming workflow, its image provenance and cleanup checks, and the live PR cases still needed before the evidence check can become required. This pilot intentionally fails closed; it does not yet authorize a merge or a release. diff --git a/scripts/evidence-gate-build-offline-feed.py b/scripts/evidence-gate-build-offline-feed.py new file mode 100644 index 000000000..9e6bfe4a5 --- /dev/null +++ b/scripts/evidence-gate-build-offline-feed.py @@ -0,0 +1,1057 @@ +#!/usr/bin/env python3 +"""Build a verified, flat offline NuGet feed from a trusted base checkout. + +This build-time utility parses one trusted repository-relative ``.slnx`` file, +then resolves the exact ``packages*.lock.json`` file each listed project uses +for the fixed ``linux-x64`` subject runtime. This excludes unrelated fixtures +and lock variants for other operating systems. It reads exact ``.nupkg`` files +in the supplied NuGet global-packages cache and +invokes the fixed ``dotnet nuget verify --all`` command on each copied archive +to obtain NuGet's authoritative ``Content hash:`` value. It never invokes +Git, a shell, or any build/restore command. The checkout must be a trusted +base revision; do not point it at a pull-request/head checkout. Every selected +path component and file must be physical (not a symbolic link). + +The accepted lock format is NuGet's JSON lock format with an integer version +of 1 or 2 and a ``dependencies`` object. ``Direct``, ``Transitive``, and +``CentralTransitive`` entries must have safe normalized package IDs/versions +and a canonical base64 SHA-512 ``contentHash``. ``Project`` entries are +validated as project references and do not become feed packages. Repeated +case-insensitive package ID/version pairs are emitted once; conflicting +content hashes fail closed. Project SDK packages, which NuGet does not record +in project locks, are admitted only through the reviewed ID/version/content-hash +pins below and only when an included project declares that exact SDK. Package +archives are located at the exact NuGet +global-packages layout ``//..nupkg``. + +The destination must not exist. It is created with exclusive directory/file +creation and contains only flat ``..nupkg`` files. The default +hard limits are 4 MiB per solution, 10,000 solution projects, 1 MiB per project +file, 32 MiB total project XML, 100,000 entries in selected project directories, +2,048 lock files, 4 MiB per lock, 32 MiB of +lock JSON, 10,000 distinct packages, 512 MiB per archive, 4 GiB total archive +bytes, 250,000 inspected cache entries, 30 seconds per NuGet verification, 64 +KiB verifier output, and 30 minutes total verification time. Callers of the +Python API may only tighten those limits. Tests may inject a content-hash +verifier; the CLI exposes no verifier override. A failed build removes the +private partial output when it can do so safely. + +CLI:: + + python3 scripts/evidence-gate-build-offline-feed.py \ + --checkout /trusted/base/checkout \ + --solution ForgeTrust.AppSurface.slnx \ + --global-packages /runner/cache/nuget/packages \ + --output /runner/temp/locked-nuget-feed + +Python API:: + + result = build_offline_feed(checkout, solution_relative_path, global_packages, output_directory) + +Use the result counts for build logs only. A successful feed proves that its +bytes have the NuGet-reported content hashes selected by the checked-in locks; +this utility does not authenticate the checkout, image, or later feed use. +The digest-pinned image build must call it only with a trusted base checkout +and must keep the resulting feed inside the reviewed subject image. NuGet +verification is a fixed, bounded subprocess: no user command, package source, +build, or restore is run. +""" + +from __future__ import annotations + +import argparse +import base64 +from dataclasses import dataclass +import json +import os +from pathlib import Path +from pathlib import PurePosixPath +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import threading +import time +from typing import Any, Callable, Sequence +import xml.etree.ElementTree as ElementTree + + +COPY_CHUNK_BYTES = 1024 * 1024 +DOTNET_EXECUTABLES = (Path("/usr/share/dotnet/dotnet"), Path("/usr/local/share/dotnet/dotnet")) +DOTNET_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/share/dotnet" +MAX_VERIFIER_OUTPUT_BYTES = 64 * 1024 +SDK_RUNTIME_IDENTIFIER = "linux-x64" +SDK_RUNTIME_IDENTIFIER_PROPERTY = "$(NETCoreSdkRuntimeIdentifier)" +PACKAGE_ENTRY_TYPES = frozenset({"Direct", "Transitive", "CentralTransitive"}) +PACKAGE_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,99}\Z") +PACKAGE_VERSION_PATTERN = re.compile( + r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)" + r"(?:\.(?:0|[1-9][0-9]*))?" + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\Z" +) +PROJECT_SDK_PACKAGE_PINS = { + ("aspire.apphost.sdk", "13.4.4"): "yYcwwYub6sFzgtrnYJHrq6Q3F+fQYQd1r7aRCDShQHqNAYO8/ObfW/jXv0eTcbwlag7Oz33RRYbMnW8QMVi5qg==", +} + + +class OfflineFeedError(Exception): + """A bounded, path-free diagnostic for an invalid offline-feed build.""" + + +@dataclass(frozen=True) +class FeedLimits: + """Hard ceilings; a build may lower but never raise any ceiling.""" + + max_solution_bytes: int = 4 * 1024 * 1024 + max_projects: int = 10_000 + max_project_file_bytes: int = 1024 * 1024 + max_total_project_bytes: int = 32 * 1024 * 1024 + max_selected_directory_entries: int = 100_000 + max_lock_files: int = 2_048 + max_lock_file_bytes: int = 4 * 1024 * 1024 + max_total_lock_bytes: int = 32 * 1024 * 1024 + max_packages: int = 10_000 + max_package_bytes: int = 512 * 1024 * 1024 + max_total_package_bytes: int = 4 * 1024 * 1024 * 1024 + max_cache_entries: int = 250_000 + max_verifier_seconds_per_archive: int = 30 + max_total_verifier_seconds: int = 30 * 60 + max_verifier_output_bytes: int = MAX_VERIFIER_OUTPUT_BYTES + + +DEFAULT_LIMITS = FeedLimits() + + +@dataclass(frozen=True) +class FeedBuildResult: + """Counts from a completed feed; no source or cache paths are exposed.""" + + lock_file_count: int + package_count: int + package_bytes: int + + +@dataclass(frozen=True) +class _LockedPackage: + package_id: str + version: str + content_hash: bytes + + @property + def identity(self) -> tuple[str, str]: + return self.package_id.lower(), self.version.lower() + + @property + def archive_name(self) -> str: + package_id, version = self.identity + return f"{package_id}.{version}.nupkg" + + +@dataclass(frozen=True) +class _Archive: + package: _LockedPackage + source: Path + size: int + + +def _fail(message: str) -> OfflineFeedError: + return OfflineFeedError(message) + + +def _validate_limits(limits: FeedLimits) -> None: + if not isinstance(limits, FeedLimits): + raise _fail("Feed limits must use the FeedLimits contract.") + for name, hard_maximum in vars(DEFAULT_LIMITS).items(): + value = getattr(limits, name) + if type(value) is not int or value < 1 or value > hard_maximum: + raise _fail("A feed limit is outside its reviewed hard ceiling.") + + +def _path_argument(value: str | os.PathLike[str], name: str) -> Path: + try: + raw = os.fspath(value) + except TypeError: + raise _fail(f"{name} must be an absolute physical path.") from None + if not isinstance(raw, str) or not raw or "\x00" in raw or not os.path.isabs(raw): + raise _fail(f"{name} must be an absolute physical path.") + if any(component in {".", ".."} for component in raw.split(os.sep)): + raise _fail(f"{name} contains a dot path component.") + return Path(raw) + + +def _physical_directory(value: str | os.PathLike[str], name: str) -> Path: + path = _path_argument(value, name) + try: + current = Path(path.anchor) + if stat.S_ISLNK(current.lstat().st_mode): + raise _fail(f"{name} traverses a symbolic link.") + for index, component in enumerate(path.parts[1:], start=1): + current = current / component + item_stat = current.lstat() + if stat.S_ISLNK(item_stat.st_mode): + raise _fail(f"{name} traverses a symbolic link.") + if index < len(path.parts) - 1 and not stat.S_ISDIR(item_stat.st_mode): + raise _fail(f"{name} contains a non-directory path component.") + final_stat = path.lstat() + if not stat.S_ISDIR(final_stat.st_mode): + raise _fail(f"{name} is not a physical directory.") + if path.resolve(strict=True) != path: + raise _fail(f"{name} is not a canonical physical path.") + except OfflineFeedError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail(f"{name} is unavailable or unsafe.") from None + return path + + +def _paths_overlap(first: Path, second: Path) -> bool: + return first == second or first in second.parents or second in first.parents + + +def _new_output_location( + value: str | os.PathLike[str], checkout: Path, cache: Path +) -> tuple[Path, Path]: + output = _path_argument(value, "The output directory") + if output == Path(output.anchor) or output.name in {"", ".", ".."}: + raise _fail("The output directory must be a new child of a physical parent directory.") + parent = _physical_directory(output.parent, "The output parent") + output = parent / output.name + if _paths_overlap(output, checkout) or _paths_overlap(output, cache): + raise _fail("The output directory must be separate from the checkout and global cache.") + try: + output.lstat() + except FileNotFoundError: + return parent, output + except OSError: + raise _fail("The output location cannot be inspected safely.") from None + raise _fail("The output directory must not already exist.") + + +def _is_lock_filename(name: str) -> bool: + return name.startswith("packages") and name.endswith(".lock.json") + + +def _selected_project_inputs(project_bytes: bytes) -> tuple[str, list[_LockedPackage]]: + if b" Path: + if not isinstance(value, str) or not value or "\x00" in value or "\\" in value: + raise _fail(f"{name} must be a safe repository-relative path.") + posix_path = PurePosixPath(value) + if posix_path.is_absolute() or any(part in {"", ".", ".."} for part in value.split("/")): + raise _fail(f"{name} must be a safe repository-relative path.") + if ":" in value.split("/", 1)[0] or any(ord(character) < 32 or ord(character) == 127 for character in value): + raise _fail(f"{name} contains an unsafe path character.") + if required_suffix is not None and posix_path.suffix != required_suffix: + raise _fail(f"{name} has an unsupported file type.") + return Path(*posix_path.parts) + + +def _physical_checkout_file( + checkout: Path, + relative_path: str | Path, + name: str, + maximum_bytes: int, +) -> tuple[Path, int]: + relative = _relative_checkout_path(os.fspath(relative_path), name) + path = checkout / relative + try: + current = checkout + for index, component in enumerate(relative.parts): + current = current / component + item_stat = current.lstat() + if stat.S_ISLNK(item_stat.st_mode): + raise _fail(f"{name} traverses a symbolic link.") + if index < len(relative.parts) - 1: + if not stat.S_ISDIR(item_stat.st_mode): + raise _fail(f"{name} contains a non-directory path component.") + elif not stat.S_ISREG(item_stat.st_mode): + raise _fail(f"{name} is not a regular physical file.") + item_stat = path.lstat() + if item_stat.st_size < 1 or item_stat.st_size > maximum_bytes: + raise _fail(f"{name} is empty or exceeds its byte limit.") + if path.resolve(strict=True) != path or path.relative_to(checkout) != relative: + raise _fail(f"{name} is not a canonical file below the trusted checkout.") + except OfflineFeedError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail(f"{name} is unavailable or unsafe.") from None + return path, item_stat.st_size + + +def _read_physical_file(path: Path, expected_size: int, maximum_bytes: int, name: str) -> bytes: + flags = os.O_RDONLY | _nofollow_flag() + try: + descriptor = os.open(path, flags) + with os.fdopen(descriptor, "rb") as source_file: + item_stat = os.fstat(source_file.fileno()) + if not stat.S_ISREG(item_stat.st_mode) or item_stat.st_size != expected_size: + raise _fail(f"{name} changed or is not a regular physical file.") + if item_stat.st_size > maximum_bytes: + raise _fail(f"{name} exceeds its byte limit.") + raw = source_file.read(maximum_bytes + 1) + except OfflineFeedError: + raise + except OSError: + raise _fail(f"{name} cannot be opened safely.") from None + if len(raw) != expected_size or len(raw) > maximum_bytes: + raise _fail(f"{name} changed while being read or exceeds its byte limit.") + return raw + + +def _select_lock_files( + checkout: Path, solution_relative_path: str | os.PathLike[str], limits: FeedLimits +) -> tuple[list[tuple[Path, int]], list[_LockedPackage]]: + solution_relative = _relative_checkout_path(os.fspath(solution_relative_path), "The solution path", ".slnx") + solution_path, solution_size = _physical_checkout_file( + checkout, + solution_relative, + "The trusted solution", + limits.max_solution_bytes, + ) + solution_bytes = _read_physical_file( + solution_path, + solution_size, + limits.max_solution_bytes, + "The trusted solution", + ) + if b" limits.max_projects: + raise _fail("The trusted solution exceeds the project-count limit.") + if not project_paths: + raise _fail("The trusted solution contains no projects.") + if len(set(project_paths)) != len(project_paths): + raise _fail("The trusted solution lists a project more than once.") + + selected_directories: dict[Path, set[str]] = {} + project_sdks: list[_LockedPackage] = [] + total_project_bytes = 0 + for project_relative in project_paths: + project_path, project_size = _physical_checkout_file( + checkout, + project_relative, + "A selected project", + limits.max_project_file_bytes, + ) + total_project_bytes += project_size + if total_project_bytes > limits.max_total_project_bytes: + raise _fail("Selected project XML exceeds its total byte limit.") + project_bytes = _read_physical_file( + project_path, + project_size, + limits.max_project_file_bytes, + "A selected project", + ) + selected_lock_name, selected_sdks = _selected_project_inputs(project_bytes) + selected_directories.setdefault(project_path.parent, set()).add(selected_lock_name) + project_sdks.extend(selected_sdks) + + lock_files: dict[Path, int] = {} + selected_entry_count = 0 + for directory, selected_names in sorted(selected_directories.items()): + found_names: set[str] = set() + try: + with os.scandir(directory) as entries: + for entry in entries: + selected_entry_count += 1 + if selected_entry_count > limits.max_selected_directory_entries: + raise _fail("Selected project directories exceed the entry-count limit.") + if entry.name not in selected_names: + continue + item_stat = entry.stat(follow_symlinks=False) + if stat.S_ISLNK(item_stat.st_mode): + raise _fail("A selected lock file is a symbolic link.") + if not stat.S_ISREG(item_stat.st_mode): + raise _fail("A selected lock input is not a regular file.") + lock_path = Path(entry.path) + if lock_path.resolve(strict=True) != lock_path: + raise _fail("A selected lock file is not physically canonical.") + if item_stat.st_size < 1 or item_stat.st_size > limits.max_lock_file_bytes: + raise _fail("A selected lock file is empty or exceeds its byte limit.") + lock_files[lock_path] = item_stat.st_size + if len(lock_files) > limits.max_lock_files: + raise _fail("Selected projects exceed the lock-file-count limit.") + found_names.add(entry.name) + except OfflineFeedError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail("A selected project directory cannot be inspected safely.") from None + + if found_names != selected_names: + raise _fail("A selected project has no regular Linux dependency lock file.") + + if not lock_files: + raise _fail("The trusted solution's project directories contain no packages*.lock.json inputs.") + return sorted(lock_files.items(), key=lambda item: item[0].relative_to(checkout).as_posix()), project_sdks + + +def _read_lock_file(path: Path, expected_size: int, limits: FeedLimits) -> bytes: + return _read_physical_file(path, expected_size, limits.max_lock_file_bytes, "A selected lock file") + + +def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON property") + result[key] = value + return result + + +def _reject_json_constant(_value: str) -> None: + raise ValueError("non-standard JSON constant") + + +def _validate_package_id(package_id: Any) -> str: + if not isinstance(package_id, str) or PACKAGE_ID_PATTERN.fullmatch(package_id) is None: + raise _fail("A lock entry contains an unsafe or malformed package ID.") + return package_id + + +def _validate_version(version: Any) -> str: + if not isinstance(version, str) or len(version) > 128 or PACKAGE_VERSION_PATTERN.fullmatch(version) is None: + raise _fail("A lock entry contains an unsafe or non-normalized package version.") + if version.endswith(".0") and version.split("-", 1)[0].count(".") == 3: + raise _fail("A lock entry contains a non-normalized four-part package version.") + return version + + +def _decode_content_hash(value: Any) -> bytes: + if not isinstance(value, str): + raise _fail("A package lock entry is missing its SHA-512 contentHash.") + try: + digest = base64.b64decode(value, validate=True) + except (ValueError, base64.binascii.Error): + raise _fail("A package lock entry has a malformed base64 contentHash.") from None + if len(digest) != 64 or base64.b64encode(digest).decode("ascii") != value: + raise _fail("A package lock entry has a non-canonical SHA-512 contentHash.") + return digest + + +def _parse_lock(raw: bytes) -> list[_LockedPackage]: + try: + document = json.loads( + raw.decode("utf-8"), + object_pairs_hook=_unique_json_object, + parse_constant=_reject_json_constant, + ) + except (UnicodeDecodeError, ValueError, RecursionError): + raise _fail("A lock file is malformed UTF-8 JSON or contains duplicate properties.") from None + if not isinstance(document, dict) or type(document.get("version")) is not int or document["version"] not in {1, 2}: + raise _fail("A lock file has an unsupported NuGet lock format version.") + dependencies = document.get("dependencies") + if not isinstance(dependencies, dict): + raise _fail("A lock file is missing its dependencies object.") + + packages: list[_LockedPackage] = [] + for target, entries in dependencies.items(): + if not isinstance(target, str) or not target or len(target) > 512 or not isinstance(entries, dict): + raise _fail("A lock file contains a malformed target-framework dependency group.") + for package_id_value, entry in entries.items(): + package_id = _validate_package_id(package_id_value) + if not isinstance(entry, dict): + raise _fail("A lock file contains a malformed dependency entry.") + entry_type = entry.get("type") + if entry_type == "Project": + project_dependencies = entry.get("dependencies", {}) + if not isinstance(project_dependencies, dict): + raise _fail("A lock file contains a malformed project-reference entry.") + for dependency_id, requested in project_dependencies.items(): + _validate_package_id(dependency_id) + if not isinstance(requested, str) or len(requested) > 512: + raise _fail("A lock file contains a malformed project-reference constraint.") + continue + if entry_type not in PACKAGE_ENTRY_TYPES: + raise _fail("A lock file contains an unsupported dependency entry type.") + version = _validate_version(entry.get("resolved")) + content_hash = _decode_content_hash(entry.get("contentHash")) + packages.append(_LockedPackage(package_id.lower(), version.lower(), content_hash)) + return packages + + +def _collect_locked_packages( + lock_files: list[tuple[Path, int]], project_sdks: list[_LockedPackage], limits: FeedLimits +) -> dict[tuple[str, str], _LockedPackage]: + total_lock_bytes = 0 + packages: dict[tuple[str, str], _LockedPackage] = {} + for path, size in lock_files: + total_lock_bytes += size + if total_lock_bytes > limits.max_total_lock_bytes: + raise _fail("Lock files exceed the total lock-byte limit.") + for package in _parse_lock(_read_lock_file(path, size, limits)): + previous = packages.get(package.identity) + if previous is not None and previous.content_hash != package.content_hash: + raise _fail("Lock files disagree on a package ID/version contentHash.") + packages[package.identity] = previous or package + if len(packages) > limits.max_packages: + raise _fail("Lock files exceed the distinct-package-count limit.") + for package in project_sdks: + previous = packages.get(package.identity) + if previous is not None and previous.content_hash != package.content_hash: + raise _fail("A project SDK pin disagrees with a lock package contentHash.") + packages[package.identity] = previous or package + if len(packages) > limits.max_packages: + raise _fail("Project SDK packages exceed the distinct-package-count limit.") + if not packages: + raise _fail("The lock files contain no NuGet package archives.") + return packages + + +class _CacheEntryBudget: + def __init__(self, maximum: int) -> None: + self.maximum = maximum + self.count = 0 + + def consume(self) -> None: + self.count += 1 + if self.count > self.maximum: + raise _fail("The NuGet cache exceeds the inspected-entry limit.") + + +def _nofollow_flag() -> int: + if not hasattr(os, "O_NOFOLLOW"): + raise _fail("This platform does not provide the required no-follow file operations.") + return os.O_NOFOLLOW + + +def _find_children( + directory: Path, + wanted_names: set[str], + *, + expected_directory: bool, + budget: _CacheEntryBudget, +) -> dict[str, Path]: + found: dict[str, Path] = {} + try: + with os.scandir(directory) as iterator: + for entry in iterator: + budget.consume() + if entry.name not in wanted_names: + continue + item_stat = entry.stat(follow_symlinks=False) + if stat.S_ISLNK(item_stat.st_mode): + raise _fail("A required NuGet cache path contains a symbolic link.") + correct_type = ( + stat.S_ISDIR(item_stat.st_mode) if expected_directory else stat.S_ISREG(item_stat.st_mode) + ) + if not correct_type: + raise _fail("A required NuGet cache path has an unsupported physical file type.") + path = Path(entry.path) + if path.resolve(strict=True) != path: + raise _fail("A required NuGet cache path is not physically canonical.") + found[entry.name] = path + except OfflineFeedError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail("The NuGet cache cannot be inspected safely.") from None + return found + + +def _locate_archives( + cache: Path, packages: dict[tuple[str, str], _LockedPackage], limits: FeedLimits +) -> list[_Archive]: + budget = _CacheEntryBudget(limits.max_cache_entries) + ids = {package_id for package_id, _version in packages} + package_directories = _find_children(cache, ids, expected_directory=True, budget=budget) + missing_ids = ids - package_directories.keys() + if missing_ids: + raise _fail("A locked package is missing from the supplied NuGet global cache.") + + versions_by_id: dict[str, set[str]] = {} + for package_id, version in packages: + versions_by_id.setdefault(package_id, set()).add(version) + version_directories: dict[tuple[str, str], Path] = {} + for package_id, versions in sorted(versions_by_id.items()): + found = _find_children( + package_directories[package_id], + versions, + expected_directory=True, + budget=budget, + ) + for version in versions: + if version not in found: + raise _fail("A locked package version is missing from the supplied NuGet global cache.") + version_directories[(package_id, version)] = found[version] + + archive_paths: dict[tuple[str, str], Path] = {} + for identity, package in sorted(packages.items()): + version_directory = version_directories[identity] + found = _find_children( + version_directory, + {package.archive_name}, + expected_directory=False, + budget=budget, + ) + source = found.get(package.archive_name) + if source is None: + raise _fail("A locked .nupkg archive is missing from the supplied NuGet global cache.") + archive_paths[identity] = source + + archives: list[_Archive] = [] + total_bytes = 0 + flags = os.O_RDONLY | _nofollow_flag() + for identity, package in sorted(packages.items()): + try: + descriptor = os.open(archive_paths[identity], flags) + try: + item_stat = os.fstat(descriptor) + finally: + os.close(descriptor) + except OSError: + raise _fail("A locked .nupkg archive cannot be opened safely.") from None + if not stat.S_ISREG(item_stat.st_mode) or item_stat.st_size < 1: + raise _fail("A locked .nupkg archive is not a non-empty regular file.") + if item_stat.st_size > limits.max_package_bytes: + raise _fail("A locked .nupkg archive exceeds the per-file byte limit.") + total_bytes += item_stat.st_size + if total_bytes > limits.max_total_package_bytes: + raise _fail("The locked package archives exceed the total byte limit.") + archives.append(_Archive(package, archive_paths[identity], item_stat.st_size)) + return archives + + +def _open_directory_descriptor(path: Path) -> int: + required_flags = ("O_DIRECTORY", "O_NOFOLLOW") + if any(not hasattr(os, name) for name in required_flags): + raise _fail("This platform does not provide the required no-follow directory operations.") + try: + return os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except OSError: + raise _fail("A physical directory cannot be opened safely.") from None + + +def _dotnet_executable() -> Path: + for candidate in DOTNET_EXECUTABLES: + try: + current = Path(candidate.anchor) + for index, component in enumerate(candidate.parts[1:], start=1): + current = current / component + item_stat = current.lstat() + if stat.S_ISLNK(item_stat.st_mode): + raise _fail("The fixed .NET verifier path contains a symbolic link.") + if index < len(candidate.parts) - 1 and not stat.S_ISDIR(item_stat.st_mode): + raise _fail("The fixed .NET verifier path is not a physical file path.") + item_stat = candidate.lstat() + if not stat.S_ISREG(item_stat.st_mode) or not os.access(candidate, os.X_OK): + raise _fail("The fixed .NET verifier is not an executable file.") + if candidate.resolve(strict=True) != candidate: + raise _fail("The fixed .NET verifier path is not canonical.") + return candidate + except FileNotFoundError: + continue + except OfflineFeedError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail("The fixed .NET verifier is unavailable or unsafe.") from None + raise _fail("The fixed .NET verifier was not found in the pinned image.") + + +def _parse_nuget_content_hash_output(output: bytes) -> str: + try: + lines = output.decode("utf-8", errors="strict").splitlines() + except UnicodeDecodeError: + raise _fail("NuGet verification returned non-UTF-8 output.") from None + hashes: list[str] = [] + for line in lines: + if line.startswith("Content hash:"): + match = re.fullmatch(r"Content hash: ([A-Za-z0-9+/]+={0,2})", line) + if match is None: + raise _fail("NuGet verification returned a malformed Content hash line.") + _decode_content_hash(match.group(1)) + hashes.append(match.group(1)) + if len(hashes) != 1: + raise _fail("NuGet verification did not return exactly one Content hash line.") + return hashes[0] + + +def _nuget_content_hash_verifier(archive_path: Path, timeout_seconds: float, output_limit: int) -> str: + executable = _dotnet_executable() + output = bytearray() + error_output = bytearray() + output_bytes = 0 + output_lock = threading.Lock() + output_exceeded = threading.Event() + process: subprocess.Popen[bytes] | None = None + + try: + with tempfile.TemporaryDirectory(prefix="evidence-gate-nuget-verify-") as working_directory: + verifier_environment = { + "PATH": DOTNET_PATH, + "HOME": working_directory, + "DOTNET_CLI_HOME": working_directory, + "DOTNET_CLI_TELEMETRY_OPTOUT": "1", + "DOTNET_NOLOGO": "1", + "DOTNET_CLI_UI_LANGUAGE": "en", + "LANG": "C", + "LC_ALL": "C", + } + process = subprocess.Popen( + [str(executable), "nuget", "verify", str(archive_path), "--all", "--verbosity", "minimal"], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=working_directory, + env=verifier_environment, + close_fds=True, + ) + + def drain(stream: Any, destination: bytearray) -> None: + nonlocal output_bytes + while True: + chunk = stream.read(8192) + if not chunk: + return + with output_lock: + remaining = output_limit - output_bytes + if remaining > 0: + destination.extend(chunk[:remaining]) + output_bytes += len(chunk) + if output_bytes > output_limit: + output_exceeded.set() + + assert process.stdout is not None and process.stderr is not None + readers = [ + threading.Thread(target=drain, args=(process.stdout, output), daemon=True), + threading.Thread(target=drain, args=(process.stderr, error_output), daemon=True), + ] + for reader in readers: + reader.start() + + deadline = time.monotonic() + timeout_seconds + timed_out = False + while process.poll() is None: + if output_exceeded.is_set(): + process.kill() + break + if time.monotonic() >= deadline: + timed_out = True + process.kill() + break + time.sleep(0.01) + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + for reader in readers: + reader.join(timeout=1) + if any(reader.is_alive() for reader in readers): + raise _fail("NuGet verification output could not be drained safely.") + if output_exceeded.is_set(): + raise _fail("NuGet verification exceeded its output-byte limit.") + if timed_out: + raise _fail("NuGet verification exceeded its time limit.") + if process.returncode != 0: + raise _fail("NuGet verification failed for a copied package archive.") + return _parse_nuget_content_hash_output(bytes(output) + b"\n" + bytes(error_output)) + except OfflineFeedError: + raise + except (OSError, subprocess.SubprocessError): + if process is not None and process.poll() is None: + process.kill() + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + raise _fail("NuGet verification could not be started or completed safely.") from None + finally: + if process is not None: + if process.stdout is not None: + process.stdout.close() + if process.stderr is not None: + process.stderr.close() + + +def _copy_archive(archive: _Archive, staging_name: str, output_fd: int, limits: FeedLimits) -> int: + source_fd = -1 + destination_fd = -1 + created = False + try: + source_fd = os.open(archive.source, os.O_RDONLY | _nofollow_flag()) + source_stat = os.fstat(source_fd) + if not stat.S_ISREG(source_stat.st_mode) or source_stat.st_size != archive.size: + raise _fail("A locked .nupkg archive changed after cache validation.") + destination_fd = os.open( + staging_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | _nofollow_flag(), + 0o644, + dir_fd=output_fd, + ) + created = True + copied_bytes = 0 + with os.fdopen(source_fd, "rb") as source_file, os.fdopen(destination_fd, "wb") as destination_file: + source_fd = destination_fd = -1 + while True: + chunk = source_file.read(COPY_CHUNK_BYTES) + if not chunk: + break + copied_bytes += len(chunk) + if copied_bytes > limits.max_package_bytes or copied_bytes > archive.size: + raise _fail("A locked .nupkg archive grew beyond its validated byte limit.") + destination_file.write(chunk) + destination_file.flush() + if copied_bytes != archive.size: + raise _fail("A locked .nupkg archive changed size while being copied.") + return copied_bytes + except OfflineFeedError: + if created: + try: + os.unlink(staging_name, dir_fd=output_fd) + except OSError: + pass + raise + except OSError as error: + if created: + try: + os.unlink(staging_name, dir_fd=output_fd) + except OSError: + pass + errno = error.errno if isinstance(error.errno, int) else "unknown" + raise _fail(f"A locked .nupkg archive could not be copied safely (errno {errno}).") from None + finally: + if source_fd >= 0: + os.close(source_fd) + if destination_fd >= 0: + os.close(destination_fd) + + +def _verify_copied_archive( + archive: _Archive, + copied_path: Path, + limits: FeedLimits, + started_at: float, + injected_verifier: Callable[[Path], str] | None, +) -> None: + if injected_verifier is None: + remaining_total = limits.max_total_verifier_seconds - (time.monotonic() - started_at) + if remaining_total <= 0: + raise _fail("NuGet verification exceeded the total time limit.") + actual_hash = _nuget_content_hash_verifier( + copied_path, + min(limits.max_verifier_seconds_per_archive, remaining_total), + limits.max_verifier_output_bytes, + ) + else: + actual_hash = injected_verifier(copied_path) + actual_digest = _decode_content_hash(actual_hash) + if actual_digest != archive.package.content_hash: + raise _fail("A copied .nupkg archive does not match NuGet's lock-file contentHash.") + + +def _promote_verified_archive(staging_name: str, archive_name: str, output_fd: int) -> None: + try: + os.link( + staging_name, + archive_name, + src_dir_fd=output_fd, + dst_dir_fd=output_fd, + follow_symlinks=False, + ) + os.unlink(staging_name, dir_fd=output_fd) + except OSError: + raise _fail("A NuGet-verified archive could not be promoted exclusively into the feed.") from None + + +def _remove_partial_output(parent_fd: int, output_name: str, output_fd: int, created_names: list[str]) -> None: + for name in reversed(created_names): + try: + os.unlink(name, dir_fd=output_fd) + except OSError: + pass + try: + os.close(output_fd) + except OSError: + pass + try: + os.rmdir(output_name, dir_fd=parent_fd) + except OSError: + pass + + +def build_offline_feed( + checkout: str | os.PathLike[str], + solution_relative_path: str | os.PathLike[str], + global_packages: str | os.PathLike[str], + output_directory: str | os.PathLike[str], + *, + limits: FeedLimits = DEFAULT_LIMITS, + _content_hash_verifier: Callable[[Path], str] | None = None, +) -> FeedBuildResult: + """Create a flat feed from solution-selected locks and NuGet-verified archives. + + ``checkout`` must be the trusted base checkout. ``solution_relative_path`` + must identify a trusted ``.slnx`` below it. ``global_packages`` must be a + separate physical NuGet global-packages cache, and ``output_directory`` + must be a nonexistent directory whose parent already exists. ``limits`` + can lower the reviewed hard ceilings but cannot raise them. The private + ``_content_hash_verifier`` seam exists only for synthetic tests; production + CLI calls always use the bounded fixed .NET verifier. + """ + + _validate_limits(limits) + _nofollow_flag() + checkout_root = _physical_directory(checkout, "The trusted checkout") + cache_root = _physical_directory(global_packages, "The NuGet global cache") + if _paths_overlap(checkout_root, cache_root): + raise _fail("The trusted checkout and NuGet global cache must be separate physical trees.") + output_parent, output_path = _new_output_location(output_directory, checkout_root, cache_root) + + lock_files, project_sdks = _select_lock_files(checkout_root, solution_relative_path, limits) + packages = _collect_locked_packages(lock_files, project_sdks, limits) + archives = _locate_archives(cache_root, packages, limits) + + parent_fd = _open_directory_descriptor(output_parent) + output_fd = -1 + created_names: list[str] = [] + output_created = False + try: + try: + os.mkdir(output_path.name, mode=0o700, dir_fd=parent_fd) + output_created = True + except FileExistsError: + raise _fail("The output directory must not already exist.") from None + except OSError: + raise _fail("The new output directory cannot be created safely.") from None + try: + output_fd = os.open( + output_path.name, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd, + ) + except OSError: + raise _fail("The new output directory cannot be opened safely.") from None + + total_bytes = 0 + verification_started = time.monotonic() + for index, archive in enumerate(archives): + staging_name = f".offline-feed-{index:05d}.tmp" + created_names.append(staging_name) + copied_bytes = _copy_archive(archive, staging_name, output_fd, limits) + _verify_copied_archive( + archive, + output_path / staging_name, + limits, + verification_started, + _content_hash_verifier, + ) + created_names.append(archive.package.archive_name) + _promote_verified_archive(staging_name, archive.package.archive_name, output_fd) + total_bytes += copied_bytes + if total_bytes > limits.max_total_package_bytes: + raise _fail("The copied package archives exceed the total byte limit.") + return FeedBuildResult(len(lock_files), len(archives), total_bytes) + except BaseException: + if output_created: + if output_fd < 0: + try: + output_fd = os.open( + output_path.name, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=parent_fd, + ) + except OSError: + output_fd = -1 + if output_fd >= 0: + _remove_partial_output(parent_fd, output_path.name, output_fd, created_names) + output_fd = -1 + else: + try: + os.rmdir(output_path.name, dir_fd=parent_fd) + except OSError: + pass + raise + finally: + if output_fd >= 0: + try: + os.close(output_fd) + except OSError: + pass + try: + os.close(parent_fd) + except OSError: + pass + + +def parse_arguments(argv: Sequence[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkout", required=True, help="Absolute trusted base checkout root.") + parser.add_argument("--solution", required=True, help="Trusted repository-relative .slnx project selection.") + parser.add_argument("--global-packages", required=True, help="Absolute physical NuGet global-packages cache root.") + parser.add_argument("--output", required=True, help="Absolute path to a new output feed directory.") + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> int: + args = parse_arguments(argv) + try: + result = build_offline_feed(args.checkout, args.solution, args.global_packages, args.output) + except OfflineFeedError as error: + print(f"error: {error}", file=sys.stderr) + return 2 + print( + f"verified offline feed: {result.package_count} packages from " + f"{result.lock_file_count} lock files ({result.package_bytes} bytes)" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-cleanup-attestation-check.py b/scripts/evidence-gate-cleanup-attestation-check.py new file mode 100644 index 000000000..3d2bfd396 --- /dev/null +++ b/scripts/evidence-gate-cleanup-attestation-check.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Validate and preserve one non-claiming subject cleanup attestation. + +The credentialless workflow runs this after the subject launcher, including +failure and cancellation paths. This helper accepts only the runner's private +per-run supervisor directory and its bounded, fixed-schema completion record. +It does not authenticate the subject checkout or issue an Evidence claim. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import stat +import sys +import time +from typing import Any, Callable + + +STATE_PREFIX = "appsurface-subject-supervisor-" +STATE_PATTERN = re.compile(r"appsurface-subject-supervisor-[0-9a-f]{32}\Z") +ATTESTATION_NAME = "cleanup-attestation.json" +OUTPUT_NAME = "evidence-gate-cleanup-attestation.json" +MAX_ATTESTATION_BYTES = 4096 +WAIT_SECONDS = 600 +EXPECTED_KEYS = frozenset({ + "schemaVersion", "claimEligible", "published", "status", "trigger", + "containerStatus", "mountStatus", "scratchStatus", "failureCode", + "cleanupDeadlineSeconds", +}) + + +class CleanupCheckError(Exception): + """A stable, non-sensitive failure of the cleanup-record check.""" + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def _owned_directory(path: Path, *, uid: int, mode: int | None = None) -> bool: + try: + info = path.lstat() + except OSError: + return False + return ( + stat.S_ISDIR(info.st_mode) + and info.st_uid == uid + and (mode is None or stat.S_IMODE(info.st_mode) == mode) + ) + + +def _read_attestation(path: Path, *, uid: int) -> bytes: + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(path, flags) + except OSError: + raise CleanupCheckError("cleanup-attestation-unavailable") from None + try: + info = os.fstat(descriptor) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != uid + or stat.S_IMODE(info.st_mode) != 0o600 + or info.st_nlink != 1 + or info.st_size <= 0 + or info.st_size > MAX_ATTESTATION_BYTES + ): + raise CleanupCheckError("cleanup-attestation-unsafe") + payload = os.read(descriptor, MAX_ATTESTATION_BYTES + 1) + if len(payload) != info.st_size: + raise CleanupCheckError("cleanup-attestation-unbounded") + return payload + finally: + os.close(descriptor) + + +def _validate_attestation(payload: bytes) -> None: + try: + record = json.loads(payload.decode("ascii"), object_pairs_hook=_unique_object) + except (UnicodeError, ValueError, RecursionError): + raise CleanupCheckError("cleanup-attestation-malformed") from None + if not isinstance(record, dict) or set(record) != EXPECTED_KEYS: + raise CleanupCheckError("cleanup-attestation-malformed") + if ( + type(record["schemaVersion"]) is not int + or record["schemaVersion"] != 1 + or record["claimEligible"] is not False + or record["published"] is not False + or record["status"] != "complete" + or record["trigger"] not in ("request", "parent-exit") + or record["containerStatus"] not in ("removed", "absent") + or record["mountStatus"] not in ("unmounted", "absent") + or record["scratchStatus"] not in ("removed", "absent") + or record["failureCode"] != "none" + or type(record["cleanupDeadlineSeconds"]) is not int + or record["cleanupDeadlineSeconds"] != WAIT_SECONDS + ): + raise CleanupCheckError("cleanup-incomplete") + + +def check_cleanup( + runner_temp: Path, + output: Path, + *, + uid: int | None = None, + wait_seconds: float = WAIT_SECONDS, + monotonic: Callable[[], float] = time.monotonic, + sleep: Callable[[float], None] = time.sleep, +) -> None: + """Wait for exactly one safe completion record and save its exact bytes.""" + runner_uid = os.geteuid() if uid is None else uid + if not runner_temp.is_absolute() or not _owned_directory(runner_temp, uid=runner_uid): + raise CleanupCheckError("runner-temp-unsafe") + if output != runner_temp / OUTPUT_NAME or output.exists() or output.is_symlink(): + raise CleanupCheckError("cleanup-output-unsafe") + try: + states = [item for item in runner_temp.iterdir() if item.name.startswith(STATE_PREFIX)] + except OSError: + raise CleanupCheckError("cleanup-state-unavailable") from None + if len(states) != 1 or STATE_PATTERN.fullmatch(states[0].name) is None: + raise CleanupCheckError("cleanup-state-ambiguous") + state = states[0] + if not _owned_directory(state, uid=runner_uid, mode=0o700): + raise CleanupCheckError("cleanup-state-unsafe") + + attestation = state / ATTESTATION_NAME + deadline = monotonic() + wait_seconds + while True: + try: + attestation.lstat() + break + except FileNotFoundError: + if monotonic() >= deadline: + raise CleanupCheckError("cleanup-attestation-timeout") from None + sleep(min(0.25, max(0.0, deadline - monotonic()))) + except OSError: + raise CleanupCheckError("cleanup-attestation-unavailable") from None + payload = _read_attestation(attestation, uid=runner_uid) + _validate_attestation(payload) + + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(output, flags, 0o600) + with os.fdopen(descriptor, "wb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + except OSError: + raise CleanupCheckError("cleanup-output-unavailable") from None + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runner-temp", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + try: + check_cleanup(args.runner_temp, args.output) + except CleanupCheckError as error: + print(f"subject cleanup check failed: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-controller.py b/scripts/evidence-gate-controller.py new file mode 100644 index 000000000..2f2ff953f --- /dev/null +++ b/scripts/evidence-gate-controller.py @@ -0,0 +1,929 @@ +#!/usr/bin/env python3 +"""Capture trusted pull-request revision evidence for the base-owned CI controller. + +The caller must run this from a trusted pull_request_target job with read-only +pull-request API access. The event path, repository identity, target branch, +workflow event, run ID, attempt, and token come from trusted workflow context. +The event payload is data only; no head code is checked out or executed. + +Same-repository output contains source.diff and the canonical +pull-request-run-identity.json contract object plus a retained bare Git store +at repository.git by default. Pass that path to the trusted CLI as --repository. +An optional external store must be a new path; the controller creates and +retains it on success, removes it on failure, and leaves successful-store +cleanup to the caller after the CLI has finished. Fork output contains only +observation.json and can never represent a gate-capable plan. A downstream +verifier must independently verify the plan/diff and reread current PR state +immediately before issuing a verdict. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import selectors +import signal +import shutil +import stat +import subprocess +import sys +import tempfile +import threading +import time +from typing import Any, Callable, Mapping, Sequence +from urllib.error import HTTPError, URLError +from urllib.parse import quote +from urllib.request import HTTPRedirectHandler, Request, build_opener + + +MAX_EVENT_BYTES = 1024 * 1024 +MAX_API_RESPONSE_BYTES = 64 * 1024 +MAX_SOURCE_DIFF_BYTES = 20 * 1024 * 1024 +MAX_CAPTURE_SECONDS = 120 +API_TIMEOUT_SECONDS = 10 +MAX_GIT_STDERR_BYTES = 4096 +MAX_TARGET_BRANCH_CHARS = 128 +ALLOWED_ACTIONS = frozenset({"opened", "synchronize", "reopened", "edited", "ready_for_review"}) +SHA_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +REPOSITORY_COMPONENT_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\Z") +TARGET_BRANCH_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,127}\Z") +NUMERIC_ID_PATTERN = re.compile(r"[1-9][0-9]{0,18}\Z") +GIT_DIFF_OPTIONS = ( + "-c", + "diff.external=", + "-c", + "diff.noprefix=false", + "-c", + "diff.mnemonicprefix=false", + "-c", + "diff.algorithm=myers", + "diff", + "--no-ext-diff", + "--no-textconv", + "--no-color", + "--binary", + "--full-index", + "--unified=3", + "--find-renames=50%", + "--find-copies=50%", + "--submodule=short", + "--ignore-submodules=none", + "--no-relative", + "--src-prefix=a/", + "--dst-prefix=b/", +) + + +class ControllerError(Exception): + """A fixed, bounded diagnostic safe for controller logs.""" + + +def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ControllerError("JSON contains duplicate object keys.") + result[key] = value + return result + + +def _reject_json_constant(_value: str) -> None: + raise ControllerError("JSON contains a non-standard numeric value.") + + +def _decode_json(data: bytes, maximum_bytes: int, description: str) -> Any: + if len(data) > maximum_bytes: + raise ControllerError(f"{description} exceeds its byte limit.") + try: + return json.loads( + data, + object_pairs_hook=_reject_duplicate_keys, + parse_constant=_reject_json_constant, + ) + except ControllerError: + raise + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError): + raise ControllerError(f"{description} is malformed JSON.") from None + + +def _read_event(path_value: str | os.PathLike[str]) -> Mapping[str, Any]: + raw_path = os.fspath(path_value) + if not raw_path or "\x00" in raw_path or ".." in Path(raw_path).parts: + raise ControllerError("The event path is malformed.") + path = Path(raw_path) + try: + file_descriptor = os.open( + path, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + ) + except (OSError, ValueError): + raise ControllerError("The event file is unavailable or unsafe.") from None + + try: + file_stat = os.fstat(file_descriptor) + if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > MAX_EVENT_BYTES: + raise ControllerError("The event file is not a bounded regular file.") + with os.fdopen(file_descriptor, "rb", closefd=False) as event_file: + event_bytes = event_file.read(MAX_EVENT_BYTES + 1) + if len(event_bytes) > MAX_EVENT_BYTES: + raise ControllerError("The event file exceeds its byte limit.") + finally: + os.close(file_descriptor) + + event = _decode_json(event_bytes, MAX_EVENT_BYTES, "The event file") + if not isinstance(event, dict): + raise ControllerError("The event payload must be a JSON object.") + return event + + +def _positive_integer(value: Any, name: str, maximum: int = (1 << 63) - 1) -> int: + if type(value) is not int or value <= 0 or value > maximum: + raise ControllerError(f"{name} must be a positive bounded integer.") + return value + + +def _environment_integer(value: str | None, name: str, maximum: int = (1 << 63) - 1) -> int: + if value is None or NUMERIC_ID_PATTERN.fullmatch(value) is None: + raise ControllerError(f"{name} must be a positive decimal integer.") + try: + parsed = int(value, 10) + except ValueError: + raise ControllerError(f"{name} must be a positive decimal integer.") from None + return _positive_integer(parsed, name, maximum) + + +def _full_sha(value: Any, name: str) -> str: + if not isinstance(value, str) or SHA_PATTERN.fullmatch(value) is None: + raise ControllerError(f"{name} must be a full lower-case 40- or 64-character Git object ID.") + return value + + +def _repository(value: Any, name: str) -> str: + if not isinstance(value, str) or value.count("/") != 1: + raise ControllerError(f"{name} must be an owner/repository name.") + owner, repository = value.split("/", 1) + if ( + REPOSITORY_COMPONENT_PATTERN.fullmatch(owner) is None + or REPOSITORY_COMPONENT_PATTERN.fullmatch(repository) is None + or owner in {".", ".."} + or repository in {".", ".."} + ): + raise ControllerError(f"{name} must be an owner/repository name.") + return value + + +def _target_branch(value: Any, name: str) -> str: + if ( + not isinstance(value, str) + or len(value) > MAX_TARGET_BRANCH_CHARS + or TARGET_BRANCH_PATTERN.fullmatch(value) is None + or value.endswith(("/", ".", ".lock")) + or "//" in value + or ".." in value + or "@{" in value + or any(part.startswith(".") or part.endswith(".lock") for part in value.split("/")) + ): + raise ControllerError(f"{name} is not a safe target branch name.") + return value + + +def _object_member(value: Any, name: str) -> Mapping[str, Any]: + if not isinstance(value, dict): + raise ControllerError(f"{name} is missing or malformed.") + return value + + +def _event_snapshot( + event: Mapping[str, Any], + repository: str, + repository_id: int, + target_branch: str, +) -> dict[str, Any]: + action = event.get("action") + if not isinstance(action, str) or action not in ALLOWED_ACTIONS: + raise ControllerError("The pull-request event action is not allowed.") + + pull_request = _object_member(event.get("pull_request"), "The pull request") + base = _object_member(pull_request.get("base"), "The event base") + head = _object_member(pull_request.get("head"), "The event head") + base_repository = _object_member(base.get("repo"), "The event base repository") + head_repository = _object_member(head.get("repo"), "The event head repository") + event_repository = _object_member(event.get("repository"), "The event repository") + + event_number = _positive_integer(event.get("number"), "The event pull-request number", (1 << 31) - 1) + pull_request_number = _positive_integer( + pull_request.get("number"), "The pull-request number", (1 << 31) - 1 + ) + if event_number != pull_request_number: + raise ControllerError("The event pull-request numbers do not match.") + + event_repo_id = _positive_integer(event_repository.get("id"), "The event repository ID") + event_base_repo_id = _positive_integer(base_repository.get("id"), "The event base repository ID") + event_head_repo_id = _positive_integer(head_repository.get("id"), "The event head repository ID") + if event_repo_id != repository_id or event_base_repo_id != repository_id: + raise ControllerError("The event repository identity does not match the trusted repository.") + event_repository_name = _repository( + event_repository.get("full_name"), + "The event repository name", + ) + if event_repository_name.casefold() != repository.casefold(): + raise ControllerError("The event repository name does not match the trusted repository.") + event_base_repository_name = _repository( + base_repository.get("full_name"), + "The event base repository name", + ) + if event_base_repository_name.casefold() != repository.casefold(): + raise ControllerError("The event base repository name does not match the trusted repository.") + + event_base_branch = _target_branch(base.get("ref"), "The event target branch") + if event_base_branch != target_branch: + raise ControllerError("The pull request targets an unexpected branch.") + + return { + "action": action, + "base_revision": _full_sha(base.get("sha"), "The event base revision"), + "head_revision": _full_sha(head.get("sha"), "The event head revision"), + "head_repository_id": event_head_repo_id, + "head_repository": _repository(head_repository.get("full_name"), "The event head repository name"), + "number": event_number, + "repository_id": event_repo_id, + "repository": repository, + "target_branch": event_base_branch, + } + + +def read_current_pull_request(repository: str, number: int, token: str) -> Mapping[str, Any]: + """Read the bounded authoritative PR API response without following redirects.""" + + encoded_repository = quote(repository, safe="/") + url = f"https://api.github.com/repos/{encoded_repository}/pulls/{number}" + request = Request( + url, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {token}", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "AppSurface-evidence-gate-controller", + }, + method="GET", + ) + + class NoRedirectHandler(HTTPRedirectHandler): + def redirect_request( + self, + _request: Any, + _fp: Any, + _code: int, + _message: str, + _headers: Any, + _url: str, + ) -> None: + return None + + try: + opener = build_opener(NoRedirectHandler) + with opener.open(request, timeout=API_TIMEOUT_SECONDS) as response: + if response.status != 200: + raise ControllerError("The authoritative pull-request API read failed.") + content_length = response.headers.get("Content-Length") + if content_length is not None: + if not content_length.isascii() or not content_length.isdecimal(): + raise ControllerError("The pull-request API response length is malformed.") + if int(content_length, 10) > MAX_API_RESPONSE_BYTES: + raise ControllerError("The pull-request API response exceeds its byte limit.") + body = response.read(MAX_API_RESPONSE_BYTES + 1) + except ControllerError: + raise + except (HTTPError, URLError, TimeoutError, OSError, ValueError): + raise ControllerError("The authoritative pull-request API read failed.") from None + + result = _decode_json(body, MAX_API_RESPONSE_BYTES, "The pull-request API response") + if not isinstance(result, dict): + raise ControllerError("The pull-request API response is malformed.") + return result + + +def _api_snapshot( + response: Mapping[str, Any], + repository: str, + repository_id: int, + expected_number: int, + target_branch: str, +) -> dict[str, Any]: + base = _object_member(response.get("base"), "The API base") + head = _object_member(response.get("head"), "The API head") + base_repository = _object_member(base.get("repo"), "The API base repository") + head_repository = _object_member(head.get("repo"), "The API head repository") + number = _positive_integer(response.get("number"), "The API pull-request number", (1 << 31) - 1) + if number != expected_number or response.get("state") != "open": + raise ControllerError("The authoritative pull request is not the open event pull request.") + + api_repository_id = _positive_integer(base_repository.get("id"), "The API base repository ID") + api_head_repository_id = _positive_integer(head_repository.get("id"), "The API head repository ID") + if api_repository_id != repository_id: + raise ControllerError("The API base repository identity does not match the trusted repository.") + api_base_repository_name = _repository( + base_repository.get("full_name"), + "The API base repository name", + ) + if api_base_repository_name.casefold() != repository.casefold(): + raise ControllerError("The API base repository name does not match the trusted repository.") + + branch = _target_branch(base.get("ref"), "The API target branch") + if branch != target_branch: + raise ControllerError("The current pull request targets an unexpected branch.") + return { + "base_revision": _full_sha(base.get("sha"), "The API base revision"), + "head_revision": _full_sha(head.get("sha"), "The API head revision"), + "head_repository_id": api_head_repository_id, + "head_repository": _repository(head_repository.get("full_name"), "The API head repository name"), + "number": number, + "repository_id": api_repository_id, + "repository": repository, + "target_branch": branch, + } + + +def _require_current_match(event_snapshot: Mapping[str, Any], api_snapshot: Mapping[str, Any]) -> None: + for field in ( + "base_revision", + "head_revision", + "head_repository_id", + "head_repository", + "number", + "repository_id", + "target_branch", + ): + event_value = event_snapshot[field] + api_value = api_snapshot[field] + if field == "head_repository": + matches = event_value.casefold() == api_value.casefold() + else: + matches = event_value == api_value + if not matches: + raise ControllerError("The event pull request is stale or does not match current GitHub state.") + + +def _git_environment() -> dict[str, str]: + inherited = os.environ + allowed = { + key: value + for key, value in inherited.items() + if key in { + "PATH", + "SystemRoot", + "WINDIR", + "TEMP", + "TMP", + "TMPDIR", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "http_proxy", + "https_proxy", + "no_proxy", + } + } + allowed.update( + { + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "NUL" if os.name == "nt" else os.devnull, + "GIT_CONFIG_COUNT": "0", + "GIT_CONFIG_PARAMETERS": "", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_EXTERNAL_DIFF": "", + "GIT_DIFF_OPTS": "", + "GIT_PAGER": "cat", + "GIT_TERMINAL_PROMPT": "0", + "GIT_ASKPASS": os.devnull, + "LC_ALL": "C", + } + ) + return allowed + + +def run_git_command( + arguments: Sequence[str], + *, + deadline: float, + maximum_output_bytes: int, +) -> bytes: + """Run a fixed Git argument vector while bounding time and both output streams.""" + + if not isinstance(arguments, (list, tuple)) or not arguments or any(not isinstance(arg, str) for arg in arguments): + raise ControllerError("A Git command was not supplied as a fixed argument array.") + argv = list(arguments) + if argv[0] != "git": + raise ControllerError("The controller may invoke only Git.") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ControllerError("Git capture exceeded its deadline.") + try: + process = subprocess.Popen( + argv, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + env=_git_environment(), + ) + except (OSError, ValueError): + raise ControllerError("The trusted Git process could not start.") from None + + assert process.stdout is not None + assert process.stderr is not None + selector = selectors.DefaultSelector() + selector.register(process.stdout, selectors.EVENT_READ, "stdout") + selector.register(process.stderr, selectors.EVENT_READ, "stderr") + output = bytearray() + stderr_count = 0 + try: + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ControllerError("Git capture exceeded its deadline.") + ready = selector.select(remaining) + if not ready: + raise ControllerError("Git capture exceeded its deadline.") + for key, _ in ready: + try: + chunk = os.read(key.fd, 64 * 1024) + except OSError: + raise ControllerError("The trusted Git process output could not be read.") from None + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + if key.data == "stdout": + if len(output) + len(chunk) > maximum_output_bytes: + raise ControllerError("Git output exceeds its reviewed byte limit.") + output.extend(chunk) + else: + stderr_count += len(chunk) + if stderr_count > MAX_GIT_STDERR_BYTES: + raise ControllerError("Git diagnostics exceed their reviewed byte limit.") + + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ControllerError("Git capture exceeded its deadline.") + try: + return_code = process.wait(timeout=remaining) + except subprocess.TimeoutExpired: + raise ControllerError("Git capture exceeded its deadline.") from None + if return_code != 0: + raise ControllerError("Git could not read the exact trusted commit pair.") + return bytes(output) + except BaseException: + if process.poll() is None: + try: + process.kill() + process.wait(timeout=1) + except (OSError, subprocess.TimeoutExpired): + pass + raise + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if not pipe.closed: + pipe.close() + + +GitRunner = Callable[..., bytes] +ApiClient = Callable[[str, int, str], Mapping[str, Any]] + + +def _invoke_api( + api_client: ApiClient, + repository: str, + number: int, + token: str, + deadline: float, + *, + enforce_alarm: bool, +) -> Mapping[str, Any]: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ControllerError("Pull-request capture exceeded its deadline.") + + if not enforce_alarm: + result = api_client(repository, number, token) + else: + # urllib's socket timeout is an idle timeout. A response that trickles bytes + # can otherwise hold the controller beyond the capture deadline. + if not hasattr(signal, "setitimer") or threading.current_thread() is not threading.main_thread(): + raise ControllerError("The controller cannot enforce the API deadline on this runner.") + previous_handler = signal.getsignal(signal.SIGALRM) + if signal.getitimer(signal.ITIMER_REAL)[0] > 0: + raise ControllerError("The controller cannot own the API deadline alarm.") + + def deadline_reached(_signal_number: int, _frame: Any) -> None: + raise ControllerError("Pull-request capture exceeded its deadline.") + + signal.signal(signal.SIGALRM, deadline_reached) + try: + signal.setitimer(signal.ITIMER_REAL, min(API_TIMEOUT_SECONDS, remaining)) + result = api_client(repository, number, token) + finally: + try: + signal.setitimer(signal.ITIMER_REAL, 0) + finally: + signal.signal(signal.SIGALRM, previous_handler) + + if time.monotonic() > deadline: + raise ControllerError("Pull-request capture exceeded its deadline.") + return result + + +def _invoke_git( + git_runner: GitRunner, + arguments: Sequence[str], + deadline: float, + maximum_output_bytes: int, +) -> bytes: + result = git_runner(arguments, deadline=deadline, maximum_output_bytes=maximum_output_bytes) + if not isinstance(result, bytes): + raise ControllerError("The trusted Git process returned malformed output.") + if len(result) > maximum_output_bytes: + raise ControllerError("Git output exceeds its reviewed byte limit.") + return result + + +def _git_prefix(object_store: Path) -> list[str]: + return ["git", "--no-pager", f"--git-dir={object_store}"] + + +def _capture_diff( + repository: str, + repository_id: int, + target_branch: str, + run_id: int, + run_attempt: int, + token: str, + event_path: str | os.PathLike[str], + output_path: str | os.PathLike[str], + *, + object_store_path: str | os.PathLike[str] | None = None, + api_client: ApiClient = read_current_pull_request, + git_runner: GitRunner = run_git_command, +) -> str: + if not isinstance(token, str) or not token or len(token) > 4096 or any(char.isspace() for char in token): + raise ControllerError("The read-only GitHub token is missing or malformed.") + repository = _repository(repository, "The trusted repository") + repository_id = _positive_integer(repository_id, "The trusted repository ID") + target_branch = _target_branch(target_branch, "The trusted target branch") + run_id = _positive_integer(run_id, "The workflow run ID") + run_attempt = _positive_integer(run_attempt, "The workflow run attempt", (1 << 31) - 1) + output = _validate_output_destination(output_path) + object_store, internal_store_path = _resolve_object_store(output, object_store_path) + + event = _read_event(event_path) + event_snapshot = _event_snapshot(event, repository, repository_id, target_branch) + deadline = time.monotonic() + MAX_CAPTURE_SECONDS + + try: + current = _invoke_api( + api_client, repository, event_snapshot["number"], token, deadline, + enforce_alarm=api_client is read_current_pull_request, + ) + except ControllerError: + raise + except Exception: + raise ControllerError("The authoritative pull-request API read failed.") from None + api_snapshot = _api_snapshot( + current, repository, repository_id, event_snapshot["number"], target_branch + ) + _require_current_match(event_snapshot, api_snapshot) + + identity = { + "BaseRevision": api_snapshot["base_revision"], + "HeadRevision": api_snapshot["head_revision"], + "HeadRepositoryId": api_snapshot["head_repository_id"], + "PullRequestNumber": api_snapshot["number"], + "RepositoryId": repository_id, + "TargetBranch": target_branch, + "WorkflowRunAttempt": run_attempt, + "WorkflowRunId": run_id, + } + + if api_snapshot["head_repository_id"] != repository_id: + observation = { + "Action": event_snapshot["action"], + "BaseRevision": event_snapshot["base_revision"], + "HeadRepositoryId": api_snapshot["head_repository_id"], + "HeadRevision": event_snapshot["head_revision"], + "Mode": "ObservationOnly", + "PullRequestNumber": event_snapshot["number"], + "RepositoryId": repository_id, + "TargetBranch": target_branch, + "WorkflowRunAttempt": run_attempt, + "WorkflowRunId": run_id, + } + _publish_output(output, {"observation.json": _canonical_json(observation)}) + return "observation" + + if api_snapshot["head_repository"].casefold() != repository.casefold(): + raise ControllerError("The same-repository head name does not match the trusted repository.") + if len(event_snapshot["base_revision"]) != len(event_snapshot["head_revision"]): + raise ControllerError("The pull-request Git object IDs use different formats.") + + stage: Path | None = None + owned_external_store: Path | None = None + try: + if internal_store_path is None: + try: + os.mkdir(object_store, 0o700) + except OSError: + raise ControllerError("The object-store destination could not be created safely.") from None + owned_external_store = object_store + else: + stage = _new_output_stage(output) + object_store = stage / internal_store_path + object_store.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + + prefix = _git_prefix(object_store) + _invoke_git( + git_runner, + ["git", "--no-pager", "init", "--bare", "--quiet", str(object_store)], + deadline, + 4096, + ) + repository_url = f"https://github.com/{repository}.git" + fetch_arguments = [ + *prefix, + "fetch", + "--depth=1", + "--no-tags", + "--no-recurse-submodules", + "--no-write-fetch-head", + repository_url, + f"+refs/heads/{target_branch}:refs/evidence/base", + f"+refs/pull/{event_snapshot['number']}/head:refs/evidence/head", + ] + _invoke_git(git_runner, fetch_arguments, deadline, 64 * 1024) + + fetched_base = _invoke_git( + git_runner, + [*prefix, "rev-parse", "--verify", "refs/evidence/base^{commit}"], + deadline, + 256, + ) + fetched_head = _invoke_git( + git_runner, + [*prefix, "rev-parse", "--verify", "refs/evidence/head^{commit}"], + deadline, + 256, + ) + fetched_base_id = _parse_rev_parse_output(fetched_base, "The fetched base revision") + fetched_head_id = _parse_rev_parse_output(fetched_head, "The fetched head revision") + if ( + _full_sha(fetched_base_id, "The fetched base revision") != event_snapshot["base_revision"] + or _full_sha(fetched_head_id, "The fetched head revision") != event_snapshot["head_revision"] + ): + raise ControllerError("The fetched Git refs do not match the event revisions.") + + diff_arguments = [ + *prefix, + *GIT_DIFF_OPTIONS, + event_snapshot["base_revision"], + event_snapshot["head_revision"], + "--", + ] + source_diff = _invoke_git(git_runner, diff_arguments, deadline, MAX_SOURCE_DIFF_BYTES) + + try: + current = _invoke_api( + api_client, repository, event_snapshot["number"], token, deadline, + enforce_alarm=api_client is read_current_pull_request, + ) + except ControllerError: + raise + except Exception: + raise ControllerError("The authoritative pull-request API read failed.") from None + api_snapshot = _api_snapshot( + current, repository, repository_id, event_snapshot["number"], target_branch + ) + _require_current_match(event_snapshot, api_snapshot) + if api_snapshot["head_repository_id"] != repository_id: + raise ControllerError("The pull request changed repository trust class during capture.") + + if stage is None: + stage = _new_output_stage(output) + _write_output_file(stage, "source.diff", source_diff) + _write_output_file(stage, "pull-request-run-identity.json", _canonical_json(identity)) + _publish_staged_output(output, stage) + stage = None + owned_external_store = None + return "captured" + finally: + if stage is not None: + _remove_owned_directory(stage) + if owned_external_store is not None: + _remove_owned_directory(owned_external_store) + + +def _canonical_json(value: Mapping[str, Any]) -> bytes: + """Match EvidenceCanonicalJson: compact JSON with ordinally sorted properties.""" + return json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("utf-8") + + +def _parse_rev_parse_output(output: bytes, name: str) -> str: + if len(output) not in {41, 65} or not output.endswith(b"\n") or output.count(b"\n") != 1: + raise ControllerError("Git returned malformed full commit IDs.") + try: + return _full_sha(output[:-1].decode("ascii"), name) + except UnicodeDecodeError: + raise ControllerError("Git returned malformed full commit IDs.") from None + + +def _new_destination_path(path_value: str | os.PathLike[str], name: str) -> Path: + raw_path = os.fspath(path_value) + if not raw_path or "\x00" in raw_path or ".." in Path(raw_path).parts: + raise ControllerError(f"The {name} path is malformed.") + path = Path(raw_path).absolute() + if path.name in {"", ".", ".."}: + raise ControllerError(f"The {name} path is malformed.") + return path + + +def _validate_output_destination(path_value: str | os.PathLike[str]) -> Path: + path = _new_destination_path(path_value, "output") + try: + if path.is_symlink() or path.exists(): + raise ControllerError("The output destination must not already exist.") + if not path.parent.is_dir(): + raise ControllerError("The output parent directory is unavailable.") + except OSError: + raise ControllerError("The output destination is unavailable or unsafe.") from None + return path + + +def _resolve_object_store( + output: Path, + object_store_path: str | os.PathLike[str] | None, +) -> tuple[Path, Path | None]: + if object_store_path is None: + return output / "repository.git", Path("repository.git") + + object_store = _new_destination_path(object_store_path, "object-store") + if object_store == output: + raise ControllerError("The object-store path must be distinct from the output directory.") + if output in object_store.parents: + relative = object_store.relative_to(output) + if object_store.exists() or object_store.is_symlink(): + raise ControllerError("The object-store destination must not already exist.") + if any(part in {"", ".", ".."} for part in relative.parts): + raise ControllerError("The object-store path is malformed.") + return object_store, relative + if object_store in output.parents: + raise ControllerError("The external object-store path must not contain the output directory.") + try: + if object_store.exists() or object_store.is_symlink(): + raise ControllerError("The object-store destination must not already exist.") + if not object_store.parent.is_dir(): + raise ControllerError("The object-store parent directory is unavailable.") + except OSError: + raise ControllerError("The object-store destination is unavailable or unsafe.") from None + return object_store, None + + +def _new_output_stage(destination: Path) -> Path: + try: + stage = Path(tempfile.mkdtemp(prefix=f".{destination.name}.stage-", dir=destination.parent)) + os.chmod(stage, 0o700) + return stage + except OSError: + raise ControllerError("The trusted capture staging directory could not be created.") from None + + +def _write_output_file(stage: Path, filename: str, content: bytes) -> None: + if filename not in { + "source.diff", + "pull-request-run-identity.json", + "observation.json", + }: + raise ControllerError("The controller attempted to publish an unexpected file.") + file_path = stage / filename + try: + descriptor = os.open( + file_path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0), + 0o600, + ) + with os.fdopen(descriptor, "wb") as output_file: + output_file.write(content) + output_file.flush() + os.fsync(output_file.fileno()) + except OSError: + raise ControllerError("The trusted capture output could not be written.") from None + + +def _publish_staged_output(destination: Path, stage: Path) -> None: + try: + directory_descriptor = os.open(stage, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(directory_descriptor) + finally: + os.close(directory_descriptor) + if destination.exists() or destination.is_symlink(): + raise ControllerError("The output destination changed during capture.") + os.rename(stage, destination) + parent_descriptor = os.open(destination.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(parent_descriptor) + finally: + os.close(parent_descriptor) + except ControllerError: + raise + except OSError: + raise ControllerError("The trusted capture output could not be published atomically.") from None + + +def _remove_owned_directory(path: Path) -> None: + try: + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + except OSError: + # Keep the primary capture failure; the job remains failed and the directory + # is still at a controller-generated, caller-selected path for operator cleanup. + pass + + +def _publish_output(destination: Path, files: Mapping[str, bytes]) -> None: + stage: Path | None = None + try: + stage = _new_output_stage(destination) + for filename, content in files.items(): + _write_output_file(stage, filename, content) + _publish_staged_output(destination, stage) + stage = None + finally: + if stage is not None: + _remove_owned_directory(stage) + + +def _read_context(environment: Mapping[str, str]) -> dict[str, Any]: + event_name = environment.get("GITHUB_EVENT_NAME") + if event_name != "pull_request_target": + raise ControllerError("This controller accepts only pull_request_target events.") + token = environment.get("GITHUB_TOKEN") + if token is None: + raise ControllerError("The read-only GitHub token is missing.") + return { + "repository": _repository(environment.get("GITHUB_REPOSITORY"), "The trusted repository"), + "repository_id": _environment_integer(environment.get("GITHUB_REPOSITORY_ID"), "GITHUB_REPOSITORY_ID"), + "event_name": event_name, + "run_id": _environment_integer(environment.get("GITHUB_RUN_ID"), "GITHUB_RUN_ID"), + "run_attempt": _environment_integer( + environment.get("GITHUB_RUN_ATTEMPT"), "GITHUB_RUN_ATTEMPT", (1 << 31) - 1 + ), + "token": token, + } + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--event", required=True, help="Path to the bounded GitHub event JSON file.") + parser.add_argument("--output", required=True, help="New output directory under an existing trusted parent.") + parser.add_argument("--target-branch", required=True, help="Trusted allowed target branch, such as main.") + parser.add_argument( + "--object-store", + help=( + "Optional new bare Git object-store path. If omitted, the retained store is OUTPUT/repository.git. " + "The caller owns cleanup after the trusted CLI has finished using it." + ), + ) + arguments = parser.parse_args(argv) + try: + context = _read_context(os.environ) + result = _capture_diff( + repository=context["repository"], + repository_id=context["repository_id"], + target_branch=arguments.target_branch, + run_id=context["run_id"], + run_attempt=context["run_attempt"], + token=context["token"], + event_path=arguments.event, + output_path=arguments.output, + object_store_path=arguments.object_store, + ) + except ControllerError as failure: + print(f"evidence-gate-controller: {failure}", file=sys.stderr) + return 2 + except (OSError, ValueError): + print("evidence-gate-controller: trusted capture failed closed.", file=sys.stderr) + return 2 + if result == "observation": + print("evidence-gate-controller: fork observation metadata captured; no gate claim is available.") + else: + print("evidence-gate-controller: exact same-repository source diff captured.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-finalize.py b/scripts/evidence-gate-finalize.py new file mode 100644 index 000000000..9324bc3a1 --- /dev/null +++ b/scripts/evidence-gate-finalize.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Publish the trusted PR verifier's one bounded GitHub and terminal verdict. + +This runs only in the base-owned verifier job. It never consumes subject output +directly: the C# verifier has already checked the plan, manifest, GitHub state, +and any selected artifacts before writing these three create-new result files. +An absent, inconsistent, or ineligible result fails closed. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import stat +import sys + + +MAX_RESULT_BYTES = 4 * 1024 * 1024 +MAX_SUMMARY_BYTES = 128 * 1024 +CODE_PATTERN = re.compile(r"ASE[A-Z]{2,4}[0-9]{3}\Z") +FALLBACK_CODE = "ASEGH003" +FALLBACK_MARKDOWN = ( + b"## AppSurface evidence gate\n\n" + b"- Verdict: **ineligible** (`ASEGH003`)\n" + b"- Verified claim: `None`\n" + b"- Diagnostic: A trusted gate result is unavailable or incomplete.\n" +) + + +class VerdictError(Exception): + """A missing or inconsistent trusted verifier result.""" + + +def _read_regular(path: Path, maximum_bytes: int) -> bytes: + descriptor = -1 + try: + descriptor = os.open( + path, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), + ) + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or not 0 < before.st_size <= maximum_bytes: + raise VerdictError("The trusted verifier output is missing or unsafe.") + data = bytearray() + while len(data) <= maximum_bytes: + chunk = os.read(descriptor, min(64 * 1024, maximum_bytes + 1 - len(data))) + if not chunk: + break + data.extend(chunk) + after = os.fstat(descriptor) + if ( + len(data) != before.st_size + or len(data) > maximum_bytes + or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) + != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + ): + raise VerdictError("The trusted verifier output changed or exceeded its bound.") + return bytes(data) + except (OSError, ValueError) as error: + raise VerdictError("The trusted verifier output is unavailable.") from error + finally: + if descriptor >= 0: + os.close(descriptor) + + +def _json_object(data: bytes) -> dict[str, object]: + try: + value = json.loads( + data, + object_pairs_hook=_unique_object, + parse_constant=_reject_non_json_number, + ) + except (UnicodeDecodeError, ValueError, RecursionError) as error: + raise VerdictError("The trusted verifier JSON is malformed.") from error + if not isinstance(value, dict): + raise VerdictError("The trusted verifier JSON has no object result.") + return value + + +def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("Duplicate JSON property") + result[key] = value + return result + + +def _reject_non_json_number(_: str) -> None: + raise ValueError("Non-JSON numeric value") + + +def _verified_verdict(directory: Path) -> tuple[bool, str, bytes]: + machine = _json_object(_read_regular(directory / "evidence-gate-verification.json", MAX_RESULT_BYTES)) + summary = _json_object(_read_regular(directory / "evidence-gate-summary.json", MAX_SUMMARY_BYTES)) + markdown = _read_regular(directory / "evidence-gate-summary.md", MAX_SUMMARY_BYTES) + try: + markdown.decode("utf-8") + except UnicodeDecodeError as error: + raise VerdictError("The trusted verifier Markdown is malformed.") from error + + eligible = machine.get("IsEligible") + code = machine.get("Code") + diagnostic = machine.get("Diagnostic") + plan_summary = machine.get("Summary") + if ( + set(machine) != {"IsEligible", "Code", "Diagnostic", "Summary"} + or set(summary) != {"eligible", "code", "diagnostic", "summary"} + or type(eligible) is not bool + or not isinstance(code, str) + or CODE_PATTERN.fullmatch(code) is None + or not isinstance(diagnostic, str) + or not 0 < len(diagnostic) <= 1024 + or (eligible and (code != "ASEVG000" or not isinstance(plan_summary, dict))) + or (not eligible and code == "ASEVG000") + or (plan_summary is not None and not isinstance(plan_summary, dict)) + or summary.get("eligible") is not eligible + or summary.get("code") != code + or summary.get("diagnostic") != diagnostic + or summary.get("summary") != plan_summary + ): + raise VerdictError("The trusted verifier outputs disagree.") + + has_evidence = plan_summary.get("ProfileHasEvidence") if isinstance(plan_summary, dict) else None + if eligible and type(has_evidence) is not bool: + raise VerdictError("The trusted verifier omitted the claim shape.") + claim = "None" if not eligible else "TargetedComplete" if has_evidence else "NoEvidenceRequired" + expected_header = ( + f"## AppSurface evidence gate\n\n" + f"- Verdict: **{'eligible' if eligible else 'ineligible'}** (`{code}`)\n" + f"- Verified claim: `{claim}`\n" + ).encode("utf-8") + if not markdown.startswith(expected_header): + raise VerdictError("The trusted verifier Markdown disagrees with the machine result.") + return eligible, code, markdown + + +def _append_summary(path: Path, content: bytes) -> None: + descriptor = -1 + try: + descriptor = os.open( + path, + os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1: + raise VerdictError("The GitHub step summary path is unsafe.") + with os.fdopen(descriptor, "ab", closefd=True) as stream: + descriptor = -1 + stream.write(content) + stream.flush() + except OSError as error: + raise VerdictError("The GitHub step summary could not be written.") from error + finally: + if descriptor >= 0: + os.close(descriptor) + + +def finalize( + verdict_directory: Path, + step_summary: Path, + controller_outcome: str, + subject_outcome: str, + verifier_outcome: str, +) -> int: + upstream_success = all( + outcome == "success" for outcome in (controller_outcome, subject_outcome, verifier_outcome) + ) + try: + eligible, code, markdown = _verified_verdict(verdict_directory) + except VerdictError: + eligible, code, markdown = False, FALLBACK_CODE, FALLBACK_MARKDOWN + + if not upstream_success: + eligible = False + if code == "ASEVG000": + code, markdown = FALLBACK_CODE, FALLBACK_MARKDOWN + + try: + _append_summary(step_summary, markdown) + except VerdictError: + print("gate=ineligible; code=ASEGH003; claim=None") + print("ASEGH003: The trusted GitHub summary could not be published; no gate claim was issued.", file=sys.stderr) + return 2 + + claim = "None" + if eligible: + claim = "TargetedComplete" if b"- Verified claim: `TargetedComplete`" in markdown else "NoEvidenceRequired" + print(f"gate={'eligible' if eligible else 'ineligible'}; code={code}; claim={claim}") + if not eligible: + print(f"{code}: A complete trusted gate claim is unavailable.", file=sys.stderr) + return 2 + return 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--verdict-directory", type=Path, required=True) + parser.add_argument("--step-summary", type=Path, required=True) + parser.add_argument("--controller-outcome", required=True) + parser.add_argument("--subject-outcome", required=True) + parser.add_argument("--verifier-outcome", required=True) + arguments = parser.parse_args() + return finalize( + arguments.verdict_directory, + arguments.step_summary, + arguments.controller_outcome, + arguments.subject_outcome, + arguments.verifier_outcome, + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-handoff.py b/scripts/evidence-gate-handoff.py new file mode 100644 index 000000000..ec100e7d7 --- /dev/null +++ b/scripts/evidence-gate-handoff.py @@ -0,0 +1,1920 @@ +#!/usr/bin/env python3 +"""Create and consume the private, bounded controller-to-subject handoff. + +The controller uses ``create`` after exact PR capture and base-owned v2 policy +planning. It archives only the captured head commit from the retained trusted +Git store and binds the archive, source diff, plan, and run identity. The +credentialless subject job uses ``execute`` to validate that bundle. An +explicitly empty documentation profile needs no OCI run; the supported code +profile materializes a regular-file-only snapshot and invokes the fixed offline +OCI launcher. The subject result is always non-claiming. + +No GitHub token, trusted object store, executable policy authority, or verifier +input is included in the subject artifact. The bounded plan carries a policy +snapshot as data; the trusted verifier independently resolves it from its own +base-owned policy. The artifact is private to one workflow run and attempt; +its contents remain untrusted after crossing the job boundary. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import selectors +import shutil +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from typing import Any, Mapping, Sequence + + +MAX_SOURCE_DIFF_BYTES = 20 * 1024 * 1024 +MAX_COBERTURA_ARTIFACT_BYTES = 20 * 1024 * 1024 +MAX_GATE_MARKDOWN_ARTIFACT_BYTES = 1 * 1024 * 1024 +MAX_GATE_JSON_ARTIFACT_BYTES = 4 * 1024 * 1024 +MAX_EVIDENCE_PLAN_BYTES = 4 * 1024 * 1024 +MAX_SNAPSHOT_ARCHIVE_BYTES = 256 * 1024 * 1024 +MAX_SNAPSHOT_EXPANDED_BYTES = 256 * 1024 * 1024 +MAX_SNAPSHOT_FILES = 250_000 +MAX_GIT_TREE_INVENTORY_BYTES = 64 * 1024 * 1024 +MAX_GIT_ARCHIVE_SECONDS = 120 +MAX_EXTRACT_SECONDS = 300 +MAX_TRUSTED_SCRIPT_BYTES = 128 * 1024 +MAX_RESULT_BYTES = 16 * 1024 +MAX_TOTAL_HANDOFF_BYTES = MAX_SOURCE_DIFF_BYTES + MAX_EVIDENCE_PLAN_BYTES + MAX_SNAPSHOT_ARCHIVE_BYTES + 512 * 1024 +MAX_GIT_STDERR_BYTES = 4096 +SHA_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +SHA256_PATTERN = re.compile(r"[0-9a-f]{64}\Z") +SUBJECT_IMAGE_PATTERN = re.compile( + r"ghcr\.io/forge-trust/appsurface-subject-native-validation@sha256:[0-9a-f]{64}\Z" +) +SUBJECT_ARTIFACTS = ( + ("cobertura", "coverage/coverage-merged/coverage.cobertura.xml", MAX_COBERTURA_ARTIFACT_BYTES), + ("gate-report", "coverage/coverage-gate/coverage-gate.md", MAX_GATE_MARKDOWN_ARTIFACT_BYTES), + ("diagnostics", "coverage/coverage-gate/coverage-gate.json", MAX_GATE_JSON_ARTIFACT_BYTES), +) +SUBJECT_ARTIFACT_EXPORT_BASENAMES = ("cobertura.xml", "gate-report.md", "diagnostics.json") +POSITIVE_DECIMAL_PATTERN = re.compile(r"[1-9][0-9]{0,18}\Z") +SUBJECT_RESULT_STEP_NAMES = ( + "dotnet-sdk-version", + "dotnet-runtime-list", + "offline-locked-restore", + "coverage-run", + "coverage-gate", +) +TRUSTED_SUBJECT_FILES = ( + "evidence-gate-handoff.py", + "evidence-gate-subject.py", + "evidence-gate-subject-supervisor.py", + "evidence-gate-cleanup-attestation-check.py", + "evidence-gate-subject-entrypoint.py", +) +SUBJECT_IMAGE_ENVIRONMENT_VARIABLE = "EVIDENCE_GATE_SUBJECT_IMAGE" +SUBJECT_LIMITS = { + "timeout_seconds": 1200, + "memory_mib": 4096, + "cpu_millis": 2000, + "pids": 256, + "output_bytes": 1024 * 1024, +} + + +class HandoffError(Exception): + """A stable bounded failure code suitable for an untrusted subject job.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +def _canonical_json(value: Mapping[str, Any]) -> bytes: + return json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("ascii") + + +def _validate_subject_execution_record( + value: Any, + *, + require_complete: bool, +) -> Mapping[str, Any]: + if not isinstance(value, dict): + raise HandoffError("ASEHB001", "The fixed subject execution record is missing or malformed.") + status = value.get("status") + expected_keys = {"claimEligible", "profileId", "schemaVersion", "status", "steps"} + if status == "failed": + expected_keys.add("diagnostic") + elif status == "completed": + expected_keys.add("artifacts") + if ( + set(value) != expected_keys + or value.get("claimEligible") is not False + or value.get("profileId") != "code-coverage" + or type(value.get("schemaVersion")) is not int + or value["schemaVersion"] != 1 + or not isinstance(status, str) + or status not in {"completed", "failed"} + or (require_complete and status != "completed") + or not isinstance(value.get("steps"), list) + ): + raise HandoffError("ASEHB001", "The fixed subject execution record has an unexpected shape.") + + steps = value["steps"] + if len(steps) > len(SUBJECT_RESULT_STEP_NAMES): + raise HandoffError("ASEHB001", "The fixed subject execution record has too many steps.") + total_output_bytes = 0 + for index, step in enumerate(steps): + if ( + not isinstance(step, dict) + or set(step) != {"exitCode", "name", "outputBytes", "stderrSha256", "stdoutSha256"} + or index >= len(SUBJECT_RESULT_STEP_NAMES) + or step.get("name") != SUBJECT_RESULT_STEP_NAMES[index] + or type(step.get("exitCode")) is not int + or type(step.get("outputBytes")) is not int + or step["outputBytes"] < 0 + or not isinstance(step.get("stdoutSha256"), str) + or SHA256_PATTERN.fullmatch(step["stdoutSha256"]) is None + or not isinstance(step.get("stderrSha256"), str) + or SHA256_PATTERN.fullmatch(step["stderrSha256"]) is None + ): + raise HandoffError("ASEHB001", "The fixed subject execution record contains malformed step proof.") + total_output_bytes += step["outputBytes"] + if total_output_bytes > SUBJECT_LIMITS["output_bytes"]: + raise HandoffError("ASEHB001", "The fixed subject execution record exceeds its output budget.") + if index + 1 < len(steps) and step["exitCode"] != 0: + raise HandoffError("ASEHB001", "A subject execution step failed before later steps were recorded.") + + if status == "completed" and ( + tuple(step["name"] for step in steps) != SUBJECT_RESULT_STEP_NAMES + or any(step["exitCode"] != 0 for step in steps) + ): + raise HandoffError("ASEHB001", "The completed subject execution omitted a required successful step.") + if status == "failed": + diagnostic = value.get("diagnostic") + if ( + not isinstance(diagnostic, dict) + or set(diagnostic) != {"code", "message"} + or not isinstance(diagnostic.get("code"), str) + or not isinstance(diagnostic.get("message"), str) + ): + raise HandoffError("ASEHB001", "The failed subject execution omitted its typed diagnostic.") + else: + _validate_subject_artifacts(value.get("artifacts")) + return value + + +def _validate_subject_artifacts(value: Any) -> None: + if not isinstance(value, list) or len(value) != len(SUBJECT_ARTIFACTS): + raise HandoffError("ASEHB001", "The completed subject execution omitted its fixed coverage artifact index.") + for artifact, (logical_name, relative_path, maximum_bytes) in zip(value, SUBJECT_ARTIFACTS, strict=True): + if ( + not isinstance(artifact, dict) + or set(artifact) != {"logicalName", "relativePath", "byteCount", "sha256"} + or artifact.get("logicalName") != logical_name + or artifact.get("relativePath") != relative_path + or type(artifact.get("byteCount")) is not int + or not 0 < artifact["byteCount"] <= maximum_bytes + or not isinstance(artifact.get("sha256"), str) + or SHA256_PATTERN.fullmatch(artifact["sha256"]) is None + ): + raise HandoffError("ASEHB001", "The completed subject execution has an unsafe or malformed coverage artifact index.") + + +def _make_execution_receipt(record: Mapping[str, Any], binding: Mapping[str, str]) -> dict[str, Any]: + validated_record = _validate_subject_execution_record( + record, + require_complete=record.get("status") == "completed", + ) + payload = {"binding": dict(binding), "record": dict(validated_record), "schemaVersion": 1} + digest = hashlib.sha256(_canonical_json(payload)).hexdigest() + return {**payload, "sha256": digest} + + +def _execution_receipt_binding( + identity: Mapping[str, Any], + manifest: Mapping[str, Any], + profile_id: str, +) -> dict[str, str]: + return { + "baseRevision": str(identity["BaseRevision"]), + "headRevision": str(identity["HeadRevision"]), + "profileId": profile_id, + "snapshotSha256": str(manifest["SnapshotArchiveSha256"]), + "workflowRunAttempt": str(identity["WorkflowRunAttempt"]), + "workflowRunId": str(identity["WorkflowRunId"]), + } + + +def _validate_execution_receipt( + value: Any, + *, + expected_binding: Mapping[str, str], +) -> None: + if not isinstance(value, dict) or set(value) != {"binding", "record", "schemaVersion", "sha256"}: + raise HandoffError("ASEHB001", "The bounded execution receipt has an unexpected shape.") + if type(value.get("schemaVersion")) is not int or value["schemaVersion"] != 1: + raise HandoffError("ASEHB001", "The bounded execution receipt schema version is unsupported.") + binding = value.get("binding") + if not isinstance(binding, dict) or binding != dict(expected_binding): + raise HandoffError("ASEHB001", "The execution receipt is bound to a different run, revision, profile, or snapshot.") + if not isinstance(value.get("sha256"), str) or SHA256_PATTERN.fullmatch(value["sha256"]) is None: + raise HandoffError("ASEHB001", "The execution receipt digest is malformed.") + record = _validate_subject_execution_record(value.get("record"), require_complete=True) + try: + digest = hashlib.sha256( + _canonical_json({"binding": binding, "record": record, "schemaVersion": value["schemaVersion"]}) + ).hexdigest() + except (TypeError, ValueError, RecursionError): + raise HandoffError("ASEHB001", "The bounded execution receipt could not be canonicalized.") from None + if value["sha256"] != digest: + raise HandoffError("ASEHB001", "The bounded execution receipt digest does not match its contents.") + + +def _validate_envelope_observation(value: Any, *, expected_image_digest: str) -> Mapping[str, Any]: + """Require the fixed host-side OCI observations, without treating them as a claim.""" + if ( + not isinstance(expected_image_digest, str) + or SUBJECT_IMAGE_PATTERN.fullmatch(expected_image_digest) is None + or not isinstance(value, dict) + or set(value) != { + "schemaVersion", "imageDigest", "profileId", "runnerEnvironment", "runtime", + "networkMode", "rootfsReadOnlyConfigured", "subjectAndDiffReadOnlyConfigured", + "scratchTmpfsQuotaVerified", "capabilityDropConfigured", "noNewPrivilegesConfigured", + "pidIpcUtsUserNamespacesConfiguredPrivate", "resourceLimitsConfigured", + } + or type(value.get("schemaVersion")) is not int + or value["schemaVersion"] != 1 + or value.get("imageDigest") != expected_image_digest + or value.get("profileId") != "code-coverage" + or value.get("runnerEnvironment") != "github-hosted" + or value.get("runtime") != "rootless-podman" + or value.get("networkMode") != "none" + or any(value.get(key) is not True for key in ( + "rootfsReadOnlyConfigured", "subjectAndDiffReadOnlyConfigured", "scratchTmpfsQuotaVerified", + "capabilityDropConfigured", "noNewPrivilegesConfigured", + "pidIpcUtsUserNamespacesConfiguredPrivate", "resourceLimitsConfigured", + )) + ): + raise HandoffError("ASEHB013", "The host-side subject envelope observation is missing or inconsistent.") + return value + + +def _make_envelope_receipt( + observation: Mapping[str, Any], binding: Mapping[str, str], *, expected_image_digest: str +) -> dict[str, Any]: + record = _validate_envelope_observation(observation, expected_image_digest=expected_image_digest) + payload = {"binding": dict(binding), "observation": dict(record), "schemaVersion": 1} + return {**payload, "sha256": hashlib.sha256(_canonical_json(payload)).hexdigest()} + + +def _validate_envelope_receipt( + value: Any, *, expected_binding: Mapping[str, str], expected_image_digest: str +) -> None: + if ( + not isinstance(value, dict) + or set(value) != {"binding", "observation", "schemaVersion", "sha256"} + or type(value.get("schemaVersion")) is not int + or value["schemaVersion"] != 1 + or value.get("binding") != dict(expected_binding) + or not isinstance(value.get("sha256"), str) + or SHA256_PATTERN.fullmatch(value["sha256"]) is None + ): + raise HandoffError("ASEHB013", "The subject envelope receipt is malformed or bound to another run.") + observation = _validate_envelope_observation( + value.get("observation"), expected_image_digest=expected_image_digest + ) + try: + digest = hashlib.sha256(_canonical_json({ + "binding": value["binding"], "observation": observation, "schemaVersion": 1, + })).hexdigest() + except (TypeError, ValueError, RecursionError): + raise HandoffError("ASEHB013", "The subject envelope receipt could not be canonicalized.") from None + if digest != value["sha256"]: + raise HandoffError("ASEHB013", "The subject envelope receipt digest does not match its contents.") + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def _reject_json_constant(_value: str) -> None: + raise ValueError("non-standard JSON constant") + + +def _read_json(path: Path, maximum_bytes: int, description: str) -> tuple[Mapping[str, Any], bytes]: + raw = _read_regular_file(path, maximum_bytes, description) + try: + parsed = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_reject_json_constant) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise HandoffError("ASEHB001", f"{description} is malformed JSON.") from None + if not isinstance(parsed, dict) or _canonical_json(parsed) != raw: + raise HandoffError("ASEHB001", f"{description} is not a canonical JSON object.") + return parsed, raw + + +def _canonical_evidence_json(value: Mapping[str, Any]) -> bytes: + """Match EvidenceCanonicalJson's compact, ordinal-property UTF-8 representation.""" + encoded = _canonical_json(value) + escaped_ascii = { + ord("+"): b"\\u002B", + ord("<"): b"\\u003C", + ord(">"): b"\\u003E", + ord("&"): b"\\u0026", + ord("'"): b"\\u0027", + ord("`"): b"\\u0060", + } + output = bytearray() + in_string = False + index = 0 + while index < len(encoded): + character = encoded[index] + if character == ord('"'): + in_string = not in_string + output.append(character) + elif in_string and character == ord("\\") and index + 1 < len(encoded): + next_character = encoded[index + 1] + if next_character == ord('"'): + output.extend(b"\\u0022") + elif next_character == ord("u") and index + 5 < len(encoded): + output.extend(b"\\u" + encoded[index + 2 : index + 6].upper()) + index += 4 + else: + output.extend(encoded[index : index + 2]) + index += 1 + elif in_string and character in escaped_ascii: + output.extend(escaped_ascii[character]) + else: + output.append(character) + index += 1 + return bytes(output) + + +def _read_evidence_plan(path: Path) -> tuple[Mapping[str, Any], bytes]: + raw = _read_regular_file(path, MAX_EVIDENCE_PLAN_BYTES, "The base-owned EvidencePlan") + try: + parsed = json.loads( + raw.decode("utf-8"), + object_pairs_hook=_unique_object, + parse_constant=_reject_json_constant, + ) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise HandoffError("ASEHB001", "The base-owned EvidencePlan is malformed JSON.") from None + try: + canonical = _canonical_evidence_json(parsed) if isinstance(parsed, dict) else b"" + except (TypeError, ValueError, RecursionError): + raise HandoffError("ASEHB001", "The base-owned EvidencePlan is not a bounded canonical JSON object.") from None + if not isinstance(parsed, dict) or canonical != raw: + raise HandoffError("ASEHB001", "The base-owned EvidencePlan is not a canonical JSON object.") + return parsed, raw + + +def _validate_evidence_plan( + plan: Mapping[str, Any], + identity: Mapping[str, Any], + source_diff_digest: str, +) -> None: + required = { + "BaseRevision", + "ChangedPaths", + "ContractVersion", + "DiffDigest", + "HeadRevision", + "MatchedRuleIds", + "NameStatusDigest", + "PlanDigest", + "PolicyDigest", + "PolicyId", + "PolicySnapshot", + "Profile", + "PullRequestRunIdentity", + "SourceDiffDigest", + } + if not required.issubset(plan) or plan.get("ContractVersion") != "2.0": + raise HandoffError("ASEHB001", "The handoff requires a revision-bound EvidencePlan contract version 2.0.") + for key in ("BaseRevision", "HeadRevision"): + value = plan.get(key) + if not isinstance(value, str) or SHA_PATTERN.fullmatch(value) is None or value != identity[key]: + raise HandoffError("ASEHB001", f"The EvidencePlan {key} does not match the captured pull-request identity.") + for key in ("PlanDigest", "PolicyDigest", "DiffDigest", "NameStatusDigest"): + if not isinstance(plan.get(key), str) or re.fullmatch(r"[0-9a-f]{64}", plan[key]) is None: + raise HandoffError("ASEHB001", f"The EvidencePlan {key} is not a lower-case SHA-256 digest.") + if plan.get("SourceDiffDigest") != source_diff_digest: + raise HandoffError("ASEHB001", "The EvidencePlan source diff digest does not match the captured source diff.") + if not isinstance(plan.get("ChangedPaths"), list) or not isinstance(plan.get("MatchedRuleIds"), list): + raise HandoffError("ASEHB001", "The EvidencePlan change inventory is malformed.") + if not isinstance(plan.get("PolicyId"), str) or not plan["PolicyId"] or len(plan["PolicyId"]) > 128: + raise HandoffError("ASEHB001", "The EvidencePlan policy identifier is malformed.") + + plan_identity = plan.get("PullRequestRunIdentity") + identity_fields = { + "RepositoryId", + "HeadRepositoryId", + "PullRequestNumber", + "TargetBranch", + "WorkflowRunId", + "WorkflowRunAttempt", + } + expected_identity = {key: identity[key] for key in identity_fields} + if not isinstance(plan_identity, dict) or set(plan_identity) != identity_fields: + raise HandoffError("ASEHB001", "The EvidencePlan pull-request run identity has an unexpected shape.") + for key, expected in expected_identity.items(): + actual = plan_identity[key] + if type(actual) is not type(expected) or actual != expected: + raise HandoffError("ASEHB001", "The EvidencePlan pull-request run identity does not match the controller capture.") + + profile = plan.get("Profile") + if not isinstance(profile, dict): + raise HandoffError("ASEHB001", "The EvidencePlan selected profile is malformed.") + profile_id = profile.get("Id") + if ( + not isinstance(profile_id, str) + or len(profile_id) > 64 + or re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", profile_id) is None + ): + raise HandoffError("ASEHB001", "The EvidencePlan profile identifier is not bounded.") + if profile.get("Scope") != "Targeted" or any( + not isinstance(profile.get(key), list) for key in ("Resources", "Producers", "Obligations") + ): + raise HandoffError("ASEHB001", "The EvidencePlan profile is not a well-formed targeted profile.") + + policy = plan.get("PolicySnapshot") + profiles = policy.get("Profiles") if isinstance(policy, dict) else None + if not isinstance(profiles, list): + raise HandoffError("ASEHB001", "The EvidencePlan policy snapshot has no closed profile set.") + matching_profiles = [item for item in profiles if isinstance(item, dict) and item.get("Id") == profile_id] + if len(matching_profiles) != 1 or matching_profiles[0] != profile: + raise HandoffError("ASEHB001", "The EvidencePlan profile is not closed by its policy snapshot.") + if profile_id == "documentation-only" and any(profile[key] for key in ("Resources", "Producers", "Obligations")): + raise HandoffError("ASEHB001", "The documentation-only EvidencePlan profile must be explicitly empty.") + + +def _read_regular_file(path: Path, maximum_bytes: int, description: str) -> bytes: + try: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)) + except (OSError, ValueError): + raise HandoffError("ASEHB001", f"{description} is unavailable or unsafe.") from None + try: + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > maximum_bytes: + raise HandoffError("ASEHB001", f"{description} is not a bounded regular file.") + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(descriptor, min(1024 * 1024, maximum_bytes + 1 - total)) + if not chunk: + break + chunks.append(chunk) + total += len(chunk) + if total > maximum_bytes: + raise HandoffError("ASEHB001", f"{description} exceeds its byte limit.") + return b"".join(chunks) + except OSError: + raise HandoffError("ASEHB001", f"{description} could not be read safely.") from None + finally: + os.close(descriptor) + + +def _write_regular_file(path: Path, content: bytes, mode: int = 0o600) -> None: + try: + descriptor = os.open( + path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + mode, + ) + with os.fdopen(descriptor, "wb") as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + except OSError: + raise HandoffError("ASEHB002", "The private handoff could not be written safely.") from None + + +def _positive_integer(value: Any, name: str) -> int: + if type(value) is not int or value <= 0 or value > (1 << 63) - 1: + raise HandoffError("ASEHB001", f"{name} is not a positive bounded integer.") + return value + + +def _validate_identity(identity: Mapping[str, Any]) -> None: + required = { + "BaseRevision", + "HeadRevision", + "HeadRepositoryId", + "PullRequestNumber", + "RepositoryId", + "TargetBranch", + "WorkflowRunAttempt", + "WorkflowRunId", + } + if set(identity) != required: + raise HandoffError("ASEHB001", "The captured pull-request identity has an unexpected shape.") + if identity["HeadRepositoryId"] != identity["RepositoryId"]: + raise HandoffError("ASEHB001", "A credentialless subject snapshot requires a same-repository pull request.") + for key in ("BaseRevision", "HeadRevision"): + if not isinstance(identity[key], str) or SHA_PATTERN.fullmatch(identity[key]) is None: + raise HandoffError("ASEHB001", f"The captured {key} is not a full lower-case Git object ID.") + if len(identity["BaseRevision"]) != len(identity["HeadRevision"]): + raise HandoffError("ASEHB001", "The captured commit IDs use different Git object formats.") + for key in ("HeadRepositoryId", "PullRequestNumber", "RepositoryId", "WorkflowRunAttempt", "WorkflowRunId"): + _positive_integer(identity[key], key) + branch = identity["TargetBranch"] + if not isinstance(branch, str) or not branch or len(branch) > 128 or any(c in branch for c in "\x00\r\n"): + raise HandoffError("ASEHB001", "The captured target branch is malformed.") + + +def _new_path(value: str | os.PathLike[str], name: str) -> Path: + raw = os.fspath(value) + if not raw or "\x00" in raw or ".." in Path(raw).parts: + raise HandoffError("ASEHB002", f"The {name} path is malformed.") + path = Path(raw).absolute() + current = Path(path.anchor) + try: + for component in path.parts[1:]: + current = current / component + metadata = current.lstat() + if stat.S_ISLNK(metadata.st_mode): + raise HandoffError("ASEHB002", f"The {name} path traverses a symbolic link.") + except HandoffError: + raise + except OSError: + raise HandoffError("ASEHB002", f"The {name} path is unavailable or unsafe.") from None + return path + + +def _new_output_directory(value: str | os.PathLike[str], name: str) -> Path: + raw = os.fspath(value) + if not raw or "\x00" in raw or ".." in Path(raw).parts: + raise HandoffError("ASEHB002", f"The {name} path is malformed.") + path = Path(raw).absolute() + parent = _new_path(path.parent, f"{name} parent") + try: + if not parent.is_dir() or path.exists() or path.is_symlink(): + raise HandoffError("ASEHB002", f"The {name} directory must be new under an existing parent.") + except OSError: + raise HandoffError("ASEHB002", f"The {name} directory is unavailable or unsafe.") from None + return path + + +def _git_environment() -> dict[str, str]: + return { + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "core.attributesFile", + "GIT_CONFIG_VALUE_0": os.devnull, + "GIT_CONFIG_PARAMETERS": "", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_ATTR_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "GIT_PAGER": "cat", + } + + +def _run_git_tree_inventory(repository: Path, revision: str) -> dict[str, tuple[str, str]]: + command = [ + "git", + "--no-pager", + "--no-replace-objects", + f"--git-dir={repository}", + "ls-tree", + "-r", + "-z", + "--full-tree", + "--no-abbrev", + revision, + ] + try: + process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + env=_git_environment(), + ) + except (OSError, ValueError): + raise HandoffError("ASEHB003", "The captured Git tree inventory process could not start.") from None + + assert process.stdout is not None and process.stderr is not None + selector = selectors.DefaultSelector() + output = bytearray() + stderr_bytes = 0 + try: + os.set_blocking(process.stdout.fileno(), False) + os.set_blocking(process.stderr.fileno(), False) + selector.register(process.stdout, selectors.EVENT_READ, "inventory") + selector.register(process.stderr, selectors.EVENT_READ, "stderr") + deadline = time.monotonic() + MAX_GIT_ARCHIVE_SECONDS + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise HandoffError("ASEHB003", "The bounded Git tree inventory deadline expired.") + ready = selector.select(min(remaining, 0.25)) + if not ready and process.poll() is not None: + continue + for key, _ in ready: + try: + chunk = os.read(key.fileobj.fileno(), 64 * 1024) + except OSError: + raise HandoffError("ASEHB003", "The captured Git tree inventory could not be read.") from None + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + if key.data == "inventory": + if len(output) + len(chunk) > MAX_GIT_TREE_INVENTORY_BYTES: + raise HandoffError("ASEHB003", "The captured Git tree inventory exceeds its byte limit.") + output.extend(chunk) + else: + stderr_bytes += len(chunk) + if stderr_bytes > MAX_GIT_STDERR_BYTES: + raise HandoffError("ASEHB003", "The captured Git tree diagnostics exceed their byte limit.") + try: + return_code = process.wait(timeout=max(0.01, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + raise HandoffError("ASEHB003", "The bounded Git tree inventory deadline expired.") from None + if return_code != 0: + raise HandoffError("ASEHB003", "Git could not inventory the captured head commit.") + except BaseException: + if process.poll() is None: + try: + process.kill() + process.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + raise + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if not pipe.closed: + pipe.close() + + inventory: dict[str, tuple[str, str]] = {} + folded_paths: set[str] = set() + records = bytes(output).split(b"\0") + if records[-1] != b"": + raise HandoffError("ASEHB004", "The captured Git tree inventory is malformed.") + for record in records[:-1]: + try: + header, raw_path = record.split(b"\t", 1) + mode_bytes, object_type_bytes, object_id_bytes = header.split(b" ") + path = raw_path.decode("utf-8", errors="strict") + normalized = "/".join(_member_path(path)) + mode = mode_bytes.decode("ascii") + object_type = object_type_bytes.decode("ascii") + object_id = object_id_bytes.decode("ascii") + except (UnicodeDecodeError, ValueError): + raise HandoffError("ASEHB004", "The captured Git tree inventory contains an unsafe entry.") from None + if mode not in {"100644", "100755"} or object_type != "blob": + raise HandoffError("ASEHB004", "The captured Git tree contains a symlink, submodule, or unsupported entry.") + if re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", object_id) is None: + raise HandoffError("ASEHB004", "The captured Git tree contains an invalid blob object ID.") + folded = normalized.casefold() + if normalized in inventory or folded in folded_paths: + raise HandoffError("ASEHB004", "The captured Git tree contains duplicate or case-colliding paths.") + if len(inventory) >= MAX_SNAPSHOT_FILES: + raise HandoffError("ASEHB004", "The captured Git tree exceeds its file-count limit.") + inventory[normalized] = (mode, object_id) + folded_paths.add(folded) + if not inventory: + raise HandoffError("ASEHB004", "The captured Git tree contains no regular files.") + return inventory + + +def _run_git_archive(repository: Path, revision: str, destination: Path) -> int: + command = ["git", "--no-pager", f"--git-dir={repository}", "archive", "--format=tar", revision] + environment = _git_environment() + try: + process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + env=environment, + ) + except (OSError, ValueError): + raise HandoffError("ASEHB003", "The trusted Git archive process could not start.") from None + + assert process.stdout is not None and process.stderr is not None + selector = selectors.DefaultSelector() + try: + os.set_blocking(process.stdout.fileno(), False) + os.set_blocking(process.stderr.fileno(), False) + selector.register(process.stdout, selectors.EVENT_READ, "archive") + selector.register(process.stderr, selectors.EVENT_READ, "stderr") + deadline = time.monotonic() + MAX_GIT_ARCHIVE_SECONDS + archive_bytes = 0 + stderr_bytes = 0 + descriptor = os.open( + destination, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + with os.fdopen(descriptor, "wb") as output: + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise HandoffError("ASEHB003", "The bounded Git archive deadline expired.") + ready = selector.select(min(remaining, 0.25)) + if not ready and process.poll() is not None: + # Drain both pipes to EOF before checking the final status. + continue + for key, _ in ready: + try: + chunk = os.read(key.fileobj.fileno(), 64 * 1024) + except OSError: + raise HandoffError("ASEHB003", "The trusted Git archive output could not be read.") from None + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + if key.data == "archive": + archive_bytes += len(chunk) + if archive_bytes > MAX_SNAPSHOT_ARCHIVE_BYTES: + raise HandoffError("ASEHB003", "The subject source snapshot exceeds its archive byte limit.") + output.write(chunk) + else: + stderr_bytes += len(chunk) + if stderr_bytes > MAX_GIT_STDERR_BYTES: + raise HandoffError("ASEHB003", "The trusted Git archive diagnostics exceed their byte limit.") + output.flush() + os.fsync(output.fileno()) + try: + return_code = process.wait(timeout=max(0.01, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + raise HandoffError("ASEHB003", "The bounded Git archive deadline expired.") from None + if return_code != 0: + raise HandoffError("ASEHB003", "Git could not archive the captured head commit.") + if archive_bytes <= 0: + raise HandoffError("ASEHB003", "Git produced an empty subject source snapshot.") + return archive_bytes + except BaseException: + if process.poll() is None: + try: + process.kill() + process.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + try: + destination.unlink(missing_ok=True) + except OSError: + pass + raise + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if not pipe.closed: + pipe.close() + + +def _member_path(name: str) -> tuple[str, ...]: + if not isinstance(name, str) or not name or "\x00" in name or "\\" in name or name.startswith("/"): + raise HandoffError("ASEHB004", "The subject source archive contains an unsafe path.") + normalized = name[:-1] if name.endswith("/") else name + parts = normalized.split("/") + if not parts or any(part in {"", ".", ".."} for part in parts): + raise HandoffError("ASEHB004", "The subject source archive contains an unsafe path.") + try: + normalized.encode("utf-8", errors="strict") + except UnicodeEncodeError: + raise HandoffError("ASEHB004", "The subject source archive path is not valid UTF-8.") from None + return tuple(parts) + + +def _scan_archive( + path: Path, + expected_blobs: Mapping[str, tuple[str, str]] | None = None, +) -> tuple[int, int, set[str]]: + metadata = path.lstat() + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size <= 0 or metadata.st_size > MAX_SNAPSHOT_ARCHIVE_BYTES: + raise HandoffError("ASEHB004", "The subject source archive is not a bounded regular file.") + count = 0 + expanded_bytes = 0 + seen: set[str] = set() + folded_seen: set[str] = set() + names: set[str] = set() + regular_files: set[str] = set() + directories: set[str] = set() + deadline = time.monotonic() + MAX_EXTRACT_SECONDS + expected_directories: set[str] | None = None + if expected_blobs is not None: + expected_directories = set() + for file_path in expected_blobs: + parts = file_path.split("/") + expected_directories.update("/".join(parts[:index]) for index in range(1, len(parts))) + try: + with tarfile.open(path, mode="r:") as archive: + for member in archive: + if time.monotonic() > deadline: + raise HandoffError("ASEHB004", "The bounded subject archive inspection deadline expired.") + parts = _member_path(member.name) + normalized = "/".join(parts) + folded = normalized.casefold() + if normalized in seen or folded in folded_seen: + raise HandoffError("ASEHB004", "The subject source archive contains duplicate or case-colliding paths.") + seen.add(normalized) + folded_seen.add(folded) + names.add(normalized) + count += 1 + if count > MAX_SNAPSHOT_FILES: + raise HandoffError("ASEHB004", "The subject source archive exceeds its file-count limit.") + if member.isdir(): + directories.add(normalized) + continue + if not member.isreg() or member.issym() or member.islnk() or member.size < 0: + raise HandoffError("ASEHB004", "The subject source archive contains a link or special file.") + regular_files.add(normalized) + expected_blob = None if expected_blobs is None else expected_blobs.get(normalized) + if expected_blobs is not None and expected_blob is None: + raise HandoffError("ASEHB004", "The subject source archive contains a path absent from the captured Git tree.") + if expected_blob is not None: + expected_mode, object_id = expected_blob + if bool(member.mode & 0o111) != (expected_mode == "100755"): + raise HandoffError("ASEHB004", "The subject source archive changes a captured Git file mode.") + digest = hashlib.sha1() if len(object_id) == 40 else hashlib.sha256() + digest.update(b"blob " + str(member.size).encode("ascii") + b"\0") + source = archive.extractfile(member) + if source is None: + raise HandoffError("ASEHB004", "A subject source archive file could not be read.") + bytes_read = 0 + with source: + while bytes_read < member.size: + if time.monotonic() > deadline: + raise HandoffError("ASEHB004", "The bounded subject archive inspection deadline expired.") + chunk = source.read(min(1024 * 1024, member.size - bytes_read)) + if not chunk: + raise HandoffError("ASEHB004", "A subject source archive file was truncated.") + digest.update(chunk) + bytes_read += len(chunk) + if source.read(1): + raise HandoffError("ASEHB004", "A subject source archive file exceeded its declared size.") + if digest.hexdigest() != object_id: + raise HandoffError("ASEHB004", "A subject source archive file differs from its captured Git blob.") + expanded_bytes += member.size + if expanded_bytes > MAX_SNAPSHOT_EXPANDED_BYTES: + raise HandoffError("ASEHB004", "The expanded subject source snapshot exceeds its byte limit.") + except HandoffError: + raise + except (OSError, tarfile.TarError, EOFError, ValueError): + raise HandoffError("ASEHB004", "The subject source archive is malformed or unreadable.") from None + if count == 0: + raise HandoffError("ASEHB004", "The subject source archive contains no entries.") + for normalized in seen: + parts = normalized.split("/") + parents = ("/".join(parts[:index]) for index in range(1, len(parts))) + if any(parent not in directories for parent in parents): + raise HandoffError("ASEHB004", "The subject source archive omits or conflicts with a parent directory entry.") + if expected_blobs is not None: + if regular_files != set(expected_blobs): + raise HandoffError("ASEHB004", "The subject source archive omits or adds a regular file from the captured Git tree.") + if directories != expected_directories: + raise HandoffError("ASEHB004", "The subject source archive directory paths differ from the captured Git tree.") + return count, expanded_bytes, names + + +def _sha256_file(path: Path, maximum_bytes: int) -> tuple[str, int]: + try: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)) + except OSError: + raise HandoffError("ASEHB001", "A handoff digest input is unavailable or unsafe.") from None + digest = hashlib.sha256() + total = 0 + try: + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode): + raise HandoffError("ASEHB001", "A handoff digest input is not a regular file.") + while True: + chunk = os.read(descriptor, 1024 * 1024) + if not chunk: + break + total += len(chunk) + if total > maximum_bytes: + raise HandoffError("ASEHB001", "A handoff digest input exceeds its byte limit.") + digest.update(chunk) + except OSError: + raise HandoffError("ASEHB001", "A handoff digest input could not be read safely.") from None + finally: + os.close(descriptor) + return digest.hexdigest(), total + + +def _safe_regular_children(root: Path) -> dict[str, Path]: + try: + root_info = root.lstat() + if not stat.S_ISDIR(root_info.st_mode): + raise HandoffError("ASEHB001", "The downloaded handoff root is not a physical directory.") + entries = list(root.iterdir()) + except HandoffError: + raise + except OSError: + raise HandoffError("ASEHB001", "The downloaded handoff directory is unavailable.") from None + result: dict[str, Path] = {} + total = 0 + for entry in entries: + try: + metadata = entry.lstat() + except OSError: + raise HandoffError("ASEHB001", "A downloaded handoff entry is unavailable.") from None + if entry.name in result or not stat.S_ISREG(metadata.st_mode): + raise HandoffError("ASEHB001", "The downloaded handoff contains an unexpected entry type or duplicate.") + total += metadata.st_size + if total > MAX_TOTAL_HANDOFF_BYTES: + raise HandoffError("ASEHB001", "The downloaded handoff exceeds its aggregate byte limit.") + result[entry.name] = entry + return result + + +def _paths_disjoint(*paths: Path) -> bool: + for index, path in enumerate(paths): + if any(path == other or path in other.parents or other in path.parents for other in paths[index + 1 :]): + return False + return True + + +def _same_file_identity(left: os.stat_result, right: os.stat_result) -> bool: + return ( + left.st_dev, + left.st_ino, + left.st_mode, + left.st_nlink, + left.st_size, + left.st_mtime_ns, + left.st_ctime_ns, + ) == ( + right.st_dev, + right.st_ino, + right.st_mode, + right.st_nlink, + right.st_size, + right.st_mtime_ns, + right.st_ctime_ns, + ) + + +def _same_inode(left: os.stat_result, right: os.stat_result) -> bool: + return left.st_dev == right.st_dev and left.st_ino == right.st_ino and stat.S_IFMT(left.st_mode) == stat.S_IFMT(right.st_mode) + + +def _remove_export_entries(directory_fd: int, *, depth: int = 0, budget: list[int]) -> None: + if depth > 64: + raise OSError("export cleanup depth exceeded") + for name in os.listdir(directory_fd): + budget[0] -= 1 + if budget[0] < 0: + raise OSError("export cleanup entry budget exceeded") + before = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if stat.S_ISDIR(before.st_mode): + child_fd = os.open( + name, + os.O_RDONLY + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0), + dir_fd=directory_fd, + ) + try: + opened = os.fstat(child_fd) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if not _same_inode(before, opened) or not _same_inode(opened, current): + raise OSError("export cleanup directory changed") + _remove_export_entries(child_fd, depth=depth + 1, budget=budget) + finally: + os.close(child_fd) + current = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + if not _same_inode(before, current): + raise OSError("export cleanup directory changed") + os.rmdir(name, dir_fd=directory_fd) + else: + # unlinkat removes a symbolic link itself; it never follows it. + os.unlink(name, dir_fd=directory_fd) + + +def _remove_subject_artifact_export(path: Path) -> None: + """Remove the one fresh export tree without following any entry links.""" + parent_fd: int | None = None + root_fd: int | None = None + parent_parent_fd: int | None = None + try: + parent_fd, parent_parent_fd, parent_name = _open_directory_nofollow(path.parent, "ASEHB009") + parent_info = os.fstat(parent_fd) + if parent_parent_fd is not None and parent_name is not None: + if not _same_file_identity(parent_info, os.stat(parent_name, dir_fd=parent_parent_fd, follow_symlinks=False)): + return + try: + before = os.stat(path.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + return + if stat.S_ISDIR(before.st_mode): + root_fd = os.open( + path.name, + os.O_RDONLY + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0), + dir_fd=parent_fd, + ) + opened = os.fstat(root_fd) + current = os.stat(path.name, dir_fd=parent_fd, follow_symlinks=False) + if ( + opened.st_uid != os.geteuid() + or stat.S_IMODE(opened.st_mode) != 0o700 + or not _same_inode(before, opened) + or not _same_inode(opened, current) + ): + raise OSError("subject artifact export is no longer the private directory created for this run") + _remove_export_entries(root_fd, budget=[MAX_SNAPSHOT_FILES]) + current = os.stat(path.name, dir_fd=parent_fd, follow_symlinks=False) + if not _same_inode(opened, current): + raise OSError("subject artifact export changed during cleanup") + os.close(root_fd) + root_fd = None + os.rmdir(path.name, dir_fd=parent_fd) + else: + os.unlink(path.name, dir_fd=parent_fd) + except FileNotFoundError: + return + except OSError: + # Cleanup is best effort after a failed handoff. Never widen its target + # or follow a path that changed while cleanup was in progress. + return + finally: + if root_fd is not None: + os.close(root_fd) + if parent_fd is not None: + os.close(parent_fd) + if parent_parent_fd is not None: + os.close(parent_parent_fd) + + +def _open_directory_nofollow(path: Path, code: str) -> tuple[int, int | None, str | None]: + """Descriptor-walk an absolute directory path and retain its named parent.""" + if not path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts[1:]): + raise HandoffError(code, "The fixed subject artifact export path is malformed.") + directory_flags = ( + os.O_RDONLY + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_DIRECTORY", 0) + | getattr(os, "O_NOFOLLOW", 0) + ) + try: + current_fd = os.open(path.anchor, directory_flags) + except OSError: + raise HandoffError(code, "The fixed subject artifact export path is unavailable or unsafe.") from None + parent_fd: int | None = None + name: str | None = None + try: + components = path.parts[1:] + for index, component in enumerate(components): + child_fd: int | None = None + try: + before = os.stat(component, dir_fd=current_fd, follow_symlinks=False) + if not stat.S_ISDIR(before.st_mode): + raise HandoffError(code, "The fixed subject artifact export path contains a non-directory component.") + child_fd = os.open(component, directory_flags, dir_fd=current_fd) + opened = os.fstat(child_fd) + after = os.stat(component, dir_fd=current_fd, follow_symlinks=False) + if ( + not stat.S_ISDIR(opened.st_mode) + or not _same_file_identity(before, opened) + or not _same_file_identity(opened, after) + ): + os.close(child_fd) + child_fd = None + raise HandoffError(code, "The fixed subject artifact export path changed during its descriptor walk.") + except HandoffError: + if child_fd is not None: + os.close(child_fd) + raise + except OSError: + if child_fd is not None: + os.close(child_fd) + raise HandoffError(code, "The fixed subject artifact export path is unavailable or unsafe.") from None + if index == len(components) - 1: + parent_fd = current_fd + current_fd = child_fd + name = component + return current_fd, parent_fd, name + os.close(current_fd) + current_fd = child_fd + return current_fd, None, None + except HandoffError: + os.close(current_fd) + if parent_fd is not None: + os.close(parent_fd) + raise + + +def _verify_subject_artifact_export( + directory: Path, + artifacts: Any, + *, + code: str, + require_private: bool, +) -> None: + """Verify the fixed export with bounded reads relative to one no-follow directory descriptor.""" + _validate_subject_artifacts(artifacts) + root_fd, parent_fd, root_name = _open_directory_nofollow(directory, code) + try: + root_info = os.fstat(root_fd) + if not stat.S_ISDIR(root_info.st_mode) or ( + require_private + and (root_info.st_uid != os.geteuid() or stat.S_IMODE(root_info.st_mode) != 0o700) + ): + raise HandoffError(code, "The fixed subject artifact export directory has unsafe permissions or type.") + if parent_fd is not None and root_name is not None: + try: + if not _same_file_identity(root_info, os.stat(root_name, dir_fd=parent_fd, follow_symlinks=False)): + raise HandoffError(code, "The fixed subject artifact export directory changed during verification.") + except OSError: + raise HandoffError(code, "The fixed subject artifact export directory changed during verification.") from None + try: + if set(os.listdir(root_fd)) != set(SUBJECT_ARTIFACT_EXPORT_BASENAMES): + raise HandoffError(code, "The fixed subject artifact export has missing or unexpected files.") + except OSError: + raise HandoffError(code, "The fixed subject artifact export could not be inventoried safely.") from None + + for artifact, basename, (_logical_name, _relative_path, maximum_bytes) in zip( + artifacts, SUBJECT_ARTIFACT_EXPORT_BASENAMES, SUBJECT_ARTIFACTS, strict=True + ): + artifact_fd: int | None = None + try: + named_before = os.stat(basename, dir_fd=root_fd, follow_symlinks=False) + if not stat.S_ISREG(named_before.st_mode): + raise HandoffError(code, "A fixed subject artifact is not a regular file.") + artifact_fd = os.open( + basename, + os.O_RDONLY + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_NONBLOCK", 0), + dir_fd=root_fd, + ) + metadata = os.fstat(artifact_fd) + expected_bytes = artifact["byteCount"] + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_size != expected_bytes + or metadata.st_size > maximum_bytes + or not _same_file_identity(named_before, metadata) + ): + raise HandoffError(code, "A fixed subject artifact has an unsafe type or byte count.") + digest = hashlib.sha256() + total = 0 + while total <= maximum_bytes: + chunk = os.read(artifact_fd, min(1024 * 1024, maximum_bytes + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > maximum_bytes: + raise HandoffError(code, "A fixed subject artifact exceeds its byte limit.") + digest.update(chunk) + if total != expected_bytes or digest.hexdigest() != artifact["sha256"]: + raise HandoffError(code, "A fixed subject artifact differs from its receipt index.") + after_read = os.fstat(artifact_fd) + named_after = os.stat(basename, dir_fd=root_fd, follow_symlinks=False) + if not _same_file_identity(metadata, after_read) or not _same_file_identity(after_read, named_after): + raise HandoffError(code, "A fixed subject artifact changed during verification.") + except HandoffError: + raise + except OSError: + raise HandoffError(code, "A fixed subject artifact is unavailable or unsafe.") from None + finally: + if artifact_fd is not None: + os.close(artifact_fd) + try: + if set(os.listdir(root_fd)) != set(SUBJECT_ARTIFACT_EXPORT_BASENAMES): + raise HandoffError(code, "The fixed subject artifact export changed during verification.") + except OSError: + raise HandoffError(code, "The fixed subject artifact export changed during verification.") from None + if parent_fd is not None and root_name is not None: + try: + if not _same_file_identity(root_info, os.stat(root_name, dir_fd=parent_fd, follow_symlinks=False)): + raise HandoffError(code, "The fixed subject artifact export directory changed during verification.") + except OSError: + raise HandoffError(code, "The fixed subject artifact export directory changed during verification.") from None + finally: + os.close(root_fd) + if parent_fd is not None: + os.close(parent_fd) + + +def create_handoff( + *, + capture_directory: str | os.PathLike[str], + trusted_scripts_directory: str | os.PathLike[str], + output_directory: str | os.PathLike[str], + plan_file: str | os.PathLike[str] | None = None, +) -> str: + capture = _new_path(capture_directory, "capture") + scripts = _new_path(trusted_scripts_directory, "trusted scripts") + output = _new_output_directory(output_directory, "handoff output") + if not stat.S_ISDIR(capture.stat().st_mode) or not stat.S_ISDIR(scripts.stat().st_mode): + raise HandoffError("ASEHB002", "The trusted capture or script directory is unavailable.") + + try: + entries = {path.name: path for path in capture.iterdir()} + except OSError: + raise HandoffError("ASEHB002", "The trusted capture directory is unavailable.") from None + stage: Path | None = None + try: + stage = Path(tempfile.mkdtemp(prefix=f".{output.name}.stage-", dir=output.parent)) + os.chmod(stage, 0o700) + trusted_hashes: dict[str, str] = {} + if "observation.json" in entries: + if plan_file is not None: + raise HandoffError("ASEHB002", "A fork observation handoff cannot include an EvidencePlan.") + if set(entries) != {"observation.json"}: + raise HandoffError("ASEHB002", "The fork observation capture contains an unexpected entry.") + observation, _ = _read_json(entries["observation.json"], 64 * 1024, "The fork observation") + if observation.get("Mode") != "ObservationOnly": + raise HandoffError("ASEHB002", "The fork capture is not observation-only.") + _copy_trusted_files(scripts, stage, ("evidence-gate-handoff.py",), trusted_hashes) + observation_bytes = _canonical_json(observation) + _write_regular_file(stage / "observation.json", observation_bytes) + manifest = { + "Mode": "ObservationOnly", + "SchemaVersion": 1, + "TrustedFiles": trusted_hashes, + "WorkflowRunAttempt": observation.get("WorkflowRunAttempt"), + "WorkflowRunId": observation.get("WorkflowRunId"), + } + _write_regular_file(stage / "handoff.json", _canonical_json(manifest)) + _publish_directory(stage, output) + stage = None + return "observation" + + if set(entries) != {"source.diff", "pull-request-run-identity.json", "repository.git"}: + raise HandoffError("ASEHB002", "The captured pull-request inputs have an unexpected file set.") + identity, _ = _read_json(entries["pull-request-run-identity.json"], 64 * 1024, "The pull-request run identity") + _validate_identity(identity) + if plan_file is None: + raise HandoffError("ASEHB001", "A base-owned EvidencePlan is required for a same-repository capture.") + plan_path = _new_path(plan_file, "EvidencePlan") + if not entries["repository.git"].is_dir() or entries["repository.git"].is_symlink(): + raise HandoffError("ASEHB002", "The retained trusted Git object store is unavailable.") + source_diff = _read_regular_file(entries["source.diff"], MAX_SOURCE_DIFF_BYTES, "The captured source diff") + diff_digest = hashlib.sha256(source_diff).hexdigest() + evidence_plan, evidence_plan_bytes = _read_evidence_plan(plan_path) + _validate_evidence_plan(evidence_plan, identity, diff_digest) + _write_regular_file(stage / "source.diff", source_diff) + _write_regular_file(stage / "pull-request-run-identity.json", _canonical_json(identity)) + _write_regular_file(stage / "evidence-plan.json", evidence_plan_bytes) + + archive_path = stage / "subject.snapshot.tar" + git_inventory = _run_git_tree_inventory(entries["repository.git"], identity["HeadRevision"]) + _run_git_archive(entries["repository.git"], identity["HeadRevision"], archive_path) + file_count, expanded_bytes, _ = _scan_archive(archive_path, git_inventory) + archive_digest, archive_bytes = _sha256_file(archive_path, MAX_SNAPSHOT_ARCHIVE_BYTES) + _copy_trusted_files(scripts, stage, TRUSTED_SUBJECT_FILES, trusted_hashes) + manifest = { + "BaseRevision": identity["BaseRevision"], + "EvidencePlanBytes": len(evidence_plan_bytes), + "EvidencePlanSha256": hashlib.sha256(evidence_plan_bytes).hexdigest(), + "HeadRevision": identity["HeadRevision"], + "Mode": "SubjectSnapshot", + "PullRequestNumber": identity["PullRequestNumber"], + "RepositoryId": identity["RepositoryId"], + "SchemaVersion": 1, + "SourceDiffBytes": len(source_diff), + "SourceDiffSha256": diff_digest, + "SnapshotArchiveBytes": archive_bytes, + "SnapshotArchiveEntryCount": file_count, + "SnapshotArchiveExpandedBytes": expanded_bytes, + "SnapshotArchiveSha256": archive_digest, + "TargetBranch": identity["TargetBranch"], + "TrustedFiles": trusted_hashes, + "WorkflowRunAttempt": identity["WorkflowRunAttempt"], + "WorkflowRunId": identity["WorkflowRunId"], + } + _write_regular_file(stage / "handoff.json", _canonical_json(manifest)) + _validate_bundle_directory(stage, manifest) + _publish_directory(stage, output) + stage = None + return "captured" + except OSError: + raise HandoffError("ASEHB002", "The private controller handoff failed closed.") from None + finally: + if stage is not None: + _remove_private_directory(stage) + + +def _copy_trusted_files(source: Path, destination: Path, names: Sequence[str], hashes: dict[str, str]) -> None: + for name in names: + content = _read_regular_file(source / name, MAX_TRUSTED_SCRIPT_BYTES, f"Trusted subject helper {name}") + _write_regular_file(destination / name, content) + hashes[name] = hashlib.sha256(content).hexdigest() + + +def _publish_directory(stage: Path, output: Path) -> None: + if output.exists() or output.is_symlink(): + raise HandoffError("ASEHB002", "The private handoff output changed during preparation.") + try: + os.rename(stage, output) + except OSError: + raise HandoffError("ASEHB002", "The private handoff could not be published atomically.") from None + + +def _remove_private_directory(path: Path) -> None: + try: + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + except OSError: + pass + + +def _validate_bundle_directory( + root: Path, + manifest: Mapping[str, Any], +) -> tuple[Mapping[str, Any] | None, Path | None, Mapping[str, Any] | None]: + entries = _safe_regular_children(root) + mode = manifest.get("Mode") + if type(manifest.get("SchemaVersion")) is not int or manifest["SchemaVersion"] != 1: + raise HandoffError("ASEHB001", "The private handoff schema version is unsupported.") + trusted_files = manifest.get("TrustedFiles") + if not isinstance(trusted_files, dict): + raise HandoffError("ASEHB001", "The private handoff trusted-file inventory is malformed.") + expected_script_names = ("evidence-gate-handoff.py",) if mode == "ObservationOnly" else TRUSTED_SUBJECT_FILES + expected_names = {"handoff.json", *expected_script_names} + identity: Mapping[str, Any] | None = None + archive_path: Path | None = None + evidence_plan: Mapping[str, Any] | None = None + if mode == "SubjectSnapshot": + expected_names.update({"evidence-plan.json", "source.diff", "pull-request-run-identity.json", "subject.snapshot.tar"}) + if set(entries) != expected_names or set(trusted_files) != set(expected_script_names): + raise HandoffError("ASEHB001", "The downloaded private handoff file set is invalid.") + identity, _ = _read_json(entries.get("pull-request-run-identity.json", root / "missing"), 64 * 1024, "The pull-request run identity") + _validate_identity(identity) + if ( + manifest.get("BaseRevision") != identity["BaseRevision"] + or manifest.get("HeadRevision") != identity["HeadRevision"] + or manifest.get("PullRequestNumber") != identity["PullRequestNumber"] + or manifest.get("RepositoryId") != identity["RepositoryId"] + or manifest.get("TargetBranch") != identity["TargetBranch"] + or manifest.get("WorkflowRunId") != identity["WorkflowRunId"] + or manifest.get("WorkflowRunAttempt") != identity["WorkflowRunAttempt"] + ): + raise HandoffError("ASEHB001", "The controller handoff does not match its captured pull-request identity.") + if not isinstance(manifest.get("SourceDiffSha256"), str) or re.fullmatch( + r"[0-9a-f]{64}", manifest["SourceDiffSha256"] + ) is None: + raise HandoffError("ASEHB001", "The captured source diff digest is malformed.") + diff_digest, diff_bytes = _sha256_file(entries["source.diff"], MAX_SOURCE_DIFF_BYTES) + if diff_digest != manifest.get("SourceDiffSha256") or diff_bytes != manifest.get("SourceDiffBytes"): + raise HandoffError("ASEHB001", "The captured source diff does not match the controller handoff digest.") + if ( + type(manifest.get("EvidencePlanBytes")) is not int + or manifest["EvidencePlanBytes"] <= 0 + or manifest["EvidencePlanBytes"] > MAX_EVIDENCE_PLAN_BYTES + or not isinstance(manifest.get("EvidencePlanSha256"), str) + or re.fullmatch(r"[0-9a-f]{64}", manifest["EvidencePlanSha256"]) is None + ): + raise HandoffError("ASEHB001", "The controller EvidencePlan digest inventory is malformed.") + plan_digest, plan_bytes = _sha256_file(entries["evidence-plan.json"], MAX_EVIDENCE_PLAN_BYTES) + if plan_digest != manifest["EvidencePlanSha256"] or plan_bytes != manifest["EvidencePlanBytes"]: + raise HandoffError("ASEHB001", "The EvidencePlan does not match the controller handoff digest.") + evidence_plan, _ = _read_evidence_plan(entries["evidence-plan.json"]) + _validate_evidence_plan(evidence_plan, identity, diff_digest) + archive_path = entries.get("subject.snapshot.tar") + archive_digest, archive_bytes = _sha256_file(archive_path, MAX_SNAPSHOT_ARCHIVE_BYTES) + if archive_digest != manifest.get("SnapshotArchiveSha256") or archive_bytes != manifest.get("SnapshotArchiveBytes"): + raise HandoffError("ASEHB001", "The subject snapshot does not match the controller handoff digest.") + entry_count, expanded_bytes, _ = _scan_archive(archive_path) + if entry_count != manifest.get("SnapshotArchiveEntryCount") or expanded_bytes != manifest.get("SnapshotArchiveExpandedBytes"): + raise HandoffError("ASEHB001", "The subject snapshot inventory does not match the controller handoff.") + elif mode == "ObservationOnly": + expected_names.add("observation.json") + if set(entries) != expected_names or set(trusted_files) != set(expected_script_names): + raise HandoffError("ASEHB001", "The downloaded private handoff file set is invalid.") + observation, _ = _read_json(entries.get("observation.json", root / "missing"), 64 * 1024, "The fork observation") + if observation.get("Mode") != "ObservationOnly": + raise HandoffError("ASEHB001", "The downloaded fork handoff is not observation-only.") + if ( + observation.get("WorkflowRunId") != manifest.get("WorkflowRunId") + or observation.get("WorkflowRunAttempt") != manifest.get("WorkflowRunAttempt") + ): + raise HandoffError("ASEHB001", "The fork observation does not match its handoff identity.") + else: + raise HandoffError("ASEHB001", "The private handoff mode is unsupported.") + for name in expected_script_names: + expected_digest = trusted_files.get(name) + if not isinstance(expected_digest, str) or re.fullmatch(r"[0-9a-f]{64}", expected_digest) is None: + raise HandoffError("ASEHB001", "The trusted subject helper digest is malformed.") + actual_digest, _ = _sha256_file(entries[name], MAX_TRUSTED_SCRIPT_BYTES) + if actual_digest != expected_digest: + raise HandoffError("ASEHB001", "A trusted subject helper does not match the controller handoff.") + return identity, archive_path, evidence_plan + + +def _extract_snapshot(archive_path: Path, destination: Path) -> tuple[int, int]: + output = _new_output_directory(destination, "subject checkout") + started = time.monotonic() + try: + os.mkdir(output, 0o700) + with tarfile.open(archive_path, mode="r:") as archive: + for member in archive: + if time.monotonic() - started > MAX_EXTRACT_SECONDS: + raise HandoffError("ASEHB005", "The bounded subject snapshot extraction deadline expired.") + parts = _member_path(member.name) + target = output.joinpath(*parts) + if member.isdir(): + try: + target.mkdir(mode=0o755, parents=False, exist_ok=True) + except FileExistsError: + if not target.is_dir() or target.is_symlink(): + raise HandoffError("ASEHB005", "A subject snapshot parent path has a conflicting file type.") from None + continue + parent = target.parent + missing: list[Path] = [] + current = parent + while current != output and not current.exists(): + missing.append(current) + current = current.parent + if current != output and (current.is_symlink() or not current.is_dir()): + raise HandoffError("ASEHB005", "A subject snapshot parent path is unsafe.") + for directory in reversed(missing): + directory.mkdir(mode=0o755) + if not member.isreg(): + raise HandoffError("ASEHB005", "The subject snapshot contains a link or special file.") + source = archive.extractfile(member) + if source is None: + raise HandoffError("ASEHB005", "A subject snapshot file could not be read.") + descriptor = os.open( + target, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + total = 0 + try: + with os.fdopen(descriptor, "wb") as output_file, source: + while total < member.size: + if time.monotonic() - started > MAX_EXTRACT_SECONDS: + raise HandoffError("ASEHB005", "The bounded subject snapshot extraction deadline expired.") + chunk = source.read(min(1024 * 1024, member.size - total)) + if not chunk: + raise HandoffError("ASEHB005", "A subject snapshot file was truncated.") + output_file.write(chunk) + total += len(chunk) + if source.read(1): + raise HandoffError("ASEHB005", "A subject snapshot file exceeded its declared size.") + output_file.flush() + os.fsync(output_file.fileno()) + os.chmod(target, 0o755 if member.mode & 0o111 else 0o644, follow_symlinks=False) + except BaseException: + try: + target.unlink(missing_ok=True) + except OSError: + pass + raise + return _scan_extracted_tree(output) + except HandoffError: + _remove_private_directory(output) + raise + except (OSError, tarfile.TarError, EOFError, ValueError): + _remove_private_directory(output) + raise HandoffError("ASEHB005", "The subject snapshot could not be materialized safely.") from None + + +def _scan_extracted_tree(root: Path) -> tuple[int, int]: + file_count = 0 + total_bytes = 0 + stack = [root] + while stack: + current = stack.pop() + with os.scandir(current) as entries: + for entry in entries: + metadata = entry.stat(follow_symlinks=False) + if stat.S_ISLNK(metadata.st_mode): + raise HandoffError("ASEHB005", "The materialized subject snapshot contains a symbolic link.") + if stat.S_ISDIR(metadata.st_mode): + stack.append(Path(entry.path)) + elif stat.S_ISREG(metadata.st_mode): + file_count += 1 + total_bytes += metadata.st_size + if file_count > MAX_SNAPSHOT_FILES or total_bytes > MAX_SNAPSHOT_EXPANDED_BYTES: + raise HandoffError("ASEHB005", "The materialized subject snapshot exceeds its fixed limits.") + else: + raise HandoffError("ASEHB005", "The materialized subject snapshot contains a special file.") + return file_count, total_bytes + + +def _write_subject_result(path: Path, value: Mapping[str, Any]) -> None: + encoded = _canonical_json(value) + b"\n" + if len(encoded) > MAX_RESULT_BYTES: + encoded = _canonical_json( + { + "claimEligible": False, + "execution": "failed", + "schemaVersion": 1, + "diagnostic": {"code": "ASEHB006", "message": "The bounded subject result exceeded its byte limit."}, + } + ) + b"\n" + parent = _new_path(path.parent, "subject result parent") + if not parent.is_dir(): + raise HandoffError("ASEHB006", "The subject result directory is unavailable.") + _write_regular_file(parent / path.name, encoded) + + +def verify_handoff( + *, + handoff_directory: str | os.PathLike[str], + fresh_capture_directory: str | os.PathLike[str], + subject_result_file: str | os.PathLike[str], + output_plan: str | os.PathLike[str], + subject_artifacts_directory: str | os.PathLike[str] | None = None, + expected_image_digest: str | None = None, +) -> None: + """Copy a downloaded plan only after binding its bundle to fresh trusted Git state. + + This runs in the base-owned verifier job, not the credentialless subject. It + validates the entire bounded handoff, compares the captured identity and + diff with an independent current-PR recapture, and checks every archive + blob and mode against that fresh Git tree. The copied plan is still + independently resolved by the .NET gate verifier before any claim. For a + code-coverage result, the separately downloaded fixed artifact payload is + read and compared with the receipt index only after the fresh recapture + has matched. That comparison remains non-claiming. + """ + handoff = _new_path(handoff_directory, "downloaded handoff") + capture = _new_path(fresh_capture_directory, "fresh verifier capture") + output = Path(output_plan).absolute() + _new_path(output.parent, "verified plan output parent") + if not capture.is_dir() or capture.is_symlink(): + raise HandoffError("ASEHB001", "The fresh verifier capture is not a physical directory.") + + entries = _safe_regular_children(handoff) + manifest, _ = _read_json(entries.get("handoff.json", handoff / "missing"), 128 * 1024, "The controller handoff manifest") + identity, archive_path, plan = _validate_bundle_directory(handoff, manifest) + if manifest.get("Mode") != "SubjectSnapshot" or identity is None or archive_path is None or plan is None: + raise HandoffError("ASEHB001", "The verifier requires a same-repository subject snapshot.") + + fresh_identity, _ = _read_json( + capture / "pull-request-run-identity.json", 64 * 1024, "The fresh verifier pull-request identity" + ) + _validate_identity(fresh_identity) + if fresh_identity != identity: + raise HandoffError("ASEHB001", "The downloaded handoff differs from the fresh pull-request identity.") + fresh_diff = _read_regular_file(capture / "source.diff", MAX_SOURCE_DIFF_BYTES, "The fresh verifier source diff") + if hashlib.sha256(fresh_diff).hexdigest() != manifest["SourceDiffSha256"]: + raise HandoffError("ASEHB001", "The downloaded handoff differs from the fresh source diff.") + repository = capture / "repository.git" + if not repository.is_dir() or repository.is_symlink(): + raise HandoffError("ASEHB003", "The fresh trusted Git object store is unavailable.") + inventory = _run_git_tree_inventory(repository, identity["HeadRevision"]) + _scan_archive(archive_path, inventory) + + subject_raw = _read_regular_file(Path(subject_result_file), MAX_RESULT_BYTES, "The credentialless subject result") + if not subject_raw.endswith(b"\n"): + raise HandoffError("ASEHB001", "The credentialless subject result is not newline-terminated canonical JSON.") + try: + subject_result = json.loads( + subject_raw[:-1], object_pairs_hook=_unique_object, parse_constant=_reject_json_constant + ) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise HandoffError("ASEHB001", "The credentialless subject result is malformed JSON.") from None + if not isinstance(subject_result, dict) or _canonical_json(subject_result) + b"\n" != subject_raw: + raise HandoffError("ASEHB001", "The credentialless subject result is not canonical JSON.") + diagnostic = subject_result.get("diagnostic") + if ( + type(subject_result.get("schemaVersion")) is not int + or subject_result["schemaVersion"] != 1 + or subject_result.get("claimEligible") is not False + or subject_result.get("mode") != "SubjectSnapshot" + or subject_result.get("workflowRunId") != str(identity["WorkflowRunId"]) + or subject_result.get("workflowRunAttempt") != str(identity["WorkflowRunAttempt"]) + or subject_result.get("headRevision") != identity["HeadRevision"] + or subject_result.get("snapshotSha256") != manifest["SnapshotArchiveSha256"] + or subject_result.get("profileId") != plan["Profile"]["Id"] + or subject_result.get("execution") != "completed" + or type(subject_result.get("exitCode")) is not int + or subject_result["exitCode"] != 0 + or not isinstance(diagnostic, dict) + or diagnostic.get("code") != "ASEHB010" + ): + raise HandoffError("ASEHB001", "The credentialless subject result does not match this successful handoff.") + if plan["Profile"]["Id"] == "code-coverage": + if expected_image_digest is None: + raise HandoffError("ASEHB013", "The trusted subject image digest is required for envelope verification.") + _validate_envelope_receipt( + subject_result.get("envelopeReceipt"), + expected_binding=_execution_receipt_binding(identity, manifest, plan["Profile"]["Id"]), + expected_image_digest=expected_image_digest, + ) + receipt = subject_result.get("executionReceipt") + _validate_execution_receipt( + receipt, + expected_binding=_execution_receipt_binding(identity, manifest, plan["Profile"]["Id"]), + ) + if subject_artifacts_directory is None: + raise HandoffError("ASEHB012", "The downloaded fixed subject artifact payload is required for code-coverage.") + try: + subject_artifacts = _new_path(subject_artifacts_directory, "downloaded subject artifact export") + except HandoffError: + raise HandoffError("ASEHB012", "The downloaded fixed subject artifact directory is unavailable or unsafe.") from None + if not isinstance(receipt, dict): + raise HandoffError("ASEHB001", "The completed execution receipt is malformed.") + _verify_subject_artifact_export( + subject_artifacts, + receipt["record"]["artifacts"], + code="ASEHB012", + require_private=False, + ) + elif subject_artifacts_directory is not None: + raise HandoffError("ASEHB012", "A documentation-only result cannot include a subject artifact payload.") + elif expected_image_digest is not None or "envelopeReceipt" in subject_result: + raise HandoffError("ASEHB013", "A documentation-only result cannot include a subject envelope.") + + plan_bytes = _read_regular_file(entries["evidence-plan.json"], MAX_EVIDENCE_PLAN_BYTES, "The verified EvidencePlan") + _write_regular_file(output, plan_bytes) + + +def execute_handoff( + *, + handoff_directory: str | os.PathLike[str], + subject_checkout: str | os.PathLike[str], + scratch_directory: str | os.PathLike[str], + artifact_export_directory: str | os.PathLike[str] | None, + result_path: str | os.PathLike[str], + image_digest: str | None, + environment: Mapping[str, str] | None = None, +) -> int: + """Execute the bounded subject handoff and write its non-claiming result. + + ``artifact_export_directory`` is required for ``code-coverage`` and must + name a new path disjoint from the downloaded handoff, checkout, and + scratch. The trusted launcher creates this private directory only after a + completed run, then exports the three fixed coverage files. This function + accepts that export only when the completed execution record's fixed + artifact index matches the bounded files exactly; any missing, extra, + linked, changed, oversized, or digest-mismatched file fails the handoff + closed and the export is removed without following links. A failed subject + run does not retain an export. ``documentation-only`` completes without + requiring, creating, or accepting an artifact export. Every result remains + ``claimEligible: false``; this seam does not produce a Passed result. + """ + result_destination = Path(result_path).absolute() + result: dict[str, Any] = { + "claimEligible": False, + "execution": "not-run", + "schemaVersion": 1, + } + artifact_export: Path | None = None + retain_artifact_export = False + try: + handoff = _new_path(handoff_directory, "downloaded handoff") + entries = _safe_regular_children(handoff) + manifest, _ = _read_json(entries.get("handoff.json", handoff / "missing"), 128 * 1024, "The controller handoff manifest") + identity, archive_path, evidence_plan = _validate_bundle_directory(handoff, manifest) + env = os.environ if environment is None else environment + run_id = env.get("GITHUB_RUN_ID", "") + attempt = env.get("GITHUB_RUN_ATTEMPT", "") + if POSITIVE_DECIMAL_PATTERN.fullmatch(run_id) is None or POSITIVE_DECIMAL_PATTERN.fullmatch(attempt) is None: + raise HandoffError("ASEHB001", "The trusted workflow run identity is missing or malformed.") + if str(manifest.get("WorkflowRunId")) != run_id or str(manifest.get("WorkflowRunAttempt")) != attempt: + raise HandoffError("ASEHB001", "The downloaded handoff belongs to a different workflow run attempt.") + repository_id = env.get("GITHUB_REPOSITORY_ID", "") + if repository_id and str(manifest.get("RepositoryId")) != repository_id: + raise HandoffError("ASEHB001", "The downloaded handoff belongs to a different repository.") + result["mode"] = manifest["Mode"] + result["workflowRunId"] = run_id + result["workflowRunAttempt"] = attempt + if manifest["Mode"] == "ObservationOnly": + result["execution"] = "observation-only" + result["diagnostic"] = {"code": "ASEHB007", "message": "Untrusted fork input is observation-only."} + _write_subject_result(result_destination, result) + return 2 + assert identity is not None and archive_path is not None and evidence_plan is not None + result["headRevision"] = identity["HeadRevision"] + result["snapshotSha256"] = manifest["SnapshotArchiveSha256"] + profile_id = evidence_plan["Profile"]["Id"] + result["profileId"] = profile_id + if profile_id == "documentation-only": + result.update( + { + "execution": "completed", + "exitCode": 0, + "diagnostic": { + "code": "ASEHB010", + "message": "The explicit empty documentation-only profile completed without OCI execution or a trusted evidence verifier.", + }, + } + ) + _write_subject_result(result_destination, result) + return 0 + if profile_id != "code-coverage": + raise HandoffError("ASEHB008", "The selected EvidencePlan profile is unsupported by the bounded subject handoff.") + if not isinstance(image_digest, str) or not image_digest: + raise HandoffError("ASEHB008", "The digest-pinned offline subject image is not configured.") + if artifact_export_directory is None: + raise HandoffError("ASEHB002", "A new private artifact export directory is required for code-coverage.") + + checkout = _new_output_directory(subject_checkout, "subject checkout") + scratch = _new_output_directory(scratch_directory, "subject scratch") + artifact_export = _new_output_directory(artifact_export_directory, "subject artifact export") + if not _paths_disjoint(handoff, checkout, scratch, artifact_export): + raise HandoffError("ASEHB002", "The subject checkout, scratch, artifact export, and handoff paths must be disjoint.") + file_count, tree_bytes = _extract_snapshot(archive_path, checkout) + result["snapshotFileCount"] = file_count + result["snapshotExpandedBytes"] = tree_bytes + + import importlib.util + + launcher_path = handoff / "evidence-gate-subject.py" + spec = importlib.util.spec_from_file_location("evidence_gate_subject_handoff", launcher_path) + if spec is None or spec.loader is None: + raise HandoffError("ASEHB008", "The trusted subject launcher could not be loaded.") + launcher = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = launcher + previous_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + spec.loader.exec_module(launcher) + finally: + sys.dont_write_bytecode = previous_dont_write_bytecode + limits = launcher.SubjectLimits(**SUBJECT_LIMITS) + subject_result = launcher.launch_subject( + subject_checkout=checkout, + image_digest=image_digest, + scratch_directory=scratch, + artifact_export_directory=artifact_export, + profile_id=profile_id, + source_diff=entries["source.diff"], + source_diff_sha256=manifest["SourceDiffSha256"], + limits=limits, + _environment=env, + ) + execution_record = subject_result.execution_record + if type(subject_result.exit_code) is not int: + raise HandoffError("ASEHB009", "The bounded subject launcher returned a malformed exit code.") + if subject_result.exit_code == 0 and not isinstance(execution_record, Mapping): + raise HandoffError("ASEHB009", "A successful subject run omitted its fixed execution record.") + execution_receipt: dict[str, Any] | None = None + envelope_receipt: dict[str, Any] | None = None + if execution_record is not None: + if not isinstance(execution_record, Mapping): + raise HandoffError("ASEHB009", "The bounded subject launcher returned a malformed execution record.") + if (subject_result.exit_code == 0 and execution_record.get("status") != "completed") or ( + subject_result.exit_code != 0 and execution_record.get("status") == "completed" + ): + raise HandoffError("ASEHB009", "The bounded subject launcher returned a completion record inconsistent with its exit code.") + try: + validated_record = _validate_subject_execution_record( + execution_record, + require_complete=subject_result.exit_code == 0, + ) + execution_receipt = _make_execution_receipt( + execution_record, + _execution_receipt_binding(identity, manifest, profile_id), + ) + except HandoffError: + raise HandoffError("ASEHB009", "The bounded subject launcher returned invalid step proof.") from None + if subject_result.exit_code == 0: + envelope_receipt = _make_envelope_receipt( + getattr(subject_result, "envelope_observation", None), + _execution_receipt_binding(identity, manifest, profile_id), + expected_image_digest=image_digest, + ) + _verify_subject_artifact_export( + artifact_export, + validated_record["artifacts"], + code="ASEHB009", + require_private=True, + ) + result.update( + { + "execution": "completed" if subject_result.exit_code == 0 else "failed", + "exitCode": subject_result.exit_code, + "profileId": profile_id, + "stdoutBytes": len(subject_result.stdout), + "stdoutSha256": hashlib.sha256(subject_result.stdout).hexdigest(), + "stderrBytes": len(subject_result.stderr), + "stderrSha256": hashlib.sha256(subject_result.stderr).hexdigest(), + } + ) + if subject_result.exit_code != 0: + if execution_receipt is not None: + result["executionReceipt"] = execution_receipt + result["diagnostic"] = {"code": "ASEHB009", "message": "The credentialless subject profile exited unsuccessfully."} + else: + assert execution_receipt is not None + assert envelope_receipt is not None + result["executionReceipt"] = execution_receipt + result["envelopeReceipt"] = envelope_receipt + result["diagnostic"] = {"code": "ASEHB010", "message": "Subject execution completed without a trusted evidence verifier."} + retain_artifact_export = True + except HandoffError as failure: + if artifact_export is not None: + _remove_subject_artifact_export(artifact_export) + result["execution"] = "failed" + result["diagnostic"] = {"code": failure.code, "message": failure.message} + except Exception: + if artifact_export is not None: + _remove_subject_artifact_export(artifact_export) + result["execution"] = "failed" + result["diagnostic"] = {"code": "ASEHB011", "message": "The credentialless subject handoff failed closed."} + try: + _write_subject_result(result_destination, result) + except HandoffError as failure: + if artifact_export is not None: + _remove_subject_artifact_export(artifact_export) + print(f"{failure.code}: {failure.message}", file=sys.stderr) + return 2 + if not retain_artifact_export and artifact_export is not None: + _remove_subject_artifact_export(artifact_export) + return 0 if result.get("execution") == "completed" else 2 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + create = subparsers.add_parser("create", help="Build the private controller handoff from a capture directory.") + create.add_argument("--capture-directory", required=True) + create.add_argument("--trusted-scripts-directory", required=True) + create.add_argument("--output-directory", required=True) + create.add_argument("--plan-file", default=None) + execute = subparsers.add_parser("execute", help="Validate and execute the handoff on the credentialless subject job.") + execute.add_argument("--handoff-directory", required=True) + execute.add_argument("--subject-checkout", required=True) + execute.add_argument("--scratch-directory", required=True) + execute.add_argument( + "--artifact-export-directory", + default=None, + help="New private output directory; required for the code-coverage profile.", + ) + execute.add_argument("--result", required=True) + execute.add_argument("--image-digest", default=None) + verify = subparsers.add_parser("verify", help="Bind the downloaded handoff to a fresh trusted PR recapture.") + verify.add_argument("--handoff-directory", required=True) + verify.add_argument("--fresh-capture-directory", required=True) + verify.add_argument("--subject-result", required=True) + verify.add_argument( + "--subject-artifacts", + default=None, + help="Downloaded fixed coverage artifacts; required for code-coverage verification.", + ) + verify.add_argument( + "--expected-image-digest", + default=None, + help="Trusted preflight image digest; required for a code-coverage envelope observation.", + ) + verify.add_argument("--output-plan", required=True) + arguments = parser.parse_args(argv) + try: + if arguments.command == "create": + outcome = create_handoff( + capture_directory=arguments.capture_directory, + trusted_scripts_directory=arguments.trusted_scripts_directory, + output_directory=arguments.output_directory, + plan_file=arguments.plan_file, + ) + print(f"evidence-gate-handoff: {outcome} controller handoff prepared.") + return 0 + if arguments.command == "verify": + verify_handoff( + handoff_directory=arguments.handoff_directory, + fresh_capture_directory=arguments.fresh_capture_directory, + subject_result_file=arguments.subject_result, + output_plan=arguments.output_plan, + subject_artifacts_directory=arguments.subject_artifacts, + expected_image_digest=arguments.expected_image_digest, + ) + print("evidence-gate-handoff: current-revision handoff verified for trusted planning.") + return 0 + environment: dict[str, str] = dict(os.environ) + if arguments.image_digest is None: + arguments.image_digest = environment.get(SUBJECT_IMAGE_ENVIRONMENT_VARIABLE) + return execute_handoff( + handoff_directory=arguments.handoff_directory, + subject_checkout=arguments.subject_checkout, + scratch_directory=arguments.scratch_directory, + artifact_export_directory=arguments.artifact_export_directory, + result_path=arguments.result, + image_digest=arguments.image_digest, + environment=environment, + ) + except HandoffError as failure: + print(f"{failure.code}: {failure.message}", file=sys.stderr) + return 2 + except (OSError, ValueError): + print("ASEHB011: The credentialless subject handoff failed closed.", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-observation.py b/scripts/evidence-gate-observation.py new file mode 100644 index 000000000..06f9782f3 --- /dev/null +++ b/scripts/evidence-gate-observation.py @@ -0,0 +1,577 @@ +#!/usr/bin/env python3 +"""Build a bounded, non-claiming observation from trusted verifier inputs. + +This command records what the base-owned verifier checked. It does not attest +the subject checkout, prove runtime enforcement or producer truth, or create a +gate verdict. Every input remains bounded and is opened without following +symbolic links, including parent directories. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import sys +from typing import Any, Mapping + + +MAX_OUTPUT_BYTES = 16 * 1024 +MAX_PLAN_BYTES = 4 * 1024 * 1024 +MAX_IDENTITY_BYTES = 16 * 1024 +MAX_SUBJECT_RESULT_BYTES = 16 * 1024 +MAX_CLEANUP_BYTES = 4 * 1024 +MAX_ARTIFACT_BYTES = { + "cobertura.xml": 20 * 1024 * 1024, + "gate-report.md": 1 * 1024 * 1024, + "diagnostics.json": 4 * 1024 * 1024, +} +ARTIFACT_INDEX = ( + ("cobertura.xml", "cobertura", "coverage/coverage-merged/coverage.cobertura.xml"), + ("gate-report.md", "gate-report", "coverage/coverage-gate/coverage-gate.md"), + ("diagnostics.json", "diagnostics", "coverage/coverage-gate/coverage-gate.json"), +) +REVISION_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +SHA256_PATTERN = re.compile(r"[0-9a-f]{64}\Z") +DECIMAL_PATTERN = re.compile(r"[1-9][0-9]{0,18}\Z") +REPOSITORY_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,99}/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\Z") +IMAGE_PATTERN = re.compile( + r"ghcr\.io/forge-trust/appsurface-subject-native-validation@sha256:[0-9a-f]{64}\Z" +) + + +class ObservationError(Exception): + """A fixed, non-sensitive failure for an invalid observation input.""" + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("ascii") + + +def _canonical_plan(value: Mapping[str, Any]) -> bytes: + """Match the EvidencePlan serializer's additional JSON string escaping.""" + encoded = _canonical(value) + escaped_ascii = { + ord("+"): b"\\u002B", + ord("<"): b"\\u003C", + ord(">"): b"\\u003E", + ord("&"): b"\\u0026", + ord("'"): b"\\u0027", + ord("`"): b"\\u0060", + } + output = bytearray() + in_string = False + index = 0 + while index < len(encoded): + character = encoded[index] + if character == ord('"'): + in_string = not in_string + output.append(character) + elif in_string and character == ord("\\") and index + 1 < len(encoded): + next_character = encoded[index + 1] + if next_character == ord('"'): + output.extend(b"\\u0022") + elif next_character == ord("u") and index + 5 < len(encoded): + output.extend(b"\\u" + encoded[index + 2 : index + 6].upper()) + index += 4 + else: + output.extend(encoded[index : index + 2]) + index += 1 + elif in_string and character in escaped_ascii: + output.extend(escaped_ascii[character]) + else: + output.append(character) + index += 1 + return bytes(output) + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON property") + result[key] = value + return result + + +def _reject_constant(_value: str) -> None: + raise ValueError("non-standard JSON constant") + + +def _absolute_parts(path: Path) -> tuple[str, ...]: + if not path.is_absolute() or ".." in path.parts or "\x00" in os.fspath(path): + raise ObservationError("unsafe path") + return path.parts[1:] + + +def _open_directory(path: Path) -> int: + parts = _absolute_parts(path) + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + descriptor = -1 + try: + descriptor = os.open("/", flags) + for component in parts: + next_descriptor = os.open(component, flags, dir_fd=descriptor) + os.close(descriptor) + descriptor = next_descriptor + metadata = os.fstat(descriptor) + if not stat.S_ISDIR(metadata.st_mode): + raise ObservationError("unsafe directory") + return descriptor + except (OSError, ValueError): + if descriptor >= 0: + os.close(descriptor) + raise ObservationError("unsafe directory") from None + + +def _read_at(directory_fd: int, name: str, maximum_bytes: int) -> bytes: + descriptor = -1 + try: + descriptor = os.open( + name, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), + dir_fd=directory_fd, + ) + before = os.fstat(descriptor) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or before.st_size <= 0 + or before.st_size > maximum_bytes + ): + raise ObservationError("unsafe file") + chunks: list[bytes] = [] + total = 0 + while total <= maximum_bytes: + chunk = os.read(descriptor, min(64 * 1024, maximum_bytes + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > maximum_bytes: + raise ObservationError("oversized file") + chunks.append(chunk) + after = os.fstat(descriptor) + if ( + total != before.st_size + or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) + != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + ): + raise ObservationError("changed file") + return b"".join(chunks) + except ObservationError: + raise + except (OSError, ValueError): + raise ObservationError("unavailable file") from None + finally: + if descriptor >= 0: + os.close(descriptor) + + +def _read_file(path: Path, maximum_bytes: int) -> bytes: + parts = _absolute_parts(path) + if not parts: + raise ObservationError("invalid file") + directory_fd = _open_directory(path.parent) + try: + return _read_at(directory_fd, parts[-1], maximum_bytes) + finally: + os.close(directory_fd) + + +def _read_json(raw: bytes) -> dict[str, Any]: + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_reject_constant) + except (UnicodeError, ValueError, RecursionError): + raise ObservationError("malformed JSON") from None + if not isinstance(value, dict): + raise ObservationError("unexpected JSON shape") + return value + + +def _require_decimal(value: Any) -> str: + if not isinstance(value, str) or DECIMAL_PATTERN.fullmatch(value) is None: + raise ObservationError("invalid identity") + return value + + +def _require_sha(value: Any, pattern: re.Pattern[str] = SHA256_PATTERN) -> str: + if not isinstance(value, str) or pattern.fullmatch(value) is None: + raise ObservationError("invalid digest") + return value + + +def _validate_identity(value: Mapping[str, Any]) -> dict[str, Any]: + if set(value) != {"EventName", "Repository", "RunIdentity", "SubjectJobId", "WorkflowId"}: + raise ObservationError("invalid verifier identity") + repository = value.get("Repository") + if not isinstance(repository, str) or REPOSITORY_PATTERN.fullmatch(repository) is None: + raise ObservationError("invalid verifier identity") + run = value.get("RunIdentity") + run_keys = { + "HeadRepositoryId", "PullRequestNumber", "RepositoryId", "TargetBranch", "WorkflowRunAttempt", "WorkflowRunId", + } + if not isinstance(run, dict) or set(run) != run_keys or value.get("EventName") != "pull_request_target": + raise ObservationError("invalid verifier identity") + if _require_decimal(value.get("WorkflowId")) != value["WorkflowId"]: + raise ObservationError("invalid verifier identity") + _require_decimal(value.get("SubjectJobId")) + for key in ("RepositoryId", "HeadRepositoryId", "PullRequestNumber", "WorkflowRunId", "WorkflowRunAttempt"): + if type(run.get(key)) is not int or not 0 < run[key] <= (1 << 63) - 1: + raise ObservationError("invalid verifier identity") + if run["RepositoryId"] != run["HeadRepositoryId"]: + raise ObservationError("invalid verifier identity") + branch = run.get("TargetBranch") + if not isinstance(branch, str) or not branch or len(branch) > 128 or any(char in branch for char in "\x00\r\n"): + raise ObservationError("invalid verifier identity") + return dict(value) + + +def _validate_plan(value: Mapping[str, Any], identity: Mapping[str, Any]) -> tuple[str, dict[str, str]]: + run = identity["RunIdentity"] + base_revision = _require_sha(value.get("BaseRevision"), REVISION_PATTERN) + head_revision = _require_sha(value.get("HeadRevision"), REVISION_PATTERN) + if len(base_revision) != len(head_revision): + raise ObservationError("plan revisions use different Git object formats") + plan_identity = value.get("PullRequestRunIdentity") + expected_plan_identity = { + key: run[key] + for key in ("RepositoryId", "HeadRepositoryId", "PullRequestNumber", "TargetBranch", "WorkflowRunId", "WorkflowRunAttempt") + } + if ( + value.get("ContractVersion") != "2.0" + or not isinstance(plan_identity, dict) + or set(plan_identity) != set(expected_plan_identity) + or any(type(plan_identity[key]) is not type(expected) or plan_identity[key] != expected for key, expected in expected_plan_identity.items()) + ): + raise ObservationError("plan binding mismatch") + profile = value.get("Profile") + if not isinstance(profile, dict) or profile.get("Scope") != "Targeted": + raise ObservationError("invalid profile") + profile_id = profile.get("Id") + if not isinstance(profile_id, str) or profile_id not in {"documentation-only", "code-coverage"}: + raise ObservationError("unsupported profile") + if any(not isinstance(profile.get(key), list) for key in ("Resources", "Producers", "Obligations")): + raise ObservationError("invalid profile") + if profile_id == "documentation-only" and any(profile[key] for key in ("Resources", "Producers", "Obligations")): + raise ObservationError("nonempty documentation profile") + policy = value.get("PolicySnapshot") + profiles = policy.get("Profiles") if isinstance(policy, dict) else None + matches = [candidate for candidate in profiles if isinstance(candidate, dict) and candidate.get("Id") == profile_id] if isinstance(profiles, list) else [] + if len(matches) != 1 or matches[0] != profile: + raise ObservationError("profile is not closed by policy snapshot") + digests = { + key: _require_sha(value.get(key)) + for key in ("PlanDigest", "PolicyDigest", "DiffDigest", "NameStatusDigest", "SourceDiffDigest") + } + if not isinstance(value.get("PolicyId"), str) or not value["PolicyId"] or len(value["PolicyId"]) > 128: + raise ObservationError("invalid plan") + return profile_id, digests + + +def _expected_receipt_binding( + identity: Mapping[str, Any], + plan: Mapping[str, Any], + profile_id: str, + snapshot_sha256: str, +) -> dict[str, str]: + run = identity["RunIdentity"] + return { + "baseRevision": plan["BaseRevision"], + "headRevision": plan["HeadRevision"], + "profileId": profile_id, + "snapshotSha256": snapshot_sha256, + "workflowRunAttempt": str(run["WorkflowRunAttempt"]), + "workflowRunId": str(run["WorkflowRunId"]), + } + + +def _validate_receipt(value: Any, binding: Mapping[str, str], member: str) -> Mapping[str, Any]: + if ( + not isinstance(value, dict) + or set(value) != {"binding", member, "schemaVersion", "sha256"} + or type(value.get("schemaVersion")) is not int + or value["schemaVersion"] != 1 + or value.get("binding") != dict(binding) + ): + raise ObservationError("invalid receipt") + digest = _require_sha(value.get("sha256")) + payload = {"binding": value["binding"], member: value[member], "schemaVersion": 1} + try: + actual_digest = hashlib.sha256(_canonical(payload)).hexdigest() + except (TypeError, ValueError, RecursionError): + raise ObservationError("invalid receipt") from None + if actual_digest != digest: + raise ObservationError("invalid receipt digest") + record = value[member] + if not isinstance(record, dict): + raise ObservationError("invalid receipt record") + return record + + +def _read_artifacts(directory: Path, indexed: Any) -> list[dict[str, Any]]: + if not isinstance(indexed, list) or len(indexed) != len(ARTIFACT_INDEX): + raise ObservationError("invalid artifact index") + directory_fd = _open_directory(directory) + try: + if set(os.listdir(directory_fd)) != set(MAX_ARTIFACT_BYTES): + raise ObservationError("unexpected artifact inventory") + results: list[dict[str, Any]] = [] + for entry, (basename, logical_name, relative_path) in zip(indexed, ARTIFACT_INDEX, strict=True): + if ( + not isinstance(entry, dict) + or set(entry) != {"logicalName", "relativePath", "byteCount", "sha256"} + or entry.get("logicalName") != logical_name + or entry.get("relativePath") != relative_path + or type(entry.get("byteCount")) is not int + or not 0 < entry["byteCount"] <= MAX_ARTIFACT_BYTES[basename] + ): + raise ObservationError("invalid artifact index") + raw = _read_at(directory_fd, basename, MAX_ARTIFACT_BYTES[basename]) + digest = hashlib.sha256(raw).hexdigest() + if len(raw) != entry["byteCount"] or digest != _require_sha(entry.get("sha256")): + raise ObservationError("artifact mismatch") + results.append({"name": basename, "byteCount": len(raw), "sha256": digest}) + if set(os.listdir(directory_fd)) != set(MAX_ARTIFACT_BYTES): + raise ObservationError("changed artifact inventory") + return results + except OSError: + raise ObservationError("unsafe artifacts") from None + finally: + os.close(directory_fd) + + +def _validate_cleanup(raw: bytes) -> None: + record = _read_json(raw) + if set(record) != { + "schemaVersion", "claimEligible", "published", "status", "trigger", "containerStatus", + "mountStatus", "scratchStatus", "failureCode", "cleanupDeadlineSeconds", + }: + raise ObservationError("invalid cleanup record") + if ( + type(record.get("schemaVersion")) is not int + or record["schemaVersion"] != 1 + or record.get("claimEligible") is not False + or record.get("published") is not False + or record.get("status") != "complete" + or record.get("trigger") not in {"request", "parent-exit"} + or record.get("containerStatus") not in {"removed", "absent"} + or record.get("mountStatus") not in {"unmounted", "absent"} + or record.get("scratchStatus") not in {"removed", "absent"} + or record.get("failureCode") != "none" + or type(record.get("cleanupDeadlineSeconds")) is not int + or record["cleanupDeadlineSeconds"] != 600 + or raw != _canonical(record) + b"\n" + ): + raise ObservationError("incomplete cleanup record") + + +def build_observation( + *, + verified_plan_path: Path, + verifier_identity_path: Path, + subject_result_path: Path, + cleanup_record_path: Path | None = None, + subject_artifacts_directory: Path | None = None, + expected_image_digest: str | None = None, +) -> dict[str, Any]: + plan_raw = _read_file(verified_plan_path, MAX_PLAN_BYTES) + identity_raw = _read_file(verifier_identity_path, MAX_IDENTITY_BYTES) + subject_raw = _read_file(subject_result_path, MAX_SUBJECT_RESULT_BYTES) + plan = _read_json(plan_raw) + identity_value = _read_json(identity_raw) + if _canonical(identity_value) != identity_raw: + raise ObservationError("noncanonical verifier identity") + identity = _validate_identity(identity_value) + if _canonical_plan(plan) != plan_raw: + raise ObservationError("noncanonical verified plan") + profile_id, digests = _validate_plan(plan, identity) + run = identity["RunIdentity"] + subject = _read_json(subject_raw) + if not subject_raw.endswith(b"\n") or _canonical(subject) + b"\n" != subject_raw: + raise ObservationError("noncanonical subject result") + snapshot_sha256 = _require_sha(subject.get("snapshotSha256")) + expected_common = { + "claimEligible": False, + "execution": "completed", + "exitCode": 0, + "headRevision": plan["HeadRevision"], + "mode": "SubjectSnapshot", + "profileId": profile_id, + "schemaVersion": 1, + "snapshotSha256": snapshot_sha256, + "workflowRunAttempt": str(run["WorkflowRunAttempt"]), + "workflowRunId": str(run["WorkflowRunId"]), + } + if any(type(subject.get(key)) is not type(expected) or subject.get(key) != expected for key, expected in expected_common.items()): + raise ObservationError("subject binding mismatch") + diagnostic = subject.get("diagnostic") + if not isinstance(diagnostic, dict) or set(diagnostic) != {"code", "message"} or diagnostic.get("code") != "ASEHB010" or not isinstance(diagnostic.get("message"), str): + raise ObservationError("invalid subject result") + + input_hashes = { + "verifiedPlan": hashlib.sha256(plan_raw).hexdigest(), + "verifierIdentity": hashlib.sha256(identity_raw).hexdigest(), + "subjectResult": hashlib.sha256(subject_raw).hexdigest(), + } + artifacts: list[dict[str, Any]] = [] + trusted_preflight: dict[str, str] | None = None + if profile_id == "documentation-only": + if cleanup_record_path is not None or subject_artifacts_directory is not None or expected_image_digest is not None: + raise ObservationError("coverage inputs forbidden for documentation-only") + if set(subject) != set(expected_common) | {"diagnostic"}: + raise ObservationError("unexpected documentation result fields") + if "envelopeReceipt" in subject or "executionReceipt" in subject: + raise ObservationError("unexpected documentation receipt") + else: + if cleanup_record_path is None or subject_artifacts_directory is None or expected_image_digest is None: + raise ObservationError("coverage inputs required") + if not isinstance(expected_image_digest, str) or IMAGE_PATTERN.fullmatch(expected_image_digest) is None: + raise ObservationError("invalid preflight image digest") + expected_fields = set(expected_common) | { + "diagnostic", "executionReceipt", "envelopeReceipt", "snapshotFileCount", "snapshotExpandedBytes", + "stdoutBytes", "stdoutSha256", "stderrBytes", "stderrSha256", + } + if set(subject) != expected_fields: + raise ObservationError("unexpected coverage result fields") + for field in ("snapshotFileCount", "snapshotExpandedBytes", "stdoutBytes", "stderrBytes"): + if type(subject.get(field)) is not int or subject[field] < 0: + raise ObservationError("invalid coverage result counters") + for field in ("stdoutSha256", "stderrSha256"): + _require_sha(subject.get(field)) + binding = _expected_receipt_binding(identity, plan, profile_id, snapshot_sha256) + execution = _validate_receipt(subject.get("executionReceipt"), binding, "record") + if ( + set(execution) != {"claimEligible", "profileId", "schemaVersion", "status", "steps", "artifacts"} + or execution.get("claimEligible") is not False + or execution.get("profileId") != "code-coverage" + or type(execution.get("schemaVersion")) is not int + or execution["schemaVersion"] != 1 + or execution.get("status") != "completed" + or not isinstance(execution.get("steps"), list) + or len(execution["steps"]) != 5 + ): + raise ObservationError("invalid execution receipt") + envelope = _validate_receipt(subject.get("envelopeReceipt"), binding, "observation") + expected_envelope_fields = { + "schemaVersion", "imageDigest", "profileId", "runnerEnvironment", "runtime", "networkMode", + "rootfsReadOnlyConfigured", "subjectAndDiffReadOnlyConfigured", "scratchTmpfsQuotaVerified", + "capabilityDropConfigured", "noNewPrivilegesConfigured", "pidIpcUtsUserNamespacesConfiguredPrivate", + "resourceLimitsConfigured", + } + if ( + set(envelope) != expected_envelope_fields + or type(envelope.get("schemaVersion")) is not int + or envelope["schemaVersion"] != 1 + or envelope.get("imageDigest") != expected_image_digest + or envelope.get("profileId") != "code-coverage" + or envelope.get("runnerEnvironment") != "github-hosted" + or envelope.get("runtime") != "rootless-podman" + or envelope.get("networkMode") != "none" + or any(envelope.get(key) is not True for key in expected_envelope_fields if key.endswith("Configured") or key == "scratchTmpfsQuotaVerified") + ): + raise ObservationError("preflight image or envelope mismatch") + artifacts = _read_artifacts(subject_artifacts_directory, execution.get("artifacts")) + cleanup_raw = _read_file(cleanup_record_path, MAX_CLEANUP_BYTES) + _validate_cleanup(cleanup_raw) + input_hashes["cleanupRecord"] = hashlib.sha256(cleanup_raw).hexdigest() + input_hashes["trustedPreflightImageDigest"] = hashlib.sha256(expected_image_digest.encode("ascii")).hexdigest() + trusted_preflight = {"subjectImageDigest": expected_image_digest} + + repository = identity["Repository"] + run_identity = { + "repositoryId": str(run["RepositoryId"]), + "headRepositoryId": str(run["HeadRepositoryId"]), + "pullRequestNumber": str(run["PullRequestNumber"]), + "targetBranch": run["TargetBranch"], + "baseRevision": plan["BaseRevision"], + "headRevision": plan["HeadRevision"], + } + return { + "claimEligible": False, + "inputSha256": input_hashes, + "profile": { + "id": profile_id, + "planDigest": digests["PlanDigest"], + "policyDigest": digests["PolicyDigest"], + "diffDigest": digests["DiffDigest"], + "sourceDiffDigest": digests["SourceDiffDigest"], + }, + "run": { + "eventName": identity["EventName"], + "repository": repository, + "workflowId": identity["WorkflowId"], + "runId": str(run["WorkflowRunId"]), + "runAttempt": str(run["WorkflowRunAttempt"]), + "subjectJobId": identity["SubjectJobId"], + "pullRequestIdentity": run_identity, + }, + "schemaVersion": 1, + "semantics": "Observation only; does not attest subject checkout, isolation enforcement, producer truth, or gate eligibility.", + "snapshotSha256": snapshot_sha256, + "subjectArtifacts": artifacts, + "trustedPreflight": trusted_preflight, + } + + +def _write_new_output(path: Path, value: Mapping[str, Any]) -> None: + raw = _canonical(value) + b"\n" + if len(raw) > MAX_OUTPUT_BYTES: + raise ObservationError("observation exceeds output limit") + parts = _absolute_parts(path) + if not parts: + raise ObservationError("invalid output path") + directory_fd = _open_directory(path.parent) + descriptor = -1 + try: + descriptor = os.open( + parts[-1], + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + 0o600, + dir_fd=directory_fd, + ) + with os.fdopen(descriptor, "wb") as output: + descriptor = -1 + output.write(raw) + output.flush() + os.fsync(output.fileno()) + except (OSError, ValueError): + raise ObservationError("observation output unavailable") from None + finally: + if descriptor >= 0: + os.close(descriptor) + os.close(directory_fd) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--verified-plan", required=True, type=Path) + parser.add_argument("--verifier-identity", required=True, type=Path) + parser.add_argument("--subject-result", required=True, type=Path) + parser.add_argument("--cleanup-record", type=Path) + parser.add_argument("--subject-artifacts-directory", type=Path) + parser.add_argument("--expected-image-digest") + parser.add_argument("--output", required=True, type=Path) + arguments = parser.parse_args(argv) + try: + observation = build_observation( + verified_plan_path=arguments.verified_plan, + verifier_identity_path=arguments.verifier_identity, + subject_result_path=arguments.subject_result, + cleanup_record_path=arguments.cleanup_record, + subject_artifacts_directory=arguments.subject_artifacts_directory, + expected_image_digest=arguments.expected_image_digest, + ) + _write_new_output(arguments.output, observation) + except ObservationError: + print("evidence-gate-observation: ASEGO001: trusted observation inputs were invalid or unsafe.", file=sys.stderr) + return 2 + print("evidence-gate-observation: bounded non-claiming observation recorded.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-policy-shadow.py b/scripts/evidence-gate-policy-shadow.py new file mode 100644 index 000000000..f619a9d76 --- /dev/null +++ b/scripts/evidence-gate-policy-shadow.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +"""Prepare fixed candidate policy-shadow inputs from a captured Git commit. + +This helper is intended for a base-owned workflow. It reads only the captured +HeadRevision's policy and fixture blobs from the retained bare Git store. It +does not check out the candidate tree or execute candidate-controlled code. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import selectors +import stat +import subprocess +import sys +import time +from typing import Any + + +MAX_FILE_BYTES = 1024 * 1024 +MAX_TREE_OUTPUT_BYTES = 64 * 1024 +MAX_GIT_STDERR_BYTES = 4096 +MAX_GIT_SECONDS = 20 +GIT_SHA_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") +POLICY_PATH = ".appsurface/evidence/evidence.policy.json" +FIXTURES_PATH = "docs/fixtures/issue-777-policy-shadow/fixtures.json" +FIXED_CANDIDATE_PATHS = (POLICY_PATH, FIXTURES_PATH) +IDENTITY_KEYS = frozenset( + { + "BaseRevision", + "HeadRepositoryId", + "HeadRevision", + "PullRequestNumber", + "RepositoryId", + "TargetBranch", + "WorkflowRunAttempt", + "WorkflowRunId", + } +) + + +class PolicyShadowPreparerError(Exception): + """A bounded diagnostic safe to print in trusted workflow logs.""" + + +def _git_environment() -> dict[str, str]: + path = os.environ.get("PATH") + if not path: + raise PolicyShadowPreparerError("The trusted Git executable is unavailable.") + return { + "PATH": path, + "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_COUNT": "0", + "GIT_CONFIG_PARAMETERS": "", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_ATTR_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "GIT_PAGER": "cat", + } + + +def _run_git(arguments: list[str], *, deadline: float, maximum_output_bytes: int) -> bytes: + if not arguments or arguments[0] != "git" or any(not isinstance(argument, str) for argument in arguments): + raise PolicyShadowPreparerError("A fixed Git argument vector is required.") + if maximum_output_bytes < 0: + raise PolicyShadowPreparerError("The Git output limit is invalid.") + if deadline <= time.monotonic(): + raise PolicyShadowPreparerError("The bounded Git deadline expired.") + + try: + process = subprocess.Popen( + arguments, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + env=_git_environment(), + ) + except (OSError, ValueError): + raise PolicyShadowPreparerError("The trusted Git process could not start.") from None + + assert process.stdout is not None and process.stderr is not None + selector = selectors.DefaultSelector() + output = bytearray() + stderr_count = 0 + try: + os.set_blocking(process.stdout.fileno(), False) + os.set_blocking(process.stderr.fileno(), False) + selector.register(process.stdout, selectors.EVENT_READ, "stdout") + selector.register(process.stderr, selectors.EVENT_READ, "stderr") + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise PolicyShadowPreparerError("The bounded Git deadline expired.") + ready = selector.select(remaining) + if not ready: + raise PolicyShadowPreparerError("The bounded Git deadline expired.") + for key, _ in ready: + if key.data == "stdout": + remaining_bytes = maximum_output_bytes + 1 - len(output) + else: + remaining_bytes = MAX_GIT_STDERR_BYTES + 1 - stderr_count + try: + chunk = os.read(key.fileobj.fileno(), min(64 * 1024, remaining_bytes)) + except OSError: + raise PolicyShadowPreparerError("The trusted Git output could not be read.") from None + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + elif key.data == "stdout": + output.extend(chunk) + if len(output) > maximum_output_bytes: + raise PolicyShadowPreparerError("Git output exceeds its reviewed byte limit.") + else: + stderr_count += len(chunk) + if stderr_count > MAX_GIT_STDERR_BYTES: + raise PolicyShadowPreparerError("Git diagnostics exceed their reviewed byte limit.") + + remaining = deadline - time.monotonic() + if remaining <= 0: + raise PolicyShadowPreparerError("The bounded Git deadline expired.") + try: + return_code = process.wait(timeout=remaining) + except subprocess.TimeoutExpired: + raise PolicyShadowPreparerError("The bounded Git deadline expired.") from None + if return_code != 0: + raise PolicyShadowPreparerError("Git could not read the exact captured head commit.") + return bytes(output) + except BaseException: + if process.poll() is None: + try: + process.kill() + process.wait(timeout=1) + except (OSError, subprocess.TimeoutExpired): + pass + raise + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if not pipe.closed: + pipe.close() + + +def _read_regular_file(path: Path, description: str) -> bytes: + try: + descriptor = os.open( + path, + os.O_RDONLY + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_NONBLOCK", 0), + ) + except (OSError, ValueError): + raise PolicyShadowPreparerError(f"{description} is unavailable or unsafe.") from None + + try: + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > MAX_FILE_BYTES: + raise PolicyShadowPreparerError(f"{description} is not a bounded regular file.") + content = bytearray() + while True: + chunk = os.read(descriptor, min(64 * 1024, MAX_FILE_BYTES + 1 - len(content))) + if not chunk: + return bytes(content) + content.extend(chunk) + if len(content) > MAX_FILE_BYTES: + raise PolicyShadowPreparerError(f"{description} exceeds its 1 MiB byte limit.") + except OSError: + raise PolicyShadowPreparerError(f"{description} could not be read safely.") from None + finally: + os.close(descriptor) + + +def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise PolicyShadowPreparerError("The captured identity contains duplicate keys.") + result[key] = value + return result + + +def _read_identity(capture_directory: Path) -> dict[str, Any]: + capture_metadata = _lstat(capture_directory, "The controller capture directory") + if not stat.S_ISDIR(capture_metadata.st_mode): + raise PolicyShadowPreparerError("The controller capture directory is unavailable or unsafe.") + identity_path = capture_directory / "pull-request-run-identity.json" + raw_identity = _read_regular_file(identity_path, "The captured pull-request run identity") + try: + identity = json.loads(raw_identity, object_pairs_hook=_reject_duplicate_keys) + except PolicyShadowPreparerError: + raise + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError): + raise PolicyShadowPreparerError("The captured pull-request run identity is malformed.") from None + if not isinstance(identity, dict) or set(identity) != IDENTITY_KEYS: + raise PolicyShadowPreparerError("The captured pull-request run identity has an unexpected shape.") + + for key in ("BaseRevision", "HeadRevision"): + revision = identity[key] + if not isinstance(revision, str) or GIT_SHA_PATTERN.fullmatch(revision) is None: + raise PolicyShadowPreparerError(f"The captured {key} is not a full lower-case Git object ID.") + if len(identity["BaseRevision"]) != len(identity["HeadRevision"]): + raise PolicyShadowPreparerError("The captured revisions use different Git object formats.") + for key in ("HeadRepositoryId", "PullRequestNumber", "RepositoryId", "WorkflowRunAttempt", "WorkflowRunId"): + value = identity[key] + if type(value) is not int or value <= 0 or value > (1 << 63) - 1: + raise PolicyShadowPreparerError(f"The captured {key} is not a positive bounded integer.") + if identity["HeadRepositoryId"] != identity["RepositoryId"]: + raise PolicyShadowPreparerError("The captured pull request is not same-repository input.") + branch = identity["TargetBranch"] + if not isinstance(branch, str) or not branch or len(branch) > 128 or any(char in branch for char in "\x00\r\n"): + raise PolicyShadowPreparerError("The captured target branch is malformed.") + return identity + + +def _lstat(path: Path, description: str) -> os.stat_result: + try: + return os.lstat(path) + except (OSError, ValueError): + raise PolicyShadowPreparerError(f"{description} is unavailable or unsafe.") from None + + +def _read_protected_base_file(protected_base: Path, relative_path: str) -> bytes: + path = protected_base + parts = relative_path.split("/") + for index, part in enumerate(parts): + path = path / part + metadata = _lstat(path, "A fixed protected-base input") + if stat.S_ISLNK(metadata.st_mode): + raise PolicyShadowPreparerError("A fixed protected-base input is a symbolic link.") + if index < len(parts) - 1 and not stat.S_ISDIR(metadata.st_mode): + raise PolicyShadowPreparerError("A fixed protected-base input has an unsafe parent.") + return _read_regular_file(path, "A fixed protected-base input") + + +def _captured_entries(repository: Path, head_revision: str, deadline: float) -> dict[str, tuple[str, str]]: + common_arguments = [ + "git", + "--no-pager", + "--no-replace-objects", + f"--git-dir={repository}", + "-c", + f"core.attributesFile={os.devnull}", + ] + object_type = _run_git( + [*common_arguments, "cat-file", "-t", head_revision], + deadline=deadline, + maximum_output_bytes=32, + ) + if object_type != b"commit\n": + raise PolicyShadowPreparerError("The captured head object is not a commit.") + + tree = _run_git( + [ + *common_arguments, + "ls-tree", + "-z", + "--full-tree", + "--no-abbrev", + head_revision, + "--", + *FIXED_CANDIDATE_PATHS, + ], + deadline=deadline, + maximum_output_bytes=MAX_TREE_OUTPUT_BYTES, + ) + result: dict[str, tuple[str, str]] = {} + if not tree: + return result + if not tree.endswith(b"\0"): + raise PolicyShadowPreparerError("The captured head tree response is malformed.") + fixed_paths = {path.encode("ascii") for path in FIXED_CANDIDATE_PATHS} + for entry in tree[:-1].split(b"\0"): + try: + header, raw_path = entry.split(b"\t", 1) + mode_bytes, object_type_bytes, object_id_bytes = header.split(b" ") + candidate_path = raw_path.decode("ascii") + mode = mode_bytes.decode("ascii") + blob_type = object_type_bytes.decode("ascii") + object_id = object_id_bytes.decode("ascii") + except (UnicodeDecodeError, ValueError): + raise PolicyShadowPreparerError("The captured head tree response is malformed.") from None + if raw_path not in fixed_paths or candidate_path in result: + raise PolicyShadowPreparerError("Git returned an unexpected fixed-path entry.") + if mode != "100644" or blob_type != "blob": + raise PolicyShadowPreparerError("A captured candidate input uses an unsafe Git file mode.") + if GIT_SHA_PATTERN.fullmatch(object_id) is None or len(object_id) != len(head_revision): + raise PolicyShadowPreparerError("A captured candidate blob has an invalid object ID.") + result[candidate_path] = (mode, object_id) + return result + + +def _write_new_file(path: Path, content: bytes) -> None: + try: + descriptor = os.open( + path, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + with os.fdopen(descriptor, "wb") as output_file: + output_file.write(content) + output_file.flush() + os.fsync(output_file.fileno()) + except OSError: + raise PolicyShadowPreparerError("A candidate policy-shadow input could not be written safely.") from None + + +def prepare(capture_directory: Path, protected_base: Path, output_directory: Path) -> Path: + """Extract the captured fixed candidate inputs into a new private directory.""" + + capture_directory = Path(capture_directory) + protected_base = Path(protected_base) + output_directory = Path(output_directory) + + protected_metadata = _lstat(protected_base, "The protected-base checkout") + if not stat.S_ISDIR(protected_metadata.st_mode): + raise PolicyShadowPreparerError("The protected-base checkout is unavailable or unsafe.") + # Confirm the two CLI base inputs are bounded regular files under fixed paths. + _read_protected_base_file(protected_base, POLICY_PATH) + _read_protected_base_file(protected_base, FIXTURES_PATH) + + identity = _read_identity(capture_directory) + repository = capture_directory / "repository.git" + repository_metadata = _lstat(repository, "The retained controller Git store") + if not stat.S_ISDIR(repository_metadata.st_mode): + raise PolicyShadowPreparerError("The retained controller Git store is unavailable or unsafe.") + + output_parent = output_directory.parent + parent_metadata = _lstat(output_parent, "The candidate output parent") + if not stat.S_ISDIR(parent_metadata.st_mode): + raise PolicyShadowPreparerError("The candidate output parent is unavailable or unsafe.") + if os.path.lexists(output_directory): + raise PolicyShadowPreparerError("The candidate output directory must be new.") + + deadline = time.monotonic() + MAX_GIT_SECONDS + entries = _captured_entries(repository, identity["HeadRevision"], deadline) + if POLICY_PATH not in entries: + raise PolicyShadowPreparerError("The captured head is missing its required candidate policy.") + + blobs: dict[str, bytes] = {} + for candidate_path in FIXED_CANDIDATE_PATHS: + entry = entries.get(candidate_path) + if entry is None: + continue + _mode, object_id = entry + blobs[candidate_path] = _run_git( + [ + "git", + "--no-pager", + "--no-replace-objects", + f"--git-dir={repository}", + "-c", + f"core.attributesFile={os.devnull}", + "cat-file", + "blob", + object_id, + ], + deadline=deadline, + maximum_output_bytes=MAX_FILE_BYTES, + ) + + try: + output_directory.mkdir(mode=0o700) + for candidate_path, content in blobs.items(): + destination = output_directory.joinpath(*candidate_path.split("/")) + destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + _write_new_file(destination, content) + except PolicyShadowPreparerError: + raise + except OSError: + raise PolicyShadowPreparerError("The candidate policy-shadow output could not be created safely.") from None + return output_directory + + +def _parse_arguments(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--capture-directory", required=True, type=Path) + parser.add_argument("--protected-base", required=True, type=Path) + parser.add_argument("--output-directory", required=True, type=Path) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + try: + arguments = _parse_arguments(argv) + output = prepare(arguments.capture_directory, arguments.protected_base, arguments.output_directory) + except PolicyShadowPreparerError as error: + print(f"evidence-gate-policy-shadow: {error}", file=sys.stderr) + return 2 + print(f"Prepared fixed candidate policy-shadow inputs in {output}.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-subject-entrypoint.py b/scripts/evidence-gate-subject-entrypoint.py new file mode 100644 index 000000000..9bd76bfd5 --- /dev/null +++ b/scripts/evidence-gate-subject-entrypoint.py @@ -0,0 +1,1082 @@ +#!/usr/bin/env python3 +"""Run the fixed, offline code-coverage subject profile. + +This executable is intended to be installed in the digest-pinned subject image +at ``/usr/local/libexec/appsurface-subject-runner``. It accepts only the +controller's fixed profile arguments; it never accepts a command or image from +the subject. The subject checkout is validated as a read-only mount and copied +without following links into private scratch, where .NET may write build output. + +The result is an execution record, not an Evidence claim. The fixed profile +checks aggregate and patch coverage against the controller-captured diff, but +the current full solution also needs container-backed tests that this offline +envelope cannot run. A later trusted verifier must independently validate any +artifacts and the execution envelope before a complete producer can exist. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass, field +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import selectors +import signal +import stat +import subprocess +import sys +import time +from typing import Callable, Mapping, Sequence +import xml.etree.ElementTree as ElementTree + + +SUBJECT_ROOT = Path("/subject") +SCRATCH_ROOT = Path("/scratch") +DEPENDENCY_SOURCE = Path("/opt/appsurface/locked-dependencies") +PATCH_DIFF_PATH = Path("/source.diff") +SOLUTION_RELATIVE_PATH = Path("ForgeTrust.AppSurface.slnx") +CLI_RELATIVE_PATH = Path("Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj") +RESULT_RELATIVE_PATH = Path("evidence-subject-result.json") +RESTORE_CONFIG_RELATIVE_PATH = Path("offline-nuget.config") +STAGED_SUBJECT_RELATIVE_PATH = Path("source") +OUTPUT_RELATIVE_PATH = Path("coverage") + +MAX_EXECUTION_SECONDS = 1200 +MAX_OUTPUT_BYTES = 1024 * 1024 +MAX_RESULT_BYTES = 16 * 1024 +MAX_SUBJECT_FILES = 250_000 +MAX_SUBJECT_BYTES = 2 * 1024 * 1024 * 1024 +MAX_SOURCE_DIFF_BYTES = 20 * 1024 * 1024 +MAX_COBERTURA_ARTIFACT_BYTES = 20 * 1024 * 1024 +MAX_GATE_MARKDOWN_ARTIFACT_BYTES = 1 * 1024 * 1024 +MAX_GATE_JSON_ARTIFACT_BYTES = 4 * 1024 * 1024 +COPY_CHUNK_BYTES = 1024 * 1024 +DOTNET_PATH = "/usr/local/bin:/usr/bin:/bin" +DOTNET_MAJOR_VERSION = 10 +SDK_RUNTIME_IDENTIFIER = "linux-x64" +SDK_RUNTIME_IDENTIFIER_PROPERTY = "$(NETCoreSdkRuntimeIdentifier)" +SHA256_PATTERN = re.compile(r"[0-9a-f]{64}\Z") +REQUIRED_ARTIFACTS = ( + ("cobertura", "coverage/coverage-merged/coverage.cobertura.xml", MAX_COBERTURA_ARTIFACT_BYTES), + ("gate-report", "coverage/coverage-gate/coverage-gate.md", MAX_GATE_MARKDOWN_ARTIFACT_BYTES), + # Policy marks diagnostics optional. This fixed profile requires its gate JSON report as a conservative extra check. + ("diagnostics", "coverage/coverage-gate/coverage-gate.json", MAX_GATE_JSON_ARTIFACT_BYTES), +) + +FIXED_PROFILE_ID = "code-coverage" +FIXED_SUBJECT_ARGUMENT = "--subject-root=/subject" +FIXED_SCRATCH_ARGUMENT = "--scratch-root=/scratch" +FIXED_DEPENDENCY_ARGUMENT = "--dependency-source=/opt/appsurface/locked-dependencies" +FIXED_OFFLINE_ARGUMENT = "--offline" + +OFFLINE_UNSUPPORTED_TEST_PROJECTS = ( + "Cli/ForgeTrust.AppSurface.Cli.Tests/ForgeTrust.AppSurface.Cli.Tests.csproj", + "Durable/ForgeTrust.AppSurface.Durable.PostgreSql.Tests/ForgeTrust.AppSurface.Durable.PostgreSql.Tests.csproj", + "examples/durable-external-activation.tests/ForgeTrust.AppSurface.DurableExternalActivationExample.Tests.csproj", + "examples/durable-postgresql.tests/DurablePostgreSqlLocalExample.Tests.csproj", +) + + +class EntrypointError(Exception): + """A stable failure suitable for a bounded machine result.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +@dataclass(frozen=True) +class Invocation: + profile_id: str + subject_root: Path + scratch_root: Path + dependency_source: Path + diff_file: Path + diff_sha256: str + offline: bool + + +@dataclass(frozen=True) +class ProcessResult: + exit_code: int + stdout: bytes + stderr: bytes + + +@dataclass(frozen=True) +class StepResult: + name: str + exit_code: int + output_bytes: int + stdout_sha256: str + stderr_sha256: str + + +@dataclass +class OutputBudget: + maximum_bytes: int + used_bytes: int = 0 + + def consume(self, count: int) -> None: + if count < 0 or self.used_bytes + count > self.maximum_bytes: + raise EntrypointError("ASESE006", "Subject process output exceeded the fixed byte limit.") + self.used_bytes += count + + +ProcessRunner = Callable[..., ProcessResult] + + +def parse_invocation(argv: Sequence[str] | None = None) -> Invocation: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--profile-id", required=True, choices=(FIXED_PROFILE_ID,)) + parser.add_argument("--subject-root", required=True, choices=(str(SUBJECT_ROOT),)) + parser.add_argument("--scratch-root", required=True, choices=(str(SCRATCH_ROOT),)) + parser.add_argument("--dependency-source", required=True, choices=(str(DEPENDENCY_SOURCE),)) + parser.add_argument("--diff-file", required=True, choices=(str(PATCH_DIFF_PATH),)) + parser.add_argument("--diff-sha256", required=True) + parser.add_argument("--offline", action="store_true", required=True) + args = parser.parse_args(argv) + if SHA256_PATTERN.fullmatch(args.diff_sha256) is None: + raise EntrypointError("ASESE012", "The controller source diff digest is malformed.") + return Invocation( + profile_id=args.profile_id, + subject_root=Path(args.subject_root), + scratch_root=Path(args.scratch_root), + dependency_source=Path(args.dependency_source), + diff_file=Path(args.diff_file), + diff_sha256=args.diff_sha256, + offline=args.offline, + ) + + +def _decode_mount_field(value: str) -> str: + return value.replace("\\040", " ").replace("\\011", "\t").replace("\\012", "\n").replace("\\134", "\\") + + +def read_mounts(mountinfo_text: str) -> dict[Path, frozenset[str]]: + mounts: dict[Path, frozenset[str]] = {} + for line in mountinfo_text.splitlines(): + left, separator, _right = line.partition(" - ") + fields = left.split() + if not separator or len(fields) < 6: + raise EntrypointError("ASESE001", "The container mount table is malformed.") + mount_path = Path(_decode_mount_field(fields[4])) + options = frozenset(fields[5].split(",")) + mounts[mount_path] = options + return mounts + + +def _effective_mount(path: Path, mounts: Mapping[Path, frozenset[str]]) -> tuple[Path, frozenset[str]]: + candidates = [mount for mount in mounts if path == mount or mount in path.parents] + if not candidates: + raise EntrypointError("ASESE001", "A required container mount is unavailable.") + mount = max(candidates, key=lambda item: len(item.parts)) + return mount, mounts[mount] + + +def _canonical_directory(path: Path, name: str) -> Path: + try: + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise EntrypointError("ASESE001", f"{name} is not a physical directory.") + resolved = path.resolve(strict=True) + except EntrypointError: + raise + except (OSError, RuntimeError, ValueError): + raise EntrypointError("ASESE001", f"{name} is unavailable.") from None + if resolved != path: + raise EntrypointError("ASESE001", f"{name} is not canonical.") + return resolved + + +def _validate_source_diff(path: Path, expected_sha256: str) -> None: + if path != PATCH_DIFF_PATH or SHA256_PATTERN.fullmatch(expected_sha256) is None: + raise EntrypointError("ASESE012", "The controller source diff configuration is invalid.") + descriptor = -1 + try: + metadata = path.lstat() + if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): + raise EntrypointError("ASESE012", "The controller source diff is not a physical regular file.") + if path.resolve(strict=True) != path or metadata.st_size > MAX_SOURCE_DIFF_BYTES: + raise EntrypointError("ASESE012", "The controller source diff is noncanonical or exceeds its byte limit.") + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)) + opened = os.fstat(descriptor) + if ( + not stat.S_ISREG(opened.st_mode) + or (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino) + or opened.st_size > MAX_SOURCE_DIFF_BYTES + ): + raise EntrypointError("ASESE012", "The controller source diff changed or exceeds its byte limit.") + digest = hashlib.sha256() + total = 0 + while True: + chunk = os.read(descriptor, min(COPY_CHUNK_BYTES, MAX_SOURCE_DIFF_BYTES + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > MAX_SOURCE_DIFF_BYTES: + raise EntrypointError("ASESE012", "The controller source diff exceeds its byte limit.") + digest.update(chunk) + after = os.fstat(descriptor) + if ( + total != opened.st_size + or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + != (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + or digest.hexdigest() != expected_sha256 + ): + raise EntrypointError( + "ASESE012", "The mounted source diff is missing, changed, or does not match its controller digest." + ) + except EntrypointError: + raise + except (OSError, RuntimeError, ValueError): + raise EntrypointError("ASESE012", "The controller source diff is unavailable or unsafe.") from None + finally: + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + raise EntrypointError("ASESE012", "The controller source diff could not be closed safely.") from None + + +def validate_mounts( + subject_root: Path, + scratch_root: Path, + dependency_source: Path, + diff_file: Path, + diff_sha256: str, + *, + mountinfo_text: str, + effective_uid: int, +) -> None: + subject = _canonical_directory(subject_root, "The subject root") + scratch = _canonical_directory(scratch_root, "The scratch root") + dependency = _canonical_directory(dependency_source, "The locked dependency source") + _validate_source_diff(diff_file, diff_sha256) + mounts = read_mounts(mountinfo_text) + + if ( + subject != SUBJECT_ROOT + or scratch != SCRATCH_ROOT + or dependency != DEPENDENCY_SOURCE + or diff_file != PATCH_DIFF_PATH + ): + raise EntrypointError( + "ASESE001", "The subject, scratch, dependency, and source diff must use their fixed paths." + ) + if mounts.get(SUBJECT_ROOT) is None or "ro" not in mounts[SUBJECT_ROOT]: + raise EntrypointError("ASESE001", "The subject mount is not read-only.") + if mounts.get(SCRATCH_ROOT) is None or "rw" not in mounts[SCRATCH_ROOT]: + raise EntrypointError("ASESE001", "The scratch mount is not writable.") + diff_options = mounts.get(PATCH_DIFF_PATH) + if diff_options is None or "ro" not in diff_options or "rw" in diff_options: + raise EntrypointError("ASESE001", "The controller source diff mount is not read-only.") + + scratch_info = scratch.stat() + if scratch_info.st_uid != effective_uid or stat.S_IMODE(scratch_info.st_mode) != 0o700: + raise EntrypointError("ASESE001", "The scratch directory is not private to the subject user.") + try: + if next(scratch.iterdir(), None) is not None: + raise EntrypointError("ASESE001", "The scratch directory must be empty at entry.") + except OSError: + raise EntrypointError("ASESE001", "The scratch directory cannot be inspected safely.") from None + + dependency_mount, dependency_options = _effective_mount(dependency, mounts) + if "ro" not in dependency_options or SCRATCH_ROOT == dependency_mount or SCRATCH_ROOT in dependency.parents: + raise EntrypointError("ASESE001", "The locked dependency source is not on a read-only image mount.") + + +def _validate_dependency_feed(root: Path) -> None: + """Scan every feed entry for physical files; locked restore verifies package hashes.""" + try: + root_info = root.stat() + if not stat.S_ISDIR(root_info.st_mode): + raise EntrypointError("ASESE002", "The locked dependency source is unavailable.") + stack = [root] + entries_seen = 0 + package_seen = False + while stack: + current = stack.pop() + with os.scandir(current) as entries: + for entry in entries: + entries_seen += 1 + if entries_seen > MAX_SUBJECT_FILES: + raise EntrypointError("ASESE002", "The locked dependency source exceeds its fixed entry limit.") + info = entry.stat(follow_symlinks=False) + if stat.S_ISLNK(info.st_mode): + raise EntrypointError("ASESE002", "The locked dependency source contains a symbolic link.") + if stat.S_ISDIR(info.st_mode): + stack.append(Path(entry.path)) + elif stat.S_ISREG(info.st_mode) and entry.name.endswith(".nupkg"): + package_seen = True + elif not stat.S_ISREG(info.st_mode): + raise EntrypointError("ASESE002", "The locked dependency source contains an unsupported file type.") + if not package_seen: + raise EntrypointError("ASESE002", "The locked dependency source contains no offline NuGet packages.") + except EntrypointError: + raise + except OSError: + raise EntrypointError("ASESE002", "The locked dependency source is unavailable or unreadable.") from None + + +def _process_environment(scratch_root: Path) -> dict[str, str]: + home = scratch_root / "dotnet-home" + temp = scratch_root / "tmp" + packages = scratch_root / "nuget-packages" + for directory in (home, temp, packages): + directory.mkdir(mode=0o700) + return { + "DOTNET_CLI_HOME": str(home), + "DOTNET_CLI_TELEMETRY_OPTOUT": "1", + "DOTNET_NOLOGO": "1", + "DOTNET_SKIP_FIRST_TIME_EXPERIENCE": "1", + "HOME": str(home), + "NUGET_PACKAGES": str(packages), + "PATH": DOTNET_PATH, + "TEMP": str(temp), + "TMP": str(temp), + "TMPDIR": str(temp), + } + + +def _terminate_process_group(process: subprocess.Popen[bytes]) -> None: + # A command can exit while a descendant still owns its redirected pipes. + # Signal the private session before reaping its leader so its group ID cannot + # be reused between the lookup and cleanup. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + except OSError: + raise EntrypointError("ASESE011", "The subject process group could not be stopped safely.") from None + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + raise EntrypointError("ASESE011", "The subject process group could not be reaped after termination.") from None + + +def run_bounded_process( + arguments: Sequence[str], + *, + working_directory: Path, + environment: Mapping[str, str], + deadline: float, + output_budget: OutputBudget, +) -> ProcessResult: + if not arguments or any(not isinstance(argument, str) or "\x00" in argument for argument in arguments): + raise EntrypointError("ASESE003", "A fixed subject process argument is malformed.") + try: + process = subprocess.Popen( + list(arguments), + cwd=working_directory, + env=dict(environment), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + close_fds=True, + start_new_session=True, + ) + except OSError: + raise EntrypointError("ASESE003", "The required offline runtime or command is unavailable.") from None + + assert process.stdout is not None and process.stderr is not None + stdout = bytearray() + stderr = bytearray() + selector = selectors.DefaultSelector() + streams = {process.stdout.fileno(): stdout, process.stderr.fileno(): stderr} + try: + for stream in (process.stdout, process.stderr): + os.set_blocking(stream.fileno(), False) + selector.register(stream, selectors.EVENT_READ) + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise EntrypointError("ASESE005", "The fixed subject execution deadline expired.") + for key, _ in selector.select(min(remaining, 0.25)): + descriptor = key.fileobj.fileno() + target = streams[descriptor] + allowance = min(COPY_CHUNK_BYTES, output_budget.maximum_bytes - output_budget.used_bytes + 1) + try: + chunk = os.read(descriptor, max(1, allowance)) + except BlockingIOError: + continue + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + output_budget.consume(len(chunk)) + target.extend(chunk) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise EntrypointError("ASESE005", "The fixed subject execution deadline expired.") + try: + exit_code = process.wait(timeout=remaining) + except subprocess.TimeoutExpired: + raise EntrypointError("ASESE005", "The fixed subject execution deadline expired.") from None + return ProcessResult(exit_code, bytes(stdout), bytes(stderr)) + except BaseException: + _terminate_process_group(process) + raise + finally: + selector.close() + for stream in (process.stdout, process.stderr): + if not stream.closed: + stream.close() + + +def _check_deadline(deadline: float) -> None: + if time.monotonic() >= deadline: + raise EntrypointError("ASESE005", "The fixed subject execution deadline expired.") + + +def _copy_subject_tree(source: Path, destination: Path, *, deadline: float) -> tuple[int, int]: + """Copy regular files without following links or accepting concurrent changes.""" + try: + source_info = source.stat() + if not stat.S_ISDIR(source_info.st_mode): + raise EntrypointError("ASESE001", "The subject root is not a directory.") + destination.mkdir(mode=0o700) + except EntrypointError: + raise + except OSError: + raise EntrypointError("ASESE003", "A private subject staging directory could not be created.") from None + + copied_files = 0 + copied_bytes = 0 + pending: list[tuple[Path, Path, bool]] = [(source, destination, True)] + while pending: + _check_deadline(deadline) + source_directory, target_directory, is_root = pending.pop() + try: + with os.scandir(source_directory) as iterator: + entries = sorted(iterator, key=lambda item: item.name) + except OSError: + raise EntrypointError("ASESE003", "The read-only subject tree could not be enumerated.") from None + for entry in entries: + _check_deadline(deadline) + source_path = source_directory / entry.name + target_path = target_directory / entry.name + try: + before = entry.stat(follow_symlinks=False) + except OSError: + raise EntrypointError("ASESE003", "A subject entry changed during staging.") from None + if stat.S_ISLNK(before.st_mode): + raise EntrypointError("ASESE003", "The subject tree contains a symbolic link.") + if stat.S_ISDIR(before.st_mode): + try: + target_path.mkdir(mode=0o700) + except OSError: + raise EntrypointError("ASESE003", "A private subject directory could not be staged.") from None + pending.append((source_path, target_path, False)) + continue + if not stat.S_ISREG(before.st_mode): + raise EntrypointError("ASESE003", "The subject tree contains an unsupported file type.") + if entry.name.casefold() == "nuget.config": + raise EntrypointError("ASESE003", "Subject-controlled NuGet configuration is unsupported.") + if before.st_nlink != 1: + raise EntrypointError("ASESE003", "The subject tree contains a hard-linked file.") + copied_files += 1 + if copied_files > MAX_SUBJECT_FILES or copied_bytes + before.st_size > MAX_SUBJECT_BYTES: + raise EntrypointError("ASESE003", "The subject tree exceeds its fixed staging limits.") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) + source_descriptor = -1 + target_descriptor = -1 + try: + source_descriptor = os.open(source_path, flags) + target_mode = 0o600 | (0o100 if before.st_mode & 0o111 else 0) + target_descriptor = os.open( + target_path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), + target_mode, + ) + except OSError: + if source_descriptor >= 0: + os.close(source_descriptor) + if target_descriptor >= 0: + os.close(target_descriptor) + raise EntrypointError("ASESE003", "A subject file could not be opened safely for staging.") from None + try: + opened = os.fstat(source_descriptor) + if ( + not stat.S_ISREG(opened.st_mode) + or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino) + or opened.st_nlink != before.st_nlink + ): + raise EntrypointError("ASESE003", "A subject file changed during staging.") + file_bytes = 0 + while True: + _check_deadline(deadline) + chunk = os.read(source_descriptor, COPY_CHUNK_BYTES) + if not chunk: + break + file_bytes += len(chunk) + copied_bytes += len(chunk) + if copied_bytes > MAX_SUBJECT_BYTES or file_bytes > before.st_size: + raise EntrypointError("ASESE003", "The subject tree exceeds its fixed staging limits.") + view = memoryview(chunk) + while view: + written = os.write(target_descriptor, view) + view = view[written:] + after = os.fstat(source_descriptor) + if ( + file_bytes != before.st_size + or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + != (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + ): + raise EntrypointError("ASESE003", "A subject file changed during staging.") + except OSError: + raise EntrypointError("ASESE003", "A subject file could not be copied safely.") from None + finally: + os.close(source_descriptor) + os.close(target_descriptor) + return copied_files, copied_bytes + + +def _project_lock_path(project: Path) -> Path: + try: + document = ElementTree.parse(project) + configured_paths = [ + element.text + for element in document.iter() + if element.tag.split("}")[-1] == "NuGetLockFilePath" + ] + except (OSError, UnicodeError, ElementTree.ParseError): + raise EntrypointError("ASESE002", "A fixed solution project file is unavailable or malformed.") from None + + if not configured_paths: + return project.with_name("packages.lock.json") + if len(configured_paths) != 1 or configured_paths[0] is None: + raise EntrypointError("ASESE002", "A fixed solution project has an ambiguous dependency lock path.") + + configured_path = configured_paths[0].strip() + relative_path = configured_path.replace(SDK_RUNTIME_IDENTIFIER_PROPERTY, SDK_RUNTIME_IDENTIFIER) + if ( + not relative_path + or "$" in relative_path + or "\\" in relative_path + or ":" in relative_path + or relative_path.startswith("/") + or any(part in {"", ".", ".."} for part in relative_path.split("/")) + ): + raise EntrypointError("ASESE002", "A fixed solution project has an unsafe or unsupported dependency lock path.") + return project.parent.joinpath(*PurePosixPath(relative_path).parts) + + +def _validate_solution_locks(staged_root: Path) -> None: + solution = staged_root / SOLUTION_RELATIVE_PATH + try: + document = ElementTree.parse(solution) + project_paths = [element.attrib.get("Path") for element in document.iter() if element.tag == "Project"] + if not project_paths: + raise EntrypointError("ASESE002", "The fixed solution contains no projects.") + for relative in project_paths: + if not relative or Path(relative).is_absolute() or ".." in Path(relative).parts: + raise EntrypointError("ASESE002", "The fixed solution contains an unsafe project path.") + project = staged_root / relative + project_info = project.lstat() + if not stat.S_ISREG(project_info.st_mode): + raise EntrypointError("ASESE002", "A fixed solution project is unavailable.") + lock_path = _project_lock_path(project) + try: + lock_info = lock_path.lstat() + except OSError: + raise EntrypointError("ASESE002", "A fixed solution project has no regular dependency lock file.") from None + if not stat.S_ISREG(lock_info.st_mode): + raise EntrypointError("ASESE002", "A fixed solution project has no regular dependency lock file.") + lock_value = json.loads(lock_path.read_text(encoding="utf-8")) + if not isinstance(lock_value, dict) or not isinstance(lock_value.get("dependencies"), dict): + raise EntrypointError("ASESE002", "A fixed solution dependency lock file is malformed.") + except EntrypointError: + raise + except (OSError, UnicodeError, ValueError, ElementTree.ParseError): + raise EntrypointError("ASESE002", "The fixed solution or one of its dependency locks is unavailable or malformed.") from None + + +def _write_offline_config(path: Path) -> None: + content = ( + '\n' + "" + f'' + "\n" + ).encode("utf-8") + try: + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(descriptor, "wb") as output: + output.write(content) + output.flush() + os.fsync(output.fileno()) + except OSError: + raise EntrypointError("ASESE003", "The fixed offline package-source configuration could not be written.") from None + + +def _step(name: str, result: ProcessResult) -> StepResult: + return StepResult( + name=name, + exit_code=result.exit_code, + output_bytes=len(result.stdout) + len(result.stderr), + stdout_sha256=hashlib.sha256(result.stdout).hexdigest(), + stderr_sha256=hashlib.sha256(result.stderr).hexdigest(), + ) + + +def _require_success(name: str, result: ProcessResult) -> StepResult: + step = _step(name, result) + if result.exit_code != 0: + raise StepFailure(step) + return step + + +class StepFailure(EntrypointError): + def __init__(self, step: StepResult) -> None: + super().__init__("ASESE008", "A fixed subject command failed.") + self.step = step + + +def _dotnet_version( + *, + runner: ProcessRunner, + working_directory: Path, + environment: Mapping[str, str], + deadline: float, + output_budget: OutputBudget, +) -> list[StepResult]: + version_result = runner( + ["dotnet", "--version"], + working_directory=working_directory, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + version_step = _require_success("dotnet-sdk-version", version_result) + version_text = version_result.stdout.decode("ascii", errors="strict").strip() + version_parts = version_text.split(".") + if not version_parts or not version_parts[0].isdecimal() or int(version_parts[0]) != DOTNET_MAJOR_VERSION: + raise EntrypointError("ASESE004", "The required .NET 10 SDK is unavailable.") + + runtime_result = runner( + ["dotnet", "--list-runtimes"], + working_directory=working_directory, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + runtime_step = _require_success("dotnet-runtime-list", runtime_result) + if not any(line.startswith("Microsoft.NETCore.App 10.") for line in runtime_result.stdout.decode("ascii", errors="strict").splitlines()): + raise EntrypointError("ASESE004", "The required .NET 10 runtime is unavailable.") + return [version_step, runtime_step] + + +def _coverage_commands(staged_root: Path, scratch_root: Path, diff_file: Path) -> tuple[list[str], list[str]]: + cli_project = str(staged_root / CLI_RELATIVE_PATH) + solution = str(staged_root / SOLUTION_RELATIVE_PATH) + coverage_output = str(scratch_root / OUTPUT_RELATIVE_PATH / "coverage-merged") + gate_output = str(scratch_root / OUTPUT_RELATIVE_PATH / "coverage-gate") + coverage_run = [ + "dotnet", + "run", + "--project", + cli_project, + "--configuration", + "Debug", + "--no-restore", + "--", + "coverage", + "run", + "--solution", + solution, + "--output", + coverage_output, + "--configuration", + "Debug", + "--parallelism", + "1", + "--exclusive-test-project", + "ForgeTrust.AppSurface.Config.Tests.csproj", + "--exclusive-test-project", + "AuthAspNetCoreDevAuthExample.Tests.csproj", + "--exclusive-test-project", + "AuthWebRazorWireProofExample.Tests.csproj", + "--exclusive-test-project", + "ForgeTrust.AppSurface.Durable.PostgreSql.Tests.csproj", + "--exclusive-test-project", + "ForgeTrust.AppSurface.DurableExternalActivationExample.Tests.csproj", + "--exclusive-test-project", + "ForgeTrust.RazorWire.Cli.Tests.csproj", + "--exclusive-test-project", + "ForgeTrust.AppSurface.Web.Tailwind.Tests.csproj", + "--test-results", + "junit", + "--slow-test-diagnostics", + "--no-restore", + ] + coverage_gate = [ + "dotnet", + "run", + "--project", + cli_project, + "--configuration", + "Debug", + "--no-restore", + "--", + "coverage", + "gate", + "--coverage", + str(Path(coverage_output) / "coverage.cobertura.xml"), + "--min-line", + "95", + "--min-branch", + "85", + "--min-patch-line", + "95", + "--min-patch-branch", + "85", + "--patch-line-mode", + "codecov", + "--diff-file", + str(diff_file), + "--output", + gate_output, + ] + return coverage_run, coverage_gate + + +def _make_result( + status: str, + steps: Sequence[StepResult], + *, + artifacts: Sequence[Mapping[str, object]] | None = None, + diagnostic: tuple[str, str] | None = None, +) -> bytes: + value: dict[str, object] = { + "claimEligible": False, + "profileId": FIXED_PROFILE_ID, + "schemaVersion": 1, + "status": status, + "steps": [ + { + "exitCode": step.exit_code, + "name": step.name, + "outputBytes": step.output_bytes, + "stderrSha256": step.stderr_sha256, + "stdoutSha256": step.stdout_sha256, + } + for step in steps + ], + } + if status == "completed": + value["artifacts"] = _validate_artifact_index(artifacts) + elif artifacts is not None: + raise EntrypointError("ASESE013", "A failed subject result cannot claim successful coverage artifacts.") + if diagnostic is not None: + value["diagnostic"] = {"code": diagnostic[0], "message": diagnostic[1]} + encoded = (json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii") + if len(encoded) > MAX_RESULT_BYTES: + raise EntrypointError("ASESE009", "The canonical subject result exceeds its fixed byte limit.") + return encoded + + +def _validate_artifact_index(value: object) -> list[dict[str, object]]: + if not isinstance(value, (list, tuple)) or len(value) != len(REQUIRED_ARTIFACTS): + raise EntrypointError("ASESE013", "The completed coverage run omitted its fixed artifact index.") + normalized: list[dict[str, object]] = [] + for item, (logical_name, relative_path, maximum_bytes) in zip(value, REQUIRED_ARTIFACTS, strict=True): + if ( + not isinstance(item, Mapping) + or set(item) != {"logicalName", "relativePath", "byteCount", "sha256"} + or item.get("logicalName") != logical_name + or item.get("relativePath") != relative_path + or type(item.get("byteCount")) is not int + or not 0 < item["byteCount"] <= maximum_bytes + or not isinstance(item.get("sha256"), str) + or SHA256_PATTERN.fullmatch(item["sha256"]) is None + ): + raise EntrypointError("ASESE013", "The completed coverage run has an invalid fixed artifact index.") + normalized.append( + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": item["byteCount"], + "sha256": item["sha256"], + } + ) + return normalized + + +def _hash_required_artifact( + scratch_root: Path, + relative_path: str, + maximum_bytes: int, + *, + deadline: float, +) -> tuple[int, str]: + parts = PurePosixPath(relative_path).parts + if not parts or PurePosixPath(relative_path).is_absolute() or any(part in {".", ".."} for part in parts): + raise EntrypointError("ASESE013", "A required coverage artifact path is unsafe.") + directory_descriptor = -1 + file_descriptor = -1 + try: + directory_descriptor = os.open( + scratch_root, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), + ) + for part in parts[:-1]: + child = os.open( + part, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), + dir_fd=directory_descriptor, + ) + os.close(directory_descriptor) + directory_descriptor = child + name = parts[-1] + before = os.stat(name, dir_fd=directory_descriptor, follow_symlinks=False) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or not 0 < before.st_size <= maximum_bytes: + raise EntrypointError("ASESE013", "A required coverage artifact is not a bounded single-link regular file.") + file_descriptor = os.open( + name, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + dir_fd=directory_descriptor, + ) + opened = os.fstat(file_descriptor) + if ( + not stat.S_ISREG(opened.st_mode) + or opened.st_nlink != 1 + or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino) + or not 0 < opened.st_size <= maximum_bytes + ): + raise EntrypointError("ASESE013", "A required coverage artifact changed or exceeds its byte limit.") + digest = hashlib.sha256() + total = 0 + while True: + _check_deadline(deadline) + chunk = os.read(file_descriptor, min(COPY_CHUNK_BYTES, maximum_bytes + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > maximum_bytes: + raise EntrypointError("ASESE013", "A required coverage artifact exceeds its byte limit.") + digest.update(chunk) + after = os.fstat(file_descriptor) + named_after = os.stat(name, dir_fd=directory_descriptor, follow_symlinks=False) + opened_identity = (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + if ( + total != opened.st_size + or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) != opened_identity + or (named_after.st_dev, named_after.st_ino, named_after.st_size, named_after.st_mtime_ns, named_after.st_ctime_ns) + != opened_identity + or not stat.S_ISREG(named_after.st_mode) + or named_after.st_nlink != 1 + ): + raise EntrypointError("ASESE013", "A required coverage artifact changed while it was being hashed.") + return total, digest.hexdigest() + except EntrypointError: + raise + except (OSError, RuntimeError, ValueError): + raise EntrypointError("ASESE013", "A required coverage artifact is unavailable or unsafe.") from None + finally: + for descriptor in (file_descriptor, directory_descriptor): + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + + +def _build_artifact_index(scratch_root: Path, *, deadline: float) -> list[dict[str, object]]: + artifacts: list[dict[str, object]] = [] + for logical_name, relative_path, maximum_bytes in REQUIRED_ARTIFACTS: + byte_count, digest = _hash_required_artifact( + scratch_root, + relative_path, + maximum_bytes, + deadline=deadline, + ) + artifacts.append( + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": byte_count, + "sha256": digest, + } + ) + return _validate_artifact_index(artifacts) + + +def _write_result(scratch_root: Path, content: bytes) -> None: + destination = scratch_root / RESULT_RELATIVE_PATH + try: + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(descriptor, "wb") as output: + output.write(content) + output.flush() + os.fsync(output.fileno()) + except OSError: + raise EntrypointError("ASESE009", "The canonical subject result could not be written safely.") from None + + +def _result_for_transport(scratch_root: Path) -> bytes: + result_path = scratch_root / RESULT_RELATIVE_PATH + descriptor = -1 + try: + descriptor = os.open(result_path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1 or metadata.st_size > MAX_RESULT_BYTES: + raise EntrypointError("ASESE009", "The canonical subject result is not a bounded regular file.") + with os.fdopen(descriptor, "rb") as result_file: + descriptor = -1 + content = result_file.read(MAX_RESULT_BYTES + 1) + if len(content) != metadata.st_size or not content or len(content) > MAX_RESULT_BYTES: + raise EntrypointError("ASESE009", "The canonical subject result is not bounded.") + return content + except EntrypointError: + raise + except OSError: + raise EntrypointError("ASESE009", "The canonical subject result could not be read safely.") from None + finally: + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + raise EntrypointError("ASESE009", "The canonical subject result could not be closed safely.") from None + + +def execute( + invocation: Invocation, + *, + mountinfo_text: str | None = None, + effective_uid: int | None = None, + runner: ProcessRunner = run_bounded_process, +) -> int: + scratch = invocation.scratch_root + steps: list[StepResult] = [] + try: + mounts_text = Path("/proc/self/mountinfo").read_text(encoding="utf-8") if mountinfo_text is None else mountinfo_text + uid = os.geteuid() if effective_uid is None else effective_uid + validate_mounts( + invocation.subject_root, + scratch, + invocation.dependency_source, + invocation.diff_file, + invocation.diff_sha256, + mountinfo_text=mounts_text, + effective_uid=uid, + ) + except EntrypointError: + raise + except OSError: + raise EntrypointError("ASESE001", "The container mount table is unavailable.") from None + + deadline = time.monotonic() + MAX_EXECUTION_SECONDS + output_budget = OutputBudget(MAX_OUTPUT_BYTES) + result_path = scratch / RESULT_RELATIVE_PATH + try: + _validate_dependency_feed(invocation.dependency_source) + environment = _process_environment(scratch) + steps.extend( + _dotnet_version( + runner=runner, + working_directory=scratch, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + ) + staged_root = scratch / STAGED_SUBJECT_RELATIVE_PATH + _copy_subject_tree(invocation.subject_root, staged_root, deadline=deadline) + _validate_solution_locks(staged_root) + _write_offline_config(scratch / RESTORE_CONFIG_RELATIVE_PATH) + try: + user_config_directory = Path(environment["HOME"]) / ".nuget" / "NuGet" + user_config_directory.mkdir(parents=True, mode=0o700) + except OSError: + raise EntrypointError("ASESE003", "The private NuGet SDK resolver configuration directory could not be created.") from None + # Project SDK resolution happens during MSBuild evaluation, before the + # restore command applies --configfile. Give that resolver the same + # fixed offline feed; no subject NuGet.Config may override it. + _write_offline_config(user_config_directory / "NuGet.Config") + + restore_result = runner( + [ + "dotnet", + "restore", + str(staged_root / SOLUTION_RELATIVE_PATH), + "--locked-mode", + "--disable-parallel", + "--configfile", + str(scratch / RESTORE_CONFIG_RELATIVE_PATH), + "--source", + str(invocation.dependency_source), + "--packages", + environment["NUGET_PACKAGES"], + ], + working_directory=staged_root, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + steps.append(_require_success("offline-locked-restore", restore_result)) + + unsupported = [ + relative + for relative in OFFLINE_UNSUPPORTED_TEST_PROJECTS + if (staged_root / relative).is_file() + ] + if unsupported: + raise EntrypointError( + "ASESE010", + "The fixed full-solution coverage profile includes container-dependent test projects " + "without a declared service or network envelope; coverage execution is unavailable.", + ) + + (scratch / OUTPUT_RELATIVE_PATH).mkdir(mode=0o700) + coverage_run, coverage_gate = _coverage_commands(staged_root, scratch, invocation.diff_file) + coverage_result = runner( + coverage_run, + working_directory=staged_root, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + steps.append(_require_success("coverage-run", coverage_result)) + gate_result = runner( + coverage_gate, + working_directory=staged_root, + environment=environment, + deadline=deadline, + output_budget=output_budget, + ) + steps.append(_require_success("coverage-gate", gate_result)) + _check_deadline(deadline) + artifacts = _build_artifact_index(scratch, deadline=deadline) + _write_result(scratch, _make_result("completed", steps, artifacts=artifacts)) + return 0 + except StepFailure as exc: + steps.append(exc.step) + _write_result(scratch, _make_result("failed", steps, diagnostic=(exc.code, exc.message))) + return 2 + except EntrypointError as exc: + _write_result(scratch, _make_result("failed", steps, diagnostic=(exc.code, exc.message))) + return 2 + + +def main(argv: Sequence[str] | None = None) -> int: + try: + invocation = parse_invocation(argv) + exit_code = execute(invocation) + content = _result_for_transport(invocation.scratch_root) + try: + sys.stdout.buffer.write(content) + sys.stdout.buffer.flush() + except OSError: + raise EntrypointError("ASESE009", "The canonical subject result could not be streamed safely.") from None + return exit_code + except EntrypointError as exc: + print(f"{exc.code}: {exc.message}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-subject-image/Containerfile b/scripts/evidence-gate-subject-image/Containerfile new file mode 100644 index 000000000..eff011b5f --- /dev/null +++ b/scripts/evidence-gate-subject-image/Containerfile @@ -0,0 +1,21 @@ +# The base is an immutable multi-platform .NET 10 SDK manifest. The built image +# must also be published and consumed by its own registry digest; a local tag +# or this base digest alone is never sufficient for the evidence gate. +FROM mcr.microsoft.com/dotnet/sdk:10.0.401@sha256:35d40304542c8689331f8cab17c65926cdf48fe711e289321d71924b230a7d29 + +# Python runs the fixed, base-owned subject entrypoint. The final registry +# digest binds the resolved Ubuntu package versions as well as the SDK image. +RUN apt-get update \ + && apt-get install --yes --no-install-recommends python3 \ + && rm -rf /var/lib/apt/lists/* + +COPY evidence-gate-subject-entrypoint.py /usr/local/libexec/appsurface-subject-runner +COPY locked-dependencies/ /opt/appsurface/locked-dependencies/ + +RUN chmod 0555 /usr/local/libexec/appsurface-subject-runner \ + && chmod -R a+rX /opt/appsurface/locked-dependencies \ + && test -x /usr/bin/python3 \ + && test -x /usr/bin/dotnet + +USER 65532:65532 +ENTRYPOINT ["/usr/local/libexec/appsurface-subject-runner"] diff --git a/scripts/evidence-gate-subject-image/README.md b/scripts/evidence-gate-subject-image/README.md new file mode 100644 index 000000000..410b9b975 --- /dev/null +++ b/scripts/evidence-gate-subject-image/README.md @@ -0,0 +1,54 @@ +# Offline evidence subject image candidate + +The [independent cleanup supervisor](https://github.com/forge-trust/AppSurface/blob/main/docs/evidence-gate-subject-supervisor.md) removes only a labeled per-run container and its verified quota-limited host tmpfs. Its attestation remains non-claiming until a trusted verifier consumes and binds it to the exact subject execution. + +## Protected-main publisher (future, non-claiming) + +[`evidence-gate-subject-image-publish.yml`](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate-subject-image-publish.yml) is a protected-main-only publisher. It runs after relevant changes land on `main`, never from a manually selected workflow revision, pull request, or unprotected branch. It first runs the complete native validation lane, which builds and validates `appsurface-subject-native-validation:local`. Only after that succeeds does a separate, credentialed job load the exact saved image archive, verify its archive SHA-256 and Docker image ID, and push it to GHCR. Immediately before pushing, it compares the triggering commit with the current `main` head and fails when they differ, so a delayed environment approval or queued run cannot publish a revision already superseded at that check. The publisher tags the image with the source commit and workflow run, reads the registry manifest descriptor and raw manifest, requires the registry config digest to match the validated local image ID, and accepts a digest only when the manifest bytes hash to the registry descriptor's SHA-256. It pulls that immutable digest and checks the image ID and `linux/amd64` platform again before creating a GitHub artifact attestation. The attestation subject is `ghcr.io/forge-trust/appsurface-subject-native-validation@sha256:…`. The workflow does not rebuild after validation, does not run for pull requests or unprotected refs, and its result does not establish evidence-gate eligibility or a coverage claim. + +Before its first run, configure the repository variable `EVIDENCE_GATE_SUBJECT_IMAGE` to exactly `ghcr.io/forge-trust/appsurface-subject-native-validation`. Create the `evidence-gate-subject-image-publish` GitHub environment, allow exactly the `main` branch, require at least one reviewer with self-review disabled, and disable administrator bypass of protection rules. The publisher checks those environment settings through GitHub's API before it downloads or loads the image. Its separate [main-ruleset guard](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/evidence-gate-subject-image-publish.yml) reads AppSurface ruleset `7295365` and the repository default branch before loading the image and again immediately before pushing it. The ruleset must actively cover `main`, prohibit force pushes and all bypass actors, require at least one pull-request approval, and dismiss stale approvals or require approval after the last push. The guard fails closed if the ruleset is replaced without a reviewed workflow update. The current ruleset permits organization-administrator bypass and does not require a fresh approval after the last push, so an administrator must correct both settings before this publisher can run. The workflow also fails closed when its repository, event, ref, image name, source SHA, run identity, or environment protection does not match the expected values. + +Add `EVIDENCE_GATE_RULESET_INSPECTION_TOKEN` as a secret in that protected publisher environment, scoped to this repository and granted repository Administration (write) permission. GitHub [omits `bypass_actors` from ruleset API responses](https://docs.github.com/en/rest/repos/rules#get-a-repository-ruleset) unless the caller can write the ruleset; the ordinary read-only workflow token cannot prove there are no bypass actors. The secret is used only for the two ruleset reads, before image download and immediately before push. A missing secret or an API response without `bypass_actors` blocks publication. Keep this administration-capable token out of the subject job and all other workflows, and prefer a short-lived repository-scoped GitHub App token when available. + +The first successful push creates a private GHCR package by default. After reviewing it, manually change its visibility to Public in package settings before enabling anonymous pulls; GitHub does not allow a public package to be made private again. Confirm the package is linked to `forge-trust/AppSurface` and that the repository has package write access. See GitHub's [Container registry access and visibility guidance](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#visibility-and-access-permissions). Record the exact digest from the run summary as the candidate image reference; tags and local Docker image IDs are not runtime references. Verify its provenance with the printed [`gh attestation verify`](https://cli.github.com/manual/gh_attestation_verify) command, which constrains the signer to this repository's publisher workflow, `refs/heads/main`, and the exact source commit. Keep this publisher explicitly non-claiming until the separate policy, isolation, and artifact-verification requirements are completed. For how `actions/attest` binds provenance and registry metadata, see [GitHub artifact attestations](https://docs.github.com/en/actions/concepts/security/artifact-attestations). + +`publish_guard.py` contains the publisher's event/ref/repository/image and run-identity checks, checks the environment and current reviewed ruleset without accepting a branch-name match as proof of protection, verifies that the transferred archive is byte-identical to the validation output, confirms the image remains `linux/amd64` with the same local image ID, and verifies the published registry digest against the raw manifest bytes. Its focused tests can be run with `python3 -m unittest discover -s scripts/evidence-gate-subject-image -p 'test_publish_guard.py'`. + +The [Containerfile](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-image/Containerfile) is the base-owned image recipe for the fixed [code-coverage subject entrypoint](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject-entrypoint.py). It starts from the digest-pinned .NET 10.0.401 SDK image, adds Python for the fixed runner, and copies a local NuGet feed into `/opt/appsurface/locked-dependencies`. The [subject launcher](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-subject.py) accepts only a published image reference ending in `@sha256:`, requires that exact digest already in rootless Podman storage, and runs it without network, credentials, or writable image layers. The [native validation lane](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) checks the host SDK feature band and Keycloak test lock selection before image validation; Aspire AppHost lock-file inputs differed under the earlier 10.0.102 image. + +Publish only from a reviewed protected-base checkout. Implementation-branch builds are local recipe checks and cannot be promoted as trusted base-owned inputs. The build context must contain `evidence-gate-subject-entrypoint.py` from that same checkout and a `locked-dependencies/` directory assembled from the solution's tracked lock files plus explicitly pinned project SDK packages. `Aspire.AppHost.Sdk` 13.4.4 is such an SDK: project SDK resolution occurs before ordinary package restore, and NuGet does not list that SDK archive in `packages.lock.json`. The [feed builder](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-build-offline-feed.py) accepts it only when a selected project declares the exact ID/version and the archive matches its reviewed content-hash pin. Every archive must match its lock or project-SDK pin; do not populate this directory from an unverified cache or from a PR checkout for publication. This is NuGet's package content hash as reported by [`dotnet nuget verify`](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-verify), not a plain SHA-512 of the `.nupkg` ZIP bytes, and the cache's `.nupkg.metadata` value alone does not authenticate the archive. A build context assembled for one policy/tool revision is not automatically valid for a later revision. The checked-in recipe pins the *base* image; after publishing, record and configure the **resulting image's** immutable registry digest. A tag, local image ID, or the base image digest is not a valid runtime value. + +Use the [offline feed builder](https://github.com/forge-trust/AppSurface/blob/main/scripts/evidence-gate-build-offline-feed.py) on that protected checkout to select only projects in `ForgeTrust.AppSurface.slnx`, resolve each project's default or `linux-x64` lock exactly as the fixed subject entrypoint does, and verify each copied package with NuGet. A macOS lock beside a selected project does not add packages to this Linux image. The builder takes a physical, already-restored NuGet global cache and a **new** destination directory. For example, after setting `trusted_checkout`, `global_packages`, and `context` to absolute physical paths and creating the empty context parent: + +```sh +python3 "$trusted_checkout/scripts/evidence-gate-build-offline-feed.py" \ + --checkout "$trusted_checkout" \ + --solution ForgeTrust.AppSurface.slnx \ + --global-packages "$global_packages" \ + --output "$context/locked-dependencies" +cp "$trusted_checkout/scripts/evidence-gate-subject-entrypoint.py" \ + "$context/evidence-gate-subject-entrypoint.py" +docker buildx build --platform linux/amd64 \ + --file "$trusted_checkout/scripts/evidence-gate-subject-image/Containerfile" \ + --tag appsurface-subject-candidate:local "$context" +``` + +The context must not contain a PR checkout. The builder fails if a selected archive is missing, linked, malformed, or has the wrong NuGet content hash; a dependency-changing PR that needs a new package therefore remains ineligible until the base-owned image or an approved mirror is refreshed. The builder does not run restore or build hooks. Its result counts are useful for audit logs, but do not attest the final image. + +Before building the image, the opt-in native lane records the Keycloak tests project's evaluated `NETCoreSdkRuntimeIdentifier` and `NuGetLockFilePath`. It requires the project to select the tracked `packages.linux-x64.lock.json`, then runs that project in locked, serial mode (`--locked-mode --disable-parallel -m:1`) without overriding the restore runtime. The host sets `NUGET_PACKAGES` to the isolated temporary cache before project evaluation so the project SDK resolver and ordinary package restore use the same candidate package supply. An untracked RID-specific lock generated by the host restore fails preflight and prints `git status --short` for the Keycloak tests directory; the script never regenerates or edits lock files. The machine-readable preflight record is written under the lane's `RUNNER_TEMP` work directory, while both evaluated property values are printed in job output. + +Run the feed assembly in a reviewed Linux .NET 10 builder. `dotnet nuget verify` also checks signatures; host trust stores can differ. A local macOS run stopped on `CommandLineParser` 2.9.1 because its historical signature chain was rejected there, while the pinned Linux SDK verified the same archive and reported a matching lock hash. Treat a verifier failure as an unavailable build input and investigate it; do not accept a cache sidecar or bypass the content-hash check. + +After building the candidate image, the native lane explicitly transfers it from Docker to rootless Podman with `docker save` and `podman load`, then requires both stores to report the same 64-hex image ID after removing an optional `sha256:` display prefix. Before the Docker cold-cache restore starts, the trusted host mounts a private 4 GiB, 262,144-inode tmpfs with `sudo -n`; rootless Podman bind-mounts only that quota-limited filesystem at `/scratch`. The smoke requests an unprivileged runner with network disabled, a read-only root, dropped capabilities, and bounded CPU, memory, process count, and duration. Its pre-start check accepts Podman's empty effective and bounding capability sets when exposed, or verifies the reported drop of every default capability with no added capabilities when those fields are absent. It also checks Podman's private namespace, unprivileged, and resource-limit request fields; these remain configuration observations, not an enforcement attestation. Only the live process's inherited, permitted, effective, bounding, and ambient zero masks establish the capability observation; `HostConfig.CapDrop` alone is not an attestation. It reads the live `/scratch` filesystem and `statvfs` block/inode limits, verifies the bind source in Podman inspect, and unmounts host scratch after removing the container. A unique container name scopes cleanup to this invocation even when `podman create` fails after creating the container but before returning its ID; scratch stays mounted if removal fails. The later cold-root ownership change is noninteractive and timed out. The script writes and prints a machine-readable JSON result marked `claimEligible: false` and `published: false`. The record is kept in `RUNNER_TEMP` and the job log; this lane does not upload or publish it as gate evidence. + +Rootless Podman 4.9 rejects the Linux `noswap` tmpfs option because it requires a rootful mount, and its `--tmpfs` parser also rejects `nr_inodes`. The launcher therefore makes no no-swap claim. The branch launcher now creates a fresh private mountpoint beneath the trusted runner scratch directory, mounts a fixed byte- and inode-limited tmpfs there with noninteractive host privilege, verifies the live mount, and bind-mounts it into the rootless container. The separate cleanup supervisor removes only the ownership-checked container before unmounting. The current implementation still needs a live native launcher and forced-kill pilot; it does not attest an execution envelope or enable a complete claim. The subject must never choose the host mount source or its options. A runner requiring a strict no-swap guarantee needs a different reviewed isolation design. + +The optional hosted validation job has a 45-minute outer deadline. Its bounded Docker-to-Podman transfer and smoke can use about 11 minutes at their individual limits, and the subsequent cold restore has a 15-minute workload limit inside a 16-minute Docker-client limit. The remaining time covers host locked restore, feed verification, image build, and cleanup; a job timeout is a failed feasibility result, not a successful scratch or restore proof. The duration must be rechecked against observed native runs before these limits inform any required gate budget. + +The smoke runs before the Docker cold restore so its evidence remains in the log if that restore fails. Podman operations are individually bounded (30 seconds, with Docker save and Podman load capped at 180 seconds each); the cold restore has a 15-minute workload timeout and a 16-minute Docker-client timeout. Those limits permit about 11 minutes for the Podman phase including termination grace, before host restore, feed/image build, and cold-root preparation. The workflow allows 45 minutes for the whole job. The [successful native pilot](../../docs/evidence-gate-rollout.md#local-pre-pilot-validation) completed this validation step in 6m11s, including feed verification, image build, Podman smoke, cold restore, and cleanup. This is one observed branch-owned run, not a required-gate latency budget. + +Run the cold-cache restore proof on native `linux/amd64`. The local arm64 Docker host could build and start the x64 candidate image, but x64 emulation aborted the .NET SDK during MSBuild project loading before NuGet resolved packages. That attempt proves neither feed completeness nor a lock mismatch; the [rollout record](../../docs/evidence-gate-rollout.md) contains the observed failure. Project SDK resolution occurs during MSBuild evaluation, before the restore command's `--configfile` is applied. The native pilot now places the same closed feed configuration in the disposable subject user's NuGet home, where the [.NET CLI reads user configuration](https://learn.microsoft.com/en-us/nuget/consume-packages/configuring-nuget-behavior#config-file-locations-and-uses), and still supplies `--configfile` for ordinary locked restore. Both paths must remain offline and source-controlled by the trusted host. The Docker subject owns its private cache as UID 65532, so the host's final nonempty-cache inspection uses bounded, noninteractive `sudo` rather than treating a permission-denied directory as empty. + +The fixed entrypoint scans the entire feed for links and special files, then restores the subject solution with `--locked-mode` and an offline NuGet config that clears all other sources. It rejects `NuGet.Config` at any level of the subject tree, and gives the project SDK resolver the same closed feed through the private subject user's config before MSBuild evaluates the projects. Do not move restore or build hooks to the trusted controller to make a dependency-changing PR pass. The [policy matrix](../../docs/evidence-gate-policy-matrix.md) keeps code coverage blocked because container-backed tests, subject checkout/isolation attestation, and complete artifact verification are not yet registered. The [rollout record](../../docs/evidence-gate-rollout.md) requires a cold-cache and dependency-change pilot before any check becomes required. + +For a Docker-only local recipe smoke check, prepare a disposable context with those two entries, then run `docker build --file scripts/evidence-gate-subject-image/Containerfile --tag appsurface-subject-candidate:local `. That check proves only that the image recipe can start; it does not prove the real feed, rootless Podman envelope, final image digest, or coverage verdict. The opt-in native lane exercises the Podman envelope, but remains branch-owned and non-claiming. Publish and configure a candidate only after the base-owned feed contents, final digest, and isolation pilot have been reviewed. diff --git a/scripts/evidence-gate-subject-image/publish_guard.py b/scripts/evidence-gate-subject-image/publish_guard.py new file mode 100644 index 000000000..bde7f8390 --- /dev/null +++ b/scripts/evidence-gate-subject-image/publish_guard.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +"""Fail-closed guards for the protected-main subject image publisher.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +EXPECTED_REPOSITORY = "forge-trust/AppSurface" +EXPECTED_REF = "refs/heads/main" +EXPECTED_IMAGE = "ghcr.io/forge-trust/appsurface-subject-native-validation" +EXPECTED_MAIN_RULESET_ID = 7295365 +SHA256_RE = re.compile(r"^sha256:[0-9a-f]{64}$") +HEX_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +GIT_SHA_RE = re.compile(r"^[0-9a-f]{40}$") +POSITIVE_DECIMAL_RE = re.compile(r"^[1-9][0-9]*$") +IMAGE_ID_RE = re.compile(r"^sha256:[0-9a-f]{64}$") +MAX_REGISTRY_METADATA_BYTES = 1024 * 1024 + + +def _unique_json_object(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate registry manifest key") + result[key] = value + return result + + +def validate_context( + *, event_name: str, repository: str, ref: str, image: str, + sha: str, run_id: str, run_attempt: str, +) -> tuple[str, str]: + if event_name != "push": + raise ValueError("publication is allowed only for pushes to the protected main branch") + if repository != EXPECTED_REPOSITORY: + raise ValueError(f"publication is restricted to {EXPECTED_REPOSITORY}") + if ref != EXPECTED_REF: + raise ValueError(f"publication is restricted to {EXPECTED_REF}") + if image != EXPECTED_IMAGE: + raise ValueError(f"EVIDENCE_GATE_SUBJECT_IMAGE must equal {EXPECTED_IMAGE}") + if not GIT_SHA_RE.fullmatch(sha): + raise ValueError("GITHUB_SHA must be a full lowercase 40-character commit SHA") + if not POSITIVE_DECIMAL_RE.fullmatch(run_id): + raise ValueError("GITHUB_RUN_ID must be a positive decimal integer") + if not POSITIVE_DECIMAL_RE.fullmatch(run_attempt): + raise ValueError("GITHUB_RUN_ATTEMPT must be a positive decimal integer") + + image_tag = f"{image}:main-{sha}-{run_id}-{run_attempt}" + return image, image_tag + + +def validate_main_head(source_sha: str, current_main_sha: str) -> None: + if not GIT_SHA_RE.fullmatch(source_sha) or not GIT_SHA_RE.fullmatch(current_main_sha): + raise ValueError("source and current main revisions must be full lowercase commit SHAs") + if source_sha != current_main_sha: + raise ValueError("validated source commit is no longer the current main revision") + + +def validate_image_identity( + *, image_id: str, operating_system: str, architecture: str, + expected_image_id: str | None = None, +) -> None: + if not IMAGE_ID_RE.fullmatch(image_id): + raise ValueError("Docker image ID must be sha256 followed by 64 lowercase hex characters") + if operating_system != "linux" or architecture != "amd64": + raise ValueError("validated subject image must be linux/amd64") + if expected_image_id is not None and image_id != expected_image_id: + raise ValueError("loaded image ID does not match the ID captured after native validation") + + +def verify_archive(archive: Path, expected_sha256: str) -> None: + if not HEX_SHA256_RE.fullmatch(expected_sha256): + raise ValueError("archive SHA-256 must be 64 lowercase hexadecimal characters") + digest = hashlib.sha256() + with archive.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + actual = digest.hexdigest() + if actual != expected_sha256: + raise ValueError("downloaded image archive does not match the validated archive SHA-256") + + +def validate_environment(environment: dict, branch_policies: dict) -> None: + if environment.get("can_admins_bypass") is not False: + raise ValueError("publisher environment must prevent administrator bypass") + deployment_policy = environment.get("deployment_branch_policy") + if not isinstance(deployment_policy, dict) or deployment_policy.get("protected_branches") is not False or deployment_policy.get("custom_branch_policies") is not True: + raise ValueError("publisher environment must use explicit custom branch policies") + + rules = environment.get("protection_rules") + has_independent_reviewer = isinstance(rules, list) and any( + isinstance(rule, dict) + and rule.get("type") == "required_reviewers" + and rule.get("prevent_self_review") is True + and isinstance(rule.get("reviewers"), list) + and len(rule["reviewers"]) > 0 + for rule in rules + ) + if not has_independent_reviewer: + raise ValueError("publisher environment must require a reviewer and prevent self-review") + + policies = branch_policies.get("branch_policies") + total_count = branch_policies.get("total_count") + if total_count != 1 or not isinstance(policies, list) or len(policies) != 1: + raise ValueError("publisher environment must allow exactly the main branch") + policy = policies[0] + # GitHub's list response omits `type` for the default branch policy in its + # documented example. An explicit tag rule is still unacceptable. + if ( + not isinstance(policy, dict) + or policy.get("type", "branch") != "branch" + or policy.get("name") != "main" + ): + raise ValueError("publisher environment must allow exactly the main branch") + + +def validate_main_ruleset(ruleset: dict, default_branch: str) -> None: + """Require the current default branch to enforce review of the final revision without bypass.""" + if default_branch != "main": + raise ValueError("publisher repository default branch must remain main") + if ( + not isinstance(ruleset, dict) + or ruleset.get("id") != EXPECTED_MAIN_RULESET_ID + or ruleset.get("enforcement") != "active" + or ruleset.get("target") != "branch" + ): + raise ValueError("publisher main ruleset must be the active reviewed ruleset") + + conditions = ruleset.get("conditions") + ref_name = conditions.get("ref_name") if isinstance(conditions, dict) else None + if ( + not isinstance(ref_name, dict) + or not isinstance(ref_name.get("include"), list) + or not any( + selector in ref_name["include"] + for selector in ("~DEFAULT_BRANCH", "refs/heads/main") + ) + or ref_name.get("exclude") != [] + ): + raise ValueError("publisher main ruleset must include main without exclusions") + if "bypass_actors" not in ruleset: + raise ValueError("publisher ruleset inspection credential must expose bypass_actors") + if ruleset["bypass_actors"] != []: + raise ValueError("publisher main ruleset must not allow review bypass actors") + + rules = ruleset.get("rules") + if not isinstance(rules, list) or not any( + isinstance(rule, dict) and rule.get("type") == "non_fast_forward" + for rule in rules + ): + raise ValueError("publisher main ruleset must prevent force pushes") + has_current_review = any( + isinstance(rule, dict) + and rule.get("type") == "pull_request" + and isinstance(rule.get("parameters"), dict) + and type(rule["parameters"].get("required_approving_review_count")) is int + and rule["parameters"]["required_approving_review_count"] >= 1 + and ( + rule["parameters"].get("dismiss_stale_reviews_on_push") is True + or rule["parameters"].get("require_last_push_approval") is True + ) + for rule in rules + ) + if not has_current_review: + raise ValueError("publisher main ruleset must review the latest pull-request revision") + + +def verify_registry_manifest( + descriptor_path: Path, + raw_manifest_path: Path, + expected_image_id: str, +) -> str: + try: + with descriptor_path.open("rb") as descriptor_file: + descriptor_bytes = descriptor_file.read(MAX_REGISTRY_METADATA_BYTES + 1) + with raw_manifest_path.open("rb") as manifest_file: + raw_manifest = manifest_file.read(MAX_REGISTRY_METADATA_BYTES + 1) + except OSError as error: + raise ValueError("registry inspection did not return valid manifest JSON") from error + if len(descriptor_bytes) > MAX_REGISTRY_METADATA_BYTES or len(raw_manifest) > MAX_REGISTRY_METADATA_BYTES: + raise ValueError("registry manifest metadata exceeds its fixed byte limit") + try: + descriptor = json.loads(descriptor_bytes, object_pairs_hook=_unique_json_object) + manifest = json.loads(raw_manifest, object_pairs_hook=_unique_json_object) + except (UnicodeError, ValueError) as error: + raise ValueError("registry inspection did not return valid manifest JSON") from error + + if not isinstance(descriptor, dict): + raise ValueError("registry manifest descriptor must be a JSON object") + digest = descriptor.get("digest") + if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest): + raise ValueError("registry manifest descriptor has no valid SHA-256 digest") + if not isinstance(manifest, dict) or manifest.get("schemaVersion") != 2: + raise ValueError("registry returned an unsupported or malformed image manifest") + supported_media_types = { + "application/vnd.docker.distribution.manifest.v2+json", + "application/vnd.oci.image.manifest.v1+json", + } + media_type = manifest.get("mediaType") + if media_type not in supported_media_types or descriptor.get("mediaType") != media_type: + raise ValueError("registry did not return a matching single-image manifest media type") + if "manifests" in manifest: + raise ValueError("registry returned an image index instead of the validated single-platform image") + config = manifest.get("config") + layers = manifest.get("layers") + if not isinstance(config, dict) or not isinstance(layers, list): + raise ValueError("registry image manifest is missing its config or layers") + if not IMAGE_ID_RE.fullmatch(expected_image_id) or config.get("digest") != expected_image_id: + raise ValueError("registry image config digest does not match the validated local image ID") + if descriptor.get("size") != len(raw_manifest): + raise ValueError("registry manifest size does not match the inspected raw manifest bytes") + + actual = "sha256:" + hashlib.sha256(raw_manifest).hexdigest() + if actual != digest: + raise ValueError("registry manifest bytes do not match the descriptor digest") + return digest + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + + context = commands.add_parser("context", help="validate the protected publisher context") + for name in ("event-name", "repository", "ref", "image", "sha", "run-id", "run-attempt"): + context.add_argument(f"--{name}", required=True) + + identity = commands.add_parser("image-identity", help="validate a Docker image identity") + identity.add_argument("--image-id", required=True) + identity.add_argument("--os", required=True) + identity.add_argument("--architecture", required=True) + identity.add_argument("--expected-image-id") + + main_head = commands.add_parser("main-head", help="require the source commit to remain main HEAD") + main_head.add_argument("--source-sha", required=True) + main_head.add_argument("--current-main-sha", required=True) + + archive = commands.add_parser("verify-archive", help="verify a transferred image archive") + archive.add_argument("--archive", required=True, type=Path) + archive.add_argument("--expected-sha256", required=True) + + environment = commands.add_parser("environment", help="require a protected publisher environment") + environment.add_argument("--environment-json", required=True, type=Path) + environment.add_argument("--branch-policies-json", required=True, type=Path) + + ruleset = commands.add_parser("main-ruleset", help="require reviewed, non-bypassable main") + ruleset.add_argument("--ruleset-json", required=True, type=Path) + ruleset.add_argument("--default-branch", required=True) + + manifest = commands.add_parser("manifest-digest", help="verify registry manifest bytes") + manifest.add_argument("--descriptor", required=True, type=Path) + manifest.add_argument("--raw-manifest", required=True, type=Path) + manifest.add_argument("--expected-image-id", required=True) + return parser + + +def main() -> int: + arguments = build_parser().parse_args() + try: + if arguments.command == "context": + image, image_tag = validate_context( + event_name=arguments.event_name, + repository=arguments.repository, + ref=arguments.ref, + image=arguments.image, + sha=arguments.sha, + run_id=arguments.run_id, + run_attempt=arguments.run_attempt, + ) + print(f"image_name={image}") + print(f"image_tag={image_tag}") + elif arguments.command == "image-identity": + validate_image_identity( + image_id=arguments.image_id, + operating_system=arguments.os, + architecture=arguments.architecture, + expected_image_id=arguments.expected_image_id, + ) + elif arguments.command == "main-head": + validate_main_head(arguments.source_sha, arguments.current_main_sha) + elif arguments.command == "verify-archive": + verify_archive(arguments.archive, arguments.expected_sha256) + elif arguments.command == "environment": + environment = json.loads(arguments.environment_json.read_text(encoding="utf-8")) + branch_policies = json.loads(arguments.branch_policies_json.read_text(encoding="utf-8")) + if not isinstance(environment, dict) or not isinstance(branch_policies, dict): + raise ValueError("publisher environment inspection must return JSON objects") + validate_environment(environment, branch_policies) + elif arguments.command == "main-ruleset": + ruleset = json.loads(arguments.ruleset_json.read_text(encoding="utf-8")) + validate_main_ruleset(ruleset, arguments.default_branch) + else: + print( + verify_registry_manifest( + arguments.descriptor, + arguments.raw_manifest, + arguments.expected_image_id, + ) + ) + except (OSError, ValueError) as error: + print(f"publisher guard failed: {error}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-subject-image/test_publish_guard.py b/scripts/evidence-gate-subject-image/test_publish_guard.py new file mode 100644 index 000000000..d701dbb9b --- /dev/null +++ b/scripts/evidence-gate-subject-image/test_publish_guard.py @@ -0,0 +1,335 @@ +import hashlib +import json +import tempfile +import unittest +from copy import deepcopy +from pathlib import Path +from unittest.mock import patch + +from publish_guard import ( + EXPECTED_IMAGE, + EXPECTED_MAIN_RULESET_ID, + EXPECTED_REF, + EXPECTED_REPOSITORY, + MAX_REGISTRY_METADATA_BYTES, + validate_context, + validate_environment, + validate_image_identity, + validate_main_head, + validate_main_ruleset, + verify_archive, + verify_registry_manifest, +) + + +class PublishGuardTests(unittest.TestCase): + def setUp(self): + self.context = { + "event_name": "push", + "repository": EXPECTED_REPOSITORY, + "ref": EXPECTED_REF, + "image": EXPECTED_IMAGE, + "sha": "a" * 40, + "run_id": "1234", + "run_attempt": "2", + } + + def test_context_returns_run_unique_registry_tag(self): + image, image_tag = validate_context(**self.context) + + self.assertEqual(EXPECTED_IMAGE, image) + self.assertEqual(f"{EXPECTED_IMAGE}:main-{'a' * 40}-1234-2", image_tag) + + def test_context_rejects_untrusted_events_and_refs(self): + for field, value in ( + ("event_name", "pull_request"), + ("event_name", "pull_request_target"), + ("event_name", "workflow_dispatch"), + ("repository", "attacker/AppSurface"), + ("ref", "refs/heads/codex/feature"), + ("ref", "refs/tags/v1.0.0"), + ): + with self.subTest(field=field, value=value), self.assertRaises(ValueError): + validate_context(**{**self.context, field: value}) + + def test_context_rejects_misconfigured_image_and_malformed_run_identity(self): + for field, value in ( + ("image", "ghcr.io/attacker/subject"), + ("sha", "a" * 39), + ("run_id", "0"), + ("run_attempt", "01"), + ): + with self.subTest(field=field, value=value), self.assertRaises(ValueError): + validate_context(**{**self.context, field: value}) + + def test_main_head_guard_rejects_stale_or_malformed_source_revision(self): + source_sha = "a" * 40 + validate_main_head(source_sha, source_sha) + with self.assertRaisesRegex(ValueError, "no longer the current main"): + validate_main_head(source_sha, "b" * 40) + with self.assertRaisesRegex(ValueError, "full lowercase commit SHAs"): + validate_main_head("not-a-sha", source_sha) + + def test_image_identity_requires_validated_linux_amd64_and_matching_id(self): + image_id = "sha256:" + "b" * 64 + validate_image_identity(image_id=image_id, operating_system="linux", architecture="amd64") + + for values in ( + {"image_id": "sha256:bad", "operating_system": "linux", "architecture": "amd64"}, + {"image_id": image_id, "operating_system": "darwin", "architecture": "amd64"}, + {"image_id": image_id, "operating_system": "linux", "architecture": "arm64"}, + { + "image_id": image_id, + "operating_system": "linux", + "architecture": "amd64", + "expected_image_id": "sha256:" + "c" * 64, + }, + ): + with self.subTest(values=values), self.assertRaises(ValueError): + validate_image_identity(**values) + + def test_archive_verification_checks_bytes_and_digest_format(self): + contents = b"immutable validated image archive\n" + digest = hashlib.sha256(contents).hexdigest() + with tempfile.TemporaryDirectory() as directory: + archive = Path(directory) / "image.tar" + archive.write_bytes(contents) + with patch.object(Path, "read_bytes", side_effect=AssertionError("archive must be streamed")): + verify_archive(archive, digest) + with self.assertRaisesRegex(ValueError, "does not match"): + verify_archive(archive, "0" * 64) + with self.assertRaisesRegex(ValueError, "64 lowercase"): + verify_archive(archive, "not-a-digest") + + def test_environment_requires_exact_main_branch_and_independent_reviewer(self): + environment = { + "can_admins_bypass": False, + "deployment_branch_policy": { + "protected_branches": False, + "custom_branch_policies": True, + }, + "protection_rules": [ + { + "type": "required_reviewers", + "prevent_self_review": True, + "reviewers": [{"type": "User"}], + } + ], + } + branch_policies = { + "total_count": 1, + "branch_policies": [{"id": 361472, "node_id": "policy-node", "name": "main"}], + } + validate_environment(environment, branch_policies) + + invalid_configurations = ( + ( + {**environment, "can_admins_bypass": True}, + branch_policies, + ), + ( + {**environment, "deployment_branch_policy": None}, + branch_policies, + ), + ( + { + **environment, + "protection_rules": [ + {"type": "required_reviewers", "prevent_self_review": False, "reviewers": [{"type": "User"}]} + ], + }, + branch_policies, + ), + ( + environment, + { + "total_count": 2, + "branch_policies": [ + {"type": "branch", "name": "main"}, + {"type": "branch", "name": "release"}, + ], + }, + ), + ( + environment, + {"total_count": 1, "branch_policies": [{"type": "branch", "name": "release"}]}, + ), + ( + environment, + {"total_count": 1, "branch_policies": [{"type": "tag", "name": "main"}]}, + ), + ( + environment, + {"total_count": 2, "branch_policies": [{"type": "branch", "name": "main"}]}, + ), + ) + for invalid_environment, invalid_branches in invalid_configurations: + with self.subTest(environment=invalid_environment, branches=invalid_branches), self.assertRaises(ValueError): + validate_environment(invalid_environment, invalid_branches) + + def test_main_ruleset_requires_reviewed_latest_revision_without_bypass(self): + ruleset = { + "id": EXPECTED_MAIN_RULESET_ID, + "enforcement": "active", + "target": "branch", + "conditions": {"ref_name": {"include": ["~DEFAULT_BRANCH"], "exclude": []}}, + "bypass_actors": [], + "rules": [ + {"type": "non_fast_forward"}, + { + "type": "pull_request", + "parameters": { + "required_approving_review_count": 1, + "dismiss_stale_reviews_on_push": True, + "require_last_push_approval": False, + }, + }, + ], + } + validate_main_ruleset(ruleset, "main") + explicit_main_ruleset = deepcopy(ruleset) + explicit_main_ruleset["conditions"]["ref_name"]["include"] = ["refs/heads/main"] + validate_main_ruleset(explicit_main_ruleset, "main") + latest_push_ruleset = deepcopy(ruleset) + latest_push_ruleset["rules"][1]["parameters"].update( + dismiss_stale_reviews_on_push=False, require_last_push_approval=True + ) + validate_main_ruleset(latest_push_ruleset, "main") + hidden_bypass_ruleset = deepcopy(ruleset) + del hidden_bypass_ruleset["bypass_actors"] + with self.assertRaisesRegex(ValueError, "must expose bypass_actors"): + validate_main_ruleset(hidden_bypass_ruleset, "main") + + invalid = [] + for field, value in ( + ("id", EXPECTED_MAIN_RULESET_ID + 1), + ("enforcement", "evaluate"), + ("target", "tag"), + ("bypass_actors", None), + ("bypass_actors", [{"actor_type": "OrganizationAdmin", "bypass_mode": "always"}]), + ("rules", [ruleset["rules"][1]]), + ): + candidate = deepcopy(ruleset) + candidate[field] = value + invalid.append(candidate) + for selectors in ( + {"include": ["refs/heads/release"], "exclude": []}, + {"include": ["~DEFAULT_BRANCH"], "exclude": ["refs/heads/main"]}, + ): + candidate = deepcopy(ruleset) + candidate["conditions"]["ref_name"] = selectors + invalid.append(candidate) + for parameters in ( + {"required_approving_review_count": 0, "dismiss_stale_reviews_on_push": True}, + {"required_approving_review_count": True, "dismiss_stale_reviews_on_push": True}, + {"required_approving_review_count": 1, "dismiss_stale_reviews_on_push": False, + "require_last_push_approval": False}, + ): + candidate = deepcopy(ruleset) + candidate["rules"][1]["parameters"] = parameters + invalid.append(candidate) + for candidate in invalid: + with self.subTest(candidate=candidate), self.assertRaises(ValueError): + validate_main_ruleset(candidate, "main") + with self.assertRaisesRegex(ValueError, "default branch"): + validate_main_ruleset(ruleset, "release") + with self.assertRaisesRegex(ValueError, "active reviewed ruleset"): + validate_main_ruleset(None, "main") + + def test_registry_manifest_requires_descriptor_raw_and_image_identity_to_agree(self): + image_id = "sha256:" + "c" * 64 + raw = json.dumps( + { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "config": {"digest": image_id}, + "layers": [], + }, + separators=(",", ":"), + ).encode() + digest = "sha256:" + hashlib.sha256(raw).hexdigest() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + descriptor = root / "descriptor.json" + manifest = root / "raw.json" + descriptor.write_text( + json.dumps( + { + "digest": digest, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "size": len(raw), + } + ), + encoding="utf-8", + ) + manifest.write_bytes(raw) + + self.assertEqual(digest, verify_registry_manifest(descriptor, manifest, image_id)) + + descriptor.write_text( + json.dumps( + { + "digest": "sha256:" + "0" * 64, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "size": len(raw), + } + ), + encoding="utf-8", + ) + with self.assertRaisesRegex(ValueError, "do not match"): + verify_registry_manifest(descriptor, manifest, image_id) + + descriptor.write_text("{}", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "no valid SHA-256"): + verify_registry_manifest(descriptor, manifest, image_id) + + descriptor.write_text( + json.dumps( + { + "digest": digest, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "size": len(raw), + } + ), + encoding="utf-8", + ) + with self.assertRaisesRegex(ValueError, "config digest"): + verify_registry_manifest(descriptor, manifest, "sha256:" + "d" * 64) + + index = json.dumps( + { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.index.v1+json", + "manifests": [], + }, + separators=(",", ":"), + ).encode() + manifest.write_bytes(index) + descriptor.write_text( + json.dumps( + { + "digest": "sha256:" + hashlib.sha256(index).hexdigest(), + "mediaType": "application/vnd.oci.image.index.v1+json", + "size": len(index), + } + ), + encoding="utf-8", + ) + with self.assertRaisesRegex(ValueError, "single-image manifest media type"): + verify_registry_manifest(descriptor, manifest, image_id) + + manifest.write_bytes(b'{"schemaVersion":2,"schemaVersion":2}') + with self.assertRaisesRegex(ValueError, "valid manifest JSON"): + verify_registry_manifest(descriptor, manifest, image_id) + + descriptor.write_bytes(b"x" * (MAX_REGISTRY_METADATA_BYTES + 1)) + with self.assertRaisesRegex(ValueError, "fixed byte limit"): + verify_registry_manifest(descriptor, manifest, image_id) + descriptor.write_text("{}", encoding="utf-8") + manifest.write_bytes(b"x" * (MAX_REGISTRY_METADATA_BYTES + 1)) + with self.assertRaisesRegex(ValueError, "fixed byte limit"): + verify_registry_manifest(descriptor, manifest, image_id) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/evidence-gate-subject-image/validate-native.sh b/scripts/evidence-gate-subject-image/validate-native.sh new file mode 100644 index 000000000..b5fb2bc73 --- /dev/null +++ b/scripts/evidence-gate-subject-image/validate-native.sh @@ -0,0 +1,837 @@ +#!/usr/bin/env bash +# Opt-in, non-claiming image feasibility check on a native Linux x64 runner. +# The protected-base evidence workflow must not use this branch-owned result as +# a subject, isolation, artifact, or gate attestation. +set -euo pipefail + +repository_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" +runner_temp="$(cd "${RUNNER_TEMP:?RUNNER_TEMP is required}" && pwd -P)" + +if [[ "$(uname -s)" != Linux || "$(uname -m)" != x86_64 ]]; then + echo 'Native Linux x64 is required for the offline subject image check.' >&2 + exit 2 +fi +if [[ "$(dotnet --version)" != 10.0.401 ]]; then + echo 'The host restore must use the image-pinned .NET SDK 10.0.401.' >&2 + exit 2 +fi + +work_root="$(mktemp -d "$runner_temp/appsurface-subject-image.XXXXXXXX")" +global_packages="$work_root/global-packages" +context="$work_root/context" +cold_root="$work_root/cold" +image_tag='appsurface-subject-native-validation:local' +rid_project_relative='Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak.Tests' +rid_project="$repository_root/$rid_project_relative/ForgeTrust.AppSurface.Auth.Aspire.Keycloak.Tests.csproj" +mkdir -m 0700 "$global_packages" "$context" "$cold_root" +export NUGET_PACKAGES="$global_packages" + +check_no_untracked_rid_locks() { + local untracked_path + local untracked_files + untracked_files="$(git -C "$repository_root" ls-files --others --exclude-standard -- "$rid_project_relative")" || return 2 + while IFS= read -r untracked_path; do + [[ -n "$untracked_path" ]] || continue + case "${untracked_path##*/}" in + packages.*.lock.json) + printf 'Untracked RID-specific lock found in %s; git status --short:\n' \ + "$rid_project_relative" >&2 + git -C "$repository_root" status --short --untracked-files=all -- \ + "$rid_project_relative" >&2 || return 2 + return 1 + ;; + esac + done <<< "$untracked_files" +} + +# This ordinary branch validation restore supplies a clean Linux package cache. +# The production evidence controller must never restore a PR head on its host. +if ! dotnet restore "$repository_root/ForgeTrust.AppSurface.slnx" \ + --locked-mode --packages "$global_packages" --verbosity quiet; then + check_no_untracked_rid_locks || true + exit 2 +fi + +# This project selects its lock file from NETCoreSdkRuntimeIdentifier. Record +# that host evaluation and explicitly verify the image's linux-x64 lock target +# before assembling or building the candidate image; locked mode never rewrites +# either lock file. +rid_properties_path="$work_root/keycloak-rid-properties.json" +rid_evidence_path="$work_root/keycloak-linux-x64-rid-preflight.json" +rid_preflight_status='failed' +rid_preflight_diagnostic='preflight-incomplete' +host_sdk_rid='unavailable' +host_lock_file='unavailable' +if ! dotnet msbuild "$rid_project" -nologo \ + -getProperty:NETCoreSdkRuntimeIdentifier,NuGetLockFilePath > "$rid_properties_path"; then + if ! check_no_untracked_rid_locks; then + rid_preflight_diagnostic='untracked-rid-specific-lock-file' + else + rid_preflight_diagnostic='msbuild-property-query-failed' + fi +elif ! rid_properties="$(python3 -c ' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as source: + result = json.load(source) +properties = result.get("Properties", result) +print("\t".join(( + str(properties.get("NETCoreSdkRuntimeIdentifier", "")), + str(properties.get("NuGetLockFilePath", "")), +))) +' "$rid_properties_path")"; then + if ! check_no_untracked_rid_locks; then + rid_preflight_diagnostic='untracked-rid-specific-lock-file' + else + rid_preflight_diagnostic='msbuild-property-output-invalid' + fi +else + IFS=$'\t' read -r host_sdk_rid host_lock_file <<< "$rid_properties" + if ! check_no_untracked_rid_locks; then + rid_preflight_diagnostic='untracked-rid-specific-lock-file' + elif [[ "$host_sdk_rid" != 'linux-x64' ]]; then + rid_preflight_diagnostic='host-sdk-rid-does-not-match-image' + elif [[ "$host_lock_file" != 'packages.linux-x64.lock.json' ]]; then + rid_preflight_diagnostic='host-lock-file-does-not-select-linux-x64' + elif ! git -C "$repository_root" ls-files --error-unmatch -- \ + "$rid_project_relative/$host_lock_file" >/dev/null 2>&1; then + rid_preflight_diagnostic='selected-linux-x64-lock-is-not-tracked' + elif [[ ! -f "$repository_root/$rid_project_relative/$host_lock_file" \ + || -L "$repository_root/$rid_project_relative/$host_lock_file" ]]; then + rid_preflight_diagnostic='selected-linux-x64-lock-is-not-a-regular-file' + elif ! dotnet restore "$rid_project" --locked-mode \ + --disable-parallel -m:1 --packages "$global_packages" --verbosity minimal; then + if ! check_no_untracked_rid_locks; then + rid_preflight_diagnostic='untracked-rid-specific-lock-file-after-linux-restore' + else + rid_preflight_diagnostic='serial-linux-x64-lock-selection-restore-failed' + fi + elif ! check_no_untracked_rid_locks; then + rid_preflight_diagnostic='untracked-rid-specific-lock-file-after-linux-restore' + else + rid_preflight_status='pass' + rid_preflight_diagnostic='' + fi +fi +RID_EVIDENCE_PATH="$rid_evidence_path" \ +RID_PREFLIGHT_STATUS="$rid_preflight_status" \ +RID_PREFLIGHT_DIAGNOSTIC="$rid_preflight_diagnostic" \ +RID_PROJECT="$rid_project" \ +HOST_SDK_RID="$host_sdk_rid" \ +HOST_LOCK_FILE="$host_lock_file" \ +RID_RESTORE_TARGET='linux-x64' \ +SDK_VERSION='10.0.401' \ +python3 -c ' +import json +import os +from pathlib import Path +record = { + "schema": "appsurface-subject-host-rid-preflight-v1", + "status": os.environ["RID_PREFLIGHT_STATUS"], + "diagnostic": os.environ["RID_PREFLIGHT_DIAGNOSTIC"] or None, + "project": os.environ["RID_PROJECT"], + "hostNETCoreSdkRuntimeIdentifier": os.environ["HOST_SDK_RID"], + "evaluatedNuGetLockFilePath": os.environ["HOST_LOCK_FILE"], + "requiredLockSelectionRuntimeIdentifier": os.environ["RID_RESTORE_TARGET"], + "restoreRuntimeArgument": None, + "serialLockedProjectRestore": os.environ["RID_PREFLIGHT_STATUS"] == "pass", + "sdkVersion": os.environ["SDK_VERSION"], +} +Path(os.environ["RID_EVIDENCE_PATH"]).write_text( + json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8" +) +' +if [[ "$rid_preflight_status" != 'pass' ]]; then + printf 'Host RID evaluation: NETCoreSdkRuntimeIdentifier=%s NuGetLockFilePath=%s\n' \ + "$host_sdk_rid" "$host_lock_file" >&2 + printf 'Host RID preflight failed (%s); evidence: %s\n' \ + "$rid_preflight_diagnostic" "$rid_evidence_path" >&2 + exit 2 +fi +printf 'Host RID evaluation: NETCoreSdkRuntimeIdentifier=%s NuGetLockFilePath=%s\n' \ + "$host_sdk_rid" "$host_lock_file" + +python3 "$repository_root/scripts/evidence-gate-build-offline-feed.py" \ + --checkout "$repository_root" \ + --solution ForgeTrust.AppSurface.slnx \ + --global-packages "$global_packages" \ + --output "$context/locked-dependencies" +cp "$repository_root/scripts/evidence-gate-subject-entrypoint.py" \ + "$context/evidence-gate-subject-entrypoint.py" +docker build --platform linux/amd64 \ + --file "$repository_root/scripts/evidence-gate-subject-image/Containerfile" \ + --tag "$image_tag" "$context" +docker_image_identity="$(docker image inspect --format '{{.Id}}|{{.Os}}|{{.Architecture}}' "$image_tag")" +IFS='|' read -r docker_image_id docker_image_os docker_image_arch <<< "$docker_image_identity" +printf 'local image ID=%s platform=%s/%s\n' "$docker_image_id" "$docker_image_os" "$docker_image_arch" + +# Podman has a separate image store. Transfer this exact Docker candidate as a +# local archive, require the image IDs to match, and smoke it before the Docker +# cold restore so the two checks report independently. This lane never claims +# eligibility or publishes the candidate. +podman_evidence_path="$work_root/rootless-podman-smoke.json" +podman_probe_path="$work_root/podman-live-scratch.json" +podman_created_inspect_path="$work_root/podman-created-inspect.json" +podman_final_inspect_path="$work_root/podman-final-inspect.json" +podman_created_checks_path="$work_root/podman-created-checks.json" +podman_final_checks_path="$work_root/podman-final-checks.json" +podman_container_name="appsurface-subject-smoke-$$-${work_root##*.}" +podman_container_id='unavailable' +podman_cli_path='unavailable' +podman_version='unavailable' +podman_info='unavailable' +podman_rootless=false +podman_image_id='unavailable' +podman_status='pending' +podman_phase='preflight' +podman_diagnostic='' +podman_container_create_attempted=false +podman_container_created=false +podman_container_started=false +podman_zero_exit=false +podman_configuration_verified=false +podman_probe_verified=false +podman_container_removed=false +podman_cleanup_attempted=false +podman_cleanup_succeeded=false +podman_evidence_written=false +scratch_tmpfs_options='unavailable' +scratch_bytes='unavailable' +scratch_inodes='unavailable' +scratch_uid='unavailable' +scratch_gid='unavailable' +podman_runner_uid="$(id -u)" +podman_runner_gid="$(id -g)" +scratch_host_mount="$work_root/quota-limited-scratch" +scratch_host_mounted=false +scratch_host_unmount_succeeded=false + +write_podman_evidence() { + PODMAN_EVIDENCE_PATH="$podman_evidence_path" \ + PODMAN_PROBE_PATH="$podman_probe_path" \ + PODMAN_CREATED_INSPECT_PATH="$podman_created_inspect_path" \ + PODMAN_FINAL_INSPECT_PATH="$podman_final_inspect_path" \ + PODMAN_CREATED_CHECKS_PATH="$podman_created_checks_path" \ + PODMAN_FINAL_CHECKS_PATH="$podman_final_checks_path" \ + PODMAN_STATUS="$podman_status" PODMAN_PHASE="$podman_phase" \ + PODMAN_DIAGNOSTIC="$podman_diagnostic" PODMAN_RUNNER_UID="$podman_runner_uid" \ + PODMAN_CLI_PATH="$podman_cli_path" PODMAN_VERSION="$podman_version" \ + PODMAN_INFO="$podman_info" PODMAN_ROOTLESS="$podman_rootless" \ + DOCKER_IMAGE_ID="$docker_image_id" PODMAN_IMAGE_ID="$podman_image_id" \ + IMAGE_TAG="$image_tag" PODMAN_CONTAINER_NAME="$podman_container_name" \ + PODMAN_CONTAINER_ID="$podman_container_id" \ + PODMAN_CONTAINER_CREATE_ATTEMPTED="$podman_container_create_attempted" \ + PODMAN_CONTAINER_CREATED="$podman_container_created" \ + PODMAN_CONTAINER_STARTED="$podman_container_started" \ + PODMAN_ZERO_EXIT="$podman_zero_exit" \ + PODMAN_CONFIGURATION_VERIFIED="$podman_configuration_verified" \ + PODMAN_PROBE_VERIFIED="$podman_probe_verified" \ + PODMAN_CONTAINER_REMOVED="$podman_container_removed" \ + PODMAN_CLEANUP_ATTEMPTED="$podman_cleanup_attempted" \ + PODMAN_CLEANUP_SUCCEEDED="$podman_cleanup_succeeded" \ + SCRATCH_TMPFS_OPTIONS="$scratch_tmpfs_options" \ + SCRATCH_BYTES="$scratch_bytes" SCRATCH_INODES="$scratch_inodes" \ + SCRATCH_UID="$scratch_uid" SCRATCH_GID="$scratch_gid" \ + SCRATCH_HOST_UNMOUNT_SUCCEEDED="$scratch_host_unmount_succeeded" \ + IMAGE_OS="$docker_image_os" IMAGE_ARCH="$docker_image_arch" \ + python3 -c ' +import json +import os +import re +from pathlib import Path + +def read_json(path): + try: + return json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError): + return None + +def integer(name): + try: + return int(os.environ[name]) + except ValueError: + return None + +def flag(name): + return os.environ[name] == "true" + +final_objects = read_json(os.environ["PODMAN_FINAL_INSPECT_PATH"]) +final = final_objects[0] if isinstance(final_objects, list) and len(final_objects) == 1 and isinstance(final_objects[0], dict) else None +observation = read_json(os.environ["PODMAN_PROBE_PATH"]) +created_checks = read_json(os.environ["PODMAN_CREATED_CHECKS_PATH"]) +final_checks = read_json(os.environ["PODMAN_FINAL_CHECKS_PATH"]) +final_state = final.get("State") if isinstance(final, dict) else None +final_state = final_state if isinstance(final_state, dict) else {} +final_config = final.get("Config") if isinstance(final, dict) else None +final_config = final_config if isinstance(final_config, dict) else {} +final_host = final.get("HostConfig") if isinstance(final, dict) else None +final_host = final_host if isinstance(final_host, dict) else {} +final_mounts = final.get("Mounts") if isinstance(final, dict) else None +final_mounts = final_mounts if isinstance(final_mounts, list) else [] +record = { + "schema": "appsurface-subject-rootless-podman-smoke-v1", + "status": os.environ["PODMAN_STATUS"], + "phase": os.environ["PODMAN_PHASE"], + "diagnostic": os.environ["PODMAN_DIAGNOSTIC"] or None, + "claimEligible": False, + "published": False, + "runner": { + "uid": integer("PODMAN_RUNNER_UID"), + "podmanPath": os.environ["PODMAN_CLI_PATH"], + "podmanVersion": os.environ["PODMAN_VERSION"], + "rootlessInfo": os.environ["PODMAN_INFO"], + "rootlessVerified": flag("PODMAN_ROOTLESS"), + }, + "image": { + "reference": os.environ["IMAGE_TAG"], + "transfer": "docker-save-podman-load", + "dockerImageId": os.environ["DOCKER_IMAGE_ID"], + "podmanImageId": os.environ["PODMAN_IMAGE_ID"], + "platform": os.environ["IMAGE_OS"] + "/" + os.environ["IMAGE_ARCH"], + "identityMatched": ( + re.fullmatch(r"[0-9a-f]{64}", os.environ["DOCKER_IMAGE_ID"].removeprefix("sha256:")) is not None + and os.environ["DOCKER_IMAGE_ID"].removeprefix("sha256:") + == os.environ["PODMAN_IMAGE_ID"].removeprefix("sha256:") + ), + }, + "container": { + "name": os.environ["PODMAN_CONTAINER_NAME"], + "id": os.environ["PODMAN_CONTAINER_ID"], + "createAttempted": flag("PODMAN_CONTAINER_CREATE_ATTEMPTED"), + "created": flag("PODMAN_CONTAINER_CREATED"), + "started": flag("PODMAN_CONTAINER_STARTED"), + "zeroExit": flag("PODMAN_ZERO_EXIT"), + "configurationVerified": flag("PODMAN_CONFIGURATION_VERIFIED"), + "liveScratchVerified": flag("PODMAN_PROBE_VERIFIED"), + "removed": flag("PODMAN_CONTAINER_REMOVED"), + "cleanupAttempted": flag("PODMAN_CLEANUP_ATTEMPTED"), + "cleanupSucceeded": flag("PODMAN_CLEANUP_SUCCEEDED"), + "createdChecks": created_checks, + "finalChecks": final_checks, + "inspect": ({ + "networkMode": final_host.get("NetworkMode"), + "readOnlyRootfs": final_host.get("ReadonlyRootfs"), + "user": final_config.get("User"), + "state": final_state.get("Status"), + "exitCode": final_state.get("ExitCode"), + "mounts": [ + {key: mount.get(key) for key in ("Type", "Source", "Destination", "RW", "Propagation")} + for mount in final_mounts if isinstance(mount, dict) + ], + } if isinstance(final, dict) else None), + "liveObservation": observation, + }, + "scratchContract": { + "mountApproach": "trusted-host-tmpfs-rootless-bind", + "hostUnmountSucceeded": flag("SCRATCH_HOST_UNMOUNT_SUCCEEDED"), + "options": os.environ["SCRATCH_TMPFS_OPTIONS"], + "bytes": integer("SCRATCH_BYTES"), + "inodes": integer("SCRATCH_INODES"), + "uid": integer("SCRATCH_UID"), + "gid": integer("SCRATCH_GID"), + "hostUid": integer("PODMAN_RUNNER_UID"), + }, +} +Path(os.environ["PODMAN_EVIDENCE_PATH"]).write_text( + json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8" +) +' +} + +podman_smoke_cleanup() { + local exit_code=$? + trap - EXIT + if [[ "$podman_evidence_written" == true ]]; then + exit "$exit_code" + fi + if [[ "$podman_container_create_attempted" == true && "$podman_cleanup_succeeded" != true ]]; then + podman_cleanup_attempted=true + if timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false rm --force --ignore \ + "$podman_container_name" >/dev/null 2>&1; then + podman_cleanup_succeeded=true + podman_container_removed=true + else + podman_status='failed' + podman_phase='cleanup' + if [[ -n "$podman_diagnostic" ]]; then + podman_diagnostic="$podman_diagnostic;container-cleanup-failed" + else + podman_diagnostic='container-cleanup-failed' + fi + [[ "$exit_code" -ne 0 ]] || exit_code=1 + fi + fi + # A failed container removal may leave the bind mount in use. Keep the host + # mount attached for runner retirement instead of detaching it underneath a + # container that may still be running. + if [[ "$scratch_host_mounted" == true \ + && ( "$podman_container_create_attempted" != true || "$podman_container_removed" == true ) ]]; then + if timeout --signal=TERM --kill-after=5s 30s sudo -n umount "$scratch_host_mount"; then + scratch_host_mounted=false + scratch_host_unmount_succeeded=true + else + podman_status='failed' + podman_phase='cleanup' + if [[ -n "$podman_diagnostic" ]]; then + podman_diagnostic="$podman_diagnostic;scratch-host-unmount-failed" + else + podman_diagnostic='scratch-host-unmount-failed' + fi + [[ "$exit_code" -ne 0 ]] || exit_code=1 + fi + fi + if [[ "$podman_status" == pending || "$podman_status" == running ]]; then + podman_status='failed' + podman_diagnostic='smoke-interrupted' + [[ "$exit_code" -ne 0 ]] || exit_code=1 + fi + if ! write_podman_evidence; then + printf 'Could not write Podman smoke evidence at %s.\n' "$podman_evidence_path" >&2 + [[ "$exit_code" -ne 0 ]] || exit_code=1 + else + podman_evidence_written=true + printf 'Podman smoke evidence path: %s\n' "$podman_evidence_path" + printf 'PODMAN_SMOKE_EVIDENCE=' + cat "$podman_evidence_path" + fi + exit "$exit_code" +} + +podman_fail() { + podman_status='failed' + podman_phase="$1" + podman_diagnostic="$2" + printf 'Rootless Podman smoke failed during %s: %s\n' "$podman_phase" "$podman_diagnostic" >&2 + exit 2 +} + +trap podman_smoke_cleanup EXIT +if [[ "$docker_image_os/$docker_image_arch" != 'linux/amd64' ]]; then + podman_fail 'preflight' 'candidate-image-platform-mismatch' +fi +if [[ "$podman_runner_uid" == '0' ]]; then + podman_fail 'preflight' 'runner-is-root' +fi +if ! command -v timeout >/dev/null 2>&1; then + podman_fail 'preflight' 'timeout-command-unavailable' +fi +if ! command -v mountpoint >/dev/null 2>&1; then + podman_fail 'preflight' 'mountpoint-command-unavailable' +fi +podman_cli_path="$(command -v podman || true)" +if [[ -z "$podman_cli_path" ]]; then + podman_cli_path='unavailable' + podman_fail 'preflight' 'podman-unavailable' +fi + +podman_phase='rootless-preflight' +if ! podman_info="$(timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false info --format '{{.Host.Security.Rootless}}')"; then + podman_fail "$podman_phase" 'podman-info-failed' +fi +if [[ "$podman_info" != 'true' ]]; then + podman_fail "$podman_phase" 'podman-is-not-rootless' +fi +podman_rootless=true +if ! podman_version="$(timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false version --format '{{.Client.Version}}')"; then + podman_fail "$podman_phase" 'podman-version-unavailable' +fi + +podman_phase='read-scratch-contract' +if ! scratch_contract="$(python3 -c ' +import runpy +import sys +values = runpy.run_path(sys.argv[1]) +print("|".join(( + str(values["MAX_PROFILE_SCRATCH_BYTES"]), + str(values["MAX_PROFILE_SCRATCH_INODES"]), + str(values["CONTAINER_UID"]), + str(values["CONTAINER_GID"]), +))) +' "$repository_root/scripts/evidence-gate-subject.py")"; then + podman_fail "$podman_phase" 'launcher-scratch-contract-unavailable' +fi +IFS='|' read -r scratch_bytes scratch_inodes scratch_uid scratch_gid <<< "$scratch_contract" +if [[ "$scratch_bytes" != '4294967296' || "$scratch_inodes" != '262144' \ + || "$scratch_uid" != '65532' || "$scratch_gid" != '65532' ]]; then + podman_fail "$podman_phase" 'launcher-scratch-contract-changed' +fi +scratch_tmpfs_options="rw,nosuid,nodev,size=$scratch_bytes,nr_inodes=$scratch_inodes,mode=0700,uid=$podman_runner_uid,gid=$podman_runner_gid" +podman_phase='mount-host-scratch' +if ! mkdir -m 0700 "$scratch_host_mount"; then + podman_fail "$podman_phase" 'scratch-mountpoint-create-failed' +fi +if ! timeout --signal=TERM --kill-after=5s 30s sudo -n mount -t tmpfs \ + -o "$scratch_tmpfs_options" \ + tmpfs "$scratch_host_mount"; then + if mountpoint -q "$scratch_host_mount"; then + scratch_host_mounted=true + fi + podman_fail "$podman_phase" 'quota-limited-host-tmpfs-mount-failed' +fi +scratch_host_mounted=true +if ! mountpoint -q "$scratch_host_mount"; then + podman_fail "$podman_phase" 'quota-limited-host-tmpfs-not-mounted' +fi + +podman_phase='image-transfer' +podman_archive="$work_root/candidate-image.docker.tar" +if ! timeout --signal=TERM --kill-after=5s 180s \ + docker save --output "$podman_archive" "$image_tag"; then + podman_fail "$podman_phase" 'docker-save-failed' +fi +if ! timeout --signal=TERM --kill-after=5s 180s \ + "$podman_cli_path" --remote=false load --input "$podman_archive"; then + podman_fail "$podman_phase" 'podman-load-failed' +fi +if ! podman_image_id="$(timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false image inspect --format '{{.Id}}' "$image_tag")"; then + podman_fail "$podman_phase" 'podman-image-inspect-failed' +fi +docker_image_hex="${docker_image_id#sha256:}" +podman_image_hex="${podman_image_id#sha256:}" +if [[ ! "$docker_image_hex" =~ ^[0-9a-f]{64}$ \ + || ! "$podman_image_hex" =~ ^[0-9a-f]{64}$ \ + || "$podman_image_hex" != "$docker_image_hex" ]]; then + podman_fail "$podman_phase" 'transferred-image-identity-mismatch' +fi +rm -f "$podman_archive" + +podman_phase='container-create' +podman_probe='import json +import os +import re +import sys + +expected_bytes, expected_inodes, expected_uid, expected_gid = map(int, sys.argv[1:5]) +with open("/proc/self/status", encoding="utf-8") as source: + status = dict(line.rstrip("\n").split(":", 1) for line in source if ":" in line) +capabilities = { + name: int(status.get(name, "-1").strip(), 16) + for name in ("CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb") +} +mounts = {} +lines = {} +with open("/proc/self/mountinfo", encoding="utf-8") as source: + for line in source: + left, separator, right = line.rstrip("\n").partition(" - ") + fields = left.split() + if not separator or len(fields) < 6: + raise RuntimeError("malformed mountinfo") + destination = fields[4].replace("\\040", " ").replace("\\011", "\t") + if destination not in ("/", "/scratch"): + continue + fs_fields = right.split() + if len(fs_fields) < 3: + raise RuntimeError("malformed mountinfo filesystem fields") + mounts[destination] = { + "type": fs_fields[0], + "mountOptions": fields[5].split(","), + "superOptions": fs_fields[2].split(","), + } + lines[destination] = line.rstrip("\n") +root_mount = mounts.get("/") +scratch_mount = mounts.get("/scratch") +if root_mount is None or scratch_mount is None: + raise RuntimeError("root or scratch mount not found") +options = set(scratch_mount["mountOptions"] + scratch_mount["superOptions"]) +values = dict(item.split("=", 1) for item in options if "=" in item) +size_match = re.fullmatch(r"([0-9]+)([kKmMgGtT]?)", values.get("size", "")) +size_scale = {"": 1, "k": 1024, "m": 1024 ** 2, "g": 1024 ** 3, "t": 1024 ** 4} +option_bytes = ( + int(size_match.group(1)) * size_scale[size_match.group(2).lower()] + if size_match else None +) +stat = os.statvfs("/scratch") +actual_bytes = stat.f_blocks * stat.f_frsize +try: + mode = int(values.get("mode", "-1"), 8) +except ValueError: + mode = -1 +checks = { + "nonRootIdentity": os.getuid() == expected_uid and os.getgid() == expected_gid, + "allCapabilitySetsEmpty": all(value == 0 for value in capabilities.values()), + "readOnlyRootMount": "ro" in root_mount["mountOptions"], + "scratchIsTmpfs": scratch_mount["type"] == "tmpfs", + "scratchReadWrite": "rw" in options, + "scratchNoSuid": "nosuid" in options, + "scratchNoDeviceNodes": "nodev" in options, + "scratchNoUnsupportedNoSwap": "noswap" not in options, + "scratchByteOption": option_bytes == expected_bytes, + "scratchInodeOption": values.get("nr_inodes") == str(expected_inodes), + "scratchByteStatvfs": actual_bytes == expected_bytes, + "scratchInodeStatvfs": stat.f_files == expected_inodes, + "scratchMode": mode == 0o700, + "scratchUid": os.stat("/scratch").st_uid == expected_uid, + "scratchGid": os.stat("/scratch").st_gid == expected_gid, +} +record = { + "schema": "appsurface-subject-podman-live-mount-v1", + "uid": os.getuid(), + "gid": os.getgid(), + "capabilities": capabilities, + "rootMount": {**root_mount, "mountInfo": lines["/"]}, + "scratchMount": {**scratch_mount, "mountInfo": lines["/scratch"]}, + "scratchStatvfs": { + "blockSize": stat.f_frsize, + "blocks": stat.f_blocks, + "bytes": actual_bytes, + "inodes": stat.f_files, + "freeBytes": stat.f_bavail * stat.f_frsize, + "freeInodes": stat.f_favail, + }, + "checks": checks, +} +print(json.dumps(record, sort_keys=True)) +if not all(checks.values()): + sys.exit(1) +' +podman_container_create_attempted=true +if ! podman_container_id="$(timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false create \ + --pull=never --name "$podman_container_name" --network=none \ + --pid=private --ipc=private --uts=private --cgroupns=private \ + --read-only --read-only-tmpfs=false --http-proxy=false \ + --userns="keep-id:uid=$scratch_uid,gid=$scratch_gid" \ + --user="$scratch_uid:$scratch_gid" \ + --cap-drop=ALL --security-opt=no-new-privileges \ + --pids-limit=64 --memory=256m --cpus=0.500 \ + --mount "type=bind,src=$scratch_host_mount,dst=/scratch,rw=true,bind-propagation=rprivate" \ + --entrypoint=/usr/bin/python3 "$image_tag" -c "$podman_probe" \ + "$scratch_bytes" "$scratch_inodes" "$scratch_uid" "$scratch_gid")"; then + podman_fail "$podman_phase" 'podman-container-create-failed' +fi +podman_container_created=true + +verify_podman_inspect() { + local inspect_path="$1" + local checks_path="$2" + local require_scratch="$3" + python3 - "$inspect_path" "$require_scratch" "$scratch_uid" "$scratch_gid" "$scratch_host_mount" \ + > "$checks_path" <<'PY' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as source: + inspected = json.load(source) +if not isinstance(inspected, list) or len(inspected) != 1 or not isinstance(inspected[0], dict): + raise SystemExit("Podman inspect did not return one container object.") +container = inspected[0] +config = container.get("Config") or {} +host = container.get("HostConfig") or {} +state = container.get("State") or {} +security = host.get("SecurityOpt") +mounts = container.get("Mounts") or [] +scratch = [mount for mount in mounts if isinstance(mount, dict) and mount.get("Destination") == "/scratch"] +effective_caps = container.get("EffectiveCaps") +bounding_caps = container.get("BoundingCaps") +reported_capability_sets_empty = ( + isinstance(effective_caps, list) and isinstance(bounding_caps, list) + and not effective_caps and not bounding_caps + and host.get("CapAdd") in (None, []) +) +expected_default_caps = { + "CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FOWNER", "CAP_FSETID", "CAP_KILL", + "CAP_NET_BIND_SERVICE", "CAP_SETFCAP", "CAP_SETGID", "CAP_SETPCAP", + "CAP_SETUID", "CAP_SYS_CHROOT", +} +drop_presentation = host.get("CapDrop") +reported_drop_request = ( + isinstance(drop_presentation, list) + and expected_default_caps.issubset(drop_presentation) + and all(isinstance(capability, str) for capability in drop_presentation) + and len(drop_presentation) == len(set(drop_presentation)) + and host.get("CapAdd") in (None, []) +) +checks = { + "networkNone": host.get("NetworkMode") == "none", + "readOnlyRoot": host.get("ReadonlyRootfs") is True, + "fixedNonRootUser": config.get("User") == f"{sys.argv[3]}:{sys.argv[4]}", + "capabilityDropRequest": reported_capability_sets_empty or ( + effective_caps is None and bounding_caps is None and reported_drop_request + ), + "privateNamespaceRequests": all( + host.get(key) == "private" for key in ("PidMode", "IpcMode", "UTSMode", "UsernsMode") + ), + "boundedResourceRequests": ( + host.get("PidsLimit") == 64 + and host.get("Memory") == 256 * 1024 * 1024 + and host.get("NanoCpus") == 500_000_000 + and host.get("CpuQuota") == 50_000 + and host.get("CpuPeriod") == 100_000 + ), + "notPrivileged": host.get("Privileged") is False, + "noNewPrivileges": isinstance(security, list) and any( + value in ("no-new-privileges", "no-new-privileges:true") for value in security + ), +} +if sys.argv[2] == "true": + checks["scratchMountedReadWriteHostTmpfs"] = ( + len(scratch) == 1 and scratch[0].get("Type") == "bind" + and scratch[0].get("Source") == sys.argv[5] and scratch[0].get("RW") is True + ) + checks["containerExitedZero"] = state.get("Status") == "exited" and state.get("ExitCode") == 0 +print(json.dumps({ + "checks": checks, + "capabilitySets": { + "effective": container.get("EffectiveCaps"), + "bounding": container.get("BoundingCaps"), + "added": host.get("CapAdd"), + "dropPresentation": host.get("CapDrop"), + }, + "resourceAndNamespacePresentation": { + key: host.get(key) for key in ( + "PidMode", "IpcMode", "UTSMode", "CgroupnsMode", "UsernsMode", + "PidsLimit", "Memory", "NanoCpus", "CpuQuota", "CpuPeriod", + "Privileged", + ) + }, + "state": state, +}, sort_keys=True)) +if not all(checks.values()): + raise SystemExit("Podman inspect did not match the smoke envelope.") +PY +} + +podman_phase='container-inspect-before-start' +if ! timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false inspect "$podman_container_id" > "$podman_created_inspect_path"; then + podman_fail "$podman_phase" 'podman-created-container-inspect-failed' +fi +if ! verify_podman_inspect "$podman_created_inspect_path" \ + "$podman_created_checks_path" false; then + podman_fail "$podman_phase" 'podman-created-container-configuration-mismatch' +fi +podman_configuration_verified=true + +podman_phase='container-start' +if ! timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false start --attach "$podman_container_id" \ + 2> "$work_root/podman-start.stderr" \ + | head -c 32768 > "$podman_probe_path"; then + podman_fail "$podman_phase" 'podman-container-start-or-live-probe-failed' +fi +podman_container_started=true +podman_zero_exit=true +if ! python3 - "$podman_probe_path" <<'PY' +import json +import sys +with open(sys.argv[1], encoding="utf-8") as source: + record = json.load(source) +if ( + record.get("schema") != "appsurface-subject-podman-live-mount-v1" + or not isinstance(record.get("checks"), dict) + or not record["checks"] + or not all(record["checks"].values()) +): + raise SystemExit("The live scratch mount observation did not verify the fixed contract.") +PY +then + podman_fail "$podman_phase" 'podman-live-scratch-contract-mismatch' +fi +podman_probe_verified=true + +podman_phase='container-inspect-after-start' +if ! timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false inspect "$podman_container_id" > "$podman_final_inspect_path"; then + podman_fail "$podman_phase" 'podman-final-container-inspect-failed' +fi +if ! verify_podman_inspect "$podman_final_inspect_path" \ + "$podman_final_checks_path" true; then + podman_fail "$podman_phase" 'podman-final-container-state-mismatch' +fi +podman_status='pass' +podman_phase='cleanup' +podman_cleanup_attempted=true +if ! timeout --signal=TERM --kill-after=5s 30s \ + "$podman_cli_path" --remote=false rm --force --ignore \ + "$podman_container_id" >/dev/null 2>&1; then + podman_status='failed' + podman_diagnostic='container-cleanup-failed' + podman_fail "$podman_phase" "$podman_diagnostic" +fi +podman_cleanup_succeeded=true +podman_container_removed=true +if ! timeout --signal=TERM --kill-after=5s 30s sudo -n umount "$scratch_host_mount"; then + podman_status='failed' + podman_diagnostic='scratch-host-unmount-failed' + podman_fail 'cleanup' "$podman_diagnostic" +fi +scratch_host_mounted=false +scratch_host_unmount_succeeded=true +podman_phase='complete' +if ! write_podman_evidence; then + podman_status='failed' + podman_phase='evidence-write' + podman_diagnostic='podman-evidence-write-failed' + podman_fail "$podman_phase" "$podman_diagnostic" +fi +podman_evidence_written=true +echo 'Rootless Podman started the transferred image with network none, read-only root, and verified 4 GiB/262144-inode scratch.' +printf 'Podman smoke evidence path: %s\n' "$podman_evidence_path" +printf 'PODMAN_SMOKE_EVIDENCE=' +cat "$podman_evidence_path" + +# The disposable source copy keeps package extraction and MSBuild obj writes +# away from the checkout. Only this copy, its empty cache, and the fixed offline +# source config enter the no-network validation container. +mkdir -m 0700 "$cold_root/source" "$cold_root/cache" "$cold_root/home" "$cold_root/tmp" +cp -a "$repository_root/." "$cold_root/source/" +cat > "$cold_root/offline-nuget.config" <<'CONFIG' + + + + + + + +CONFIG +# Project SDK resolution runs while MSBuild evaluates the project, before the +# restore command's --configfile is applied. Give that resolver the same closed +# feed through the private subject user's NuGet configuration. +mkdir -m 0700 "$cold_root/home/.nuget" "$cold_root/home/.nuget/NuGet" +cp "$cold_root/offline-nuget.config" "$cold_root/home/.nuget/NuGet/NuGet.Config" +timeout --signal=TERM --kill-after=5s 120s sudo -n chown -R 65532:65532 "$cold_root" + +if timeout --signal=TERM --kill-after=10s 16m \ + docker run --rm --platform linux/amd64 \ + --pull never --network none --read-only --user 65532:65532 \ + --cap-drop ALL --security-opt no-new-privileges \ + --pids-limit 256 --memory 4g --cpus 2 \ + --mount "type=bind,src=$cold_root,dst=/work" \ + --tmpfs /tmp:rw,noexec,nosuid,nodev,size=512m,mode=1777 \ + --workdir /work/source \ + --env HOME=/work/home \ + --env DOTNET_CLI_HOME=/work/home \ + --env DOTNET_CLI_TELEMETRY_OPTOUT=1 \ + --env DOTNET_NOLOGO=1 \ + --env NUGET_PACKAGES=/work/cache \ + --env NUGET_HTTP_CACHE_PATH=/work/http-cache \ + --env TMPDIR=/work/tmp \ + --entrypoint /bin/sh "$image_tag" -c ' + exec timeout --signal=TERM --kill-after=10s 15m \ + dotnet restore /work/source/ForgeTrust.AppSurface.slnx \ + --locked-mode --disable-parallel -m:1 \ + --configfile /work/offline-nuget.config \ + --source /opt/appsurface/locked-dependencies \ + --packages /work/cache --verbosity minimal + '; then + : +else + cold_restore_exit_code=$? + printf 'Docker cold restore failed (exit %s; workload limit 15m, client limit 16m).\n' \ + "$cold_restore_exit_code" >&2 + exit "$cold_restore_exit_code" +fi + +if ! cache_entry="$(timeout --signal=TERM --kill-after=5s 30s \ + sudo -n find "$cold_root/cache" -mindepth 1 -maxdepth 1 -print -quit)"; then + echo 'The offline package cache could not be inspected after restore.' >&2 + exit 2 +fi +if [[ -z "$cache_entry" ]]; then + echo 'The offline restore produced no packages in its empty cache.' >&2 + exit 2 +fi +echo 'Native Linux x64 cold-cache locked restore passed with only the embedded feed.' diff --git a/scripts/evidence-gate-subject-supervisor.py b/scripts/evidence-gate-subject-supervisor.py new file mode 100644 index 000000000..fa118f0ef --- /dev/null +++ b/scripts/evidence-gate-subject-supervisor.py @@ -0,0 +1,1354 @@ +#!/usr/bin/env python3 +"""Independently reap one fixed AppSurface OCI subject run. + +The launcher starts this process before creating its container. ``start`` +creates a private run directory and manifest, then starts a detached supervisor +which watches the launcher's PID and Linux process start time. On normal +completion the launcher invokes ``request``; if it is killed, the supervisor +detects that the exact parent process has exited. The supervisor has no shell +or caller-supplied command support. It removes only a container bearing this +run's random ownership label and exact scratch bind, then unmounts only the +matching fixed-quota tmpfs. It writes a small, non-claiming attestation outside +the tmpfs. + +This helper does not establish a complete isolation envelope or an eligible +Evidence claim. Its detached process is independent of launcher SIGKILL, but +cannot survive destruction of the runner VM or an external job cgroup kill. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import json +import os +from pathlib import Path +import re +import selectors +import shutil +import signal +import stat +import subprocess +import sys +import time +from typing import Any, Callable, Mapping, Sequence + + +PODMAN_PATH = "/usr/bin/podman" +SUDO_PATH = "/usr/bin/sudo" +ENGINE_PATH = "/usr/bin:/usr/local/bin:/bin" +MOUNTINFO_PATH = Path("/proc/self/mountinfo") +PROC_ROOT = Path("/proc") +TOKEN_PATTERN = re.compile(r"[0-9a-f]{32}\Z") +RUN_DIRECTORY_PATTERN = re.compile(r"appsurface-subject-supervisor-([0-9a-f]{32})\Z") +CONTAINER_PATTERN = re.compile(r"ase-subject-([1-9][0-9]{0,18})-([1-9][0-9]{0,8})-([0-9a-f]{12})\Z") +MOUNTPOINT_PATTERN = re.compile(r"quota-limited-scratch-[0-9a-f]{16}\Z") +OWNER_LABEL = "io.forge-trust.appsurface.cleanup-token" +MANIFEST_NAME = "supervisor.json" +REQUEST_NAME = "cleanup-request.json" +ATTESTATION_NAME = "cleanup-attestation.json" +SUBJECT_RESULT_NAME = "evidence-subject-result.json" +MAX_SUBJECT_RESULT_BYTES = 16 * 1024 +MAX_MANIFEST_BYTES = 4096 +MAX_REQUEST_BYTES = 512 +MAX_ATTESTATION_BYTES = 4096 +MAX_COMMAND_OUTPUT_BYTES = 256 * 1024 +MAX_COMMAND_SECONDS = 30 +SUPERVISOR_STARTUP_SECONDS = 10 +MAX_PARENT_LIFETIME_SECONDS = 30 * 60 +CLEANUP_DEADLINE_SECONDS = 10 * 60 +PARENT_POLL_SECONDS = 0.2 +TMPFS_BYTES = 4 * 1024**3 +TMPFS_INODES = 262_144 + + +class SupervisorError(Exception): + """A fixed, safe diagnostic for malformed supervisor input.""" + + def __init__(self, code: str) -> None: + super().__init__(code) + self.code = code + + +class CommandError(Exception): + """A bounded trusted-command failure identified by a stable code.""" + + def __init__(self, code: str) -> None: + super().__init__(code) + self.code = code + + +@dataclass(frozen=True) +class CommandResult: + returncode: int + stdout: bytes + stderr: bytes + + +@dataclass(frozen=True) +class Manifest: + token: str + container_name: str + scratch_directory: Path + mountpoint: Path + parent_pid: int + parent_start_time: int + scratch_device: int + scratch_inode: int + mountpoint_device: int + mountpoint_inode: int + + +@dataclass(frozen=True) +class _Mount: + filesystem: str + source: str + mount_options: tuple[str, ...] + super_options: tuple[str, ...] + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + raise ValueError("duplicate JSON key") + value[key] = item + return value + + +def _decode_json(data: bytes, *, maximum_bytes: int, code: str) -> Any: + if not data or len(data) > maximum_bytes: + raise SupervisorError(code) + try: + return json.loads(data.decode("utf-8"), object_pairs_hook=_unique_object) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise SupervisorError(code) from None + + +def _canonical_path(value: str | os.PathLike[str], code: str) -> Path: + try: + raw = os.fspath(value) + except TypeError: + raise SupervisorError(code) from None + if ( + not isinstance(raw, str) + or not raw + or "\x00" in raw + or any(character in raw for character in ",\r\n") + or not Path(raw).is_absolute() + or raw != str(Path(raw)) + or any(part in {".", ".."} for part in raw.split("/")) + ): + raise SupervisorError(code) + path = Path(raw) + current = Path(path.anchor) + try: + for part in path.parts[1:]: + current = current / part + info = current.lstat() + if stat.S_ISLNK(info.st_mode): + raise SupervisorError(code) + if path.resolve(strict=True) != path: + raise SupervisorError(code) + except SupervisorError: + raise + except (OSError, RuntimeError, ValueError): + raise SupervisorError(code) from None + return path + + +def _check_directory(path: Path, *, uid: int, mode: int | None, code: str) -> os.stat_result: + try: + info = path.lstat() + except OSError: + raise SupervisorError(code) from None + if not stat.S_ISDIR(info.st_mode) or info.st_uid != uid: + raise SupervisorError(code) + if mode is not None and stat.S_IMODE(info.st_mode) != mode: + raise SupervisorError(code) + return info + + +def _check_owned_regular_file(path: Path, *, uid: int, maximum_bytes: int, code: str) -> bytes: + flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + fd = os.open(path, flags) + except OSError: + raise SupervisorError(code) from None + try: + info = os.fstat(fd) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != uid + or stat.S_IMODE(info.st_mode) != 0o600 + or info.st_nlink != 1 + or info.st_size > maximum_bytes + ): + raise SupervisorError(code) + data = bytearray() + while len(data) <= maximum_bytes: + chunk = os.read(fd, min(4096, maximum_bytes + 1 - len(data))) + if not chunk: + break + data.extend(chunk) + if len(data) > maximum_bytes: + raise SupervisorError(code) + return bytes(data) + finally: + os.close(fd) + + +def _validate_context(environment: Mapping[str, str], *, uid: int) -> tuple[Path, Path, Path]: + runner_temp_value = environment.get("RUNNER_TEMP", "") + home_value = environment.get("HOME", "") + runtime_value = environment.get("XDG_RUNTIME_DIR") or f"/run/user/{uid}" + runner_temp = _canonical_path(runner_temp_value, "invalid-runner-temp") + home = _canonical_path(home_value, "invalid-home") + runtime = _canonical_path(runtime_value, "invalid-runtime-directory") + for path, mode in ((runner_temp, None), (home, None), (runtime, None)): + _check_directory(path, uid=uid, mode=mode, code="invalid-runner-context") + if stat.S_IMODE(runner_temp.stat().st_mode) & 0o022: + raise SupervisorError("invalid-runner-temp") + runtime_info = runtime.stat() + if stat.S_IMODE(runtime_info.st_mode) & 0o077: + raise SupervisorError("invalid-runtime-directory") + return runner_temp, home, runtime + + +def _validate_manifest_path(value: str | os.PathLike[str], runner_temp: Path, uid: int) -> tuple[Path, Path]: + manifest_path = _canonical_path(value, "invalid-manifest-path") + state_directory = manifest_path.parent + match = RUN_DIRECTORY_PATTERN.fullmatch(state_directory.name) + if ( + manifest_path.name != MANIFEST_NAME + or state_directory.parent != runner_temp + or match is None + ): + raise SupervisorError("invalid-manifest-path") + _check_directory(state_directory, uid=uid, mode=0o700, code="invalid-state-directory") + return state_directory, manifest_path + + +def _read_manifest( + value: str | os.PathLike[str], + *, + environment: Mapping[str, str], + uid: int, + gid: int, +) -> tuple[Manifest, Path, Path]: + runner_temp, home, runtime = _validate_context(environment, uid=uid) + state_directory, manifest_path = _validate_manifest_path(value, runner_temp, uid) + raw = _check_owned_regular_file( + manifest_path, + uid=uid, + maximum_bytes=MAX_MANIFEST_BYTES, + code="invalid-manifest", + ) + document = _decode_json(raw, maximum_bytes=MAX_MANIFEST_BYTES, code="invalid-manifest") + expected_keys = { + "containerName", "mountpoint", "mountpointDevice", "mountpointInode", "ownerToken", + "parentPid", "parentStartTime", "schemaVersion", "scratchDevice", "scratchDirectory", + "scratchInode", + } + if not isinstance(document, dict) or set(document) != expected_keys: + raise SupervisorError("invalid-manifest") + token = document.get("ownerToken") + name = document.get("containerName") + scratch_value = document.get("scratchDirectory") + mountpoint_value = document.get("mountpoint") + parent_pid = document.get("parentPid") + parent_start = document.get("parentStartTime") + scratch_device = document.get("scratchDevice") + scratch_inode = document.get("scratchInode") + mountpoint_device = document.get("mountpointDevice") + mountpoint_inode = document.get("mountpointInode") + if ( + type(document.get("schemaVersion")) is not int + or document["schemaVersion"] != 1 + or not isinstance(token, str) + or TOKEN_PATTERN.fullmatch(token) is None + or state_directory.name != f"appsurface-subject-supervisor-{token}" + or not isinstance(name, str) + or CONTAINER_PATTERN.fullmatch(name) is None + or type(parent_pid) is not int + or parent_pid <= 1 + or type(parent_start) is not int + or parent_start <= 0 + or any(type(value) is not int or value < 0 for value in ( + scratch_device, scratch_inode, mountpoint_device, mountpoint_inode + )) + ): + raise SupervisorError("invalid-manifest") + + scratch = _canonical_path(scratch_value, "invalid-scratch-path") + mountpoint = _canonical_path(mountpoint_value, "invalid-mountpoint") + if ( + scratch.parent != runner_temp + or mountpoint.parent != scratch + or MOUNTPOINT_PATTERN.fullmatch(mountpoint.name) is None + or scratch == state_directory + or scratch in state_directory.parents + or state_directory in scratch.parents + ): + raise SupervisorError("invalid-scratch-path") + scratch_info = _check_directory(scratch, uid=uid, mode=0o700, code="invalid-scratch-directory") + _check_directory(mountpoint, uid=uid, mode=0o700, code="invalid-mountpoint") + if (scratch_info.st_dev, scratch_info.st_ino) != (scratch_device, scratch_inode): + raise SupervisorError("invalid-scratch-directory") + if ( + not stat.S_ISDIR(mountpoint.stat().st_mode) + or mountpoint.stat().st_uid != uid + or mountpoint.stat().st_gid != gid + or stat.S_IMODE(mountpoint.stat().st_mode) != 0o700 + ): + raise SupervisorError("invalid-mountpoint") + # Validate the current process identity context now; command execution uses + # this narrow allowlist rather than inheriting runner credentials. + del home, runtime + manifest = Manifest( + token, name, scratch, mountpoint, parent_pid, parent_start, + scratch_device, scratch_inode, mountpoint_device, mountpoint_inode, + ) + return manifest, state_directory, runner_temp + + +def _write_new_file(directory: Path, name: str, content: bytes, *, mode: int = 0o600) -> None: + if len(content) > MAX_MANIFEST_BYTES: + raise SupervisorError("record-too-large") + directory_fd = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + fd = os.open(name, flags, mode, dir_fd=directory_fd) + try: + view = memoryview(content) + while view: + written = os.write(fd, view) + view = view[written:] + os.fsync(fd) + finally: + os.close(fd) + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + +def _atomic_attestation(directory: Path, document: Mapping[str, Any]) -> None: + payload = (json.dumps(document, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + if len(payload) > MAX_ATTESTATION_BYTES: + raise SupervisorError("attestation-too-large") + directory_fd = os.open(directory, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)) + temporary_name = ".cleanup-attestation.tmp" + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + created_temporary = False + try: + fd = os.open(temporary_name, flags, 0o600, dir_fd=directory_fd) + created_temporary = True + try: + view = memoryview(payload) + while view: + written = os.write(fd, view) + view = view[written:] + os.fsync(fd) + finally: + os.close(fd) + os.link( + temporary_name, + ATTESTATION_NAME, + src_dir_fd=directory_fd, + dst_dir_fd=directory_fd, + follow_symlinks=False, + ) + os.unlink(temporary_name, dir_fd=directory_fd) + created_temporary = False + os.fsync(directory_fd) + finally: + if created_temporary: + try: + os.unlink(temporary_name, dir_fd=directory_fd) + except OSError: + pass + os.close(directory_fd) + + +def read_process_identity(pid: int, *, proc_root: Path = PROC_ROOT) -> tuple[int, str] | None: + """Return Linux ``starttime`` ticks and process state for a PID, if readable.""" + try: + raw = (proc_root / str(pid) / "stat").read_text(encoding="ascii") + closing_paren = raw.rfind(")") + if closing_paren < 0: + return None + fields = raw[closing_paren + 1 :].split() + # The substring starts at stat field 3 (state); starttime is field 22. + if len(fields) <= 19 or len(fields[0]) != 1: + return None + return int(fields[19]), fields[0] + except (OSError, UnicodeError, ValueError): + return None + + +def _parent_state( + manifest: Manifest, + *, + proc_root: Path, + identity_reader: Callable[[int], tuple[int, str] | None] = read_process_identity, +) -> bool | None: + """True means the exact launcher lives; False means it exited or PID changed.""" + pid_path = proc_root / str(manifest.parent_pid) + try: + info = pid_path.stat() + except FileNotFoundError: + return False + except OSError: + return None + if info.st_uid != os.geteuid(): + return False + identity = identity_reader(manifest.parent_pid) + if identity is None: + return None + start_time, state = identity + if start_time != manifest.parent_start_time or state in {"Z", "X"}: + return False + return True + + +def _read_request(state_directory: Path, token: str, *, uid: int) -> bool | None: + request_path = state_directory / REQUEST_NAME + try: + raw = _check_owned_regular_file( + request_path, + uid=uid, + maximum_bytes=MAX_REQUEST_BYTES, + code="invalid-request", + ) + except SupervisorError as exc: + if exc.code == "invalid-request": + try: + request_path.lstat() + except FileNotFoundError: + return False + except OSError: + return None + return None + try: + document = _decode_json(raw, maximum_bytes=MAX_REQUEST_BYTES, code="invalid-request") + except SupervisorError: + return None + if document != {"ownerToken": token, "schemaVersion": 1}: + return None + return True + + +def _request_cleanup(manifest_path: str | os.PathLike[str], token: str, *, environment: Mapping[str, str]) -> None: + uid = os.geteuid() + manifest, state_directory, _ = _read_manifest( + manifest_path, environment=environment, uid=uid, gid=os.getegid() + ) + if not isinstance(token, str) or token != manifest.token: + raise SupervisorError("owner-token-mismatch") + content = (json.dumps({"ownerToken": token, "schemaVersion": 1}, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + try: + _write_new_file(state_directory, REQUEST_NAME, content, mode=0o600) + except FileExistsError: + if _read_request(state_directory, token, uid=uid) is not True: + raise SupervisorError("invalid-request") from None + + +def _parse_mountinfo(text: str, mountpoint: Path) -> _Mount | None: + matches: list[_Mount] = [] + for line in text.splitlines(): + left, separator, right = line.partition(" - ") + left_fields = left.split() + right_fields = right.split() + if not separator or len(left_fields) < 6 or len(right_fields) < 3: + raise ValueError("malformed mountinfo") + decoded_path = re.sub(r"\\([0-7]{3})", lambda match: chr(int(match.group(1), 8)), left_fields[4]) + if decoded_path != str(mountpoint): + continue + matches.append( + _Mount( + right_fields[0], + right_fields[1], + tuple(left_fields[5].split(",")), + tuple(right_fields[2].split(",")), + ) + ) + if len(matches) > 1: + raise ValueError("ambiguous mountpoint") + return matches[0] if matches else None + + +def _size_bytes(value: str) -> int | None: + match = re.fullmatch(r"([0-9]+)([kKmMgGtT]?)", value) + if match is None: + return None + scale = {"": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4} + return int(match.group(1)) * scale[match.group(2).lower()] + + +def _matching_owned_mount( + mount: _Mount, + mountpoint: Path, + *, + uid: int, + gid: int, + statvfs: Callable[[str | os.PathLike[str]], Any], +) -> bool: + options: dict[str, str] = {} + for item in mount.super_options: + key, separator, value = item.partition("=") + if separator: + if key in options: + return False + options[key] = value + try: + info = mountpoint.stat() + filesystem = statvfs(mountpoint) + mode = int(options.get("mode", "-1"), 8) + actual_bytes = filesystem.f_blocks * filesystem.f_frsize + return ( + mount.filesystem == "tmpfs" + and mount.source == "tmpfs" + and {"rw", "nosuid", "nodev"}.issubset(set(mount.mount_options + mount.super_options)) + and {"ro", "suid", "dev", "noswap"}.isdisjoint(set(mount.mount_options + mount.super_options)) + and _size_bytes(options.get("size", "")) == TMPFS_BYTES + and options.get("nr_inodes") == str(TMPFS_INODES) + and mode == 0o700 + and int(options.get("uid", "-1")) == uid + and int(options.get("gid", "-1")) == gid + and stat.S_ISDIR(info.st_mode) + and stat.S_IMODE(info.st_mode) == 0o700 + and info.st_uid == uid + and info.st_gid == gid + and actual_bytes == TMPFS_BYTES + and filesystem.f_files == TMPFS_INODES + ) + except (OSError, ValueError, OverflowError, AttributeError): + return False + + +def _remove_owned_scratch(manifest: Manifest, *, runner_temp: Path, uid: int, gid: int) -> str: + """Remove only the fixed result record and exact, identity-checked scratch directories.""" + runner_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + scratch_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + runner_fd = os.open(runner_temp, runner_flags) + except OSError: + return "unsafe" + try: + try: + scratch_fd = os.open(manifest.scratch_directory.name, scratch_flags, dir_fd=runner_fd) + except OSError: + return "unsafe" + try: + scratch_info = os.fstat(scratch_fd) + if ( + not stat.S_ISDIR(scratch_info.st_mode) + or scratch_info.st_uid != uid + or stat.S_IMODE(scratch_info.st_mode) != 0o700 + or (scratch_info.st_dev, scratch_info.st_ino) + != (manifest.scratch_device, manifest.scratch_inode) + ): + return "unsafe" + try: + mount_info = os.stat( + manifest.mountpoint.name, + dir_fd=scratch_fd, + follow_symlinks=False, + ) + except FileNotFoundError: + mount_info = None + except OSError: + return "unsafe" + if mount_info is not None: + if ( + not stat.S_ISDIR(mount_info.st_mode) + or mount_info.st_uid != uid + or mount_info.st_gid != gid + or stat.S_IMODE(mount_info.st_mode) != 0o700 + or (mount_info.st_dev, mount_info.st_ino) + != (manifest.mountpoint_device, manifest.mountpoint_inode) + ): + return "unsafe" + try: + os.rmdir(manifest.mountpoint.name, dir_fd=scratch_fd) + except OSError: + return "failed" + + try: + with os.scandir(scratch_fd) as directory_entries: + entries: list[str] = [] + for entry in directory_entries: + entries.append(entry.name) + if len(entries) == 2: + break + except OSError: + return "failed" + if len(entries) > 1 or any(name != SUBJECT_RESULT_NAME for name in entries): + return "preserved" + if entries: + result_fd = -1 + try: + result_fd = os.open( + SUBJECT_RESULT_NAME, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + dir_fd=scratch_fd, + ) + result_info = os.fstat(result_fd) + if ( + not stat.S_ISREG(result_info.st_mode) + or result_info.st_uid != uid + or stat.S_IMODE(result_info.st_mode) != 0o600 + or result_info.st_nlink != 1 + or result_info.st_size > MAX_SUBJECT_RESULT_BYTES + ): + return "unsafe" + except OSError: + return "unsafe" + finally: + if result_fd >= 0: + os.close(result_fd) + try: + current_result = os.stat( + SUBJECT_RESULT_NAME, + dir_fd=scratch_fd, + follow_symlinks=False, + ) + if (current_result.st_dev, current_result.st_ino) != ( + result_info.st_dev, result_info.st_ino + ): + return "unsafe" + except OSError: + return "unsafe" + try: + os.unlink(SUBJECT_RESULT_NAME, dir_fd=scratch_fd) + except OSError: + return "failed" + + try: + current = os.stat( + manifest.scratch_directory.name, + dir_fd=runner_fd, + follow_symlinks=False, + ) + if (current.st_dev, current.st_ino) != (manifest.scratch_device, manifest.scratch_inode): + return "unsafe" + os.rmdir(manifest.scratch_directory.name, dir_fd=runner_fd) + except OSError: + return "failed" + return "removed" + finally: + os.close(scratch_fd) + finally: + os.close(runner_fd) + + +def _container_names(item: Any) -> set[str] | None: + if not isinstance(item, dict): + return None + names = item.get("Names", item.get("Name")) + if isinstance(names, str): + values = [names] + elif isinstance(names, list) and all(isinstance(name, str) for name in names): + values = names + else: + return None + normalized = {value[1:] if value.startswith("/") else value for value in values} + return normalized + + +def _list_target_container( + manifest: Manifest, + *, + executor: Callable[..., CommandResult], + environment: Mapping[str, str], + timeout_seconds: float, +) -> tuple[str, Any | None]: + result = executor( + [ + PODMAN_PATH, + "--remote=false", + "ps", + "--all", + "--no-trunc", + "--format=json", + ], + timeout_seconds=timeout_seconds, + maximum_output_bytes=MAX_COMMAND_OUTPUT_BYTES, + environment=environment, + ) + if result.returncode != 0: + return "unverified", None + value = _decode_json(result.stdout, maximum_bytes=MAX_COMMAND_OUTPUT_BYTES, code="invalid-container-list") + if not isinstance(value, list) or len(value) > 4096: + return "unverified", None + exact: list[Any] = [] + for item in value: + names = _container_names(item) + if names is None: + return "unverified", None + if manifest.container_name in names: + exact.append(item) + if not exact: + return "absent", None + if len(exact) != 1: + return "unverified", None + return "present", exact[0] + + +def _confirm_container_absent( + manifest: Manifest, + *, + executor: Callable[..., CommandResult], + environment: Mapping[str, str], + timeout_seconds: Callable[[], float], + sleep: Callable[[float], None], + observations: int = 5, +) -> bool: + """Require several separated full inventory reads before treating absence as stable.""" + for index in range(observations): + status, _ = _list_target_container( + manifest, + executor=executor, + environment=environment, + timeout_seconds=timeout_seconds(), + ) + if status != "absent": + return False + if index + 1 < observations: + sleep(0.25) + return True + + +def _inspect_owned_container( + manifest: Manifest, + *, + executor: Callable[..., CommandResult], + environment: Mapping[str, str], + timeout_seconds: float, +) -> tuple[str, str | None]: + listing_status, _ = _list_target_container( + manifest, executor=executor, environment=environment, timeout_seconds=timeout_seconds + ) + if listing_status != "present": + return listing_status, None + inspected = executor( + [PODMAN_PATH, "--remote=false", "inspect", "--format=json", manifest.container_name], + timeout_seconds=timeout_seconds, + maximum_output_bytes=MAX_COMMAND_OUTPUT_BYTES, + environment=environment, + ) + if inspected.returncode != 0: + return "unverified", None + document = _decode_json(inspected.stdout, maximum_bytes=MAX_COMMAND_OUTPUT_BYTES, code="invalid-container-inspect") + if not isinstance(document, list) or len(document) != 1 or not isinstance(document[0], dict): + return "unverified", None + item = document[0] + name = item.get("Name") + if isinstance(name, str) and name.startswith("/"): + name = name[1:] + config = item.get("Config") + labels = config.get("Labels") if isinstance(config, dict) else None + mounts = item.get("Mounts") + if ( + name != manifest.container_name + or not isinstance(labels, dict) + or labels.get(OWNER_LABEL) != manifest.token + or not isinstance(mounts, list) + ): + return "unverified", None + expected_mounts = [ + mount + for mount in mounts + if isinstance(mount, dict) + and mount.get("Destination") == "/scratch" + and mount.get("Type") == "bind" + and mount.get("Source") == str(manifest.mountpoint) + ] + if len(expected_mounts) != 1: + return "unverified", None + container_id = item.get("Id", item.get("ID")) + if not isinstance(container_id, str) or re.fullmatch(r"[0-9a-f]{12,64}", container_id) is None: + return "unverified", None + return "owned", container_id + + +def _safe_command_environment(home: Path, runtime: Path, runner_temp: Path) -> dict[str, str]: + return { + "PATH": ENGINE_PATH, + "HOME": str(home), + "XDG_RUNTIME_DIR": str(runtime), + "TMPDIR": str(runner_temp), + "REGISTRY_AUTH_FILE": "/dev/null", + } + + +def _run_command( + arguments: Sequence[str], + *, + timeout_seconds: float, + maximum_output_bytes: int, + environment: Mapping[str, str], +) -> CommandResult: + if ( + not arguments + or any(not isinstance(value, str) or not value or "\x00" in value for value in arguments) + or timeout_seconds <= 0 + or maximum_output_bytes <= 0 + ): + raise CommandError("invalid-command") + try: + process = subprocess.Popen( + list(arguments), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + start_new_session=True, + bufsize=0, + cwd="/", + env=dict(environment), + ) + except (OSError, ValueError): + raise CommandError("command-start-failed") from None + + selector = selectors.DefaultSelector() + stdout = bytearray() + stderr = bytearray() + deadline = time.monotonic() + timeout_seconds + try: + if process.stdout is None or process.stderr is None: + raise CommandError("command-start-failed") + for pipe, label in ((process.stdout, "stdout"), (process.stderr, "stderr")): + os.set_blocking(pipe.fileno(), False) + selector.register(pipe, selectors.EVENT_READ, label) + while selector.get_map() or process.poll() is None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise CommandError("command-timeout") + for key, _ in selector.select(min(0.1, remaining)): + target = stdout if key.data == "stdout" else stderr + available = maximum_output_bytes - len(stdout) - len(stderr) + try: + chunk = os.read(key.fileobj.fileno(), min(64 * 1024, available + 1)) + except BlockingIOError: + continue + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + target.extend(chunk) + if len(stdout) + len(stderr) > maximum_output_bytes: + raise CommandError("command-output-exceeded") + return CommandResult(process.wait(), bytes(stdout), bytes(stderr)) + except CommandError: + _terminate_process_group(process) + raise + except (OSError, ValueError, selectors.SelectorError): + _terminate_process_group(process) + raise CommandError("command-io-failed") from None + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if pipe is not None and not pipe.closed: + pipe.close() + + +def _terminate_process_group(process: subprocess.Popen[bytes]) -> None: + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + pass + except OSError: + try: + process.terminate() + except OSError: + pass + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + # The CLI leader may exit while a descendant retains a captured pipe; + # terminate the private session even if that leader has already exited. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + except OSError: + try: + process.kill() + except OSError: + pass + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + + +def _cleanup( + manifest: Manifest, + *, + home: Path, + runtime: Path, + runner_temp: Path, + uid: int, + gid: int, + executor: Callable[..., CommandResult], + mountinfo_reader: Callable[[], str], + statvfs: Callable[[str | os.PathLike[str]], Any], + monotonic: Callable[[], float], + sleep: Callable[[float], None], + cleanup_deadline: float, +) -> dict[str, str]: + statuses = { + "containerStatus": "unverified", + "mountStatus": "unverified", + "scratchStatus": "preserved", + } + command_environment = _safe_command_environment(home, runtime, runner_temp) + + def command_timeout() -> float: + remaining = cleanup_deadline - monotonic() + if remaining <= 0: + raise CommandError("cleanup-deadline-expired") + return min(MAX_COMMAND_SECONDS, remaining) + + # Revalidate the path tree immediately before acting. Cleanup uses only + # fixed-name unlink/rmdir operations anchored to directory descriptors. + try: + current_scratch = _canonical_path(manifest.scratch_directory, "invalid-scratch-path") + current_mountpoint = _canonical_path(manifest.mountpoint, "invalid-mountpoint") + if current_scratch != manifest.scratch_directory or current_mountpoint != manifest.mountpoint: + raise SupervisorError("invalid-scratch-path") + scratch_info = _check_directory(current_scratch, uid=uid, mode=0o700, code="invalid-scratch-directory") + if (scratch_info.st_dev, scratch_info.st_ino) != (manifest.scratch_device, manifest.scratch_inode): + raise SupervisorError("invalid-scratch-directory") + _check_directory(current_mountpoint, uid=uid, mode=0o700, code="invalid-mountpoint") + except SupervisorError: + return statuses + + try: + container_status, container_id = _inspect_owned_container( + manifest, + executor=executor, + environment=command_environment, + timeout_seconds=command_timeout(), + ) + except (CommandError, SupervisorError): + container_status, container_id = "unverified", None + + if container_status == "absent": + try: + stable_absence = _confirm_container_absent( + manifest, + executor=executor, + environment=command_environment, + timeout_seconds=command_timeout, + sleep=sleep, + ) + except (CommandError, SupervisorError): + stable_absence = False + statuses["containerStatus"] = "absent" if stable_absence else "unverified" + elif container_status == "owned" and container_id is not None: + try: + removed = executor( + [PODMAN_PATH, "--remote=false", "rm", "--force", "--ignore", container_id], + timeout_seconds=command_timeout(), + maximum_output_bytes=4096, + environment=command_environment, + ) + if removed.returncode == 0: + post_status, _ = _list_target_container( + manifest, + executor=executor, + environment=command_environment, + timeout_seconds=command_timeout(), + ) + stable_absence = ( + _confirm_container_absent( + manifest, + executor=executor, + environment=command_environment, + timeout_seconds=command_timeout, + sleep=sleep, + ) + if post_status == "absent" + else False + ) + statuses["containerStatus"] = "removed" if stable_absence else "failed" + else: + statuses["containerStatus"] = "failed" + except (CommandError, SupervisorError): + statuses["containerStatus"] = "failed" + else: + statuses["containerStatus"] = container_status + + if statuses["containerStatus"] not in {"absent", "removed"}: + return statuses + + try: + mount = _parse_mountinfo(mountinfo_reader(), manifest.mountpoint) + except (OSError, UnicodeError, ValueError, OverflowError): + return statuses + + if mount is None: + statuses["mountStatus"] = "absent" + statuses["scratchStatus"] = _remove_owned_scratch( + manifest, runner_temp=runner_temp, uid=uid, gid=gid + ) + return statuses + + if not _matching_owned_mount(mount, manifest.mountpoint, uid=uid, gid=gid, statvfs=statvfs): + return statuses + try: + unmounted = executor( + [SUDO_PATH, "-n", "umount", "--", str(manifest.mountpoint)], + timeout_seconds=command_timeout(), + maximum_output_bytes=4096, + environment=command_environment, + ) + if unmounted.returncode != 0: + statuses["mountStatus"] = "failed" + return statuses + if _parse_mountinfo(mountinfo_reader(), manifest.mountpoint) is not None: + statuses["mountStatus"] = "failed" + return statuses + statuses["mountStatus"] = "unmounted" + statuses["scratchStatus"] = _remove_owned_scratch( + manifest, runner_temp=runner_temp, uid=uid, gid=gid + ) + except CommandError as exc: + statuses["mountStatus"] = "failed" if exc.code != "cleanup-deadline-expired" else "deadline-expired" + except (OSError, UnicodeError, ValueError, OverflowError): + statuses["mountStatus"] = "failed" + return statuses + + +def _attestation( + *, + trigger: str, + statuses: Mapping[str, str], + failure_code: str, +) -> dict[str, Any]: + complete = ( + statuses.get("containerStatus") in {"removed", "absent"} + and statuses.get("mountStatus") in {"unmounted", "absent"} + and statuses.get("scratchStatus") in {"removed", "absent"} + and failure_code == "none" + ) + return { + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "complete" if complete else "incomplete", + "trigger": trigger, + "containerStatus": statuses.get("containerStatus", "not-attempted"), + "mountStatus": statuses.get("mountStatus", "not-attempted"), + "scratchStatus": statuses.get("scratchStatus", "not-attempted"), + "failureCode": failure_code, + "cleanupDeadlineSeconds": CLEANUP_DEADLINE_SECONDS, + } + + +def run_supervisor( + manifest_path: str | os.PathLike[str], + *, + environment: Mapping[str, str] | None = None, + effective_uid: int | None = None, + effective_gid: int | None = None, + proc_root: Path = PROC_ROOT, + proc_identity_reader: Callable[[int], tuple[int, str] | None] | None = None, + mountinfo_reader: Callable[[], str] | None = None, + executor: Callable[..., CommandResult] = _run_command, + statvfs: Callable[[str | os.PathLike[str]], Any] = os.statvfs, + monotonic: Callable[[], float] = time.monotonic, + sleep: Callable[[float], None] = time.sleep, + max_parent_lifetime_seconds: float = MAX_PARENT_LIFETIME_SECONDS, + cleanup_deadline_seconds: float = CLEANUP_DEADLINE_SECONDS, + ready_fd: int | None = None, +) -> int: + env = dict(os.environ if environment is None else environment) + uid = os.geteuid() if effective_uid is None else effective_uid + gid = os.getegid() if effective_gid is None else effective_gid + manifest, state_directory, runner_temp = _read_manifest( + manifest_path, environment=env, uid=uid, gid=gid + ) + _, home, runtime = _validate_context(env, uid=uid) + if ready_fd is not None: + try: + os.write(ready_fd, b"READY\n") + finally: + os.close(ready_fd) + read_mountinfo = mountinfo_reader or (lambda: MOUNTINFO_PATH.read_text(encoding="utf-8")) + started_at = monotonic() + trigger: str | None = None + failure_code = "none" + invalid_request_seen = False + while trigger is None: + requested = _read_request(state_directory, manifest.token, uid=uid) + if requested is None: + invalid_request_seen = True + if requested: + trigger = "request" + break + parent_state = _parent_state( + manifest, + proc_root=proc_root, + identity_reader=proc_identity_reader + or (lambda pid: read_process_identity(pid, proc_root=proc_root)), + ) + if parent_state is False: + trigger = "parent-exit" + if invalid_request_seen: + failure_code = "invalid-request" + break + if parent_state is None: + # Never unmount resources while the parent might still be alive. + if monotonic() - started_at >= max_parent_lifetime_seconds: + trigger = "parent-unverifiable" + failure_code = "parent-unverifiable" + break + elif monotonic() - started_at >= max_parent_lifetime_seconds: + trigger = "supervisor-lease-expired" + failure_code = "supervisor-lease-expired" + break + sleep(min(PARENT_POLL_SECONDS, max(0.0, started_at + max_parent_lifetime_seconds - monotonic()))) + + statuses = { + "containerStatus": "not-attempted", + "mountStatus": "not-attempted", + "scratchStatus": "not-attempted", + } + if trigger in {"request", "parent-exit"}: + cleanup_started = monotonic() + try: + statuses = _cleanup( + manifest, + home=home, + runtime=runtime, + runner_temp=runner_temp, + uid=uid, + gid=gid, + executor=executor, + mountinfo_reader=read_mountinfo, + statvfs=statvfs, + monotonic=monotonic, + sleep=sleep, + cleanup_deadline=cleanup_started + cleanup_deadline_seconds, + ) + except Exception: + statuses = { + "containerStatus": "unverified", + "mountStatus": "unverified", + "scratchStatus": "preserved", + } + failure_code = "cleanup-internal-error" + if any(value in {"failed", "unverified", "unsafe", "deadline-expired", "preserved"} for value in statuses.values()): + failure_code = "resource-cleanup-incomplete" + record = _attestation(trigger=trigger or "unknown", statuses=statuses, failure_code=failure_code) + try: + _atomic_attestation(state_directory, record) + except (OSError, SupervisorError): + return 2 + return 0 if record["status"] == "complete" else 1 + + +def _prepare_and_start( + *, + container_name: str, + scratch_directory_value: str, + mountpoint_value: str, + parent_pid: int, + parent_start_time: int, + environment: Mapping[str, str], +) -> dict[str, Any]: + uid = os.geteuid() + gid = os.getegid() + runner_temp, home, runtime = _validate_context(environment, uid=uid) + if not isinstance(container_name, str) or CONTAINER_PATTERN.fullmatch(container_name) is None: + raise SupervisorError("invalid-container-name") + scratch = _canonical_path(scratch_directory_value, "invalid-scratch-path") + mountpoint = _canonical_path(mountpoint_value, "invalid-mountpoint") + if ( + scratch.parent != runner_temp + or mountpoint.parent != scratch + or MOUNTPOINT_PATTERN.fullmatch(mountpoint.name) is None + ): + raise SupervisorError("invalid-scratch-path") + scratch_info = _check_directory(scratch, uid=uid, mode=0o700, code="invalid-scratch-directory") + mount_info = _check_directory(mountpoint, uid=uid, mode=0o700, code="invalid-mountpoint") + if mount_info.st_gid != gid: + raise SupervisorError("invalid-mountpoint") + + if type(parent_pid) is not int or parent_pid <= 1 or type(parent_start_time) is not int or parent_start_time <= 0: + raise SupervisorError("invalid-parent-identity") + parent_identity = read_process_identity(parent_pid) + try: + parent_uid = (PROC_ROOT / str(parent_pid)).stat().st_uid + except OSError: + raise SupervisorError("parent-identity-unavailable") from None + if ( + parent_identity is None + or parent_uid != uid + or parent_identity[0] != parent_start_time + or parent_identity[1] in {"Z", "X"} + ): + raise SupervisorError("parent-identity-unavailable") + + token = os.urandom(16).hex() + state_directory = runner_temp / f"appsurface-subject-supervisor-{token}" + try: + os.mkdir(state_directory, 0o700) + except OSError: + raise SupervisorError("state-directory-create-failed") from None + state_info = state_directory.lstat() + if state_info.st_uid != uid or stat.S_IMODE(state_info.st_mode) != 0o700: + try: + state_directory.rmdir() + except OSError: + pass + raise SupervisorError("state-directory-create-failed") + document = { + "schemaVersion": 1, + "ownerToken": token, + "containerName": container_name, + "scratchDirectory": str(scratch), + "mountpoint": str(mountpoint), + "parentPid": parent_pid, + "parentStartTime": parent_start_time, + "scratchDevice": scratch_info.st_dev, + "scratchInode": scratch_info.st_ino, + "mountpointDevice": mount_info.st_dev, + "mountpointInode": mount_info.st_ino, + } + manifest_path = state_directory / MANIFEST_NAME + payload = (json.dumps(document, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + try: + _write_new_file(state_directory, MANIFEST_NAME, payload) + child_environment = { + "PATH": ENGINE_PATH, + "HOME": str(home), + "XDG_RUNTIME_DIR": str(runtime), + "RUNNER_TEMP": str(runner_temp), + } + ready_read_fd, ready_write_fd = os.pipe() + try: + child = subprocess.Popen( + [ + sys.executable, + str(Path(__file__).resolve()), + "supervise", + "--manifest", + str(manifest_path), + "--ready-fd", + str(ready_write_fd), + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + shell=False, + close_fds=True, + pass_fds=(ready_write_fd,), + start_new_session=True, + cwd="/", + env=child_environment, + ) + finally: + os.close(ready_write_fd) + + try: + selector = selectors.DefaultSelector() + try: + selector.register(ready_read_fd, selectors.EVENT_READ) + events = selector.select(SUPERVISOR_STARTUP_SECONDS) + ready = os.read(ready_read_fd, 16) if events else b"" + finally: + selector.close() + os.close(ready_read_fd) + child_identity = read_process_identity(child.pid) + if ( + ready != b"READY\n" + or child.poll() is not None + or child_identity is None + or child_identity[1] in {"Z", "X"} + ): + raise SupervisorError("supervisor-not-ready") + except BaseException: + try: + os.killpg(child.pid, signal.SIGTERM) + except OSError: + pass + try: + child.wait(timeout=1) + except subprocess.TimeoutExpired: + try: + os.killpg(child.pid, signal.SIGKILL) + except OSError: + pass + try: + child.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + raise + except (OSError, ValueError): + raise SupervisorError("supervisor-start-failed") from None + return { + "schemaVersion": 1, + "claimEligible": False, + "ownerToken": token, + "stateDirectory": str(state_directory), + "manifestPath": str(manifest_path), + "supervisorPid": child.pid, + "supervisorStartTime": child_identity[0], + "supervisorReady": True, + "ownerLabel": OWNER_LABEL, + } + + +def _main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Bounded non-claiming OCI subject cleanup supervisor") + subparsers = parser.add_subparsers(dest="operation", required=True) + start_parser = subparsers.add_parser("start", help="start an independent cleanup supervisor") + start_parser.add_argument("--container-name", required=True) + start_parser.add_argument("--scratch-directory", required=True) + start_parser.add_argument("--mountpoint", required=True) + start_parser.add_argument("--parent-pid", required=True, type=int) + start_parser.add_argument("--parent-start-time", required=True, type=int) + request_parser = subparsers.add_parser("request", help="request cleanup after normal completion") + request_parser.add_argument("--manifest", required=True) + request_parser.add_argument("--owner-token", required=True) + supervise_parser = subparsers.add_parser("supervise", help=argparse.SUPPRESS) + supervise_parser.add_argument("--manifest", required=True) + supervise_parser.add_argument("--ready-fd", required=True, type=int) + arguments = parser.parse_args(argv) + environment = dict(os.environ) + try: + if arguments.operation == "start": + response = _prepare_and_start( + container_name=arguments.container_name, + scratch_directory_value=arguments.scratch_directory, + mountpoint_value=arguments.mountpoint, + parent_pid=arguments.parent_pid, + parent_start_time=arguments.parent_start_time, + environment=environment, + ) + print(json.dumps(response, sort_keys=True, separators=(",", ":"))) + return 0 + if arguments.operation == "request": + if TOKEN_PATTERN.fullmatch(arguments.owner_token) is None: + raise SupervisorError("invalid-owner-token") + _request_cleanup(arguments.manifest, arguments.owner_token, environment=environment) + return 0 + if arguments.operation == "supervise": + return run_supervisor(arguments.manifest, environment=environment, ready_fd=arguments.ready_fd) + except SupervisorError as exc: + print(f"subject supervisor failed: {exc.code}", file=sys.stderr) + return 2 + except (OSError, ValueError, CommandError): + print("subject supervisor failed: operation-error", file=sys.stderr) + return 2 + return 2 + + +if __name__ == "__main__": + raise SystemExit(_main()) diff --git a/scripts/evidence-gate-subject.py b/scripts/evidence-gate-subject.py new file mode 100644 index 000000000..3d823501b --- /dev/null +++ b/scripts/evidence-gate-subject.py @@ -0,0 +1,2177 @@ +#!/usr/bin/env python3 +"""Launch one bounded, credentialless AppSurface subject profile with rootless Podman. + +This is an execution primitive, not an evidence verifier or a gate. It accepts +only controller-owned paths, a digest-pinned image, a policy profile ID, and +validated resource limits. The writable container scratch is a fixed-size, +fixed-inode host tmpfs bind mount; the trusted entrypoint streams its small +fixed result record over the attached process output, where this launcher +validates it and writes it outside the mount to private host scratch. Only the +three indexed coverage artifacts may be copied out; all other container +scratch artifacts are discarded. The image must contain the trusted fixed entrypoint +``/usr/local/libexec/appsurface-subject-runner`` and its locked offline inputs. +The entrypoint receives a fixed profile contract; this program never reads a +command from the subject checkout. Only ``code-coverage`` is enabled, with +network disabled. Resource-backed profiles remain rejected until their +network/resource envelope has a separately reviewed implementation. + +The launcher consumes the bounded result record in memory, then requires an +independent supervisor's completed cleanup attestation before returning. The +supervisor removes the container, private host tmpfs, and per-run scratch. All +output remains untrusted; even exit code zero does not create complete Evidence +or authorize a CI verdict. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import secrets +import selectors +import shutil +import signal +import stat +import subprocess +import sys +import threading +import time +from typing import Any, Callable, Mapping, Protocol, Sequence + + +ENGINE_PATH = "/usr/bin:/usr/local/bin:/bin" +SUDO_PATH = "/usr/bin/sudo" +MOUNTINFO_PATH = Path("/proc/self/mountinfo") +PROC_ROOT = Path("/proc") +CONTAINER_ENTRYPOINT = "/usr/local/libexec/appsurface-subject-runner" +SUPERVISOR_SCRIPT_NAME = "evidence-gate-subject-supervisor.py" +SUPERVISOR_OWNER_LABEL = "io.forge-trust.appsurface.cleanup-token" +SUPERVISOR_CLEANUP_DEADLINE_SECONDS = 10 * 60 +SUPERVISOR_STARTUP_TIMEOUT_SECONDS = 30 +MAX_SUPERVISOR_RECORD_BYTES = 4096 +SUPERVISOR_TOKEN_PATTERN = re.compile(r"[0-9a-f]{32}\Z") +CONTAINER_UID = 65532 +CONTAINER_GID = 65532 +PODMAN_DEFAULT_CAPABILITIES = frozenset( + { + "CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FOWNER", "CAP_FSETID", "CAP_KILL", + "CAP_NET_BIND_SERVICE", "CAP_SETFCAP", "CAP_SETGID", "CAP_SETPCAP", + "CAP_SETUID", "CAP_SYS_CHROOT", + } +) +ENGINE_PHASE_TIMEOUT_SECONDS = 10 +MOUNT_PHASE_TIMEOUT_SECONDS = 30 +CLEANUP_TIMEOUT_SECONDS = 5 +MAX_ENGINE_OUTPUT_BYTES = 256 * 1024 +MAX_PROFILE_TIMEOUT_SECONDS = 1200 +MAX_PROFILE_MEMORY_MIB = 4096 +MAX_PROFILE_CPU_MILLIS = 2000 +MAX_PROFILE_PIDS = 256 +MAX_PROFILE_OUTPUT_BYTES = 1024 * 1024 +MAX_PROFILE_SCRATCH_BYTES = 4 * 1024 * 1024 * 1024 +MAX_PROFILE_SCRATCH_INODES = 262_144 +MAX_SUBJECT_RESULT_BYTES = 16 * 1024 +MAX_SOURCE_DIFF_BYTES = 20 * 1024 * 1024 +MAX_COBERTURA_ARTIFACT_BYTES = 20 * 1024 * 1024 +MAX_GATE_MARKDOWN_ARTIFACT_BYTES = 1 * 1024 * 1024 +MAX_GATE_JSON_ARTIFACT_BYTES = 4 * 1024 * 1024 +MAX_EXPORTED_ARTIFACT_BYTES = 25 * 1024 * 1024 +ARTIFACT_EXPORT_TIMEOUT_SECONDS = 2 * 60 +ARTIFACT_EXPORT_READ_BYTES = 64 * 1024 +MIN_OUTPUT_BYTES = 4096 +SOURCE_DIFF_CONTAINER_PATH = "/source.diff" +SOURCE_DIFF_SHA256_PATTERN = re.compile(r"[0-9a-f]{64}\Z") +SUBJECT_ARTIFACTS = ( + ("cobertura", "coverage/coverage-merged/coverage.cobertura.xml", MAX_COBERTURA_ARTIFACT_BYTES), + ("gate-report", "coverage/coverage-gate/coverage-gate.md", MAX_GATE_MARKDOWN_ARTIFACT_BYTES), + ("diagnostics", "coverage/coverage-gate/coverage-gate.json", MAX_GATE_JSON_ARTIFACT_BYTES), +) +SUBJECT_ARTIFACT_EXPORT_NAMES = ("cobertura.xml", "gate-report.md", "diagnostics.json") +IMAGE_REFERENCE_PATTERN = re.compile(r"[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}\Z") +RUN_ID_PATTERN = re.compile(r"[1-9][0-9]{0,18}\Z") +RUN_ATTEMPT_PATTERN = re.compile(r"[1-9][0-9]{0,8}\Z") +SUBJECT_RESULT_RELATIVE_PATH = "evidence-subject-result.json" +SUBJECT_RESULT_STEP_NAMES = ( + "dotnet-sdk-version", + "dotnet-runtime-list", + "offline-locked-restore", + "coverage-run", + "coverage-gate", +) +SUBJECT_STEP_DIGEST_PATTERN = re.compile(r"[0-9a-f]{64}\Z") + +# This is a closed registry, intentionally independent of subject files and +# policy-provided command strings. Resource-backed profiles are named here so +# they fail with an actionable, stable diagnostic instead of an unknown-profile +# fallback that might accidentally grant a weaker capability. +RESOURCE_BACKED_PROFILES = frozenset( + { + "postgresql-integration", + "keycloak-theme-integration", + "package-release-preparation", + "pr-conservative", + "protected-release", + } +) +PROFILE_ENTRYPOINT_ARGUMENTS: Mapping[str, tuple[str, ...]] = { + "code-coverage": ( + "--profile-id=code-coverage", + "--subject-root=/subject", + "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", + "--diff-file=/source.diff", + "--offline", + ), +} +CONTAINER_ENVIRONMENT = ( + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "HOME=/scratch/home", + "TMPDIR=/scratch/tmp", + "TMP=/scratch/tmp", + "TEMP=/scratch/tmp", + "DOTNET_CLI_HOME=/scratch/home/.dotnet", + "DOTNET_CLI_TELEMETRY_OPTOUT=1", + "DOTNET_NOLOGO=1", + "NUGET_PACKAGES=/opt/appsurface/locked-dependencies", +) + + +class SubjectLauncherError(Exception): + """A stable, bounded launcher diagnostic safe to print in trusted logs.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + self.message = message + + +class _ProcessCancelled(Exception): + pass + + +class _ProcessTimedOut(Exception): + pass + + +class _ProcessOutputExceeded(Exception): + pass + + +class _ProcessStartFailed(Exception): + pass + + +class _ProcessCouldNotStop(Exception): + pass + + +@dataclass(frozen=True) +class SubjectLimits: + """Controller-selected limits, each checked against a reviewed hard cap.""" + + timeout_seconds: int + memory_mib: int + cpu_millis: int + pids: int + output_bytes: int + + +@dataclass(frozen=True) +class CommandResult: + returncode: int + stdout: bytes + stderr: bytes + + +@dataclass(frozen=True) +class SubjectRunResult: + """Bounded subject data and host OCI observation; neither is gate-eligible alone.""" + + exit_code: int + stdout: bytes + stderr: bytes + scratch_directory: Path + execution_record: Mapping[str, Any] | None = None + artifact_export_directory: Path | None = None + envelope_observation: Mapping[str, Any] | None = None + + @property + def claim_eligible(self) -> bool: + return False + + +@dataclass(frozen=True) +class SupervisorSession: + """Validated identity and private paths for one detached cleanup supervisor.""" + + owner_token: str + owner_label: str + manifest_path: Path + state_directory: Path + supervisor_pid: int + supervisor_start_time: int + ready: bool + state_directory_device: int + state_directory_inode: int + + @property + def attestation_path(self) -> Path: + return self.state_directory / "cleanup-attestation.json" + + +class CleanupSupervisorClient(Protocol): + """Public lifecycle seam used by ``run_profile`` and its integration tests.""" + + def start( + self, + *, + container_name: str, + scratch_directory: Path, + mountpoint: Path, + runner_temp: Path, + home: Path, + runtime: Path, + parent_pid: int, + ) -> SupervisorSession: ... + + def assert_alive(self, session: SupervisorSession) -> None: ... + + def request_and_wait(self, session: SupervisorSession) -> Mapping[str, Any]: ... + + +CommandExecutor = Callable[..., CommandResult] + + +def _linux_process_identity(pid: int, *, proc_root: Path = PROC_ROOT) -> tuple[int, str] | None: + """Read the Linux process start time and state used to reject PID reuse.""" + try: + raw = (proc_root / str(pid) / "stat").read_text(encoding="ascii") + closing_paren = raw.rfind(")") + if closing_paren < 0: + return None + fields = raw[closing_paren + 1 :].split() + if len(fields) <= 19 or len(fields[0]) != 1: + return None + return int(fields[19]), fields[0] + except (OSError, UnicodeError, ValueError): + return None + + +def _read_private_json_record(path: Path, *, directory: Path, uid: int, maximum_bytes: int) -> Mapping[str, Any]: + """Read a bounded regular file without following a replaced path or symlink.""" + try: + directory_info = directory.lstat() + if ( + not stat.S_ISDIR(directory_info.st_mode) + or directory_info.st_uid != uid + or stat.S_IMODE(directory_info.st_mode) != 0o700 + ): + raise ValueError("unsafe record directory") + directory_fd = os.open( + directory, + os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0), + ) + try: + opened_directory_info = os.fstat(directory_fd) + if ( + opened_directory_info.st_dev != directory_info.st_dev + or opened_directory_info.st_ino != directory_info.st_ino + or opened_directory_info.st_uid != uid + or stat.S_IMODE(opened_directory_info.st_mode) != 0o700 + ): + raise ValueError("record directory changed") + fd = os.open( + path.name, + os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + dir_fd=directory_fd, + ) + try: + info = os.fstat(fd) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != uid + or stat.S_IMODE(info.st_mode) != 0o600 + or info.st_nlink != 1 + or info.st_size <= 0 + or info.st_size > maximum_bytes + ): + raise ValueError("unsafe record") + chunks: list[bytes] = [] + remaining = maximum_bytes + 1 + while remaining: + chunk = os.read(fd, min(4096, remaining)) + if not chunk: + break + chunks.append(chunk) + remaining -= len(chunk) + content = b"".join(chunks) + if len(content) > maximum_bytes: + raise ValueError("oversized record") + finally: + os.close(fd) + finally: + os.close(directory_fd) + except FileNotFoundError: + raise + except (OSError, ValueError): + raise _fail("ASEGS017", "The cleanup supervisor record is unavailable or unsafe.") from None + try: + value = _parse_json(content, "cleanup supervisor record") + except SubjectLauncherError: + raise _fail("ASEGS017", "The cleanup supervisor record is malformed.") from None + if not isinstance(value, dict): + raise _fail("ASEGS017", "The cleanup supervisor record is malformed.") + return value + + +class SubjectCleanupSupervisorClient: + """Start and communicate with the fixed detached cleanup supervisor.""" + + def __init__( + self, + *, + runner_temp: Path, + home: Path, + runtime: Path, + executor: CommandExecutor | None = None, + process_identity_reader: Callable[[int], tuple[int, str] | None] = _linux_process_identity, + monotonic: Callable[[], float] = time.monotonic, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + self.runner_temp = runner_temp + self.home = home + self.runtime = runtime + self.executor = executor or _run_command + self.process_identity_reader = process_identity_reader + self.monotonic = monotonic + self.sleep = sleep + self.uid = os.geteuid() + self.environment = { + "PATH": ENGINE_PATH, + "HOME": str(home), + "XDG_RUNTIME_DIR": str(runtime), + "RUNNER_TEMP": str(runner_temp), + } + self.script_path = Path(__file__).resolve().with_name(SUPERVISOR_SCRIPT_NAME) + + def _run(self, arguments: Sequence[str], *, timeout_seconds: float) -> CommandResult: + return self.executor( + arguments, + timeout_seconds=timeout_seconds, + maximum_output_bytes=MAX_SUPERVISOR_RECORD_BYTES, + environment=self.environment, + cancel_event=threading.Event(), + ) + + def _validate_session_paths(self, session: SupervisorSession) -> Path: + if ( + not isinstance(session, SupervisorSession) + or session.ready is not True + or not isinstance(session.owner_token, str) + or SUPERVISOR_TOKEN_PATTERN.fullmatch(session.owner_token) is None + or session.owner_label != SUPERVISOR_OWNER_LABEL + or type(session.supervisor_pid) is not int + or session.supervisor_pid <= 1 + or type(session.supervisor_start_time) is not int + or session.supervisor_start_time <= 0 + ): + raise _fail("ASEGS017", "The cleanup supervisor did not provide a ready owned session.") + expected_state = self.runner_temp / f"appsurface-subject-supervisor-{session.owner_token}" + expected_manifest = expected_state / "supervisor.json" + try: + state = _path_without_symlink_components(session.state_directory, "The cleanup supervisor state") + manifest = _path_without_symlink_components(session.manifest_path, "The cleanup supervisor manifest") + info = state.lstat() + if ( + state != expected_state + or manifest != expected_manifest + or state.parent != self.runner_temp + or info.st_uid != self.uid + or not stat.S_ISDIR(info.st_mode) + or stat.S_IMODE(info.st_mode) != 0o700 + or (info.st_dev, info.st_ino) + != (session.state_directory_device, session.state_directory_inode) + ): + raise ValueError("state identity mismatch") + except (SubjectLauncherError, OSError, ValueError): + raise _fail("ASEGS017", "The cleanup supervisor state path is unsafe.") from None + return state + + def start( + self, + *, + container_name: str, + scratch_directory: Path, + mountpoint: Path, + runner_temp: Path, + home: Path, + runtime: Path, + parent_pid: int, + ) -> SupervisorSession: + if runner_temp != self.runner_temp or home != self.home or runtime != self.runtime: + raise _fail("ASEGS017", "The cleanup supervisor context differs from the validated runner paths.") + try: + resolved_script = _path_without_symlink_components( + self.script_path, "The trusted cleanup supervisor" + ) + if not stat.S_ISREG(resolved_script.stat().st_mode): + raise _fail("ASEGS017", "The trusted cleanup supervisor is unavailable.") + except (SubjectLauncherError, OSError): + raise _fail("ASEGS017", "The trusted cleanup supervisor is unavailable.") from None + parent_identity = self.process_identity_reader(parent_pid) + if ( + parent_identity is None + or not isinstance(parent_identity, tuple) + or len(parent_identity) != 2 + or parent_identity[1] in {"Z", "X"} + ): + raise _fail("ASEGS017", "The launcher process identity could not be verified for cleanup.") + parent_start_time = parent_identity[0] + result = self._run( + [ + sys.executable, + str(resolved_script), + "start", + "--container-name", + container_name, + "--scratch-directory", + str(scratch_directory), + "--mountpoint", + str(mountpoint), + "--parent-pid", + str(parent_pid), + "--parent-start-time", + str(parent_start_time), + ], + timeout_seconds=SUPERVISOR_STARTUP_TIMEOUT_SECONDS, + ) + if ( + result.returncode != 0 + or result.stderr + or len(result.stdout) > MAX_SUPERVISOR_RECORD_BYTES + ): + raise _fail("ASEGS017", "The cleanup supervisor failed its bounded startup handshake.") + document = _parse_json(result.stdout, "cleanup supervisor readiness record") + expected_keys = { + "schemaVersion", "claimEligible", "ownerToken", "stateDirectory", "manifestPath", + "supervisorPid", "supervisorStartTime", "supervisorReady", "ownerLabel", + } + if ( + not isinstance(document, dict) + or set(document) != expected_keys + or type(document.get("schemaVersion")) is not int + or document.get("schemaVersion") != 1 + or document.get("claimEligible") is not False + or document.get("supervisorReady") is not True + or document.get("ownerLabel") != SUPERVISOR_OWNER_LABEL + or not isinstance(document.get("ownerToken"), str) + or SUPERVISOR_TOKEN_PATTERN.fullmatch(document["ownerToken"]) is None + or type(document.get("supervisorPid")) is not int + or document["supervisorPid"] <= 1 + or type(document.get("supervisorStartTime")) is not int + or document["supervisorStartTime"] <= 0 + or not isinstance(document.get("stateDirectory"), str) + or not isinstance(document.get("manifestPath"), str) + ): + raise _fail("ASEGS017", "The cleanup supervisor readiness record is incomplete.") + token = document["ownerToken"] + session = SupervisorSession( + owner_token=token, + owner_label=SUPERVISOR_OWNER_LABEL, + manifest_path=Path(document["manifestPath"]), + state_directory=Path(document["stateDirectory"]), + supervisor_pid=document["supervisorPid"], + supervisor_start_time=document["supervisorStartTime"], + ready=True, + state_directory_device=-1, + state_directory_inode=-1, + ) + state = self._validate_session_start_paths(session) + manifest = _read_private_json_record( + session.manifest_path, + directory=state, + uid=self.uid, + maximum_bytes=MAX_SUPERVISOR_RECORD_BYTES, + ) + if ( + manifest.get("schemaVersion") != 1 + or manifest.get("ownerToken") != token + or manifest.get("containerName") != container_name + or manifest.get("scratchDirectory") != str(scratch_directory) + or manifest.get("mountpoint") != str(mountpoint) + or manifest.get("parentPid") != parent_pid + or manifest.get("parentStartTime") != parent_start_time + ): + raise _fail("ASEGS017", "The cleanup supervisor manifest does not match this subject run.") + state_info = state.lstat() + session = SupervisorSession( + **{**session.__dict__, "state_directory_device": state_info.st_dev, "state_directory_inode": state_info.st_ino} + ) + self._validate_session_paths(session) + try: + session.attestation_path.lstat() + except FileNotFoundError: + pass + except OSError: + raise _fail("ASEGS017", "The cleanup supervisor attestation path is unsafe.") from None + else: + raise _fail("ASEGS017", "The cleanup supervisor returned a stale attestation.") + self.assert_alive(session) + return session + + def _validate_session_start_paths(self, session: SupervisorSession) -> Path: + expected_state = self.runner_temp / f"appsurface-subject-supervisor-{session.owner_token}" + expected_manifest = expected_state / "supervisor.json" + try: + state = _path_without_symlink_components(session.state_directory, "The cleanup supervisor state") + manifest = _path_without_symlink_components(session.manifest_path, "The cleanup supervisor manifest") + state_info = state.lstat() + if ( + state != expected_state + or manifest != expected_manifest + or state.parent != self.runner_temp + or state_info.st_uid != self.uid + or not stat.S_ISDIR(state_info.st_mode) + or stat.S_IMODE(state_info.st_mode) != 0o700 + ): + raise ValueError("unsafe state path") + return state + except (SubjectLauncherError, OSError, ValueError): + raise _fail("ASEGS017", "The cleanup supervisor state path is unsafe.") from None + + def assert_alive(self, session: SupervisorSession) -> None: + self._validate_session_paths(session) + identity = self.process_identity_reader(session.supervisor_pid) + if ( + identity is None + or not isinstance(identity, tuple) + or len(identity) != 2 + or identity[0] != session.supervisor_start_time + or identity[1] in {"Z", "X"} + ): + raise _fail("ASEGS017", "The cleanup supervisor stopped before subject setup completed.") + + def request_and_wait(self, session: SupervisorSession) -> Mapping[str, Any]: + state = self._validate_session_paths(session) + try: + session.attestation_path.lstat() + except FileNotFoundError: + pass + except OSError: + raise _fail("ASEGS017", "The cleanup supervisor attestation path is unsafe.") from None + else: + record = _read_private_json_record( + session.attestation_path, + directory=state, + uid=self.uid, + maximum_bytes=MAX_SUPERVISOR_RECORD_BYTES, + ) + self._validate_attestation(record) + return record + self.assert_alive(session) + deadline = self.monotonic() + SUPERVISOR_CLEANUP_DEADLINE_SECONDS + request = self._run( + [ + sys.executable, + str(self.script_path), + "request", + "--manifest", + str(session.manifest_path), + "--owner-token", + session.owner_token, + ], + timeout_seconds=min( + SUPERVISOR_STARTUP_TIMEOUT_SECONDS, + max(0.001, deadline - self.monotonic()), + ), + ) + if request.returncode != 0 or request.stdout or request.stderr: + raise _fail("ASEGS017", "The cleanup supervisor rejected the bounded cleanup request.") + attestation_path = session.attestation_path + while True: + try: + _path_without_symlink_components(state, "The cleanup supervisor state") + record = _read_private_json_record( + attestation_path, + directory=state, + uid=self.uid, + maximum_bytes=MAX_SUPERVISOR_RECORD_BYTES, + ) + except FileNotFoundError: + if self.monotonic() >= deadline: + raise _fail("ASEGS017", "The cleanup supervisor did not produce a completed attestation.") from None + self.sleep(min(0.2, max(0.0, deadline - self.monotonic()))) + continue + self._validate_attestation(record) + return record + + @staticmethod + def _validate_attestation(record: Mapping[str, Any]) -> None: + expected_keys = { + "schemaVersion", "claimEligible", "published", "status", "trigger", "containerStatus", + "mountStatus", "scratchStatus", "failureCode", "cleanupDeadlineSeconds", + } + if ( + not isinstance(record, Mapping) + or set(record) != expected_keys + or type(record.get("schemaVersion")) is not int + or record.get("schemaVersion") != 1 + or record.get("claimEligible") is not False + or record.get("published") is not False + or record.get("status") != "complete" + or record.get("trigger") not in {"request", "parent-exit"} + or record.get("containerStatus") not in {"removed", "absent"} + or record.get("mountStatus") not in {"unmounted", "absent"} + or record.get("scratchStatus") not in {"removed", "absent"} + or record.get("failureCode") != "none" + or record.get("cleanupDeadlineSeconds") != SUPERVISOR_CLEANUP_DEADLINE_SECONDS + ): + raise _fail("ASEGS017", "The cleanup supervisor attestation is incomplete; no claim may be issued.") + + +def _fail(code: str, message: str) -> SubjectLauncherError: + return SubjectLauncherError(code, message) + + +def _bounded_integer(value: Any, name: str, minimum: int, maximum: int) -> int: + if type(value) is not int or value < minimum or value > maximum: + raise _fail("ASEGS001", f"{name} is outside its controller-approved bounds.") + return value + + +def _validate_limits(limits: SubjectLimits) -> None: + if not isinstance(limits, SubjectLimits): + raise _fail("ASEGS001", "Controller-owned profile limits are required.") + _bounded_integer(limits.timeout_seconds, "Execution timeout", 1, MAX_PROFILE_TIMEOUT_SECONDS) + _bounded_integer(limits.memory_mib, "Memory limit", 256, MAX_PROFILE_MEMORY_MIB) + _bounded_integer(limits.cpu_millis, "CPU limit", 250, MAX_PROFILE_CPU_MILLIS) + if limits.cpu_millis % 250 != 0: + raise _fail("ASEGS001", "CPU limit must use a supported quarter-core increment.") + _bounded_integer(limits.pids, "PID limit", 32, MAX_PROFILE_PIDS) + _bounded_integer(limits.output_bytes, "Output limit", MIN_OUTPUT_BYTES, MAX_PROFILE_OUTPUT_BYTES) + + +def _path_without_symlink_components(value: str | os.PathLike[str], name: str) -> Path: + raw = os.fspath(value) + if not isinstance(raw, str) or not raw or "\x00" in raw or not Path(raw).is_absolute(): + raise _fail("ASEGS002", f"{name} must be an absolute controller-owned path.") + path = Path(raw) + if any(part in {".", ".."} for part in path.parts): + raise _fail("ASEGS002", f"{name} contains an unsafe path component.") + current = Path(path.anchor) + try: + for part in path.parts[1:]: + current = current / part + item_stat = current.lstat() + if stat.S_ISLNK(item_stat.st_mode): + raise _fail("ASEGS002", f"{name} traverses a symbolic link.") + resolved = path.resolve(strict=True) + except SubjectLauncherError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail("ASEGS002", f"{name} is unavailable or unsafe.") from None + if resolved != path: + raise _fail("ASEGS002", f"{name} is not canonical.") + return resolved + + +def _validate_subject_root(value: str | os.PathLike[str]) -> Path: + raw = os.fspath(value) + if any(char in raw for char in ",\r\n"): + raise _fail("ASEGS002", "The trusted subject checkout path contains an unsafe mount option character.") + path = _path_without_symlink_components(value, "The trusted subject checkout") + try: + if not stat.S_ISDIR(path.stat().st_mode): + raise _fail("ASEGS002", "The trusted subject checkout is not a directory.") + except OSError: + raise _fail("ASEGS002", "The trusted subject checkout is unavailable.") from None + return path + + +def _validate_runner_context( + environment: Mapping[str, str], + *, + system_name: str, + effective_uid: int, +) -> tuple[Path, Path, Path]: + if system_name != "Linux": + raise _fail("ASEGS003", "Subject execution requires a Linux runner.") + if effective_uid == 0: + raise _fail("ASEGS003", "Subject execution cannot run as host root.") + if environment.get("GITHUB_ACTIONS") != "true" or environment.get("RUNNER_ENVIRONMENT") != "github-hosted": + raise _fail("ASEGS003", "Subject execution requires an ephemeral GitHub-hosted runner.") + if RUN_ID_PATTERN.fullmatch(environment.get("GITHUB_RUN_ID", "")) is None: + raise _fail("ASEGS003", "Trusted GitHub run identity is missing or malformed.") + if RUN_ATTEMPT_PATTERN.fullmatch(environment.get("GITHUB_RUN_ATTEMPT", "")) is None: + raise _fail("ASEGS003", "Trusted GitHub run attempt is missing or malformed.") + + try: + runner_temp = _path_without_symlink_components(environment["RUNNER_TEMP"], "RUNNER_TEMP") + home = _path_without_symlink_components(environment["HOME"], "The host engine home") + runtime_value = environment.get("XDG_RUNTIME_DIR") or f"/run/user/{effective_uid}" + runtime = _path_without_symlink_components(runtime_value, "The rootless engine runtime directory") + if not all(stat.S_ISDIR(path.stat().st_mode) for path in (runner_temp, home, runtime)): + raise _fail("ASEGS003", "The hosted runner directories are unavailable.") + runtime_stat = runtime.stat() + if runtime_stat.st_uid != effective_uid or stat.S_IMODE(runtime_stat.st_mode) & 0o077: + raise _fail("ASEGS003", "The rootless engine runtime directory is not private to this runner user.") + except KeyError: + raise _fail("ASEGS003", "The hosted runner directory context is incomplete.") from None + except OSError: + raise _fail("ASEGS003", "The hosted runner directory context is unavailable.") from None + return runner_temp, home, runtime + + +def _validate_scratch_path(value: str | os.PathLike[str], runner_temp: Path) -> Path: + raw = os.fspath(value) + if not isinstance(raw, str) or not raw or "\x00" in raw or not Path(raw).is_absolute(): + raise _fail("ASEGS002", "The scratch path must be an absolute new path under RUNNER_TEMP.") + path = Path(raw) + if any(part in {".", ".."} for part in path.parts) or any(char in raw for char in ",\r\n"): + raise _fail("ASEGS002", "The scratch path contains an unsafe component.") + if path.parent != runner_temp or path.name in {"", ".", ".."}: + raise _fail("ASEGS002", "The scratch directory must be a direct child of RUNNER_TEMP.") + try: + path.lstat() + except FileNotFoundError: + return path + except OSError: + raise _fail("ASEGS002", "The scratch destination cannot be inspected safely.") from None + raise _fail("ASEGS002", "The scratch directory must be new and must not already exist.") + + +def _paths_overlap(first: Path, second: Path) -> bool: + return first == second or first in second.parents or second in first.parents + + +def _validate_artifact_export_path(value: str | os.PathLike[str], runner_temp: Path) -> Path: + """Validate a new direct-child path for the private, non-claiming artifact export.""" + raw = os.fspath(value) + if not isinstance(raw, str) or not raw or "\x00" in raw or not Path(raw).is_absolute(): + raise _fail("ASEGS021", "The artifact export path must be an absolute new path under RUNNER_TEMP.") + path = Path(raw) + if ( + str(path) != raw + or any(part in {".", ".."} for part in path.parts) + or any(char in raw for char in ",\r\n") + or path.parent != runner_temp + or path.name in {"", ".", ".."} + ): + raise _fail("ASEGS021", "The artifact export directory must be a direct child of RUNNER_TEMP.") + try: + path.lstat() + except FileNotFoundError: + return path + except OSError: + raise _fail("ASEGS021", "The artifact export destination cannot be inspected safely.") from None + raise _fail("ASEGS021", "The artifact export directory must be new and must not already exist.") + + +def _validate_image_reference(image: str) -> None: + if not isinstance(image, str) or IMAGE_REFERENCE_PATTERN.fullmatch(image) is None: + raise _fail("ASEGS004", "The subject image must use a canonical sha256 digest reference.") + image_name = image.split("@", 1)[0] + if "//" in image_name or any(part in {".", ".."} for part in image_name.split("/")): + raise _fail("ASEGS004", "The subject image reference is malformed.") + + +def _validate_profile(profile_id: str) -> tuple[str, ...]: + if not isinstance(profile_id, str): + raise _fail("ASEGS005", "The subject profile ID is malformed.") + if profile_id in RESOURCE_BACKED_PROFILES: + raise _fail( + "ASEGS005", + "Resource-backed subject profiles are disabled until an explicit bounded network envelope is implemented.", + ) + arguments = PROFILE_ENTRYPOINT_ARGUMENTS.get(profile_id) + if arguments is None: + raise _fail("ASEGS005", "The subject profile is not in the controller-owned offline profile registry.") + return arguments + + +def _validate_source_diff(value: str | os.PathLike[str], expected_sha256: str) -> Path: + if not isinstance(expected_sha256, str) or SOURCE_DIFF_SHA256_PATTERN.fullmatch(expected_sha256) is None: + raise _fail("ASEGS020", "The controller source diff digest is malformed.") + raw = os.fspath(value) + if not isinstance(raw, str) or any(character in raw for character in ",\r\n"): + raise _fail("ASEGS020", "The controller source diff path contains an unsafe mount option character.") + path = _path_without_symlink_components(value, "The controller source diff") + descriptor = -1 + try: + metadata = path.lstat() + if ( + stat.S_ISLNK(metadata.st_mode) + or not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_size <= 0 + or metadata.st_size > MAX_SOURCE_DIFF_BYTES + ): + raise _fail("ASEGS020", "The controller source diff is not a bounded, private regular file.") + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)) + opened = os.fstat(descriptor) + if ( + not stat.S_ISREG(opened.st_mode) + or opened.st_nlink != 1 + or (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino) + or opened.st_size <= 0 + or opened.st_size > MAX_SOURCE_DIFF_BYTES + ): + raise _fail("ASEGS020", "The controller source diff changed or exceeds its byte limit.") + digest = hashlib.sha256() + total = 0 + while True: + chunk = os.read(descriptor, min(1024 * 1024, MAX_SOURCE_DIFF_BYTES + 1 - total)) + if not chunk: + break + total += len(chunk) + if total > MAX_SOURCE_DIFF_BYTES: + raise _fail("ASEGS020", "The controller source diff exceeds its byte limit.") + digest.update(chunk) + after = os.fstat(descriptor) + if ( + total != opened.st_size + or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns) + != (opened.st_dev, opened.st_ino, opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + or digest.hexdigest() != expected_sha256 + ): + raise _fail("ASEGS020", "The controller source diff changed or does not match its digest.") + except SubjectLauncherError: + raise + except (OSError, RuntimeError, ValueError): + raise _fail("ASEGS020", "The controller source diff is unavailable or unsafe.") from None + finally: + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + raise _fail("ASEGS020", "The controller source diff could not be closed safely.") from None + return path + + +def _resolve_podman() -> str: + candidate = shutil.which("podman", path=ENGINE_PATH) + if candidate is None: + raise _fail("ASEGS006", "The required rootless Podman engine is unavailable.") + try: + resolved = Path(candidate).resolve(strict=True) + info = resolved.stat() + if not stat.S_ISREG(info.st_mode) or not os.access(resolved, os.X_OK): + raise _fail("ASEGS006", "The Podman engine binary is unavailable or unsafe.") + if info.st_uid != 0 or stat.S_IMODE(info.st_mode) & 0o022: + raise _fail("ASEGS006", "The Podman engine binary is not protected by the runner image.") + except SubjectLauncherError: + raise + except (OSError, RuntimeError): + raise _fail("ASEGS006", "The Podman engine binary is unavailable or unsafe.") from None + return str(resolved) + + +def _signal_process_group(process: Any, signal_number: int) -> None: + try: + os.killpg(process.pid, signal_number) + except ProcessLookupError: + return + except OSError: + try: + if signal_number == signal.SIGTERM: + process.terminate() + else: + process.kill() + except OSError: + pass + + +def _stop_process(process: Any) -> None: + _signal_process_group(process, signal.SIGTERM) + if process.poll() is None: + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + # The CLI leader may exit while a descendant still holds a captured pipe. + _signal_process_group(process, signal.SIGKILL) + if process.poll() is None: + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + raise _ProcessCouldNotStop from None + + +def _run_command( + arguments: Sequence[str], + *, + timeout_seconds: float, + maximum_output_bytes: int, + environment: Mapping[str, str], + cancel_event: threading.Event, +) -> CommandResult: + """Run a trusted fixed argv with bounded combined output and hard cancellation.""" + if not arguments or any(not isinstance(argument, str) or "\x00" in argument for argument in arguments): + raise _ProcessStartFailed + try: + process = subprocess.Popen( + list(arguments), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + close_fds=True, + start_new_session=True, + bufsize=0, + cwd="/", + env=dict(environment), + ) + except (OSError, ValueError): + raise _ProcessStartFailed from None + + selector = selectors.DefaultSelector() + stdout = bytearray() + stderr = bytearray() + deadline = time.monotonic() + timeout_seconds + try: + if process.stdout is None or process.stderr is None: + raise _ProcessStartFailed + for pipe, label in ((process.stdout, "stdout"), (process.stderr, "stderr")): + os.set_blocking(pipe.fileno(), False) + selector.register(pipe, selectors.EVENT_READ, label) + + while selector.get_map() or process.poll() is None: + if cancel_event.is_set(): + _stop_process(process) + raise _ProcessCancelled + remaining = deadline - time.monotonic() + if remaining <= 0: + _stop_process(process) + raise _ProcessTimedOut + for key, _ in selector.select(min(0.1, remaining)): + stream = stdout if key.data == "stdout" else stderr + remaining_output = maximum_output_bytes - len(stdout) - len(stderr) + try: + chunk = os.read(key.fileobj.fileno(), min(64 * 1024, remaining_output + 1)) + except BlockingIOError: + continue + if not chunk: + selector.unregister(key.fileobj) + key.fileobj.close() + continue + stream.extend(chunk) + if len(stdout) + len(stderr) > maximum_output_bytes: + _stop_process(process) + raise _ProcessOutputExceeded + + return CommandResult(process.wait(), bytes(stdout), bytes(stderr)) + except (_ProcessCancelled, _ProcessTimedOut, _ProcessOutputExceeded, _ProcessStartFailed): + if process.poll() is None: + _stop_process(process) + raise + except (OSError, ValueError, selectors.SelectorError): + if process.poll() is None: + _stop_process(process) + raise _ProcessStartFailed from None + except BaseException: + if process.poll() is None: + _stop_process(process) + raise + finally: + selector.close() + for pipe in (process.stdout, process.stderr): + if pipe is not None and not pipe.closed: + pipe.close() + + +def _parse_json(data: bytes, description: str) -> Any: + def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + try: + return json.loads(data.decode("utf-8"), object_pairs_hook=unique_object) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise _fail("ASEGS007", f"The rootless OCI engine returned malformed {description}.") from None + + +def _expect_success(result: CommandResult, stage: str) -> CommandResult: + if result.returncode != 0: + raise _fail("ASEGS008", f"The rootless OCI engine failed during {stage}.") + return result + + +def _preflight_rootless_engine( + engine: str, + *, + environment: Mapping[str, str], + cancel_event: threading.Event, + executor: CommandExecutor, +) -> None: + result = _expect_success( + executor( + [engine, "--remote=false", "info", "--format=json"], + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=MAX_ENGINE_OUTPUT_BYTES, + environment=environment, + cancel_event=cancel_event, + ), + "engine capability inspection", + ) + info = _parse_json(result.stdout, "engine capability document") + host = info.get("host") if isinstance(info, dict) else None + security = host.get("security") if isinstance(host, dict) else None + controllers = host.get("cgroupControllers") if isinstance(host, dict) else None + if ( + not isinstance(host, dict) + or not isinstance(security, dict) + or security.get("rootless") is not True + or host.get("cgroupVersion") != "v2" + or not isinstance(controllers, list) + or not all(isinstance(controller, str) for controller in controllers) + or not {"cpu", "memory", "pids"}.issubset(set(controllers)) + ): + raise _fail("ASEGS009", "Rootless OCI, cgroup v2, CPU, memory, and PID enforcement are required.") + + +def _verify_local_image( + engine: str, + image: str, + *, + environment: Mapping[str, str], + cancel_event: threading.Event, + executor: CommandExecutor, +) -> None: + exists = executor( + [engine, "--remote=false", "image", "exists", image], + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=4096, + environment=environment, + cancel_event=cancel_event, + ) + if exists.returncode != 0: + raise _fail("ASEGS010", "The pinned subject image is not already present in local engine storage.") + inspected = _expect_success( + executor( + [engine, "--remote=false", "image", "inspect", "--format=json", image], + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=MAX_ENGINE_OUTPUT_BYTES, + environment=environment, + cancel_event=cancel_event, + ), + "pinned image inspection", + ) + images = _parse_json(inspected.stdout, "pinned image document") + if not isinstance(images, list) or len(images) != 1 or not isinstance(images[0], dict): + raise _fail("ASEGS011", "The pinned subject image inspection was ambiguous.") + item = images[0] + config = item.get("Config") + digests = item.get("RepoDigests") + if not isinstance(config, dict) or not isinstance(digests, list) or image not in digests: + raise _fail("ASEGS011", "The local image does not prove the exact controller-pinned digest.") + declared_volumes = config.get("Volumes") + if declared_volumes not in (None, {}): + raise _fail("ASEGS011", "The pinned subject image declares writable or anonymous volumes.") + + +def _cpu_argument(cpu_millis: int) -> str: + whole, fraction = divmod(cpu_millis, 1000) + return f"{whole}.{fraction:03d}" + + +def _container_create_arguments( + engine: str, + *, + name: str, + image: str, + owner_token: str, + subject_root: Path, + source_diff: Path, + scratch_mountpoint: Path, + profile_arguments: Sequence[str], + limits: SubjectLimits, +) -> list[str]: + subject_mount = f"type=bind,src={subject_root},dst=/subject,ro=true,bind-propagation=rprivate" + diff_mount = f"type=bind,src={source_diff},dst={SOURCE_DIFF_CONTAINER_PATH},ro=true,bind-propagation=rprivate" + scratch_mount = ( + f"type=bind,src={scratch_mountpoint},dst=/scratch,rw=true,bind-propagation=rprivate" + ) + arguments = [ + engine, + "--remote=false", + "create", + "--pull=never", + "--http-proxy=false", + f"--name={name}", + f"--label={SUPERVISOR_OWNER_LABEL}={owner_token}", + "--network=none", + "--pid=private", + "--ipc=private", + "--uts=private", + "--cgroupns=private", + "--read-only", + "--read-only-tmpfs=false", + "--image-volume=ignore", + "--userns=keep-id:uid=65532,gid=65532", + "--user=65532:65532", + "--cap-drop=ALL", + "--security-opt=no-new-privileges", + f"--pids-limit={limits.pids}", + f"--memory={limits.memory_mib}m", + f"--cpus={_cpu_argument(limits.cpu_millis)}", + "--mount", + subject_mount, + "--mount", + diff_mount, + "--mount", + scratch_mount, + "--unsetenv-all", + ] + arguments.extend(f"--env={value}" for value in CONTAINER_ENVIRONMENT) + arguments.extend( + [ + "--workdir=/subject", + f"--entrypoint={CONTAINER_ENTRYPOINT}", + image, + *profile_arguments, + ] + ) + return arguments + + +def _one_inspect_object(data: bytes) -> Mapping[str, Any]: + inspected = _parse_json(data, "container configuration") + if not isinstance(inspected, list) or len(inspected) != 1 or not isinstance(inspected[0], dict): + raise _fail("ASEGS012", "The created container configuration was ambiguous.") + return inspected[0] + + +def _decode_mountinfo_field(value: str) -> str: + return re.sub(r"\\([0-7]{3})", lambda match: chr(int(match.group(1), 8)), value) + + +def _host_scratch_mount_is_present(mountpoint: Path) -> bool: + """Detect a partial mount after a failed mount command so cleanup can still remove it.""" + try: + with MOUNTINFO_PATH.open(encoding="utf-8") as mountinfo: + for line in mountinfo: + left, separator, _ = line.rstrip("\n").partition(" - ") + fields = left.split() + if not separator or len(fields) < 6: + raise ValueError("malformed mountinfo record") + if _decode_mountinfo_field(fields[4]) == str(mountpoint): + return True + return False + except (OSError, UnicodeError, ValueError, OverflowError): + raise _fail("ASEGS019", "The host scratch mount state could not be inspected safely.") from None + + +def _size_option_bytes(value: str) -> int | None: + match = re.fullmatch(r"([0-9]+)([kKmMgGtT]?)", value) + if match is None: + return None + scales = {"": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4} + return int(match.group(1)) * scales[match.group(2).lower()] + + +def _verify_host_scratch_mount(mountpoint: Path, *, host_uid: int, host_gid: int) -> None: + """Require the live host mount and statvfs limits to match the fixed contract.""" + try: + matching_mounts: list[tuple[str, str, list[str], list[str]]] = [] + with MOUNTINFO_PATH.open(encoding="utf-8") as mountinfo: + for line in mountinfo: + left, separator, right = line.rstrip("\n").partition(" - ") + fields = left.split() + if not separator or len(fields) < 6: + raise ValueError("malformed mountinfo record") + if _decode_mountinfo_field(fields[4]) != str(mountpoint): + continue + filesystem_fields = right.split() + if len(filesystem_fields) < 3: + raise ValueError("malformed mountinfo filesystem fields") + matching_mounts.append( + ( + filesystem_fields[0], + filesystem_fields[1], + fields[5].split(","), + filesystem_fields[2].split(","), + ) + ) + if len(matching_mounts) != 1: + raise ValueError("the scratch mount is missing or ambiguous") + + filesystem_type, source, mount_options, super_options = matching_mounts[0] + option_flags = set(mount_options + super_options) + option_values: dict[str, str] = {} + for option in super_options: + key, separator, value = option.partition("=") + if separator: + if key in option_values: + raise ValueError("duplicate tmpfs option") + option_values[key] = value + + mount_stat = mountpoint.stat() + filesystem_stat = os.statvfs(mountpoint) + mode_value = int(option_values.get("mode", "-1"), 8) + actual_bytes = filesystem_stat.f_blocks * filesystem_stat.f_frsize + if ( + filesystem_type != "tmpfs" + or source != "tmpfs" + or not {"rw", "nosuid", "nodev"}.issubset(option_flags) + or {"ro", "suid", "dev", "noswap"}.intersection(option_flags) + or _size_option_bytes(option_values.get("size", "")) != MAX_PROFILE_SCRATCH_BYTES + or option_values.get("nr_inodes") != str(MAX_PROFILE_SCRATCH_INODES) + or mode_value != 0o700 + or option_values.get("uid") != str(host_uid) + or option_values.get("gid") != str(host_gid) + or not stat.S_ISDIR(mount_stat.st_mode) + or stat.S_IMODE(mount_stat.st_mode) != 0o700 + or mount_stat.st_uid != host_uid + or mount_stat.st_gid != host_gid + or actual_bytes != MAX_PROFILE_SCRATCH_BYTES + or filesystem_stat.f_files != MAX_PROFILE_SCRATCH_INODES + ): + raise ValueError("the live tmpfs does not match the fixed quota and identity") + except (OSError, UnicodeError, ValueError, OverflowError): + raise _fail("ASEGS019", "The live quota-limited host scratch mount could not be verified.") from None + + +def _verify_container_configuration( + data: bytes, + *, + subject_root: Path, + source_diff: Path, + scratch_mountpoint: Path, + limits: SubjectLimits, + profile_arguments: Sequence[str], + owner_token: str, +) -> None: + container = _one_inspect_object(data) + config = container.get("Config") + host = container.get("HostConfig") + mounts = container.get("Mounts") + if not isinstance(config, dict) or not isinstance(host, dict) or not isinstance(mounts, list): + raise _fail("ASEGS012", "The created container omitted required isolation settings.") + + expected_entrypoint = [CONTAINER_ENTRYPOINT] + expected_command = list(profile_arguments) + if config.get("Entrypoint") != expected_entrypoint or config.get("Cmd") != expected_command: + raise _fail("ASEGS012", "The created container command differs from the fixed trusted profile command.") + if config.get("User") != f"{CONTAINER_UID}:{CONTAINER_GID}" or config.get("WorkingDir") != "/subject": + raise _fail("ASEGS012", "The created container is not using its fixed non-root identity and work directory.") + if config.get("Env") != list(CONTAINER_ENVIRONMENT): + raise _fail("ASEGS012", "The created container environment differs from the fixed credentialless allowlist.") + labels = config.get("Labels") + if not isinstance(labels, dict) or labels.get(SUPERVISOR_OWNER_LABEL) != owner_token: + raise _fail("ASEGS012", "The created container does not carry this run's cleanup ownership label.") + if host.get("ReadonlyRootfs") is not True: + raise _fail("ASEGS012", "The created container root filesystem is not read-only.") + cap_drop = host.get("CapDrop") + security_options = host.get("SecurityOpt") + if not isinstance(cap_drop, list) or not all(isinstance(value, str) for value in cap_drop): + raise _fail("ASEGS012", "The created container omitted capability-drop verification.") + if not isinstance(security_options, list) or not all(isinstance(value, str) for value in security_options): + raise _fail("ASEGS012", "The created container omitted no-new-privileges verification.") + # Rootless Podman 4.9 expands ALL into its default capability names in + # inspect, while other versions may retain the literal request. + dropped = set(cap_drop) + if ( + not (cap_drop == ["ALL"] or ( + len(dropped) == len(cap_drop) and PODMAN_DEFAULT_CAPABILITIES.issubset(dropped) + )) + ) or not { + "no-new-privileges", + "no-new-privileges:true", + }.intersection(set(security_options)): + raise _fail("ASEGS012", "The created container did not drop every capability and enable no-new-privileges.") + if len(security_options) != 1 or host.get("CapAdd") not in (None, []): + raise _fail("ASEGS012", "The created container has an additional security option or added capability.") + if host.get("NetworkMode") != "none": + raise _fail("ASEGS012", "The created container has network access.") + if ( + host.get("PidsLimit") != limits.pids + or host.get("Memory") != limits.memory_mib * 1024 * 1024 + or host.get("NanoCpus") != limits.cpu_millis * 1_000_000 + ): + raise _fail("ASEGS012", "The created container resource limits do not match the validated profile limits.") + devices = host.get("Devices") + if not isinstance(devices, list): + raise _fail("ASEGS012", "The created container omitted device access verification.") + if host.get("Privileged") is not False or devices: + raise _fail("ASEGS012", "The created container has a privileged or device capability.") + if host.get("Tmpfs") not in (None, {}): + raise _fail("ASEGS012", "The created container has an undeclared tmpfs mount.") + if ( + host.get("PortBindings") not in (None, {}) + or host.get("PidMode") != "private" + or host.get("IpcMode") != "private" + or host.get("UTSMode") != "private" + or host.get("CgroupnsMode") not in (None, "private") + or host.get("UsernsMode") != "private" + ): + raise _fail("ASEGS012", "The created container shares a host namespace or publishes a port.") + + if len(mounts) != 3: + raise _fail("ASEGS012", "The created container has an unexpected host mount.") + by_destination = {mount.get("Destination"): mount for mount in mounts if isinstance(mount, dict)} + if set(by_destination) != {"/subject", SOURCE_DIFF_CONTAINER_PATH, "/scratch"}: + raise _fail("ASEGS012", "The created container has an unexpected host mount.") + subject_mount = by_destination["/subject"] + diff_mount = by_destination[SOURCE_DIFF_CONTAINER_PATH] + scratch_mount = by_destination["/scratch"] + if ( + subject_mount.get("Type") != "bind" + or Path(str(subject_mount.get("Source"))).resolve() != subject_root + or subject_mount.get("RW") is not False + or subject_mount.get("Propagation") != "rprivate" + or diff_mount.get("Type") != "bind" + or Path(str(diff_mount.get("Source"))).resolve() != source_diff + or diff_mount.get("RW") is not False + or diff_mount.get("Propagation") != "rprivate" + or scratch_mount.get("Type") != "bind" + or Path(str(scratch_mount.get("Source"))).resolve() != scratch_mountpoint + or scratch_mount.get("RW") is not True + or scratch_mount.get("Propagation") != "rprivate" + ): + raise _fail( + "ASEGS012", "Subject, source diff, and scratch bind mounts do not match the read-only/private contract." + ) + + +def _verify_container_stopped(data: bytes) -> None: + """Require Podman to report the attached subject container as exited.""" + container = _one_inspect_object(data) + state = container.get("State") + if ( + not isinstance(state, dict) + or type(state.get("Running")) is not bool + or state.get("Running") is not False + or state.get("Status") != "exited" + ): + raise _fail("ASEGS012", "The subject container was not verified stopped before artifact export.") + + +def _validate_subject_result_content(content: bytes, *, expected_status: str) -> Mapping[str, Any]: + if not content or len(content) > MAX_SUBJECT_RESULT_BYTES: + raise _fail("ASEGS018", "The exported subject result is not bounded; no claim may be issued.") + try: + value = _parse_json(content, "bounded subject result") + except SubjectLauncherError: + raise _fail("ASEGS018", "The exported subject result is malformed; no claim may be issued.") from None + if not isinstance(value, dict): + raise _fail("ASEGS018", "The exported subject result does not match the fixed non-claiming record.") + status = value.get("status") + expected_keys = {"claimEligible", "profileId", "schemaVersion", "status", "steps"} + if status == "failed": + expected_keys.add("diagnostic") + elif status == "completed": + expected_keys.add("artifacts") + actual_keys_match = set(value) == expected_keys + if status == "completed" and "artifacts" not in value: + actual_keys_match = set(value) == expected_keys - {"artifacts"} + if ( + not actual_keys_match + or value.get("claimEligible") is not False + or value.get("profileId") != "code-coverage" + or type(value.get("schemaVersion")) is not int + or value.get("schemaVersion") != 1 + or not isinstance(status, str) + or status != expected_status + or status not in {"completed", "failed"} + or not isinstance(value.get("steps"), list) + ): + raise _fail("ASEGS018", "The exported subject result does not match the fixed completed non-claiming record.") + steps = value["steps"] + if len(steps) > len(SUBJECT_RESULT_STEP_NAMES): + raise _fail("ASEGS018", "The exported subject result contains too many fixed execution steps.") + total_output_bytes = 0 + for index, step in enumerate(steps): + if ( + not isinstance(step, dict) + or set(step) != {"exitCode", "name", "outputBytes", "stderrSha256", "stdoutSha256"} + or index >= len(SUBJECT_RESULT_STEP_NAMES) + or step.get("name") != SUBJECT_RESULT_STEP_NAMES[index] + or type(step.get("exitCode")) is not int + or type(step.get("outputBytes")) is not int + or step["outputBytes"] < 0 + or not isinstance(step.get("stdoutSha256"), str) + or SUBJECT_STEP_DIGEST_PATTERN.fullmatch(step["stdoutSha256"]) is None + or not isinstance(step.get("stderrSha256"), str) + or SUBJECT_STEP_DIGEST_PATTERN.fullmatch(step["stderrSha256"]) is None + ): + raise _fail("ASEGS018", "The exported subject result contains malformed or unexpected step proof.") + total_output_bytes += step["outputBytes"] + if total_output_bytes > MAX_PROFILE_OUTPUT_BYTES: + raise _fail("ASEGS018", "The exported subject step proof exceeds its fixed output budget.") + if index + 1 < len(steps) and step["exitCode"] != 0: + raise _fail("ASEGS018", "A subject execution step failed before later steps were recorded.") + if status == "completed" and ( + tuple(step["name"] for step in steps) != SUBJECT_RESULT_STEP_NAMES + or any(step["exitCode"] != 0 for step in steps) + ): + raise _fail("ASEGS018", "The completed subject result omitted a required successful execution step.") + if status == "failed": + diagnostic = value.get("diagnostic") + if ( + not isinstance(diagnostic, dict) + or set(diagnostic) != {"code", "message"} + or not isinstance(diagnostic.get("code"), str) + or not isinstance(diagnostic.get("message"), str) + ): + raise _fail("ASEGS018", "The failed subject result omitted its typed diagnostic.") + else: + _validate_subject_artifacts(value.get("artifacts")) + try: + canonical = (json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii") + except (TypeError, ValueError, RecursionError): + raise _fail("ASEGS018", "The exported subject result could not be canonicalized safely.") from None + if content != canonical: + raise _fail("ASEGS018", "The exported subject result is not canonical; no claim may be issued.") + return value + + +def _validate_subject_artifacts(value: Any) -> None: + if not isinstance(value, list) or len(value) != len(SUBJECT_ARTIFACTS): + raise _fail("ASEGS021", "The completed subject result omitted its fixed coverage artifact index.") + for artifact, (logical_name, relative_path, maximum_bytes) in zip(value, SUBJECT_ARTIFACTS, strict=True): + if ( + not isinstance(artifact, dict) + or set(artifact) != {"logicalName", "relativePath", "byteCount", "sha256"} + or artifact.get("logicalName") != logical_name + or artifact.get("relativePath") != relative_path + or type(artifact.get("byteCount")) is not int + or not 0 < artifact["byteCount"] <= maximum_bytes + or not isinstance(artifact.get("sha256"), str) + or SUBJECT_STEP_DIGEST_PATTERN.fullmatch(artifact["sha256"]) is None + ): + raise _fail("ASEGS021", "The completed subject result contains an unsafe or malformed coverage artifact index.") + + +def _open_directory_without_symlinks(path: Path) -> int: + """Open every path component as a directory descriptor without following links.""" + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC + descriptor = os.open(path.anchor, flags) + try: + for component in path.parts[1:]: + child = os.open(component, flags, dir_fd=descriptor) + os.close(descriptor) + descriptor = child + return descriptor + except BaseException: + os.close(descriptor) + raise + + +def _check_artifact_export_deadline(deadline: float) -> None: + if time.monotonic() > deadline: + raise _fail("ASEGS021", "A fixed coverage artifact export exceeded its two-minute bound.") + + +def _artifact_stat_identity(value: os.stat_result) -> tuple[int, int, int, int, int, int, int]: + return ( + value.st_dev, + value.st_ino, + value.st_mode, + value.st_nlink, + value.st_size, + value.st_mtime_ns, + value.st_ctime_ns, + ) + + +def _export_subject_artifacts( + scratch_mountpoint: Path, + destination: Path, + artifact_index: Any, + *, + effective_uid: int, +) -> None: + """Copy only the indexed fixed artifacts into an exclusive private host directory. + + Source and destination paths are walked through directory descriptors with + no-follow flags. Each source must remain a single-link regular file whose + exact length and digest match the already validated completed result index. + This private export is diagnostic input for a later handoff and never makes + a run claim-eligible. + """ + try: + _validate_subject_artifacts(artifact_index) + except SubjectLauncherError: + raise _fail("ASEGS021", "The completed result has a missing or unsafe fixed coverage artifact index.") from None + artifacts = artifact_index + if sum(artifact["byteCount"] for artifact in artifacts) > MAX_EXPORTED_ARTIFACT_BYTES: + raise _fail("ASEGS021", "The fixed coverage artifacts exceed their aggregate export budget.") + + source_root_fd = -1 + destination_fd = -1 + source_directory_fds: list[int] = [] + source_file_fd = -1 + destination_file_fd = -1 + created_names: list[str] = [] + try: + source_root_fd = _open_directory_without_symlinks(scratch_mountpoint) + destination_fd = _open_directory_without_symlinks(destination) + destination_stat = os.fstat(destination_fd) + if ( + not stat.S_ISDIR(destination_stat.st_mode) + or stat.S_IMODE(destination_stat.st_mode) != 0o700 + or destination_stat.st_uid != effective_uid + ): + raise _fail("ASEGS021", "The artifact export directory is not a private mode-0700 directory.") + + aggregate_bytes = 0 + for (_logical_name, relative_path, maximum_bytes), artifact, export_name in zip( + SUBJECT_ARTIFACTS, artifacts, SUBJECT_ARTIFACT_EXPORT_NAMES, strict=True + ): + deadline = time.monotonic() + ARTIFACT_EXPORT_TIMEOUT_SECONDS + source_directory_fd = source_root_fd + source_directory_fds = [] + components = relative_path.split("/") + for component in components[:-1]: + _check_artifact_export_deadline(deadline) + child_directory_fd = os.open( + component, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=source_directory_fd, + ) + source_directory_fds.append(child_directory_fd) + source_directory_fd = child_directory_fd + _check_artifact_export_deadline(deadline) + _check_artifact_export_deadline(deadline) + source_file_fd = os.open( + components[-1], + os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=source_directory_fd, + ) + _check_artifact_export_deadline(deadline) + before = os.fstat(source_file_fd) + declared_bytes = artifact["byteCount"] + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or before.st_size <= 0 + or before.st_size > maximum_bytes + or before.st_size != declared_bytes + ): + raise _fail("ASEGS021", "A fixed coverage artifact has an unsafe file type or length.") + + destination_file_fd = os.open( + export_name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, + dir_fd=destination_fd, + ) + created_names.append(export_name) + os.fchmod(destination_file_fd, 0o600) + digest = hashlib.sha256() + copied_bytes = 0 + while True: + _check_artifact_export_deadline(deadline) + chunk = os.read(source_file_fd, min(ARTIFACT_EXPORT_READ_BYTES, declared_bytes + 1 - copied_bytes)) + _check_artifact_export_deadline(deadline) + if not chunk: + break + copied_bytes += len(chunk) + aggregate_bytes += len(chunk) + if copied_bytes > declared_bytes or copied_bytes > maximum_bytes: + raise _fail("ASEGS021", "A fixed coverage artifact grew beyond its indexed length.") + if aggregate_bytes > MAX_EXPORTED_ARTIFACT_BYTES: + raise _fail("ASEGS021", "The fixed coverage artifacts exceed their aggregate export budget.") + digest.update(chunk) + chunk_offset = 0 + while chunk_offset < len(chunk): + _check_artifact_export_deadline(deadline) + written = os.write(destination_file_fd, chunk[chunk_offset:]) + _check_artifact_export_deadline(deadline) + if written <= 0: + raise _fail("ASEGS021", "A fixed coverage artifact could not be written completely.") + chunk_offset += written + + after = os.fstat(source_file_fd) + if ( + _artifact_stat_identity(before) != _artifact_stat_identity(after) + or copied_bytes != declared_bytes + or digest.hexdigest() != artifact["sha256"] + ): + raise _fail("ASEGS021", "A fixed coverage artifact changed or disagreed with its indexed digest.") + _check_artifact_export_deadline(deadline) + os.fsync(destination_file_fd) + _check_artifact_export_deadline(deadline) + destination_stat = os.fstat(destination_file_fd) + if ( + not stat.S_ISREG(destination_stat.st_mode) + or destination_stat.st_nlink != 1 + or stat.S_IMODE(destination_stat.st_mode) != 0o600 + or destination_stat.st_size != declared_bytes + ): + raise _fail("ASEGS021", "A fixed coverage artifact export has unsafe destination metadata.") + os.close(destination_file_fd) + destination_file_fd = -1 + os.close(source_file_fd) + source_file_fd = -1 + for descriptor in reversed(source_directory_fds): + os.close(descriptor) + source_directory_fds = [] + + os.fsync(destination_fd) + except SubjectLauncherError: + for descriptor_name in ("destination_file_fd", "source_file_fd"): + descriptor = locals()[descriptor_name] + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + if descriptor_name == "destination_file_fd": + destination_file_fd = -1 + else: + source_file_fd = -1 + for name in reversed(created_names): + if destination_fd >= 0: + try: + os.unlink(name, dir_fd=destination_fd) + except OSError: + pass + raise + except OSError: + for descriptor_name in ("destination_file_fd", "source_file_fd"): + descriptor = locals()[descriptor_name] + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + if descriptor_name == "destination_file_fd": + destination_file_fd = -1 + else: + source_file_fd = -1 + for name in reversed(created_names): + if destination_fd >= 0: + try: + os.unlink(name, dir_fd=destination_fd) + except OSError: + pass + raise _fail("ASEGS021", "The fixed coverage artifacts could not be exported safely.") from None + finally: + for descriptor in (destination_file_fd, source_file_fd, *reversed(source_directory_fds), destination_fd, source_root_fd): + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + + +def _remove_artifact_export_directory(path: Path, runner_temp: Path, *, effective_uid: int) -> None: + """Remove this run's fixed export files and empty private directory without following links.""" + parent_fd = -1 + directory_fd = -1 + try: + parent_fd = _open_directory_without_symlinks(runner_temp) + try: + entry_stat = os.stat(path.name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + return + if not stat.S_ISDIR(entry_stat.st_mode): + raise _fail("ASEGS017", "The private artifact export directory changed type during cleanup.") + directory_fd = os.open( + path.name, + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=parent_fd, + ) + directory_stat = os.fstat(directory_fd) + if ( + directory_stat.st_uid != effective_uid + or stat.S_IMODE(directory_stat.st_mode) != 0o700 + ): + raise _fail("ASEGS017", "The private artifact export directory changed permissions during cleanup.") + for name in SUBJECT_ARTIFACT_EXPORT_NAMES: + try: + os.unlink(name, dir_fd=directory_fd) + except FileNotFoundError: + pass + os.close(directory_fd) + directory_fd = -1 + os.rmdir(path.name, dir_fd=parent_fd) + except SubjectLauncherError: + raise + except OSError: + raise _fail("ASEGS017", "The private artifact export directory could not be removed safely.") from None + finally: + for descriptor in (directory_fd, parent_fd): + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + + +def _write_subject_result_export(scratch: Path, content: bytes) -> None: + result_path = scratch / SUBJECT_RESULT_RELATIVE_PATH + descriptor = -1 + created = False + try: + descriptor = os.open( + result_path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + created = True + with os.fdopen(descriptor, "wb") as output: + descriptor = -1 + output.write(content) + output.flush() + os.fsync(output.fileno()) + except OSError: + if descriptor >= 0: + try: + os.close(descriptor) + except OSError: + pass + if created: + try: + result_path.unlink() + except OSError: + pass + raise _fail("ASEGS018", "The bounded subject result could not be saved safely; no claim may be issued.") from None + + +def _export_subject_result(scratch: Path, content: bytes, *, expected_status: str) -> Mapping[str, Any]: + value = _validate_subject_result_content(content, expected_status=expected_status) + _write_subject_result_export(scratch, content) + return value + + +def _check_cancel(cancel_event: threading.Event) -> None: + if cancel_event.is_set(): + raise _fail("ASEGS013", "Subject execution was cancelled.") + + +def _raise_process_error(error: Exception, stage: str) -> None: + if isinstance(error, _ProcessCancelled): + raise _fail("ASEGS013", f"Subject execution was cancelled during {stage}.") from None + if isinstance(error, _ProcessTimedOut): + raise _fail("ASEGS014", f"The bounded {stage} deadline expired.") from None + if isinstance(error, _ProcessOutputExceeded): + raise _fail("ASEGS015", f"The bounded {stage} output limit was exceeded.") from None + if isinstance(error, _ProcessCouldNotStop): + raise _fail("ASEGS016", f"The {stage} process could not be stopped safely.") from None + if isinstance(error, _ProcessStartFailed): + raise _fail("ASEGS008", f"The trusted process could not start during {stage}.") from None + raise error + + +def launch_subject( + *, + subject_checkout: str | os.PathLike[str], + image_digest: str, + scratch_directory: str | os.PathLike[str], + profile_id: str, + source_diff: str | os.PathLike[str], + source_diff_sha256: str, + artifact_export_directory: str | os.PathLike[str], + limits: SubjectLimits, + cancel_event: threading.Event | None = None, + _environment: Mapping[str, str] | None = None, + _system_name: str | None = None, + _effective_uid: int | None = None, + _engine_path: str | None = None, + _host_mount_verifier: Callable[..., None] | None = None, + _command_executor: CommandExecutor = _run_command, + supervisor_client: CleanupSupervisorClient | None = None, +) -> SubjectRunResult: + """Run the private fixed profile and optionally export its indexed artifacts. + + ``artifact_export_directory`` is a required, fresh direct child of + ``RUNNER_TEMP``. For ``code-coverage`` it receives only three fixed + basenames after a zero-exit attached run, a completed validated artifact + index, and an independent stopped-container inspection. Each file is + bounded and checked against that index. This private export is diagnostic + material only; ``claim_eligible`` remains false for every result. The fixed + host-side envelope observation is returned only after live OCI inspection + and supervisor cleanup. It does not independently attest the checkout. + """ + _validate_limits(limits) + profile_arguments = _validate_profile(profile_id) + diff_path = _validate_source_diff(source_diff, source_diff_sha256) + profile_arguments = (*profile_arguments, f"--diff-sha256={source_diff_sha256}") + _validate_image_reference(image_digest) + subject_root = _validate_subject_root(subject_checkout) + env = dict(os.environ if _environment is None else _environment) + system_name = platform.system() if _system_name is None else _system_name + effective_uid = os.geteuid() if _effective_uid is None else _effective_uid + runner_temp, home, runtime = _validate_runner_context( + env, + system_name=system_name, + effective_uid=effective_uid, + ) + scratch = _validate_scratch_path(scratch_directory, runner_temp) + artifact_export = _validate_artifact_export_path(artifact_export_directory, runner_temp) + if _paths_overlap(scratch, subject_root): + raise _fail("ASEGS002", "The subject checkout and scratch directory must be disjoint.") + if _paths_overlap(artifact_export, subject_root): + raise _fail("ASEGS021", "The artifact export directory must be disjoint from the subject checkout.") + if ( + diff_path == subject_root + or subject_root in diff_path.parents + or diff_path == scratch + or scratch in diff_path.parents + ): + raise _fail( + "ASEGS020", "The controller source diff must be outside the subject checkout and scratch directory." + ) + if _paths_overlap(artifact_export, diff_path) or _paths_overlap(artifact_export, scratch): + raise _fail("ASEGS021", "The artifact export directory must be disjoint from the source diff and scratch.") + + event = cancel_event if cancel_event is not None else threading.Event() + host_gid = os.getegid() + _check_cancel(event) + engine = _resolve_podman() if _engine_path is None else _engine_path + # Only the trusted engine receives host paths. No GitHub token, workflow + # variable, subject environment, or socket endpoint is inherited. + engine_environment = { + "PATH": ENGINE_PATH, + "HOME": str(home), + "XDG_RUNTIME_DIR": str(runtime), + "TMPDIR": str(runner_temp), + "REGISTRY_AUTH_FILE": "/dev/null", + } + try: + _preflight_rootless_engine( + engine, + environment=engine_environment, + cancel_event=event, + executor=_command_executor, + ) + _check_cancel(event) + _verify_local_image( + engine, + image_digest, + environment=engine_environment, + cancel_event=event, + executor=_command_executor, + ) + except SubjectLauncherError: + raise + except (_ProcessCancelled, _ProcessTimedOut, _ProcessOutputExceeded, _ProcessStartFailed, _ProcessCouldNotStop) as exc: + _raise_process_error(exc, "OCI preflight") + + try: + os.mkdir(scratch, 0o700) + os.chmod(scratch, 0o700) + except OSError: + raise _fail("ASEGS002", "The new scratch directory could not be created safely.") from None + + scratch_stat = scratch.stat() + if not stat.S_ISDIR(scratch_stat.st_mode) or stat.S_IMODE(scratch_stat.st_mode) != 0o700: + raise _fail("ASEGS002", "The new scratch directory permissions are unsafe.") + + scratch_mountpoint = scratch / f"quota-limited-scratch-{secrets.token_hex(8)}" + try: + scratch_mountpoint.mkdir(mode=0o700) + os.chmod(scratch_mountpoint, 0o700) + except OSError: + raise _fail("ASEGS002", "The private scratch mountpoint could not be created safely.") from None + + run_id = env["GITHUB_RUN_ID"] + attempt = env["GITHUB_RUN_ATTEMPT"] + container_name = f"ase-subject-{run_id}-{attempt}-{secrets.token_hex(6)}" + supervisor = supervisor_client or SubjectCleanupSupervisorClient( + runner_temp=runner_temp, + home=home, + runtime=runtime, + executor=_command_executor, + ) + try: + supervisor_session = supervisor.start( + container_name=container_name, + scratch_directory=scratch, + mountpoint=scratch_mountpoint, + runner_temp=runner_temp, + home=home, + runtime=runtime, + parent_pid=os.getpid(), + ) + if not isinstance(supervisor_session, SupervisorSession) or supervisor_session.ready is not True: + raise _fail("ASEGS017", "The cleanup supervisor did not complete its readiness handshake.") + owner_token = supervisor_session.owner_token + if ( + not isinstance(owner_token, str) + or SUPERVISOR_TOKEN_PATTERN.fullmatch(owner_token) is None + or supervisor_session.owner_label != SUPERVISOR_OWNER_LABEL + ): + raise _fail("ASEGS017", "The cleanup supervisor returned an invalid ownership token.") + except SubjectLauncherError: + for directory in (scratch_mountpoint, scratch): + try: + directory.rmdir() + except OSError: + pass + raise + except Exception: + for directory in (scratch_mountpoint, scratch): + try: + directory.rmdir() + except OSError: + pass + raise _fail("ASEGS017", "The cleanup supervisor failed before subject setup.") from None + primary_error: BaseException | None = None + result: SubjectRunResult | None = None + artifact_export_created = False + envelope_observation: Mapping[str, Any] | None = None + try: + _check_cancel(event) + supervisor.assert_alive(supervisor_session) + if _paths_overlap(artifact_export, supervisor_session.state_directory): + raise _fail("ASEGS021", "The artifact export directory and supervisor state must be disjoint.") + mount_options = ( + "rw,nosuid,nodev," + f"size={MAX_PROFILE_SCRATCH_BYTES}," + f"nr_inodes={MAX_PROFILE_SCRATCH_INODES}," + f"mode=0700,uid={effective_uid},gid={host_gid}" + ) + mount_result = _command_executor( + [ + SUDO_PATH, + "-n", + "mount", + "-t", + "tmpfs", + "-o", + mount_options, + "tmpfs", + str(scratch_mountpoint), + ], + timeout_seconds=MOUNT_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=4096, + environment=engine_environment, + cancel_event=event, + ) + if mount_result.returncode != 0: + raise _fail("ASEGS019", "The quota-limited host scratch mount failed.") + mount_verifier = _verify_host_scratch_mount if _host_mount_verifier is None else _host_mount_verifier + mount_verifier(scratch_mountpoint, host_uid=effective_uid, host_gid=host_gid) + _check_cancel(event) + supervisor.assert_alive(supervisor_session) + _expect_success( + _command_executor( + _container_create_arguments( + engine, + name=container_name, + image=image_digest, + owner_token=owner_token, + subject_root=subject_root, + source_diff=diff_path, + scratch_mountpoint=scratch_mountpoint, + profile_arguments=profile_arguments, + limits=limits, + ), + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=4096, + environment=engine_environment, + cancel_event=event, + ), + "container creation", + ) + _check_cancel(event) + inspect_result = _expect_success( + _command_executor( + [engine, "--remote=false", "inspect", "--format=json", container_name], + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=MAX_ENGINE_OUTPUT_BYTES, + environment=engine_environment, + cancel_event=event, + ), + "container isolation verification", + ) + _verify_container_configuration( + inspect_result.stdout, + subject_root=subject_root, + source_diff=diff_path, + scratch_mountpoint=scratch_mountpoint, + limits=limits, + profile_arguments=profile_arguments, + owner_token=owner_token, + ) + # This record is produced by the base-owned host launcher only after + # checking the live mount, image, and OCI configuration. It is an + # observation for the separate verifier, not a claim from subject code. + envelope_observation = { + "schemaVersion": 1, + "imageDigest": image_digest, + "profileId": profile_id, + "runnerEnvironment": "github-hosted", + "runtime": "rootless-podman", + "networkMode": "none", + "rootfsReadOnlyConfigured": True, + "subjectAndDiffReadOnlyConfigured": True, + "scratchTmpfsQuotaVerified": True, + "capabilityDropConfigured": True, + "noNewPrivilegesConfigured": True, + "pidIpcUtsUserNamespacesConfiguredPrivate": True, + "resourceLimitsConfigured": True, + } + _check_cancel(event) + started = _command_executor( + [engine, "--remote=false", "start", "--attach", container_name], + timeout_seconds=limits.timeout_seconds, + maximum_output_bytes=limits.output_bytes + MAX_SUBJECT_RESULT_BYTES, + environment=engine_environment, + cancel_event=event, + ) + if len(started.stderr) > limits.output_bytes: + raise _fail("ASEGS015", "The bounded subject execution output limit was exceeded.") + execution_record: Mapping[str, Any] | None = None + if started.stdout: + execution_record = _export_subject_result( + scratch, + started.stdout, + expected_status="completed" if started.returncode == 0 else "failed", + ) + elif started.returncode == 0: + raise _fail("ASEGS018", "The completed subject omitted its bounded non-claiming result record.") + artifact_export_result: Path | None = None + if started.returncode == 0: + if execution_record is None or execution_record.get("status") != "completed": + raise _fail("ASEGS018", "The completed subject omitted its validated coverage artifact index.") + stopped_result = _expect_success( + _command_executor( + [engine, "--remote=false", "inspect", "--format=json", container_name], + timeout_seconds=ENGINE_PHASE_TIMEOUT_SECONDS, + maximum_output_bytes=MAX_ENGINE_OUTPUT_BYTES, + environment=engine_environment, + cancel_event=event, + ), + "stopped-container verification", + ) + _verify_container_stopped(stopped_result.stdout) + try: + os.mkdir(artifact_export, 0o700) + except OSError: + raise _fail("ASEGS021", "The new private artifact export directory could not be created safely.") from None + artifact_export_created = True + try: + os.chmod(artifact_export, 0o700) + _export_subject_artifacts( + scratch_mountpoint, + artifact_export, + execution_record.get("artifacts"), + effective_uid=effective_uid, + ) + except SubjectLauncherError: + raise + except BaseException: + raise _fail("ASEGS021", "The fixed coverage artifacts could not be exported safely.") from None + artifact_export_result = artifact_export + result = SubjectRunResult( + exit_code=started.returncode, + stdout=b"", + stderr=started.stderr, + scratch_directory=scratch, + execution_record=execution_record, + artifact_export_directory=artifact_export_result, + envelope_observation=envelope_observation, + ) + except BaseException as exc: + primary_error = exc + cleanup_error: SubjectLauncherError | None = None + try: + supervisor_record = supervisor.request_and_wait(supervisor_session) + SubjectCleanupSupervisorClient._validate_attestation(supervisor_record) + except SubjectLauncherError as exc: + cleanup_error = exc + except Exception: + cleanup_error = _fail("ASEGS017", "The cleanup supervisor did not attest complete cleanup.") + if primary_error is not None: + if artifact_export_created: + try: + _remove_artifact_export_directory(artifact_export, runner_temp, effective_uid=effective_uid) + except SubjectLauncherError: + pass + if isinstance(primary_error, SubjectLauncherError): + raise primary_error + if isinstance(primary_error, (_ProcessCancelled, _ProcessTimedOut, _ProcessOutputExceeded, _ProcessStartFailed, _ProcessCouldNotStop)): + _raise_process_error(primary_error, "subject execution") + if isinstance(primary_error, KeyboardInterrupt): + raise primary_error + raise _fail("ASEGS008", "The trusted OCI execution phase failed.") from None + if cleanup_error is not None: + if artifact_export_created: + _remove_artifact_export_directory(artifact_export, runner_temp, effective_uid=effective_uid) + raise cleanup_error + if result is None: + if artifact_export_created: + _remove_artifact_export_directory(artifact_export, runner_temp, effective_uid=effective_uid) + raise _fail("ASEGS008", "The trusted OCI execution phase returned no process result.") + return result + + +def _positive_cli_integer(value: str) -> int: + if not value.isascii() or not value.isdecimal() or value.startswith("0"): + raise argparse.ArgumentTypeError("must be a positive decimal integer") + try: + return int(value, 10) + except ValueError: + raise argparse.ArgumentTypeError("must be a positive decimal integer") from None + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--subject-checkout", required=True) + parser.add_argument("--image-digest", required=True) + parser.add_argument("--scratch-directory", required=True) + parser.add_argument("--profile-id", required=True) + parser.add_argument("--source-diff", required=True) + parser.add_argument("--source-diff-sha256", required=True) + parser.add_argument("--artifact-export-directory", required=True) + parser.add_argument("--timeout-seconds", required=True, type=_positive_cli_integer) + parser.add_argument("--memory-mib", required=True, type=_positive_cli_integer) + parser.add_argument("--cpu-millis", required=True, type=_positive_cli_integer) + parser.add_argument("--pids", required=True, type=_positive_cli_integer) + parser.add_argument("--output-bytes", required=True, type=_positive_cli_integer) + args = parser.parse_args(argv) + try: + result = launch_subject( + subject_checkout=args.subject_checkout, + image_digest=args.image_digest, + scratch_directory=args.scratch_directory, + profile_id=args.profile_id, + source_diff=args.source_diff, + source_diff_sha256=args.source_diff_sha256, + artifact_export_directory=args.artifact_export_directory, + limits=SubjectLimits( + timeout_seconds=args.timeout_seconds, + memory_mib=args.memory_mib, + cpu_millis=args.cpu_millis, + pids=args.pids, + output_bytes=args.output_bytes, + ), + ) + except SubjectLauncherError as exc: + print(f"{exc.code}: {exc.message}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print("ASEGS013: Subject execution was cancelled.", file=sys.stderr) + return 130 + print( + json.dumps( + { + "claimEligible": False, + "exitCode": result.exit_code, + "outputBytes": len(result.stdout) + len(result.stderr), + "profileId": args.profile_id, + }, + separators=(",", ":"), + sort_keys=True, + ) + ) + # The standalone command is deliberately non-green: only a later trusted + # verifier may convert this non-claiming execution into a CI verdict. + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-verifier-context.py b/scripts/evidence-gate-verifier-context.py new file mode 100644 index 000000000..0d11806ce --- /dev/null +++ b/scripts/evidence-gate-verifier-context.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Resolve a trusted verifier identity for the current pull-request workflow run. + +Run only from the base-owned verifier job after a fresh controller recapture. The +captured identity is trusted input; the workflow run and subject-job IDs come +from GitHub's attempt-specific API, never from a downloaded subject artifact. +This command writes no verdict and does not attest the subject checkout. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import stat +import sys +from typing import Any, Callable, Mapping +from urllib.error import HTTPError, URLError +from urllib.parse import quote, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + + +MAX_IDENTITY_BYTES = 16 * 1024 +MAX_API_BYTES = 512 * 1024 +API_TIMEOUT_SECONDS = 10 +SUBJECT_JOB_NAME = "Evidence gate subject (credentialless, non-claiming)" +REPOSITORY_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,99}/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\Z") +DECIMAL_PATTERN = re.compile(r"[1-9][0-9]{0,18}\Z") +RUN_IDENTITY_KEYS = frozenset( + {"BaseRevision", "HeadRevision", "HeadRepositoryId", "PullRequestNumber", "RepositoryId", "TargetBranch", "WorkflowRunAttempt", "WorkflowRunId"} +) +EXPECTED_RUN_IDENTITY_KEYS = RUN_IDENTITY_KEYS - {"BaseRevision", "HeadRevision"} +REVISION_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})\Z") + + +class VerifierContextError(Exception): + """Fixed diagnostic for an unavailable or inconsistent trusted identity.""" + + +def _positive(value: Any, name: str) -> int: + if type(value) is not int or value <= 0 or value > (1 << 63) - 1: + raise VerifierContextError(f"{name} is not a positive bounded integer.") + return value + + +def _environment_positive(environment: Mapping[str, str], name: str) -> int: + raw = environment.get(name, "") + if DECIMAL_PATTERN.fullmatch(raw) is None: + raise VerifierContextError(f"{name} is missing or malformed.") + return _positive(int(raw, 10), name) + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON property") + result[key] = value + return result + + +def _reject_constant(_value: str) -> None: + raise ValueError("nonstandard JSON number") + + +def _parse_object(raw: bytes, maximum: int, description: str) -> dict[str, Any]: + if len(raw) > maximum: + raise VerifierContextError(f"{description} exceeds its byte limit.") + try: + value = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_reject_constant) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError, RecursionError): + raise VerifierContextError(f"{description} is malformed JSON.") from None + if not isinstance(value, dict): + raise VerifierContextError(f"{description} is not a JSON object.") + return value + + +def _canonical(value: Mapping[str, Any]) -> bytes: + return json.dumps(value, ensure_ascii=True, separators=(",", ":"), sort_keys=True).encode("ascii") + + +def _read_identity(path: Path) -> dict[str, Any]: + try: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)) + except (OSError, ValueError): + raise VerifierContextError("The fresh controller identity is unavailable or unsafe.") from None + try: + metadata = os.fstat(descriptor) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > MAX_IDENTITY_BYTES: + raise VerifierContextError("The fresh controller identity is not a bounded regular file.") + raw = os.read(descriptor, MAX_IDENTITY_BYTES + 1) + finally: + os.close(descriptor) + identity = _parse_object(raw, MAX_IDENTITY_BYTES, "The fresh controller identity") + if set(identity) != RUN_IDENTITY_KEYS or _canonical(identity) != raw: + raise VerifierContextError("The fresh controller identity is not a canonical run identity.") + for key in RUN_IDENTITY_KEYS - {"BaseRevision", "HeadRevision", "TargetBranch"}: + _positive(identity[key], f"The {key} value") + base_revision = identity["BaseRevision"] + head_revision = identity["HeadRevision"] + if ( + not isinstance(base_revision, str) + or not isinstance(head_revision, str) + or REVISION_PATTERN.fullmatch(base_revision) is None + or REVISION_PATTERN.fullmatch(head_revision) is None + or len(base_revision) != len(head_revision) + ): + raise VerifierContextError("The fresh controller revisions are malformed.") + branch = identity["TargetBranch"] + if not isinstance(branch, str) or not branch or len(branch) > 128 or any(char.isspace() for char in branch): + raise VerifierContextError("The fresh target branch is malformed.") + return identity + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, _request: Any, _fp: Any, _code: int, _message: str, _headers: Any, _url: str) -> None: + return None + + +def _read_api(path: str, *, api_base: str, token: str) -> dict[str, Any]: + request = Request( + api_base.rstrip("/") + "/" + path, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {token}", + "X-GitHub-Api-Version": "2026-03-10", + "User-Agent": "AppSurface-evidence-gate-verifier-context", + }, + method="GET", + ) + try: + with build_opener(_NoRedirect).open(request, timeout=API_TIMEOUT_SECONDS) as response: + if response.status != 200: + raise VerifierContextError("The attempt-specific GitHub API read failed.") + length = response.headers.get("Content-Length") + if length is not None and (not length.isascii() or not length.isdecimal() or int(length) > MAX_API_BYTES): + raise VerifierContextError("The attempt-specific GitHub API response length is invalid.") + raw = response.read(MAX_API_BYTES + 1) + except VerifierContextError: + raise + except (HTTPError, URLError, TimeoutError, OSError, ValueError): + raise VerifierContextError("The attempt-specific GitHub API read failed.") from None + return _parse_object(raw, MAX_API_BYTES, "The attempt-specific GitHub API response") + + +def resolve_identity( + captured: Mapping[str, Any], + environment: Mapping[str, str], + api_get: Callable[[str], Mapping[str, Any]], +) -> dict[str, Any]: + """Bind one captured PR identity to the current base-owned run and unique subject job.""" + repository = environment.get("GITHUB_REPOSITORY", "") + if REPOSITORY_PATTERN.fullmatch(repository) is None or any( + component in {".", ".."} for component in repository.split("/") + ): + raise VerifierContextError("The trusted repository name is malformed.") + if environment.get("GITHUB_EVENT_NAME") != "pull_request_target": + raise VerifierContextError("The trusted workflow event is not pull_request_target.") + repository_id = _environment_positive(environment, "GITHUB_REPOSITORY_ID") + run_id = _environment_positive(environment, "GITHUB_RUN_ID") + attempt = _environment_positive(environment, "GITHUB_RUN_ATTEMPT") + if ( + captured.get("RepositoryId") != repository_id + or captured.get("WorkflowRunId") != run_id + or captured.get("WorkflowRunAttempt") != attempt + or captured.get("HeadRepositoryId") != repository_id + ): + raise VerifierContextError("The fresh controller identity differs from the trusted workflow context.") + + encoded_repository = quote(repository, safe="/") + prefix = f"repos/{encoded_repository}/actions/runs/{run_id}/attempts/{attempt}" + workflow = api_get(prefix) + workflow_repository = workflow.get("repository") + if ( + not isinstance(workflow_repository, dict) + or _positive(workflow.get("id"), "The API run ID") != run_id + or _positive(workflow.get("run_attempt"), "The API run attempt") != attempt + or workflow.get("event") != "pull_request_target" + or _positive(workflow_repository.get("id"), "The API repository ID") != repository_id + or not isinstance(workflow_repository.get("full_name"), str) + or workflow_repository["full_name"].casefold() != repository.casefold() + ): + raise VerifierContextError("The GitHub workflow attempt does not match the trusted controller context.") + workflow_id = _positive(workflow.get("workflow_id"), "The workflow ID") + + jobs_response = api_get(prefix + "/jobs?per_page=100") + jobs = jobs_response.get("jobs") + if ( + not isinstance(jobs, list) + or len(jobs) > 100 + or type(jobs_response.get("total_count")) is not int + or jobs_response.get("total_count") != len(jobs) + ): + raise VerifierContextError("The attempt-specific subject-job list is incomplete or malformed.") + matches = [job for job in jobs if isinstance(job, dict) and job.get("name") == SUBJECT_JOB_NAME] + if len(matches) != 1: + raise VerifierContextError("The attempt-specific subject job is missing or ambiguous.") + job = matches[0] + job_id = _positive(job.get("id"), "The subject job ID") + if ( + _positive(job.get("run_id"), "The API subject run ID") != run_id + or job.get("status") != "completed" + or job.get("conclusion") != "success" + or ("run_attempt" in job and _positive(job["run_attempt"], "The API subject run attempt") != attempt) + ): + raise VerifierContextError("The subject job is not a successful job from this run attempt.") + return { + "EventName": "pull_request_target", + "Repository": repository, + # The captured revision-bound identity has two more fields than the + # canonical EvidencePullRequestRunIdentity consumed by the .NET host. + # The verified plan carries base/head revisions separately. + "RunIdentity": {key: captured[key] for key in EXPECTED_RUN_IDENTITY_KEYS}, + "SubjectJobId": str(job_id), + "WorkflowId": str(workflow_id), + } + + +def write_new_identity(path: Path, value: Mapping[str, Any]) -> None: + try: + descriptor = os.open( + path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + with os.fdopen(descriptor, "wb") as output: + output.write(_canonical(value)) + output.flush() + os.fsync(output.fileno()) + except (OSError, ValueError): + raise VerifierContextError("The trusted verifier identity output could not be written safely.") from None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--fresh-identity", required=True) + parser.add_argument("--output", required=True) + arguments = parser.parse_args(argv) + try: + identity = _read_identity(Path(arguments.fresh_identity)) + api_base = os.environ.get("GITHUB_API_URL", "https://api.github.com") + try: + url = urlsplit(api_base) + except ValueError: + raise VerifierContextError("The trusted GitHub API endpoint is malformed.") from None + if url.scheme != "https" or not url.netloc or url.username or url.password or url.query or url.fragment: + raise VerifierContextError("The trusted GitHub API endpoint is malformed.") + token = os.environ.get("GITHUB_TOKEN", "") + if not token or len(token) > 4096 or any(char.isspace() or ord(char) < 32 for char in token): + raise VerifierContextError("The trusted GitHub API token is unavailable.") + expected = resolve_identity(identity, os.environ, lambda path: _read_api(path, api_base=api_base, token=token)) + write_new_identity(Path(arguments.output), expected) + print("evidence-gate-verifier-context: current workflow and subject-job identity captured.") + return 0 + except VerifierContextError as error: + print(f"evidence-gate-verifier-context: ASEVC001: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/evidence-gate-verify-cleanup.py b/scripts/evidence-gate-verify-cleanup.py new file mode 100644 index 000000000..25fc5a715 --- /dev/null +++ b/scripts/evidence-gate-verify-cleanup.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Require a bounded completed subject cleanup record before trusted PR verification. + +The trusted workflow requires the subject cleanup step and same-run upload to +succeed. The record remains non-claiming: its JSON does not independently +attest the subject checkout, execution envelope, or producer outputs. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import stat +import sys +from typing import Any + + +MAX_PLAN_BYTES = 1_048_576 +MAX_ATTESTATION_BYTES = 4_096 +EXPECTED_KEYS = frozenset({ + "schemaVersion", "claimEligible", "published", "status", "trigger", + "containerStatus", "mountStatus", "scratchStatus", "failureCode", + "cleanupDeadlineSeconds", +}) + + +class CleanupVerificationError(Exception): + """A stable, non-sensitive reason to reject the downloaded cleanup record.""" + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def _read_regular(path: Path, maximum_bytes: int, code: str) -> bytes: + """Read through no-follow directory descriptors, rejecting unsafe entries.""" + if not path.is_absolute() or any(part in (".", "..") for part in path.parts): + raise CleanupVerificationError(code) + directory_flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0) + # A malicious FIFO must fail fstat instead of blocking the verifier at open. + file_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | os.O_NONBLOCK + descriptor = -1 + try: + descriptor = os.open("/", directory_flags) + for part in path.parts[1:-1]: + next_descriptor = os.open(part, directory_flags, dir_fd=descriptor) + os.close(descriptor) + descriptor = next_descriptor + file_descriptor = os.open(path.name, file_flags, dir_fd=descriptor) + try: + metadata = os.fstat(file_descriptor) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_size <= 0 + or metadata.st_size > maximum_bytes + ): + raise CleanupVerificationError(code) + chunks: list[bytes] = [] + remaining = metadata.st_size + while remaining: + chunk = os.read(file_descriptor, remaining) + if not chunk: + raise CleanupVerificationError(code) + chunks.append(chunk) + remaining -= len(chunk) + if os.read(file_descriptor, 1): + raise CleanupVerificationError(code) + return b"".join(chunks) + finally: + os.close(file_descriptor) + except (OSError, OverflowError, ValueError): + raise CleanupVerificationError(code) from None + finally: + if descriptor >= 0: + os.close(descriptor) + + +def _parse_json(payload: bytes, code: str) -> dict[str, Any]: + try: + document = json.loads( + payload.decode("ascii"), + object_pairs_hook=_unique_object, + ) + except (UnicodeError, ValueError, RecursionError): + raise CleanupVerificationError(code) from None + if not isinstance(document, dict): + raise CleanupVerificationError(code) + return document + + +def verify_cleanup(plan_path: Path, attestation_path: Path) -> None: + """Require completion for coverage; reject an unexpected record for empty work.""" + plan = _parse_json(_read_regular(plan_path, MAX_PLAN_BYTES, "ASEGC001"), "ASEGC001") + profile = plan.get("Profile") + profile_id = profile.get("Id") if isinstance(profile, dict) else None + if profile_id == "documentation-only": + if os.path.lexists(attestation_path): + raise CleanupVerificationError("ASEGC004") + return + if profile_id != "code-coverage": + raise CleanupVerificationError("ASEGC004") + + payload = _read_regular(attestation_path, MAX_ATTESTATION_BYTES, "ASEGC002") + record = _parse_json(payload, "ASEGC002") + if set(record) != EXPECTED_KEYS: + raise CleanupVerificationError("ASEGC002") + if ( + type(record["schemaVersion"]) is not int + or record["schemaVersion"] != 1 + or record["claimEligible"] is not False + or record["published"] is not False + or record["status"] != "complete" + or record["trigger"] not in ("request", "parent-exit") + or record["containerStatus"] not in ("removed", "absent") + or record["mountStatus"] not in ("unmounted", "absent") + or record["scratchStatus"] not in ("removed", "absent") + or record["failureCode"] != "none" + or type(record["cleanupDeadlineSeconds"]) is not int + or record["cleanupDeadlineSeconds"] != 600 + ): + raise CleanupVerificationError("ASEGC003") + expected = (json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + if payload != expected: + raise CleanupVerificationError("ASEGC002") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--plan", required=True, type=Path) + parser.add_argument("--attestation", required=True, type=Path) + arguments = parser.parse_args() + try: + verify_cleanup(arguments.plan, arguments.attestation) + except CleanupVerificationError as error: + print(f"{error}: Trusted cleanup verification failed closed.", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/tests/test_evidence_gate_build_offline_feed.py b/scripts/tests/test_evidence_gate_build_offline_feed.py new file mode 100644 index 000000000..b02e3c1df --- /dev/null +++ b/scripts/tests/test_evidence_gate_build_offline_feed.py @@ -0,0 +1,677 @@ +"""Synthetic lock/cache tests for the trusted offline NuGet feed builder.""" + +from __future__ import annotations + +import base64 +from dataclasses import replace +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-build-offline-feed.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_build_offline_feed", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +offline_feed = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = offline_feed +SPEC.loader.exec_module(offline_feed) + + +class EvidenceGateBuildOfflineFeedTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory(prefix="evidence-gate-offline-feed-tests-") + self.root = Path(self.temporary_directory.name).resolve() + self.checkout = self.root / "trusted-checkout" + self.checkout.mkdir() + self.cache = self.root / "global-packages" + self.cache.mkdir() + self.output = self.root / "feed" + self.solution_relative_path = "Synthetic.slnx" + self.solution_projects: set[str] = set() + self.verifier_calls: list[str] = [] + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + @staticmethod + def content_hash(package_bytes: bytes) -> str: + digest = hashlib.sha512(b"synthetic NuGet content hash\x00" + package_bytes).digest() + return base64.b64encode(digest).decode("ascii") + + def package_entry( + self, + package_id: str = "Example.Package", + version: str = "1.2.3", + package_bytes: bytes = b"synthetic nupkg bytes", + ) -> tuple[str, dict[str, str], bytes]: + return package_id, { + "type": "Direct", + "requested": f"[{version}, )", + "resolved": version, + "contentHash": self.content_hash(package_bytes), + }, package_bytes + + def write_lock( + self, + relative_path: str, + entries: dict[str, dict[str, object]], + *, + select_project: bool = True, + lock_property: str | None = None, + ) -> Path: + path = self.checkout / relative_path + path.parent.mkdir(parents=True, exist_ok=True) + project_path = path.parent / "Synthetic.csproj" + project_xml = ( + f"{lock_property}" + "" + if lock_property is not None + else "" + ) + project_path.write_text(project_xml, encoding="utf-8") + if select_project: + self.solution_projects.add(project_path.relative_to(self.checkout).as_posix()) + path.write_text( + json.dumps({"version": 2, "dependencies": {"net10.0": entries}}), + encoding="utf-8", + ) + return path + + def cache_package( + self, + package_id: str, + version: str, + package_bytes: bytes, + ) -> Path: + package_id = package_id.lower() + version = version.lower() + directory = self.cache / package_id / version + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"{package_id}.{version}.nupkg" + path.write_bytes(package_bytes) + return path + + def write_solution(self, project_paths: set[str] | None = None) -> Path: + selected_projects = self.solution_projects if project_paths is None else project_paths + project_elements = "".join( + f'' + for path in sorted(selected_projects) + ) + solution_path = self.checkout / self.solution_relative_path + solution_path.write_text(f"{project_elements}", encoding="utf-8") + return solution_path + + def fake_content_hash_verifier(self, archive_path: Path) -> str: + self.assertTrue(archive_path.name.startswith(".offline-feed-")) + self.verifier_calls.append(archive_path.name) + return self.content_hash(archive_path.read_bytes()) + + def build( + self, + *, + limits: object | None = None, + write_solution: bool = True, + ) -> offline_feed.FeedBuildResult: + if write_solution: + self.write_solution() + options: dict[str, object] = {} + if limits is not None: + options["limits"] = limits + options["_content_hash_verifier"] = self.fake_content_hash_verifier + return offline_feed.build_offline_feed( + self.checkout, + self.solution_relative_path, + self.cache, + self.output, + **options, + ) + + def test_success_selects_only_linux_project_locks_and_creates_flat_verified_feed(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("DefaultProject/packages.lock.json", {package_id: entry}) + self.write_lock( + "RidProject/packages.osx-arm64.lock.json", + { + "Uncached.Mac.Package": { + "type": "Transitive", + "resolved": "7.8.9", + "contentHash": self.content_hash(b"not in Linux cache"), + } + }, + select_project=False, + ) + self.write_lock( + "RidProject/packages.linux-x64.lock.json", + { + "Example.Rid.Package": { + "type": "Transitive", + "resolved": "4.5.6-beta.1", + "contentHash": self.content_hash(b"rid archive"), + } + }, + lock_property="packages.$(NETCoreSdkRuntimeIdentifier).lock.json", + ) + rid_bytes = b"rid archive" + self.cache_package(package_id, "1.2.3", package_bytes) + self.cache_package("Example.Rid.Package", "4.5.6-beta.1", rid_bytes) + + result = self.build() + + self.assertEqual(2, result.lock_file_count) + self.assertEqual(2, result.package_count) + self.assertEqual(len(package_bytes) + len(rid_bytes), result.package_bytes) + self.assertEqual( + {"example.package.1.2.3.nupkg", "example.rid.package.4.5.6-beta.1.nupkg"}, + {path.name for path in self.output.iterdir()}, + ) + self.assertEqual(package_bytes, (self.output / "example.package.1.2.3.nupkg").read_bytes()) + self.assertEqual(2, len(self.verifier_calls)) + self.assertNotEqual( + base64.b64encode(hashlib.sha512(package_bytes).digest()).decode("ascii"), + entry["contentHash"], + ) + + def test_duplicate_identity_across_frameworks_and_locks_is_emitted_once(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("A/packages.lock.json", {package_id: entry}) + self.write_lock("B/packages.lock.json", {package_id.lower(): entry}) + self.cache_package(package_id, "1.2.3", package_bytes) + + result = self.build() + + self.assertEqual(1, result.package_count) + self.assertEqual(1, len(list(self.output.iterdir()))) + + def test_project_references_are_not_treated_as_nuget_archives(self) -> None: + self.write_lock( + "Project/packages.lock.json", + { + "sample.project": { + "type": "Project", + "dependencies": {"Example.Package": "[1.2.3, )"}, + }, + "Example.Package": { + "type": "CentralTransitive", + "resolved": "1.2.3", + "contentHash": self.content_hash(b"archive"), + }, + }, + ) + self.cache_package("Example.Package", "1.2.3", b"archive") + + result = self.build() + + self.assertEqual(1, result.package_count) + + def test_declared_pinned_project_sdk_is_verified_and_added_to_offline_feed(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("AppHost/packages.lock.json", {package_id: entry}) + (self.checkout / "AppHost/Synthetic.csproj").write_text( + '', + encoding="utf-8", + ) + sdk_bytes = b"synthetic Aspire project SDK archive" + self.cache_package(package_id, "1.2.3", package_bytes) + self.cache_package("Aspire.AppHost.Sdk", "13.4.4", sdk_bytes) + + with patch.dict( + offline_feed.PROJECT_SDK_PACKAGE_PINS, + {("aspire.apphost.sdk", "13.4.4"): self.content_hash(sdk_bytes)}, + ): + result = self.build() + + self.assertEqual(2, result.package_count) + self.assertEqual( + {"example.package.1.2.3.nupkg", "aspire.apphost.sdk.13.4.4.nupkg"}, + {path.name for path in self.output.iterdir()}, + ) + self.assertEqual(2, len(self.verifier_calls)) + + def test_unreviewed_project_sdk_version_fails_before_feed_creation(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("AppHost/packages.lock.json", {package_id: entry}) + (self.checkout / "AppHost/Synthetic.csproj").write_text( + '', + encoding="utf-8", + ) + self.cache_package(package_id, "1.2.3", package_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "unreviewed project SDK package"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_project_sdk_pin_conflicting_with_lock_hash_fails_closed(self) -> None: + package_id, entry, package_bytes = self.package_entry( + package_id="Aspire.AppHost.Sdk", version="13.4.4", package_bytes=b"different archive" + ) + self.write_lock("AppHost/packages.lock.json", {package_id: entry}) + (self.checkout / "AppHost/Synthetic.csproj").write_text( + '', + encoding="utf-8", + ) + self.cache_package(package_id, "13.4.4", package_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "pin disagrees"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_pinned_project_sdk_missing_from_cache_fails_before_feed_creation(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("AppHost/packages.lock.json", {package_id: entry}) + (self.checkout / "AppHost/Synthetic.csproj").write_text( + '', + encoding="utf-8", + ) + self.cache_package(package_id, "1.2.3", package_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "missing from the supplied NuGet global cache"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_unreviewed_root_project_sdk_fails_before_feed_creation(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("AppHost/packages.lock.json", {package_id: entry}) + (self.checkout / "AppHost/Synthetic.csproj").write_text( + '', encoding="utf-8" + ) + self.cache_package(package_id, "1.2.3", package_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "unreviewed root project SDK"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_conflicting_content_hashes_fail_before_output_creation(self) -> None: + package_id, first, first_bytes = self.package_entry(package_bytes=b"first") + _package_id, conflicting, _conflicting_bytes = self.package_entry(package_bytes=b"second") + self.write_lock("A/packages.lock.json", {package_id: first}) + self.write_lock( + "B/packages.linux-x64.lock.json", + {package_id.lower(): conflicting}, + lock_property="packages.$(NETCoreSdkRuntimeIdentifier).lock.json", + ) + self.cache_package(package_id, "1.2.3", first_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "disagree"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_missing_archive_fails_before_output_creation(self) -> None: + package_id, entry, _package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + (self.cache / package_id.lower() / "1.2.3").mkdir(parents=True) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "missing"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_missing_selected_linux_lock_fails_even_when_macos_lock_exists(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock( + "Project/packages.osx-arm64.lock.json", + {package_id: entry}, + lock_property="packages.$(NETCoreSdkRuntimeIdentifier).lock.json", + ) + self.cache_package(package_id, "1.2.3", package_bytes) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "Linux dependency lock"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_ambiguous_or_unbounded_project_xml_fails_before_feed_creation(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.cache_package(package_id, "1.2.3", package_bytes) + project = self.checkout / "Project/Synthetic.csproj" + project.write_text( + "packages.lock.json" + "packages.other.lock.json", + encoding="utf-8", + ) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "ambiguous"): + self.build() + + project.write_text("", encoding="utf-8") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "byte limit"): + self.build(limits=replace(offline_feed.DEFAULT_LIMITS, max_project_file_bytes=1)) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "total byte limit"): + self.build(limits=replace(offline_feed.DEFAULT_LIMITS, max_total_project_bytes=1)) + self.assertFalse(self.output.exists()) + + def test_archive_with_wrong_nuget_content_hash_fails_and_removes_partial_output(self) -> None: + package_id, entry, _package_bytes = self.package_entry(package_bytes=b"locked bytes") + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.cache_package(package_id, "1.2.3", b"different bytes") + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "NuGet.*contentHash"): + self.build() + + self.assertFalse(self.output.exists()) + + def test_later_hash_failure_removes_earlier_verified_packages(self) -> None: + first_id, first_entry, first_bytes = self.package_entry("First.Package", package_bytes=b"first archive") + second_id, second_entry, second_bytes = self.package_entry("Second.Package", package_bytes=b"second archive") + self.write_lock("Project/packages.lock.json", {first_id: first_entry, second_id: second_entry}) + self.cache_package(first_id, "1.2.3", first_bytes) + self.cache_package(second_id, "1.2.3", second_bytes) + self.write_solution() + verified: list[Path] = [] + + def fail_second(archive_path: Path) -> str: + verified.append(archive_path) + if len(verified) == 2: + self.assertTrue((self.output / "first.package.1.2.3.nupkg").is_file()) + return self.content_hash(b"wrong archive") + return self.content_hash(archive_path.read_bytes()) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "NuGet.*contentHash"): + offline_feed.build_offline_feed( + self.checkout, + self.solution_relative_path, + self.cache, + self.output, + _content_hash_verifier=fail_second, + ) + + self.assertEqual(2, len(verified)) + self.assertFalse(self.output.exists()) + + def test_symlinked_lock_file_and_symlinked_lock_directory_fail_closed(self) -> None: + package_id, entry, _package_bytes = self.package_entry() + lock = self.write_lock("Project/packages.lock.json", {package_id: entry}) + outside = self.root / "outside.lock.json" + outside.write_text(json.dumps({"version": 2, "dependencies": {}}), encoding="utf-8") + lock.unlink() + lock.symlink_to(outside) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build() + + lock.unlink() + outside_project = self.root / "outside-project" + outside_project.mkdir() + (outside_project / "Synthetic.csproj").write_text("", encoding="utf-8") + (outside_project / "packages.lock.json").write_text( + json.dumps({"version": 2, "dependencies": {"net10.0": {}}}), + encoding="utf-8", + ) + linked_directory = self.checkout / "linked-project" + linked_directory.symlink_to(outside_project, target_is_directory=True) + self.solution_projects = {"linked-project/Synthetic.csproj"} + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build() + + def test_symlinked_checkout_argument_is_rejected(self) -> None: + package_id, entry, _package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.write_solution() + link = self.root / "checkout-link" + link.symlink_to(self.checkout, target_is_directory=True) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + offline_feed.build_offline_feed(link, self.solution_relative_path, self.cache, self.output) + + def test_symlinked_cache_id_version_or_archive_is_rejected(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + outside = self.root / "package-outside" + outside.mkdir() + (outside / "1.2.3").mkdir() + (outside / "1.2.3" / "example.package.1.2.3.nupkg").write_bytes(package_bytes) + (self.cache / "example.package").symlink_to(outside, target_is_directory=True) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build() + + def test_symlinked_cache_version_and_archive_are_rejected(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + outside = self.root / "outside-version" + outside.mkdir() + (outside / "example.package.1.2.3.nupkg").write_bytes(package_bytes) + (self.cache / "example.package").mkdir() + (self.cache / "example.package" / "1.2.3").symlink_to(outside, target_is_directory=True) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build() + + (self.cache / "example.package" / "1.2.3").unlink() + version_directory = self.cache / "example.package" / "1.2.3" + version_directory.mkdir() + (version_directory / "example.package.1.2.3.nupkg").symlink_to(outside / "example.package.1.2.3.nupkg") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build() + + def test_existing_output_and_output_under_input_roots_are_rejected(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.cache_package(package_id, "1.2.3", package_bytes) + self.output.mkdir() + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "must not already exist"): + self.build() + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "separate"): + offline_feed.build_offline_feed( + self.checkout, + self.solution_relative_path, + self.cache, + self.checkout / "feed", + _content_hash_verifier=self.fake_content_hash_verifier, + ) + + def test_malformed_duplicate_json_properties_and_unsafe_package_paths_fail(self) -> None: + lock = self.write_lock("Project/packages.lock.json", {}) + lock.write_text('{"version":2,"version":2,"dependencies":{}}', encoding="utf-8") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "malformed"): + self.build() + + lock.unlink() + self.write_lock( + "Project/packages.lock.json", + {"../escape": {"type": "Direct", "resolved": "1.2.3", "contentHash": "A" * 88}}, + ) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "package ID"): + self.build() + + def test_missing_hash_or_invalid_hash_fails_closed(self) -> None: + self.write_lock( + "Project/packages.lock.json", + {"Example.Package": {"type": "Direct", "resolved": "1.2.3", "contentHash": "not base64"}}, + ) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "base64"): + self.build() + + def test_lock_file_count_total_bytes_and_package_budgets_are_enforced(self) -> None: + package_id, entry, package_bytes = self.package_entry(package_bytes=b"four") + self.write_lock("A/packages.lock.json", {package_id: entry}) + self.write_lock( + "B/packages.linux-x64.lock.json", + {"Second.Package": { + "type": "Transitive", + "resolved": "2.3.4", + "contentHash": self.content_hash(b"other"), + }}, + lock_property="packages.$(NETCoreSdkRuntimeIdentifier).lock.json", + ) + self.cache_package(package_id, "1.2.3", package_bytes) + self.cache_package("Second.Package", "2.3.4", b"other") + + count_limits = replace(offline_feed.DEFAULT_LIMITS, max_lock_files=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "lock-file-count"): + self.build(limits=count_limits) + + byte_limits = replace(offline_feed.DEFAULT_LIMITS, max_total_lock_bytes=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "lock-byte"): + self.build(limits=byte_limits) + + package_limits = replace(offline_feed.DEFAULT_LIMITS, max_package_bytes=3) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "per-file byte"): + self.build(limits=package_limits) + + count_package_limits = replace(offline_feed.DEFAULT_LIMITS, max_packages=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "distinct-package-count"): + self.build(limits=count_package_limits) + + single_lock_limits = replace(offline_feed.DEFAULT_LIMITS, max_lock_file_bytes=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "lock file"): + self.build(limits=single_lock_limits) + + total_package_limits = replace(offline_feed.DEFAULT_LIMITS, max_total_package_bytes=3) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "total byte"): + self.build(limits=total_package_limits) + + selected_entry_limits = replace(offline_feed.DEFAULT_LIMITS, max_selected_directory_entries=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "Selected project directories"): + self.build(limits=selected_entry_limits) + + cache_entry_limits = replace(offline_feed.DEFAULT_LIMITS, max_cache_entries=1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "inspected-entry"): + self.build(limits=cache_entry_limits) + self.assertFalse(self.output.exists()) + + def test_unlisted_fixture_locks_do_not_contribute_missing_packages(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("SelectedProject/packages.lock.json", {package_id: entry}) + self.write_lock( + "tests/config-key-compatibility/previous-provider-plugin/packages.lock.json", + { + "Absent.Historical.Package": { + "type": "Direct", + "resolved": "9.8.7", + "contentHash": self.content_hash(b"not cached"), + } + }, + select_project=False, + ) + self.cache_package(package_id, "1.2.3", package_bytes) + + result = self.build() + + self.assertEqual(1, result.lock_file_count) + self.assertEqual(1, result.package_count) + self.assertEqual({"example.package.1.2.3.nupkg"}, {path.name for path in self.output.iterdir()}) + + def test_solution_and_selected_project_paths_reject_links_and_traversal(self) -> None: + package_id, entry, _package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + solution_path = self.write_solution() + external_solution = self.root / "external.slnx" + external_solution.write_text(solution_path.read_text(encoding="utf-8"), encoding="utf-8") + solution_path.unlink() + solution_path.symlink_to(external_solution) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + self.build(write_solution=False) + + solution_path.unlink() + solution_path.write_text('', encoding="utf-8") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "relative path"): + self.build(write_solution=False) + + def test_solution_rejects_missing_and_duplicate_project_selections(self) -> None: + self.write_lock("Project/packages.lock.json", {}) + solution_path = self.checkout / self.solution_relative_path + solution_path.write_text("", encoding="utf-8") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "no projects"): + self.build(write_solution=False) + + solution_path.write_text( + '' + '', + encoding="utf-8", + ) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "more than once"): + self.build(write_solution=False) + self.assertFalse(self.output.exists()) + + def test_output_parent_must_be_a_physical_directory(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.cache_package(package_id, "1.2.3", package_bytes) + self.write_solution() + linked_parent = self.root / "linked-output-parent" + linked_parent.symlink_to(self.root, target_is_directory=True) + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "symbolic link"): + offline_feed.build_offline_feed( + self.checkout, + self.solution_relative_path, + self.cache, + linked_parent / "feed", + _content_hash_verifier=self.fake_content_hash_verifier, + ) + self.assertFalse(self.output.exists()) + + def test_nuget_content_hash_parser_requires_one_valid_fixed_line(self) -> None: + expected = self.content_hash(b"package") + output = f"Package signature verification result: OK\nContent hash: {expected}\n".encode("utf-8") + self.assertEqual(expected, offline_feed._parse_nuget_content_hash_output(output)) + + for invalid in ( + b"No content hash\n", + f"Content hash: {expected}\nContent hash: {expected}\n".encode("ascii"), + b"Content hash: not-base64\n", + ): + with self.subTest(invalid=invalid), self.assertRaises(offline_feed.OfflineFeedError): + offline_feed._parse_nuget_content_hash_output(invalid) + + def test_nuget_verifier_requires_a_successful_bounded_process(self) -> None: + verifier = self.root / "dotnet" + archive = self.root / "package.nupkg" + archive.write_bytes(b"synthetic archive") + expected = self.content_hash(b"synthetic archive") + + def write_verifier(body: str) -> None: + verifier.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8") + verifier.chmod(0o755) + + with patch.object(offline_feed, "DOTNET_EXECUTABLES", (verifier,)): + write_verifier(f"printf '%s\\n' 'Content hash: {expected}'") + self.assertEqual(expected, offline_feed._nuget_content_hash_verifier(archive, 2, 4096)) + + write_verifier("exit 3") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "verification failed"): + offline_feed._nuget_content_hash_verifier(archive, 2, 4096) + + write_verifier("printf '%0256d\\n' 1") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "output-byte limit"): + offline_feed._nuget_content_hash_verifier(archive, 2, 128) + + write_verifier("while :; do :; done") + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "time limit"): + offline_feed._nuget_content_hash_verifier(archive, 0.05, 4096) + + def test_limits_cannot_be_raised_or_set_to_boolean(self) -> None: + package_limits = replace(offline_feed.DEFAULT_LIMITS, max_packages=offline_feed.DEFAULT_LIMITS.max_packages + 1) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "hard ceiling"): + self.build(limits=package_limits) + + invalid_limits = replace(offline_feed.DEFAULT_LIMITS, max_packages=True) + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "hard ceiling"): + self.build(limits=invalid_limits) + + def test_successful_feed_uses_exclusive_new_output(self) -> None: + package_id, entry, package_bytes = self.package_entry() + self.write_lock("Project/packages.lock.json", {package_id: entry}) + self.cache_package(package_id, "1.2.3", package_bytes) + self.output.mkdir() + + with self.assertRaisesRegex(offline_feed.OfflineFeedError, "must not already exist"): + self.build() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_cleanup_attestation_check.py b/scripts/tests/test_evidence_gate_cleanup_attestation_check.py new file mode 100644 index 000000000..cd8457a8b --- /dev/null +++ b/scripts/tests/test_evidence_gate_cleanup_attestation_check.py @@ -0,0 +1,120 @@ +"""Failure-closed checks for the workflow's independent cleanup receipt.""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-cleanup-attestation-check.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_cleanup_attestation_check", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +checker = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(checker) + + +class CleanupAttestationCheckTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix="cleanup-check-") + self.root = Path(self.temporary.name).resolve() + self.runner_temp = self.root / "runner-temp" + self.runner_temp.mkdir(mode=0o755) + self.state = self.runner_temp / (checker.STATE_PREFIX + "a" * 32) + self.state.mkdir(mode=0o700) + self.attestation = self.state / checker.ATTESTATION_NAME + self.output = self.runner_temp / checker.OUTPUT_NAME + self.record = { + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "complete", + "trigger": "request", + "containerStatus": "removed", + "mountStatus": "unmounted", + "scratchStatus": "removed", + "failureCode": "none", + "cleanupDeadlineSeconds": 600, + } + + def tearDown(self) -> None: + self.temporary.cleanup() + + def _write(self, payload: bytes | None = None) -> bytes: + payload = payload or (json.dumps(self.record, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + self.attestation.write_bytes(payload) + self.attestation.chmod(0o600) + return payload + + def _check(self, **overrides: object) -> None: + checker.check_cleanup( + self.runner_temp, + self.output, + uid=os.geteuid(), + wait_seconds=0, + **overrides, + ) + + def test_complete_private_record_is_copied_byte_for_byte_from_runner_temp(self) -> None: + payload = self._write() + + self._check() + + self.assertEqual(payload, self.output.read_bytes()) + self.assertEqual(0o600, self.output.stat().st_mode & 0o777) + + def test_missing_or_ambiguous_supervisor_state_fails_closed(self) -> None: + self.state.rmdir() + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-state-ambiguous"): + self._check() + + self.state.mkdir(mode=0o700) + (self.runner_temp / (checker.STATE_PREFIX + "b" * 32)).mkdir(mode=0o700) + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-state-ambiguous"): + self._check() + + def test_missing_attestation_times_out_without_creating_output(self) -> None: + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-attestation-timeout"): + self._check() + self.assertFalse(self.output.exists()) + + def test_symlink_or_incomplete_attestation_fails_closed(self) -> None: + target = self.root / "forged.json" + target.write_bytes(json.dumps(self.record).encode("ascii")) + self.attestation.symlink_to(target) + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-attestation-unavailable"): + self._check() + + self.attestation.unlink() + self.record["status"] = "incomplete" + self._write() + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-incomplete"): + self._check() + self.assertFalse(self.output.exists()) + + def test_malformed_and_oversized_records_fail_closed(self) -> None: + self._write(b'{"status":"complete","status":"complete"}') + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-attestation-malformed"): + self._check() + + self._write(b"x" * (checker.MAX_ATTESTATION_BYTES + 1)) + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-attestation-unsafe"): + self._check() + + def test_state_mode_and_preexisting_output_are_rejected(self) -> None: + self._write() + self.state.chmod(0o755) + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-state-unsafe"): + self._check() + + self.state.chmod(0o700) + self.output.write_bytes(b"old") + with self.assertRaisesRegex(checker.CleanupCheckError, "cleanup-output-unsafe"): + self._check() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_controller.py b/scripts/tests/test_evidence_gate_controller.py new file mode 100644 index 000000000..86851c6be --- /dev/null +++ b/scripts/tests/test_evidence_gate_controller.py @@ -0,0 +1,664 @@ +"""Security-boundary tests for the trusted pull-request capture helper.""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest +from unittest import mock + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-controller.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_controller", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +controller = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = controller +SPEC.loader.exec_module(controller) + + +BASE_SHA = "a" * 40 +HEAD_SHA = "b" * 40 +TOKEN = "test-read-only-token-must-not-be-written" +DIFF = b"diff --git a/src/example.cs b/src/example.cs\n+trusted capture bytes\n" + + +def event_document( + *, + base_sha: str = BASE_SHA, + head_sha: str = HEAD_SHA, + head_repository_id: int = 123, + head_repository: str = "forge-trust/AppSurface", + action: str = "opened", +) -> dict[str, object]: + return { + "action": action, + "number": 777, + "repository": {"id": 123, "full_name": "forge-trust/AppSurface"}, + "pull_request": { + "number": 777, + "base": { + "ref": "main", + "sha": base_sha, + "repo": {"id": 123, "full_name": "forge-trust/AppSurface"}, + }, + "head": { + "sha": head_sha, + "repo": {"id": head_repository_id, "full_name": head_repository}, + }, + }, + } + + +def api_document( + *, + base_sha: str = BASE_SHA, + head_sha: str = HEAD_SHA, + head_repository_id: int = 123, + head_repository: str = "forge-trust/AppSurface", +) -> dict[str, object]: + return { + "number": 777, + "state": "open", + "base": { + "ref": "main", + "sha": base_sha, + "repo": {"id": 123, "full_name": "forge-trust/AppSurface"}, + }, + "head": { + "sha": head_sha, + "repo": {"id": head_repository_id, "full_name": head_repository}, + }, + } + + +class FakeApi: + def __init__(self, *responses: dict[str, object]) -> None: + self.responses = list(responses) + self.calls: list[tuple[str, int, str]] = [] + + def __call__(self, repository: str, number: int, token: str) -> dict[str, object]: + self.calls.append((repository, number, token)) + if not self.responses: + raise AssertionError("unexpected extra API call") + return self.responses.pop(0) + + +class FakeGit: + def __init__(self, source_diff: bytes = DIFF, base_sha: str = BASE_SHA, head_sha: str = HEAD_SHA) -> None: + self.source_diff = source_diff + self.base_sha = base_sha + self.head_sha = head_sha + self.calls: list[list[str]] = [] + self.object_store_paths: list[Path] = [] + + def __call__( + self, + arguments: list[str], + *, + deadline: float, + maximum_output_bytes: int, + ) -> bytes: + self.calls.append(list(arguments)) + self.assertions(deadline, maximum_output_bytes) + if "init" in arguments: + object_store = Path(arguments[-1]) + object_store.mkdir(parents=True, exist_ok=True) + (object_store / ".fixture-store").write_bytes(b"retained") + self.object_store_paths.append(object_store) + return b"" + if "fetch" in arguments: + return b"" + if "rev-parse" in arguments: + ref = arguments[-1] + if ref == "refs/evidence/base^{commit}": + return (self.base_sha + "\n").encode("ascii") + if ref == "refs/evidence/head^{commit}": + return (self.head_sha + "\n").encode("ascii") + raise AssertionError(f"unexpected ref: {ref}") + if "diff" in arguments: + return self.source_diff + raise AssertionError(f"unexpected Git command: {arguments}") + + @staticmethod + def assertions(deadline: float, maximum_output_bytes: int) -> None: + if deadline <= time.monotonic(): + raise AssertionError("Git was invoked after its deadline") + if maximum_output_bytes <= 0: + raise AssertionError("Git output limit must be positive") + + +class EvidenceGateControllerTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory(prefix="evidence-gate-tests-") + self.root = Path(self.temporary_directory.name) + self.event_path = self.root / "event.json" + self.output_path = self.root / "capture" + self.write_event(event_document()) + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + def write_event(self, event: object) -> None: + if isinstance(event, bytes): + self.event_path.write_bytes(event) + else: + self.event_path.write_text(json.dumps(event), encoding="utf-8") + + def capture( + self, + api: FakeApi | None = None, + git: FakeGit | None = None, + *, + repository: str = "forge-trust/AppSurface", + repository_id: int = 123, + target_branch: str = "main", + event_path: Path | None = None, + output_path: Path | None = None, + object_store_path: Path | None = None, + ) -> tuple[str, FakeApi, FakeGit]: + api = api or FakeApi(api_document(), api_document()) + git = git or FakeGit() + result = controller._capture_diff( + repository=repository, + repository_id=repository_id, + target_branch=target_branch, + run_id=456, + run_attempt=2, + token=TOKEN, + event_path=event_path or self.event_path, + output_path=output_path or self.output_path, + object_store_path=object_store_path, + api_client=api, + git_runner=git, + ) + return result, api, git + + def test_same_repository_capture_matches_fixed_git_diff_and_canonical_identity(self) -> None: + result, api, git = self.capture() + + self.assertEqual("captured", result) + self.assertEqual(2, len(api.calls)) + self.assertEqual([("forge-trust/AppSurface", 777, TOKEN)] * 2, api.calls) + self.assertEqual(DIFF, (self.output_path / "source.diff").read_bytes()) + self.assertEqual( + b'{"BaseRevision":"' + BASE_SHA.encode("ascii") + b'","HeadRepositoryId":123,"HeadRevision":"' + + HEAD_SHA.encode("ascii") + b'","PullRequestNumber":777,"RepositoryId":123,' + b'"TargetBranch":"main","WorkflowRunAttempt":2,"WorkflowRunId":456}', + (self.output_path / "pull-request-run-identity.json").read_bytes(), + ) + self.assertEqual( + {"pull-request-run-identity.json", "repository.git", "source.diff"}, + {path.name for path in self.output_path.iterdir()}, + ) + retained_store = self.output_path / "repository.git" + self.assertTrue(retained_store.is_dir()) + self.assertEqual(b"retained", (retained_store / ".fixture-store").read_bytes()) + self.assertEqual( + Path("repository.git"), + git.object_store_paths[0].relative_to(git.object_store_paths[0].parents[0]), + ) + output_bytes = b"".join( + path.read_bytes() for path in self.output_path.rglob("*") if path.is_file() + ) + self.assertNotIn(TOKEN.encode(), output_bytes) + + fetch = next(call for call in git.calls if "fetch" in call) + self.assertEqual( + [ + "fetch", + "--depth=1", + "--no-tags", + "--no-recurse-submodules", + "--no-write-fetch-head", + "https://github.com/forge-trust/AppSurface.git", + "+refs/heads/main:refs/evidence/base", + "+refs/pull/777/head:refs/evidence/head", + ], + fetch[3:], + ) + diff = next(call for call in git.calls if "diff" in call) + self.assertEqual( + [ + "-c", + "diff.external=", + "-c", + "diff.noprefix=false", + "-c", + "diff.mnemonicprefix=false", + "-c", + "diff.algorithm=myers", + "diff", + "--no-ext-diff", + "--no-textconv", + "--no-color", + "--binary", + "--full-index", + "--unified=3", + "--find-renames=50%", + "--find-copies=50%", + "--submodule=short", + "--ignore-submodules=none", + "--no-relative", + "--src-prefix=a/", + "--dst-prefix=b/", + BASE_SHA, + HEAD_SHA, + "--", + ], + diff[3:], + ) + self.assertTrue(all(isinstance(call, list) for call in git.calls)) + + def test_api_capture_deadline_rejects_a_delayed_response(self) -> None: + def slow_api(_repository: str, _number: int, _token: str) -> dict[str, object]: + time.sleep(0.02) + return api_document() + + with mock.patch.object(controller, "MAX_CAPTURE_SECONDS", 0.001): + with self.assertRaisesRegex(controller.ControllerError, "deadline"): + controller._capture_diff( + repository="forge-trust/AppSurface", + repository_id=123, + target_branch="main", + run_id=456, + run_attempt=2, + token=TOKEN, + event_path=self.event_path, + output_path=self.output_path, + api_client=slow_api, + git_runner=FakeGit(), + ) + self.assertFalse(self.output_path.exists()) + + def test_production_api_alarm_interrupts_a_slow_body_read(self) -> None: + if not hasattr(controller.signal, "setitimer"): + self.skipTest("The production controller requires POSIX deadline alarms.") + + def slow_read(_repository: str, _number: int, _token: str) -> dict[str, object]: + time.sleep(0.3) + return api_document() + + previous_handler = controller.signal.getsignal(controller.signal.SIGALRM) + with self.assertRaisesRegex(controller.ControllerError, "deadline"): + controller._invoke_api( + slow_read, "forge-trust/AppSurface", 777, TOKEN, + time.monotonic() + 0.03, enforce_alarm=True, + ) + self.assertIs(previous_handler, controller.signal.getsignal(controller.signal.SIGALRM)) + + def test_stale_base_or_head_is_rejected_before_git_fetch(self) -> None: + changed = "c" * 40 + cases = ( + api_document(base_sha=changed), + api_document(head_sha=changed), + ) + for current in cases: + with self.subTest(current_base=current["base"]["sha"], current_head=current["head"]["sha"]): + api = FakeApi(current) + git = FakeGit() + with self.assertRaisesRegex(controller.ControllerError, "stale"): + self.capture(api=api, git=git) + self.assertEqual([], git.calls) + self.assertFalse(self.output_path.exists()) + + def test_fork_emits_observation_only_metadata_without_git_or_gate_identity(self) -> None: + fork_event = event_document( + head_repository_id=987, + head_repository="contributor/AppSurface", + ) + self.write_event(fork_event) + fork_api = api_document( + head_repository_id=987, + head_repository="contributor/AppSurface", + ) + result, api, git = self.capture(api=FakeApi(fork_api)) + + self.assertEqual("observation", result) + self.assertEqual(1, len(api.calls)) + self.assertEqual([], git.calls) + self.assertEqual({"observation.json"}, {path.name for path in self.output_path.iterdir()}) + observation = json.loads((self.output_path / "observation.json").read_bytes()) + self.assertEqual("ObservationOnly", observation["Mode"]) + self.assertEqual(BASE_SHA, observation["BaseRevision"]) + self.assertEqual(HEAD_SHA, observation["HeadRevision"]) + self.assertNotIn("Plan", observation) + self.assertNotIn("PullRequestRunIdentity", observation) + self.assertNotIn(TOKEN, (self.output_path / "observation.json").read_text(encoding="utf-8")) + + def test_external_object_store_is_retained_for_cli_and_removed_after_failed_capture(self) -> None: + external_store = self.root / "trusted-objects.git" + result, _, git = self.capture(object_store_path=external_store) + + self.assertEqual("captured", result) + self.assertTrue(external_store.is_dir()) + self.assertEqual(b"retained", (external_store / ".fixture-store").read_bytes()) + self.assertEqual(external_store, git.object_store_paths[0]) + self.assertFalse((self.output_path / "repository.git").exists()) + + self.output_path = self.root / "failed-capture" + failing_store = self.root / "failed-objects.git" + api = FakeApi(api_document(), api_document(head_sha="c" * 40)) + with self.assertRaisesRegex(controller.ControllerError, "stale"): + self.capture(api=api, git=FakeGit(), output_path=self.output_path, object_store_path=failing_store) + self.assertFalse(failing_store.exists()) + self.assertFalse(self.output_path.exists()) + + def test_internal_object_store_path_is_preserved_inside_output(self) -> None: + nested_store = self.output_path / "git" / "objects.git" + result, _, git = self.capture(object_store_path=nested_store) + + self.assertEqual("captured", result) + self.assertTrue(nested_store.is_dir()) + self.assertEqual(b"retained", (nested_store / ".fixture-store").read_bytes()) + self.assertEqual( + Path("git/objects.git"), + git.object_store_paths[0].relative_to(git.object_store_paths[0].parents[1]), + ) + self.assertFalse((self.output_path / "repository.git").exists()) + + def test_existing_external_object_store_is_never_taken_or_removed(self) -> None: + existing_store = self.root / "already-owned.git" + existing_store.mkdir() + sentinel = existing_store / "keep.txt" + sentinel.write_text("caller-owned", encoding="utf-8") + api = FakeApi(api_document()) + git = FakeGit() + + with self.assertRaisesRegex(controller.ControllerError, "must not already exist"): + self.capture(api=api, git=git, object_store_path=existing_store) + + self.assertEqual("caller-owned", sentinel.read_text(encoding="utf-8")) + self.assertEqual([], api.calls) + self.assertEqual([], git.calls) + + def test_external_object_store_is_removed_when_atomic_output_publication_fails(self) -> None: + external_store = self.root / "publication-failure.git" + api = FakeApi(api_document(), api_document()) + + with mock.patch.object( + controller, + "_publish_staged_output", + side_effect=controller.ControllerError("injected publication failure"), + ): + with self.assertRaisesRegex(controller.ControllerError, "injected publication failure"): + self.capture( + api=api, + git=FakeGit(), + object_store_path=external_store, + output_path=self.output_path, + ) + + self.assertFalse(external_store.exists()) + self.assertFalse(self.output_path.exists()) + + def test_fork_does_not_create_requested_object_store(self) -> None: + self.write_event( + event_document(head_repository_id=987, head_repository="contributor/AppSurface") + ) + external_store = self.root / "fork-objects.git" + fork_api = api_document( + head_repository_id=987, + head_repository="contributor/AppSurface", + ) + + result, _, git = self.capture( + api=FakeApi(fork_api), + git=FakeGit(), + object_store_path=external_store, + ) + + self.assertEqual("observation", result) + self.assertFalse(external_store.exists()) + self.assertEqual([], git.calls) + + def test_retained_store_contains_both_exact_commits_and_reproduces_source_diff(self) -> None: + source = self.root / "source" + source.mkdir() + self.run_local_git(["init", "--quiet", str(source)]) + self.run_local_git(["-C", str(source), "config", "user.name", "Controller Fixture"]) + self.run_local_git(["-C", str(source), "config", "user.email", "fixture@example.invalid"]) + subject = source / "src" / "example.cs" + subject.parent.mkdir() + subject.write_text("base content\n", encoding="utf-8") + self.run_local_git(["-C", str(source), "add", "src/example.cs"]) + self.run_local_git(["-C", str(source), "commit", "--quiet", "-m", "base"]) + base_sha = self.run_local_git(["-C", str(source), "rev-parse", "HEAD"]).strip() + subject.write_text("head content\n", encoding="utf-8") + self.run_local_git(["-C", str(source), "commit", "--quiet", "-am", "head"]) + head_sha = self.run_local_git(["-C", str(source), "rev-parse", "HEAD"]).strip() + self.run_local_git(["-C", str(source), "update-ref", "refs/heads/main", base_sha]) + self.run_local_git(["-C", str(source), "update-ref", "refs/pull/777/head", head_sha]) + + remote = self.root / "remote.git" + self.run_local_git(["init", "--bare", "--quiet", str(remote)]) + self.run_local_git( + [ + "--git-dir", + str(remote), + "fetch", + "--quiet", + str(source), + "+refs/heads/main:refs/heads/main", + "+refs/pull/777/head:refs/pull/777/head", + ] + ) + self.write_event(event_document(base_sha=base_sha, head_sha=head_sha)) + api = FakeApi( + api_document(base_sha=base_sha, head_sha=head_sha), + api_document(base_sha=base_sha, head_sha=head_sha), + ) + real_git_calls: list[list[str]] = [] + + def local_remote_git( + arguments: list[str], + *, + deadline: float, + maximum_output_bytes: int, + ) -> bytes: + real_git_calls.append(list(arguments)) + actual_arguments = list(arguments) + if "fetch" in actual_arguments: + remote_position = actual_arguments.index("https://github.com/forge-trust/AppSurface.git") + actual_arguments[remote_position] = str(remote) + return controller.run_git_command( + actual_arguments, + deadline=deadline, + maximum_output_bytes=maximum_output_bytes, + ) + + result = controller._capture_diff( + repository="forge-trust/AppSurface", + repository_id=123, + target_branch="main", + run_id=456, + run_attempt=2, + token=TOKEN, + event_path=self.event_path, + output_path=self.output_path, + api_client=api, + git_runner=local_remote_git, + ) + + self.assertEqual("captured", result) + retained_store = self.output_path / "repository.git" + self.assertTrue(retained_store.is_dir()) + self.assertEqual( + base_sha, + self.run_local_git(["--git-dir", str(retained_store), "rev-parse", "refs/evidence/base"]).strip(), + ) + self.assertEqual( + head_sha, + self.run_local_git(["--git-dir", str(retained_store), "rev-parse", "refs/evidence/head"]).strip(), + ) + for revision in (base_sha, head_sha): + self.assertEqual( + "commit", + self.run_local_git(["--git-dir", str(retained_store), "cat-file", "-t", revision]).strip(), + ) + regenerated = self.run_local_git_bytes( + [ + "--no-pager", + f"--git-dir={retained_store}", + *controller.GIT_DIFF_OPTIONS, + base_sha, + head_sha, + "--", + ] + ) + self.assertEqual((self.output_path / "source.diff").read_bytes(), regenerated) + self.assertTrue(any("fetch" in call for call in real_git_calls)) + + def test_malformed_event_json_and_duplicate_keys_fail_closed(self) -> None: + for payload in (b"{broken", b'{"action":"opened","action":"synchronize"}'): + with self.subTest(payload=payload): + self.write_event(payload) + api = FakeApi(api_document()) + git = FakeGit() + with self.assertRaises(controller.ControllerError): + self.capture(api=api, git=git) + self.assertEqual([], api.calls) + self.assertEqual([], git.calls) + + def test_malformed_or_symlink_event_path_fails_closed(self) -> None: + with self.assertRaisesRegex(controller.ControllerError, "event path"): + self.capture(event_path=self.root / ".." / "event.json") + + link = self.root / "event-link.json" + try: + link.symlink_to(self.event_path) + except (OSError, NotImplementedError): + self.skipTest("symlinks are unavailable on this host") + with self.assertRaisesRegex(controller.ControllerError, "unsafe"): + self.capture(event_path=link) + + def test_malformed_sha_action_numeric_id_and_target_branch_are_rejected(self) -> None: + cases = ( + event_document(base_sha="A" * 40), + event_document(head_sha="b" * 39), + event_document(action="labeled"), + event_document(), + ) + for malformed in cases: + if malformed["action"] == "opened" and malformed["pull_request"]["base"]["sha"] == BASE_SHA: + malformed["repository"]["id"] = "123" + self.write_event(malformed) + with self.assertRaises(controller.ControllerError): + self.capture(api=FakeApi(api_document()), git=FakeGit()) + self.assertFalse(self.output_path.exists()) + + self.write_event(event_document()) + with self.assertRaisesRegex(controller.ControllerError, "unexpected branch"): + self.capture(target_branch="release") + + def test_output_path_traversal_and_existing_output_fail_closed(self) -> None: + with self.assertRaisesRegex(controller.ControllerError, "output path"): + self.capture(output_path=self.root / ".." / "outside") + self.output_path.mkdir() + with self.assertRaisesRegex(controller.ControllerError, "must not already exist"): + self.capture() + + def test_oversized_git_diff_is_rejected_before_any_output_is_published(self) -> None: + api = FakeApi(api_document()) + git = FakeGit(b"x" * (controller.MAX_SOURCE_DIFF_BYTES + 1)) + with self.assertRaisesRegex(controller.ControllerError, "byte limit"): + self.capture(api=api, git=git) + self.assertFalse(self.output_path.exists()) + self.assertEqual(1, len(api.calls)) + + def test_fetched_revision_mismatch_and_mid_capture_staleness_are_rejected(self) -> None: + api = FakeApi(api_document(), api_document()) + git = FakeGit(base_sha="c" * 40) + with self.assertRaisesRegex(controller.ControllerError, "fetched Git refs"): + self.capture(api=api, git=git) + self.assertFalse(self.output_path.exists()) + + changed_head = api_document(head_sha="c" * 40) + api = FakeApi(api_document(), changed_head) + git = FakeGit() + with self.assertRaisesRegex(controller.ControllerError, "stale"): + self.capture(api=api, git=git) + self.assertFalse(self.output_path.exists()) + + def test_untrusted_repository_text_cannot_become_a_git_argument(self) -> None: + api = FakeApi(api_document()) + git = FakeGit() + with self.assertRaisesRegex(controller.ControllerError, "owner/repository"): + self.capture( + api=api, + git=git, + repository="forge-trust/AppSurface;touch-pwned", + ) + self.assertEqual([], api.calls) + self.assertEqual([], git.calls) + + def test_process_runner_uses_an_argument_array_shell_false_and_drops_token(self) -> None: + class PipeProcess: + def __init__(self) -> None: + stdout_read, stdout_write = os.pipe() + stderr_read, stderr_write = os.pipe() + os.write(stdout_write, b"bounded") + os.close(stdout_write) + os.close(stderr_write) + self.stdout = os.fdopen(stdout_read, "rb", buffering=0) + self.stderr = os.fdopen(stderr_read, "rb", buffering=0) + self.returncode = 0 + + def poll(self) -> int: + return self.returncode + + def wait(self, timeout: float | None = None) -> int: + return self.returncode + + def kill(self) -> None: + self.returncode = -9 + + command = ["git", "--no-pager", "--git-dir=/tmp/fixed.git", "cat-file", "-t", HEAD_SHA] + with mock.patch.dict(os.environ, {"GITHUB_TOKEN": TOKEN}, clear=False): + with mock.patch.object(controller.subprocess, "Popen", return_value=PipeProcess()) as popen: + result = controller.run_git_command( + command, + deadline=time.monotonic() + 5, + maximum_output_bytes=64, + ) + + self.assertEqual(b"bounded", result) + args, kwargs = popen.call_args + self.assertEqual(command, args[0]) + self.assertIsInstance(args[0], list) + self.assertIs(kwargs["shell"], False) + self.assertEqual("1", kwargs["env"]["GIT_NO_REPLACE_OBJECTS"]) + self.assertNotIn("GITHUB_TOKEN", kwargs["env"]) + self.assertNotIn(TOKEN, repr(kwargs)) + + def test_nonpositive_and_string_ids_are_not_accepted(self) -> None: + for invalid in (0, -1, True, "777"): + with self.subTest(invalid=invalid), self.assertRaises(controller.ControllerError): + controller._positive_integer(invalid, "test ID") + + @staticmethod + def run_local_git(arguments: list[str]) -> str: + return EvidenceGateControllerTests.run_local_git_bytes(arguments).decode("utf-8") + + @staticmethod + def run_local_git_bytes(arguments: list[str]) -> bytes: + result = subprocess.run( + ["git", *arguments], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + check=False, + ) + if result.returncode != 0: + raise AssertionError("The local Git fixture command failed.") + return result.stdout + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_finalize.py b/scripts/tests/test_evidence_gate_finalize.py new file mode 100644 index 000000000..e41e1fa3b --- /dev/null +++ b/scripts/tests/test_evidence_gate_finalize.py @@ -0,0 +1,195 @@ +"""Regression tests for the base-owned GitHub gate verdict publisher.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-finalize.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_finalize", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +publisher = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(publisher) + + +class GateVerdictPublisherTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix="trusted-gate-finalize-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.verdict = self.root / "verdict" + self.verdict.mkdir() + self.step_summary = self.root / "step-summary.md" + + def _write_verdict(self, eligible: bool = True) -> None: + code = "ASEVG000" if eligible else "ASEVG006" + diagnostic = "The current pull request has a verified result." + plan_summary = {"ProfileHasEvidence": False} if eligible else None + machine = { + "IsEligible": eligible, + "Code": code, + "Diagnostic": diagnostic, + "Summary": plan_summary, + } + summary = { + "eligible": eligible, + "code": code, + "diagnostic": diagnostic, + "summary": plan_summary, + } + claim = "NoEvidenceRequired" if eligible else "None" + markdown = ( + "## AppSurface evidence gate\n\n" + f"- Verdict: **{'eligible' if eligible else 'ineligible'}** (`{code}`)\n" + f"- Verified claim: `{claim}`\n" + f"- Diagnostic: {diagnostic}\n" + ) + (self.verdict / "evidence-gate-verification.json").write_text(json.dumps(machine), encoding="utf-8") + (self.verdict / "evidence-gate-summary.json").write_text(json.dumps(summary), encoding="utf-8") + (self.verdict / "evidence-gate-summary.md").write_text(markdown, encoding="utf-8") + + def _finalize( + self, controller: str = "success", subject: str = "success", verifier: str = "success" + ) -> tuple[int, str]: + output = io.StringIO() + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()): + result = publisher.finalize(self.verdict, self.step_summary, controller, subject, verifier) + return result, output.getvalue() + + def test_verified_empty_profile_passes_and_publishes_same_markdown(self) -> None: + self._write_verdict() + expected = (self.verdict / "evidence-gate-summary.md").read_bytes() + + result, output = self._finalize() + + self.assertEqual(0, result) + self.assertEqual("gate=eligible; code=ASEVG000; claim=NoEvidenceRequired\n", output) + self.assertEqual(expected, self.step_summary.read_bytes()) + + def test_cli_exits_with_the_verified_result(self) -> None: + self._write_verdict() + command = [ + sys.executable, + str(SCRIPT), + "--verdict-directory", str(self.verdict), + "--step-summary", str(self.step_summary), + "--controller-outcome", "success", + "--subject-outcome", "success", + "--verifier-outcome", "success", + ] + + completed = subprocess.run(command, check=False, capture_output=True, text=True) + self.assertEqual(0, completed.returncode, completed.stderr) + self.assertIn("code=ASEVG000", completed.stdout) + + command[-1] = "failure" + completed = subprocess.run(command, check=False, capture_output=True, text=True) + self.assertEqual(2, completed.returncode) + self.assertIn("code=ASEGH003", completed.stdout) + + def test_ineligible_verifier_result_fails_with_its_diagnostic_code(self) -> None: + self._write_verdict(eligible=False) + + result, output = self._finalize() + + self.assertEqual(2, result) + self.assertIn("code=ASEVG006; claim=None", output) + self.assertIn(b"**ineligible** (`ASEVG006`)", self.step_summary.read_bytes()) + + def test_missing_or_inconsistent_output_falls_back_to_fixed_failure(self) -> None: + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + machine = self.verdict / "evidence-gate-verification.json" + machine.write_bytes(b'{"IsEligible":true,"IsEligible":true}') + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + machine.write_bytes(b'{"IsEligible":NaN}') + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + raw = json.loads(machine.read_text(encoding="utf-8")) + raw["Unexpected"] = "ignored only by an unsafe publisher" + machine.write_text(json.dumps(raw), encoding="utf-8") + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + markdown = self.verdict / "evidence-gate-summary.md" + markdown.write_bytes(markdown.read_bytes() + b"\xff") + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + summary = self.verdict / "evidence-gate-summary.json" + summary.write_text(summary.read_text(encoding="utf-8").replace("ASEVG000", "ASEVG006"), encoding="utf-8") + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + self._write_verdict() + markdown = self.verdict / "evidence-gate-summary.md" + markdown.write_text( + markdown.read_text(encoding="utf-8").replace("NoEvidenceRequired", "TargetedComplete"), + encoding="utf-8", + ) + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003", output) + + def test_upstream_failure_prevents_success_even_with_eligible_result(self) -> None: + self._write_verdict() + outcomes_to_check = ( + ("failure", "success", "success"), + ("success", "skipped", "success"), + ("success", "success", "failure"), + ) + for outcomes in outcomes_to_check: + with self.subTest(outcomes=outcomes): + self.step_summary.write_bytes(b"") + result, output = self._finalize(*outcomes) + self.assertEqual(2, result) + self.assertIn("code=ASEGH003; claim=None", output) + self.assertIn(b"**ineligible** (`ASEGH003`)", self.step_summary.read_bytes()) + + def test_linked_or_oversized_results_and_summary_write_failure_fail_closed(self) -> None: + self._write_verdict() + machine = self.verdict / "evidence-gate-verification.json" + machine.unlink() + machine.symlink_to(self.verdict / "evidence-gate-summary.json") + result, _ = self._finalize() + self.assertEqual(2, result) + + machine.unlink() + machine.write_bytes(b"x" * (publisher.MAX_RESULT_BYTES + 1)) + result, _ = self._finalize() + self.assertEqual(2, result) + + self._write_verdict() + self.step_summary.unlink() + self.step_summary.symlink_to(self.root / "elsewhere.md") + result, output = self._finalize() + self.assertEqual(2, result) + self.assertIn("code=ASEGH003; claim=None", output) + self.assertFalse((self.root / "elsewhere.md").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_fixture.py b/scripts/tests/test_evidence_gate_fixture.py new file mode 100644 index 000000000..8bfe56a2c --- /dev/null +++ b/scripts/tests/test_evidence_gate_fixture.py @@ -0,0 +1,78 @@ +"""Keep the checked-in revision-bound docs fixture tied to real Git objects.""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ROOT / "docs" / "fixtures" / "issue-777-docs-only" + + +class EvidenceGateFixtureTests(unittest.TestCase): + def test_bundle_and_fixed_diff_match_immutable_metadata(self) -> None: + metadata = json.loads((FIXTURE / "fixture.json").read_text()) + bundle = FIXTURE / "repository.bundle" + source_diff = (FIXTURE / "source.diff").read_bytes() + policy = (FIXTURE / "policy.json").read_bytes() + + self.assertEqual(metadata["bundleSha256"], hashlib.sha256(bundle.read_bytes()).hexdigest()) + self.assertEqual(metadata["sourceDiffSha256"], hashlib.sha256(source_diff).hexdigest()) + self.assertEqual(metadata["policySha256"], hashlib.sha256(policy).hexdigest()) + self.assertEqual(metadata["changedPath"], "docs/fixture-note.md") + + with tempfile.TemporaryDirectory(prefix="appsurface-777-fixture-") as temporary: + repository = Path(temporary) / "repository" + environment = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")} + environment.update({"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "LC_ALL": "C"}) + + def git(*arguments: str) -> bytes: + result = subprocess.run( + ["git", "-C", str(repository), *arguments], + env=environment, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=30, + ) + return result.stdout + + subprocess.run( + ["git", "clone", "--quiet", str(bundle), str(repository)], + env=environment, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=30, + ) + base = metadata["baseRevision"] + head = metadata["headRevision"] + self.assertEqual(base, git("rev-parse", "fixture-base").decode().strip()) + self.assertEqual(head, git("rev-parse", "HEAD").decode().strip()) + + diff_options = ( + "-c", "diff.external=", "-c", "diff.noprefix=false", + "-c", "diff.mnemonicprefix=false", "-c", "diff.algorithm=myers", + ) + source_options = ( + "diff", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", + "--full-index", "--unified=3", "--find-renames=50%", "--find-copies=50%", + "--submodule=short", "--ignore-submodules=none", "--no-relative", + "--src-prefix=a/", "--dst-prefix=b/", base, head, "--", + ) + self.assertEqual(source_diff, git(*diff_options, *source_options)) + status = git(*diff_options, "diff", "--name-status", "-z", "--no-ext-diff", + "--no-textconv", "--no-color", "--find-renames=50%", + "--find-copies=50%", "--submodule=short", "--ignore-submodules=none", + "--no-relative", base, head, "--") + self.assertEqual(b"M\0docs/fixture-note.md\0", status) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_handoff.py b/scripts/tests/test_evidence_gate_handoff.py new file mode 100644 index 000000000..de22e5ffa --- /dev/null +++ b/scripts/tests/test_evidence_gate_handoff.py @@ -0,0 +1,1205 @@ +"""Focused tests for the private evidence-gate controller handoff.""" + +from __future__ import annotations + +from contextlib import redirect_stdout +import importlib.util +import hashlib +import io +import json +import os +from pathlib import Path +import shutil +import sys +import subprocess +import tarfile +import tempfile +import unittest +from unittest.mock import patch + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-handoff.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_handoff", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +handoff = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = handoff +SPEC.loader.exec_module(handoff) +IMAGE = "ghcr.io/forge-trust/appsurface-subject-native-validation@sha256:" + "f" * 64 + + +class HandoffPathTests(unittest.TestCase): + def test_evidence_json_matches_dotnet_escaping_for_git_path_characters(self) -> None: + self.assertEqual( + b'{"Value":"a\\u002Bb\\u0060\\u0022\\\\"}', + handoff._canonical_evidence_json({"Value": 'a+b`"\\'}), + ) + self.assertEqual( + b'{"Value":"ends-with-backslash\\\\"}', + handoff._canonical_evidence_json({"Value": "ends-with-backslash\\"}), + ) + self.assertEqual( + b'{"Value":"quote\\u0022plus\\u002Bbacktick\\u0060"}', + handoff._canonical_evidence_json({"Value": 'quote"plus+backtick`'}), + ) + self.assertEqual( + b'{"Value":"\\\\u00af\\u002B"}', + handoff._canonical_evidence_json({"Value": "\\u00af+"}), + ) + self.assertEqual( + b'{"Value":"caf\\u00E9"}', + handoff._canonical_evidence_json({"Value": "café"}), + ) + + def test_new_output_directory_can_be_created_under_physical_parent(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-handoff-") as temporary: + parent = Path(temporary).resolve() / "physical-parent" + parent.mkdir() + output = handoff._new_output_directory(parent / "new-handoff", "handoff output") + + self.assertEqual(parent / "new-handoff", output) + self.assertFalse(output.exists()) + output.mkdir(mode=0o700) + self.assertTrue(output.is_dir()) + + def test_descriptor_walk_reports_identity_mismatch_without_masking_it(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-artifact-walk-") as temporary: + directory = Path(temporary).resolve() + with patch.object(handoff, "_same_file_identity", return_value=False): + with self.assertRaises(handoff.HandoffError) as failure: + handoff._open_directory_nofollow(directory, "ASEHB012") + + self.assertEqual("ASEHB012", failure.exception.code) + self.assertIn("changed during its descriptor walk", failure.exception.message) + + +class HandoffArchiveTests(unittest.TestCase): + def _git(self, directory: Path, *arguments: str) -> str: + completed = subprocess.run( + ["git", *arguments], + cwd=directory, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + return completed.stdout.strip() + + def _write_plan( + self, + root: Path, + capture: Path, + *, + profile_id: str = "code-coverage", + snapshot_profile_id: str | None = None, + scope: str = "Targeted", + resources: list[object] | None = None, + producers: list[object] | None = None, + obligations: list[object] | None = None, + identity_overrides: dict[str, object] | None = None, + revision_overrides: dict[str, str] | None = None, + source_diff_digest: str | None = None, + ) -> Path: + identity, _ = handoff._read_json(capture / "pull-request-run-identity.json", 64 * 1024, "test identity") + source_diff = (capture / "source.diff").read_bytes() + profile = { + "Id": profile_id, + "Scope": scope, + "Resources": [] if resources is None else resources, + "Producers": [] if producers is None else producers, + "Obligations": [] if obligations is None else obligations, + } + snapshot_profile = dict(profile) + snapshot_profile["Id"] = profile_id if snapshot_profile_id is None else snapshot_profile_id + plan_identity = { + key: identity[key] + for key in ( + "RepositoryId", + "HeadRepositoryId", + "PullRequestNumber", + "TargetBranch", + "WorkflowRunId", + "WorkflowRunAttempt", + ) + } + if identity_overrides: + plan_identity.update(identity_overrides) + plan = { + "BaseRevision": identity["BaseRevision"], + "ChangedPaths": [], + "ContractVersion": "2.0", + "DiffDigest": "d" * 64, + "HeadRevision": identity["HeadRevision"], + "MatchedRuleIds": [], + "NameStatusDigest": "e" * 64, + "PlanDigest": "b" * 64, + "PolicyDigest": "a" * 64, + "PolicyId": "test-policy", + "PolicySnapshot": { + "Id": "test-policy", + "Version": "1", + "ConservativeProfileId": profile_id, + "Profiles": [snapshot_profile], + "Rules": [], + }, + "Profile": profile, + "PullRequestRunIdentity": plan_identity, + "SourceDiffDigest": hashlib.sha256(source_diff).hexdigest() + if source_diff_digest is None + else source_diff_digest, + } + if revision_overrides: + plan.update(revision_overrides) + path = root / "evidence-plan.json" + path.write_bytes(handoff._canonical_evidence_json(plan)) + return path + + def _capture(self, root: Path, *, attributes: str | None = None) -> tuple[Path, Path, Path]: + worktree = root / "worktree" + capture = root / "capture" + scripts = root / "trusted-scripts" + worktree.mkdir(parents=True) + capture.mkdir() + scripts.mkdir() + self._git(worktree, "init", "--quiet") + self._git(worktree, "config", "user.name", "Evidence Gate Test") + self._git(worktree, "config", "user.email", "evidence-gate@example.invalid") + + (worktree / "base.txt").write_text("base\n", encoding="utf-8") + self._git(worktree, "add", "base.txt") + self._git(worktree, "commit", "--quiet", "-m", "base") + base_revision = self._git(worktree, "rev-parse", "HEAD") + + if attributes is not None: + (worktree / ".gitattributes").write_text(attributes, encoding="utf-8") + (worktree / "subject.txt").write_text("subject $Format:%H$\n", encoding="utf-8") + (worktree / "nested").mkdir() + (worktree / "nested" / "source.txt").write_text("nested source\n", encoding="utf-8") + if attributes and "export-ignore" in attributes: + (worktree / "omitted.txt").write_text("tracked but ignored by git archive\n", encoding="utf-8") + self._git(worktree, "add", ".") + self._git(worktree, "commit", "--quiet", "-m", "subject") + head_revision = self._git(worktree, "rev-parse", "HEAD") + self._git(worktree, "clone", "--bare", "--quiet", str(worktree), str(capture / "repository.git")) + + identity = { + "BaseRevision": base_revision, + "HeadRevision": head_revision, + "HeadRepositoryId": 123, + "PullRequestNumber": 7, + "RepositoryId": 123, + "TargetBranch": "main", + "WorkflowRunAttempt": 1, + "WorkflowRunId": 456, + } + (capture / "pull-request-run-identity.json").write_bytes(handoff._canonical_json(identity)) + (capture / "source.diff").write_bytes(b"bounded test diff\n") + for name in handoff.TRUSTED_SUBJECT_FILES: + shutil.copyfile(SCRIPT.parent / name, scripts / name) + plan_file = self._write_plan(root, capture) + return capture, scripts, plan_file + + def _execute( + self, + output: Path, + root: Path, + *, + image_digest: str | None = None, + environment: dict[str, str] | None = None, + artifact_export_directory: Path | None = None, + ) -> tuple[int, Path]: + result_path = root / "subject-result.json" + exit_code = handoff.execute_handoff( + handoff_directory=output, + subject_checkout=root / "subject-checkout", + scratch_directory=root / "subject-scratch", + artifact_export_directory=artifact_export_directory or root / "subject-artifacts", + result_path=result_path, + image_digest=image_digest, + environment=environment + or { + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + }, + ) + return exit_code, result_path + + def _create(self, capture: Path, scripts: Path, plan_file: Path, output: Path) -> str: + return handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output, + plan_file=plan_file, + ) + + def _write_test_launcher( + self, + scripts: Path, + *, + exit_code: int = 0, + include_record: bool = True, + include_envelope: bool = True, + step_mutation: str | None = None, + artifact_mutation: str | None = None, + ) -> None: + step_names = ( + "dotnet-sdk-version", + "dotnet-runtime-list", + "offline-locked-restore", + "coverage-run", + "coverage-gate", + ) + export_payloads = { + "cobertura.xml": b"coverage", + "gate-report.md": b"report", + "diagnostics.json": b"{}", + } + execution_record = { + "artifacts": [ + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": len(export_payloads[basename]), + "sha256": hashlib.sha256(export_payloads[basename]).hexdigest(), + } + for (logical_name, relative_path, _maximum_bytes), basename in zip( + handoff.SUBJECT_ARTIFACTS, + handoff.SUBJECT_ARTIFACT_EXPORT_BASENAMES, + strict=True, + ) + ], + "claimEligible": False, + "profileId": "code-coverage", + "schemaVersion": 1, + "status": "completed", + "steps": [ + { + "exitCode": 0, + "name": name, + "outputBytes": 0, + "stderrSha256": "0" * 64, + "stdoutSha256": "0" * 64, + } + for name in step_names + ], + } + (scripts / "evidence-gate-subject.py").write_text( + f"""import os +from types import SimpleNamespace + +class SubjectLimits: + def __init__(self, **values): + self.values = values + +def launch_subject( + *, subject_checkout, image_digest, scratch_directory, profile_id, + artifact_export_directory, source_diff, source_diff_sha256, limits, _environment +): + with open(_environment['TEST_PROFILE_LOG'], 'w', encoding='utf-8') as log: + log.write(profile_id) + if 'TEST_DIFF_LOG' in _environment: + with open(source_diff, 'rb') as diff_file: + diff_hex = diff_file.read().hex() + with open(_environment['TEST_DIFF_LOG'], 'w', encoding='ascii') as log: + log.write(source_diff_sha256 + ':' + diff_hex) + execution_record = {execution_record!r} + artifact_payloads = {export_payloads!r} + if {exit_code} == 0: + artifact_export_directory.mkdir(mode=0o700) + for basename, payload in artifact_payloads.items(): + if {artifact_mutation!r} == 'missing' and basename == 'cobertura.xml': + continue + if {artifact_mutation!r} == 'digest-mismatch' and basename == 'cobertura.xml': + payload = b'X' * len(payload) + with open(artifact_export_directory / basename, 'wb') as artifact: + artifact.write(payload) + if {artifact_mutation!r} == 'extra': + (artifact_export_directory / 'unexpected.txt').write_bytes(b'unexpected') + elif {artifact_mutation!r} == 'symlink': + outside = artifact_export_directory.parent / 'outside-artifact.txt' + outside.write_bytes(b'coverage') + (artifact_export_directory / 'cobertura.xml').unlink() + os.symlink(outside, artifact_export_directory / 'cobertura.xml') + if {step_mutation!r} == 'omit-last': + execution_record['steps'].pop() + elif {step_mutation!r} == 'rename-first': + execution_record['steps'][0]['name'] = 'unexpected-step' + return SimpleNamespace( + exit_code={exit_code}, + stdout=b'completed', + stderr=b'', + execution_record=execution_record if {exit_code} == 0 and {include_record} else None, + envelope_observation={{ + 'schemaVersion': 1, + 'imageDigest': image_digest, + 'profileId': profile_id, + 'runnerEnvironment': 'github-hosted', + 'runtime': 'rootless-podman', + 'networkMode': 'none', + 'rootfsReadOnlyConfigured': True, + 'subjectAndDiffReadOnlyConfigured': True, + 'scratchTmpfsQuotaVerified': True, + 'capabilityDropConfigured': True, + 'noNewPrivilegesConfigured': True, + 'pidIpcUtsUserNamespacesConfiguredPrivate': True, + 'resourceLimitsConfigured': True, + }} if {exit_code} == 0 and {include_envelope} else None, + ) +""", + encoding="utf-8", + ) + + @staticmethod + def _resign_execution_receipt(result: dict[str, object]) -> None: + receipt = result["executionReceipt"] + assert isinstance(receipt, dict) + payload = { + "binding": receipt["binding"], + "record": receipt["record"], + "schemaVersion": receipt["schemaVersion"], + } + receipt["sha256"] = hashlib.sha256(handoff._canonical_json(payload)).hexdigest() + + @staticmethod + def _resign_envelope_receipt(result: dict[str, object]) -> None: + receipt = result["envelopeReceipt"] + assert isinstance(receipt, dict) + payload = { + "binding": receipt["binding"], + "observation": receipt["observation"], + "schemaVersion": receipt["schemaVersion"], + } + receipt["sha256"] = hashlib.sha256(handoff._canonical_json(payload)).hexdigest() + + def test_valid_handoff_round_trip_accepts_sha256_source_diff(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-round-trip-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + + self.assertEqual( + "captured", + self._create(capture, scripts, plan_file, output), + ) + + manifest, _ = handoff._read_json(output / "handoff.json", 128 * 1024, "handoff manifest") + identity, archive, evidence_plan = handoff._validate_bundle_directory(output, manifest) + self.assertIsNotNone(identity) + self.assertEqual("code-coverage", evidence_plan["Profile"]["Id"]) + self.assertEqual(identity["HeadRevision"], manifest["HeadRevision"]) + self.assertRegex(manifest["SourceDiffSha256"], r"^[0-9a-f]{64}$") + self.assertEqual(len(plan_file.read_bytes()), manifest["EvidencePlanBytes"]) + self.assertEqual(hashlib.sha256(plan_file.read_bytes()).hexdigest(), manifest["EvidencePlanSha256"]) + self.assertIsNotNone(archive) + + exit_code, result_path = self._execute(output, root) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("ASEHB008", result["diagnostic"]["code"]) + + def test_trusted_verifier_copies_only_a_bundle_matching_fresh_git_state(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-verify-handoff-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="documentation-only") + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + subject_exit, subject_result = self._execute(output, root) + self.assertEqual(0, subject_exit) + verified_plan = root / "verified-plan.json" + + with redirect_stdout(io.StringIO()): + self.assertEqual( + 0, + handoff.main( + [ + "verify", + "--handoff-directory", str(output), + "--fresh-capture-directory", str(capture), + "--subject-result", str(subject_result), + "--output-plan", str(verified_plan), + ] + ), + ) + + self.assertEqual(plan_file.read_bytes(), verified_plan.read_bytes()) + + def test_documentation_only_verifier_rejects_subject_envelope_inputs(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-docs-envelope-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="documentation-only") + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + subject_exit, subject_result = self._execute(output, root) + self.assertEqual(0, subject_exit) + original_result = subject_result.read_bytes() + + for name, subject_artifacts, expected_image, add_receipt, expected_code in ( + ("artifact-payload", root / "unexpected-artifacts", None, False, "ASEHB012"), + ("image-argument", None, IMAGE, False, "ASEHB013"), + ("envelope-receipt", None, None, True, "ASEHB013"), + ): + with self.subTest(name=name): + if add_receipt: + result = json.loads(original_result) + result["envelopeReceipt"] = {} + subject_result.write_bytes(handoff._canonical_json(result) + b"\n") + else: + subject_result.write_bytes(original_result) + verified = root / f"verified-{name}.json" + with self.assertRaises(handoff.HandoffError) as failure: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=subject_result, + output_plan=verified, + subject_artifacts_directory=subject_artifacts, + expected_image_digest=expected_image, + ) + self.assertEqual(expected_code, failure.exception.code) + self.assertFalse(verified.exists()) + + def test_code_coverage_verifier_rejects_invalid_downloaded_artifact_exports(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-downloaded-artifacts-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(root / "selected-profile.txt"), + }, + ) + self.assertEqual(0, exit_code) + exported = root / "subject-artifacts" + scenarios = ("missing-directory", "missing-file", "extra-file", "symlink", "mutation", "oversize") + for scenario in scenarios: + with self.subTest(scenario=scenario): + candidate = root / f"downloaded-{scenario}" + shutil.copytree(exported, candidate) + if scenario == "missing-directory": + shutil.rmtree(candidate) + elif scenario == "missing-file": + (candidate / "cobertura.xml").unlink() + elif scenario == "extra-file": + (candidate / "unexpected.txt").write_bytes(b"extra") + elif scenario == "symlink": + (candidate / "cobertura.xml").unlink() + outside = root / "outside-artifact" + outside.write_bytes(b"coverage") + os.symlink(outside, candidate / "cobertura.xml") + elif scenario == "mutation": + (candidate / "cobertura.xml").write_bytes(b"tampered") + elif scenario == "oversize": + with (candidate / "cobertura.xml").open("wb") as stream: + stream.truncate(handoff.MAX_COBERTURA_ARTIFACT_BYTES + 1) + + verified = root / f"verified-{scenario}.json" + with self.assertRaises(handoff.HandoffError) as failure: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=verified, + subject_artifacts_directory=candidate, + expected_image_digest=IMAGE, + ) + self.assertEqual("ASEHB012", failure.exception.code) + self.assertFalse(verified.exists()) + + with self.assertRaises(handoff.HandoffError) as missing_flag: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / "verified-missing-flag.json", + expected_image_digest=IMAGE, + ) + self.assertEqual("ASEHB012", missing_flag.exception.code) + self.assertFalse((root / "verified-missing-flag.json").exists()) + + missing_component = root / "symlink-parent" / "downloaded" + (root / "outside-artifacts").mkdir() + (root / "symlink-parent").symlink_to(root / "outside-artifacts", target_is_directory=True) + with self.assertRaises(handoff.HandoffError) as unsafe_path: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / "verified-unsafe-path.json", + subject_artifacts_directory=missing_component, + expected_image_digest=IMAGE, + ) + self.assertEqual("ASEHB012", unsafe_path.exception.code) + self.assertFalse((root / "verified-unsafe-path.json").exists()) + + valid_result = json.loads(result_path.read_bytes()) + receipt = valid_result["executionReceipt"] + receipt["record"]["artifacts"][0]["sha256"] = "0" * 64 + self._resign_execution_receipt(valid_result) + result_path.write_bytes(handoff._canonical_json(valid_result) + b"\n") + with self.assertRaises(handoff.HandoffError) as index_mismatch: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / "verified-index-mismatch.json", + subject_artifacts_directory=exported, + expected_image_digest=IMAGE, + ) + self.assertEqual("ASEHB012", index_mismatch.exception.code) + self.assertFalse((root / "verified-index-mismatch.json").exists()) + + def test_successful_subject_export_failure_is_cleaned_and_remains_non_claiming(self) -> None: + for mutation in ("missing", "extra", "symlink", "digest-mismatch"): + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory( + prefix="evidence-gate-invalid-export-" + ) as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts, artifact_mutation=mutation) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(root / "selected-profile.txt"), + }, + ) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_bytes()) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertEqual("ASEHB009", result["diagnostic"]["code"]) + self.assertNotIn("executionReceipt", result) + self.assertFalse((root / "subject-artifacts").exists()) + + def test_trusted_verifier_rejects_stale_identity_or_changed_diff(self) -> None: + for mismatch in ("identity", "diff"): + with self.subTest(mismatch=mismatch), tempfile.TemporaryDirectory(prefix="evidence-gate-stale-handoff-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="documentation-only") + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + subject_exit, subject_result = self._execute(output, root) + self.assertEqual(0, subject_exit) + verified_plan = root / "verified-plan.json" + if mismatch == "identity": + identity, _ = handoff._read_json(capture / "pull-request-run-identity.json", 64 * 1024, "test identity") + identity["WorkflowRunAttempt"] = 2 + (capture / "pull-request-run-identity.json").write_bytes(handoff._canonical_json(identity)) + else: + (capture / "source.diff").write_bytes(b"a later exact source diff\n") + + with self.assertRaises(handoff.HandoffError): + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=subject_result, + output_plan=verified_plan, + ) + self.assertFalse(verified_plan.exists()) + + def test_trusted_verifier_rejects_a_forged_subject_result(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-forged-result-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="documentation-only") + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + subject_exit, subject_result = self._execute(output, root) + self.assertEqual(0, subject_exit) + valid_result = json.loads(subject_result.read_bytes()) + for field, value in ( + ("headRevision", "0" * 40), + ("workflowRunAttempt", "2"), + ("snapshotSha256", "0" * 64), + ("profileId", "code-coverage"), + ("claimEligible", True), + ("execution", "failed"), + ("exitCode", 2), + ("diagnostic", {"code": "ASEHB009", "message": "failed"}), + ): + with self.subTest(field=field): + result = dict(valid_result, **{field: value}) + subject_result.write_bytes(handoff._canonical_json(result) + b"\n") + with self.assertRaises(handoff.HandoffError): + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=subject_result, + output_plan=root / "verified-plan.json", + ) + self.assertFalse((root / "verified-plan.json").exists()) + + def test_empty_documentation_only_profile_succeeds_without_oci(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-docs-only-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="documentation-only") + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + + exit_code, result_path = self._execute(output, root) + + self.assertEqual(0, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("completed", result["execution"]) + self.assertEqual(0, result["exitCode"]) + self.assertEqual("documentation-only", result["profileId"]) + self.assertEqual("ASEHB010", result["diagnostic"]["code"]) + self.assertFalse((root / "subject-checkout").exists()) + self.assertFalse((root / "subject-scratch").exists()) + self.assertFalse((root / "subject-artifacts").exists()) + + def test_code_coverage_profile_is_passed_to_the_bounded_launcher(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-code-coverage-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts) + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + profile_log = root / "selected-profile.txt" + diff_log = root / "selected-diff.txt" + + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(profile_log), + "TEST_DIFF_LOG": str(diff_log), + }, + ) + + self.assertEqual("code-coverage", profile_log.read_text(encoding="utf-8")) + captured_diff = (capture / "source.diff").read_bytes() + self.assertEqual( + f"{hashlib.sha256(captured_diff).hexdigest()}:{captured_diff.hex()}", + diff_log.read_text(encoding="ascii"), + ) + self.assertEqual(0, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("completed", result["execution"]) + self.assertEqual("code-coverage", result["profileId"]) + self.assertEqual(1, result["executionReceipt"]["schemaVersion"]) + self.assertEqual( + handoff.SUBJECT_RESULT_STEP_NAMES, + tuple(step["name"] for step in result["executionReceipt"]["record"]["steps"]), + ) + self.assertRegex(result["executionReceipt"]["sha256"], r"^[0-9a-f]{64}$") + downloaded_artifacts = root / "downloaded-subject-artifacts" + shutil.copytree(root / "subject-artifacts", downloaded_artifacts) + verified_plan = root / "verified-plan.json" + with redirect_stdout(io.StringIO()): + self.assertEqual( + 0, + handoff.main( + [ + "verify", + "--handoff-directory", str(output), + "--fresh-capture-directory", str(capture), + "--subject-result", str(result_path), + "--subject-artifacts", str(downloaded_artifacts), + "--expected-image-digest", IMAGE, + "--output-plan", str(verified_plan), + ] + ), + ) + self.assertEqual(plan_file.read_bytes(), verified_plan.read_bytes()) + + def test_code_coverage_verifier_rejects_missing_or_tampered_execution_receipts(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-receipt-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + profile_log = root / "selected-profile.txt" + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(profile_log), + }, + ) + self.assertEqual(0, exit_code) + valid_result = json.loads(result_path.read_bytes()) + receipt_mutations = { + "omitted-receipt": lambda value: value.pop("executionReceipt"), + "omitted-step": lambda value: value["executionReceipt"]["record"]["steps"].pop(), + "duplicate-step": lambda value: value["executionReceipt"]["record"]["steps"][1].update( + name=value["executionReceipt"]["record"]["steps"][0]["name"] + ), + "reordered-step": lambda value: value["executionReceipt"]["record"]["steps"].__setitem__( + slice(0, 2), + reversed(value["executionReceipt"]["record"]["steps"][:2]), + ), + "nonzero-step": lambda value: value["executionReceipt"]["record"]["steps"][4].update(exitCode=1), + "wrong-run-id": lambda value: value["executionReceipt"]["binding"].update(workflowRunId="999"), + "wrong-attempt": lambda value: value["executionReceipt"]["binding"].update(workflowRunAttempt="2"), + "wrong-base": lambda value: value["executionReceipt"]["binding"].update(baseRevision="0" * 40), + "wrong-head": lambda value: value["executionReceipt"]["binding"].update(headRevision="0" * 40), + "wrong-profile": lambda value: value["executionReceipt"]["binding"].update(profileId="documentation-only"), + "wrong-snapshot": lambda value: value["executionReceipt"]["binding"].update(snapshotSha256="0" * 64), + "wrong-receipt-schema": lambda value: value["executionReceipt"].update(schemaVersion=2), + "claimable-record": lambda value: value["executionReceipt"]["record"].update(claimEligible=True), + "omitted-artifacts": lambda value: value["executionReceipt"]["record"].pop("artifacts"), + "duplicate-artifact": lambda value: value["executionReceipt"]["record"]["artifacts"][1].update( + logicalName=value["executionReceipt"]["record"]["artifacts"][0]["logicalName"], + relativePath=value["executionReceipt"]["record"]["artifacts"][0]["relativePath"], + ), + "reordered-artifacts": lambda value: value["executionReceipt"]["record"]["artifacts"].reverse(), + "unsafe-artifact-path": lambda value: value["executionReceipt"]["record"]["artifacts"][0].update( + relativePath="../coverage.cobertura.xml" + ), + "oversized-artifact": lambda value: value["executionReceipt"]["record"]["artifacts"][2].update( + byteCount=handoff.MAX_GATE_JSON_ARTIFACT_BYTES + 1 + ), + "malformed-artifact-digest": lambda value: value["executionReceipt"]["record"]["artifacts"][1].update( + sha256="not-a-digest" + ), + } + for name, mutate in receipt_mutations.items(): + with self.subTest(mutation=name): + result = json.loads(json.dumps(valid_result)) + mutate(result) + if name not in {"omitted-receipt", "wrong-receipt-schema"}: + self._resign_execution_receipt(result) + result_path.write_bytes(handoff._canonical_json(result) + b"\n") + with self.assertRaises(handoff.HandoffError): + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / f"verified-{name}.json", + subject_artifacts_directory=root / "subject-artifacts", + expected_image_digest=IMAGE, + ) + self.assertFalse((root / f"verified-{name}.json").exists()) + + digest_tampered = json.loads(json.dumps(valid_result)) + digest_tampered["executionReceipt"]["sha256"] = "0" * 64 + result_path.write_bytes(handoff._canonical_json(digest_tampered) + b"\n") + with self.assertRaisesRegex(handoff.HandoffError, "digest does not match"): + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / "verified-digest-tampered.json", + subject_artifacts_directory=root / "subject-artifacts", + expected_image_digest=IMAGE, + ) + self.assertFalse((root / "verified-digest-tampered.json").exists()) + + def test_code_coverage_host_envelope_must_match_trusted_image_and_run(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-envelope-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(root / "selected-profile.txt"), + }, + ) + self.assertEqual(0, exit_code) + valid_result = json.loads(result_path.read_bytes()) + self.assertEqual(IMAGE, valid_result["envelopeReceipt"]["observation"]["imageDigest"]) + exported = root / "subject-artifacts" + + def missing(value: dict[str, object]) -> None: + value.pop("envelopeReceipt") + + def wrong_image(value: dict[str, object]) -> None: + value["envelopeReceipt"]["observation"]["imageDigest"] = IMAGE[:-1] + "0" + + def weakened_network(value: dict[str, object]) -> None: + value["envelopeReceipt"]["observation"]["networkMode"] = "bridge" + + def false_isolation(value: dict[str, object]) -> None: + value["envelopeReceipt"]["observation"]["capabilityDropConfigured"] = False + + def wrong_head(value: dict[str, object]) -> None: + value["envelopeReceipt"]["binding"]["headRevision"] = "0" * 40 + + def extra_field(value: dict[str, object]) -> None: + value["envelopeReceipt"]["observation"]["extra"] = True + + def stale_digest(value: dict[str, object]) -> None: + value["envelopeReceipt"]["sha256"] = "0" * 64 + + for name, mutate in ( + ("missing", missing), + ("wrong-image", wrong_image), + ("weakened-network", weakened_network), + ("false-isolation", false_isolation), + ("wrong-head", wrong_head), + ("extra-field", extra_field), + ("stale-digest", stale_digest), + ): + with self.subTest(mutation=name): + altered = json.loads(json.dumps(valid_result)) + mutate(altered) + if name not in {"missing", "stale-digest"}: + self._resign_envelope_receipt(altered) + result_path.write_bytes(handoff._canonical_json(altered) + b"\n") + verified = root / f"verified-{name}.json" + with self.assertRaises(handoff.HandoffError) as failure: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=verified, + subject_artifacts_directory=exported, + expected_image_digest=IMAGE, + ) + self.assertEqual("ASEHB013", failure.exception.code) + self.assertFalse(verified.exists()) + + result_path.write_bytes(handoff._canonical_json(valid_result) + b"\n") + for supplied_image in (None, IMAGE[:-1] + "0", "sha256:" + "f" * 64): + with self.subTest(supplied_image=supplied_image): + with self.assertRaises(handoff.HandoffError) as failure: + handoff.verify_handoff( + handoff_directory=output, + fresh_capture_directory=capture, + subject_result_file=result_path, + output_plan=root / "verified-wrong-preflight.json", + subject_artifacts_directory=exported, + expected_image_digest=supplied_image, + ) + self.assertEqual("ASEHB013", failure.exception.code) + + def test_code_coverage_handoff_fails_when_launcher_omits_host_envelope(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-missing-envelope-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts, include_envelope=False) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(root / "selected-profile.txt"), + }, + ) + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_bytes()) + self.assertEqual("ASEHB013", result["diagnostic"]["code"]) + self.assertNotIn("envelopeReceipt", result) + self.assertFalse((root / "subject-artifacts").exists()) + + def test_code_coverage_handoff_fails_without_or_with_invalid_step_proof(self) -> None: + scenarios = ( + ("missing-record", {"include_record": False}), + ("missing-step", {"step_mutation": "omit-last"}), + ("renamed-step", {"step_mutation": "rename-first"}), + ) + for name, options in scenarios: + with self.subTest(scenario=name), tempfile.TemporaryDirectory(prefix="evidence-gate-step-failure-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts, **options) + output = root / "handoff" + self._create(capture, scripts, plan_file, output) + profile_log = root / "selected-profile.txt" + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(profile_log), + }, + ) + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_bytes()) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertNotIn("executionReceipt", result) + self.assertEqual("ASEHB009", result["diagnostic"]["code"]) + + def test_failed_bounded_launcher_returns_two_and_remains_non_claiming(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-launch-failure-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + self._write_test_launcher(scripts, exit_code=17) + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + profile_log = root / "selected-profile.txt" + + exit_code, result_path = self._execute( + output, + root, + image_digest=IMAGE, + environment={ + "GITHUB_RUN_ID": "456", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY_ID": "123", + "TEST_PROFILE_LOG": str(profile_log), + }, + ) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertEqual(17, result["exitCode"]) + self.assertEqual("ASEHB009", result["diagnostic"]["code"]) + + def test_fork_observation_remains_non_claiming_and_exits_two(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-fork-observation-") as temporary: + root = Path(temporary).resolve() + capture = root / "capture" + scripts = root / "trusted-scripts" + output_parent = root / "outputs" + capture.mkdir() + scripts.mkdir() + output_parent.mkdir() + (capture / "observation.json").write_bytes( + handoff._canonical_json( + {"Mode": "ObservationOnly", "WorkflowRunAttempt": 1, "WorkflowRunId": 456} + ) + ) + shutil.copyfile(SCRIPT, scripts / "evidence-gate-handoff.py") + output = output_parent / "handoff" + + self.assertEqual( + "observation", + handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output, + ), + ) + exit_code, result_path = self._execute( + output, + root, + environment={"GITHUB_RUN_ID": "456", "GITHUB_RUN_ATTEMPT": "1"}, + ) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("observation-only", result["execution"]) + self.assertEqual("ASEHB007", result["diagnostic"]["code"]) + + def test_missing_plan_is_rejected_for_same_repository_capture(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-missing-plan-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "EvidencePlan is required"): + handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output_parent / "handoff", + ) + + def test_tampered_handoff_plan_fails_execution(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-plan-tamper-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + plan, _ = handoff._read_evidence_plan(output / "evidence-plan.json") + tampered = dict(plan) + tampered["PolicyDigest"] = "c" * 64 + (output / "evidence-plan.json").write_bytes(handoff._canonical_evidence_json(tampered)) + + exit_code, result_path = self._execute(output, root) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertEqual("ASEHB001", result["diagnostic"]["code"]) + + def test_missing_or_changed_trusted_supervisor_fails_before_subject_execution(self) -> None: + for mutation in ("missing", "changed"): + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory( + prefix="evidence-gate-supervisor-handoff-" + ) as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root) + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + supervisor = output / "evidence-gate-subject-supervisor.py" + if mutation == "missing": + supervisor.unlink() + else: + supervisor.write_bytes(supervisor.read_bytes() + b"\n# changed\n") + + exit_code, result_path = self._execute(output, root) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertEqual("ASEHB001", result["diagnostic"]["code"]) + + def test_revision_mismatch_in_plan_is_rejected_during_capture(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-plan-revision-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, revision_overrides={"BaseRevision": "0" * 40}) + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "BaseRevision does not match"): + handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output_parent / "handoff", + plan_file=plan_file, + ) + + def test_pull_request_identity_mismatch_in_plan_is_rejected(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-plan-identity-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, identity_overrides={"WorkflowRunAttempt": 2}) + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "run identity does not match"): + handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output_parent / "handoff", + plan_file=plan_file, + ) + + def test_profile_not_closed_by_policy_snapshot_is_rejected(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-plan-profile-mismatch-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, snapshot_profile_id="documentation-only") + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "not closed by its policy snapshot"): + handoff.create_handoff( + capture_directory=capture, + trusted_scripts_directory=scripts, + output_directory=output_parent / "handoff", + plan_file=plan_file, + ) + + def test_unsupported_policy_profile_fails_closed_without_substitute(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-unsupported-profile-") as temporary: + root = Path(temporary).resolve() + capture, scripts, _ = self._capture(root) + plan_file = self._write_plan(root, capture, profile_id="postgresql-integration") + output_parent = root / "outputs" + output_parent.mkdir() + output = output_parent / "handoff" + self._create(capture, scripts, plan_file, output) + + exit_code, result_path = self._execute(output, root) + + self.assertEqual(2, exit_code) + result = json.loads(result_path.read_text(encoding="utf-8")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["execution"]) + self.assertEqual("postgresql-integration", result["profileId"]) + self.assertEqual("ASEHB008", result["diagnostic"]["code"]) + self.assertFalse((root / "subject-checkout").exists()) + + def test_export_ignore_omission_is_rejected_against_git_tree(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-export-ignore-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root, attributes="omitted.txt export-ignore\n") + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "omits or adds a regular file") as failure: + self._create(capture, scripts, plan_file, output_parent / "handoff") + + self.assertEqual("ASEHB004", failure.exception.code) + + def test_export_subst_transformation_is_rejected_against_git_blob(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-export-subst-") as temporary: + root = Path(temporary).resolve() + capture, scripts, plan_file = self._capture(root, attributes="subject.txt export-subst\n") + output_parent = root / "outputs" + output_parent.mkdir() + + with self.assertRaisesRegex(handoff.HandoffError, "differs from its captured Git blob") as failure: + self._create(capture, scripts, plan_file, output_parent / "handoff") + + self.assertEqual("ASEHB004", failure.exception.code) + + def test_archive_case_collision_is_rejected(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-gate-case-collision-") as temporary: + archive_path = Path(temporary) / "snapshot.tar" + with tarfile.open(archive_path, "w") as archive: + for name in ("Directory", "directory"): + member = tarfile.TarInfo(name) + member.type = tarfile.DIRTYPE + archive.addfile(member) + + with self.assertRaisesRegex(handoff.HandoffError, "case-colliding") as failure: + handoff._scan_archive(archive_path) + + self.assertEqual("ASEHB004", failure.exception.code) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_observation.py b/scripts/tests/test_evidence_gate_observation.py new file mode 100644 index 000000000..99a62c939 --- /dev/null +++ b/scripts/tests/test_evidence_gate_observation.py @@ -0,0 +1,353 @@ +"""Tests for the trusted, non-claiming verifier observation builder.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-observation.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_observation", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +observation = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = observation +SPEC.loader.exec_module(observation) + + +class TrustedObservationTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix="trusted-observation-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name).resolve() + self.plan_path = self.root / "verified-plan.json" + self.identity_path = self.root / "verifier-identity.json" + self.subject_path = self.root / "subject-result.json" + self.cleanup_path = self.root / "cleanup.json" + self.artifacts_path = self.root / "artifacts" + self.output_path = self.root / "observation.json" + self.repository = "forge-trust/AppSurface" + self.base_revision = "a" * 40 + self.head_revision = "b" * 40 + self.snapshot_sha256 = "c" * 64 + self.image_digest = "ghcr.io/forge-trust/appsurface-subject-native-validation@sha256:" + "d" * 64 + self.identity = { + "EventName": "pull_request_target", + "Repository": self.repository, + "RunIdentity": { + "HeadRepositoryId": 321, + "PullRequestNumber": 777, + "RepositoryId": 321, + "TargetBranch": "main", + "WorkflowRunAttempt": 2, + "WorkflowRunId": 654321, + }, + "SubjectJobId": "5678", + "WorkflowId": "1234", + } + self.plan = self._plan("documentation-only") + self.subject = self._subject("documentation-only") + self._write_inputs() + + def _plan(self, profile_id: str) -> dict[str, object]: + empty = profile_id == "documentation-only" + selected_profile = { + "Id": profile_id, + "Scope": "Targeted", + "Resources": [] if empty else [{"Id": "coverage"}], + "Producers": [] if empty else [{"Id": "coverage"}], + "Obligations": [] if empty else [{"Id": "coverage"}], + } + return { + "BaseRevision": self.base_revision, + "ChangedPaths": [], + "ContractVersion": "2.0", + "DiffDigest": "1" * 64, + "HeadRevision": self.head_revision, + "MatchedRuleIds": [], + "NameStatusDigest": "2" * 64, + "PlanDigest": "3" * 64, + "PolicyDigest": "4" * 64, + "PolicyId": "appsurface", + "PolicySnapshot": {"Profiles": [selected_profile]}, + "Profile": selected_profile, + "PullRequestRunIdentity": { + "RepositoryId": 321, + "HeadRepositoryId": 321, + "PullRequestNumber": 777, + "TargetBranch": "main", + "WorkflowRunId": 654321, + "WorkflowRunAttempt": 2, + }, + "SourceDiffDigest": "5" * 64, + } + + def _subject(self, profile_id: str) -> dict[str, object]: + result: dict[str, object] = { + "claimEligible": False, + "execution": "completed", + "exitCode": 0, + "headRevision": self.head_revision, + "mode": "SubjectSnapshot", + "profileId": profile_id, + "schemaVersion": 1, + "snapshotSha256": self.snapshot_sha256, + "workflowRunAttempt": "2", + "workflowRunId": "654321", + "diagnostic": { + "code": "ASEHB010", + "message": "Subject execution completed without a trusted evidence verifier.", + }, + } + if profile_id == "code-coverage": + result.update({ + "snapshotFileCount": 14, + "snapshotExpandedBytes": 1024, + "stdoutBytes": 100, + "stdoutSha256": "6" * 64, + "stderrBytes": 0, + "stderrSha256": "7" * 64, + }) + binding = { + "baseRevision": self.base_revision, + "headRevision": self.head_revision, + "profileId": profile_id, + "snapshotSha256": self.snapshot_sha256, + "workflowRunAttempt": "2", + "workflowRunId": "654321", + } + artifact_index = [] + self.artifacts_path.mkdir(exist_ok=True) + for basename, logical_name, relative_path in observation.ARTIFACT_INDEX: + raw = ("fixed artifact: " + basename).encode("ascii") + (self.artifacts_path / basename).write_bytes(raw) + artifact_index.append({ + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": len(raw), + "sha256": hashlib.sha256(raw).hexdigest(), + }) + record = { + "claimEligible": False, + "profileId": "code-coverage", + "schemaVersion": 1, + "status": "completed", + "steps": [ + { + "exitCode": 0, + "name": name, + "outputBytes": 0, + "stderrSha256": "8" * 64, + "stdoutSha256": "9" * 64, + } + for name in ("dotnet-sdk-version", "dotnet-runtime-list", "offline-locked-restore", "coverage-run", "coverage-gate") + ], + "artifacts": artifact_index, + } + result["executionReceipt"] = self._receipt(binding, "record", record) + envelope = { + "schemaVersion": 1, + "imageDigest": self.image_digest, + "profileId": "code-coverage", + "runnerEnvironment": "github-hosted", + "runtime": "rootless-podman", + "networkMode": "none", + "rootfsReadOnlyConfigured": True, + "subjectAndDiffReadOnlyConfigured": True, + "scratchTmpfsQuotaVerified": True, + "capabilityDropConfigured": True, + "noNewPrivilegesConfigured": True, + "pidIpcUtsUserNamespacesConfiguredPrivate": True, + "resourceLimitsConfigured": True, + } + result["envelopeReceipt"] = self._receipt(binding, "observation", envelope) + return result + + @staticmethod + def _receipt(binding: dict[str, str], member: str, record: dict[str, object]) -> dict[str, object]: + payload = {"binding": binding, member: record, "schemaVersion": 1} + return {**payload, "sha256": hashlib.sha256(observation._canonical(payload)).hexdigest()} + + @staticmethod + def _write_json(path: Path, value: object) -> None: + path.write_bytes(observation._canonical(value)) + + def _write_inputs(self) -> None: + self._write_json(self.plan_path, self.plan) + self._write_json(self.identity_path, self.identity) + self.subject_path.write_bytes(observation._canonical(self.subject) + b"\n") + + def _build(self, **overrides: object) -> dict[str, object]: + options: dict[str, object] = { + "verified_plan_path": self.plan_path, + "verifier_identity_path": self.identity_path, + "subject_result_path": self.subject_path, + } + options.update(overrides) + return observation.build_observation(**options) + + def _coverage_inputs(self) -> dict[str, object]: + self.plan = self._plan("code-coverage") + self.subject = self._subject("code-coverage") + self._write_inputs() + self.cleanup_path.write_bytes(observation._canonical({ + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "complete", + "trigger": "request", + "containerStatus": "removed", + "mountStatus": "unmounted", + "scratchStatus": "removed", + "failureCode": "none", + "cleanupDeadlineSeconds": 600, + }) + b"\n") + return { + "cleanup_record_path": self.cleanup_path, + "subject_artifacts_directory": self.artifacts_path, + "expected_image_digest": self.image_digest, + } + + def test_documentation_observation_is_canonical_bounded_and_nonclaiming(self) -> None: + self.assertEqual( + { + "HeadRepositoryId", "PullRequestNumber", "RepositoryId", "TargetBranch", "WorkflowRunAttempt", "WorkflowRunId", + }, + set(self.identity["RunIdentity"]), + ) + result = self._build() + encoded = observation._canonical(result) + b"\n" + + self.assertLessEqual(len(encoded), observation.MAX_OUTPUT_BYTES) + self.assertEqual(encoded, observation._canonical(json.loads(encoded)) + b"\n") + self.assertIs(result["claimEligible"], False) + self.assertEqual("documentation-only", result["profile"]["id"]) + self.assertIsNone(result["trustedPreflight"]) + self.assertEqual([], result["subjectArtifacts"]) + self.assertEqual(hashlib.sha256(self.plan_path.read_bytes()).hexdigest(), result["inputSha256"]["verifiedPlan"]) + self.assertNotIn(str(self.root), encoded.decode("ascii")) + + def test_coverage_binds_trusted_image_preflight_and_fixed_artifact_bytes(self) -> None: + self.base_revision = "e" * 40 + self.head_revision = "f" * 40 + result = self._build(**self._coverage_inputs()) + + self.assertIs(result["claimEligible"], False) + self.assertEqual(self.base_revision, result["run"]["pullRequestIdentity"]["baseRevision"]) + self.assertEqual(self.head_revision, result["run"]["pullRequestIdentity"]["headRevision"]) + self.assertEqual({"subjectImageDigest": self.image_digest}, result["trustedPreflight"]) + self.assertEqual( + hashlib.sha256(self.image_digest.encode("ascii")).hexdigest(), + result["inputSha256"]["trustedPreflightImageDigest"], + ) + self.assertEqual(3, len(result["subjectArtifacts"])) + for artifact in result["subjectArtifacts"]: + raw = (self.artifacts_path / artifact["name"]).read_bytes() + self.assertEqual(hashlib.sha256(raw).hexdigest(), artifact["sha256"]) + + def test_coverage_requires_preflight_digest_and_rejects_receipt_mismatch(self) -> None: + inputs = self._coverage_inputs() + with self.assertRaises(observation.ObservationError): + self._build(cleanup_record_path=inputs["cleanup_record_path"], subject_artifacts_directory=inputs["subject_artifacts_directory"]) + + with self.assertRaises(observation.ObservationError): + self._build(**{**inputs, "expected_image_digest": self.image_digest[:-1] + "0"}) + + self.plan["BaseRevision"] = "e" * 40 + self._write_json(self.plan_path, self.plan) + with self.assertRaises(observation.ObservationError): + self._build(**inputs) + + def test_documentation_only_forbids_coverage_inputs_and_unexpected_receipts(self) -> None: + with self.assertRaises(observation.ObservationError): + self._build(expected_image_digest=self.image_digest) + + self.subject["envelopeReceipt"] = {} + self._write_inputs() + with self.assertRaises(observation.ObservationError): + self._build() + + def test_rejects_wrong_plan_or_subject_identity_bindings(self) -> None: + self.identity["RunIdentity"]["WorkflowRunAttempt"] = 1 + self._write_inputs() + with self.assertRaises(observation.ObservationError): + self._build() + + self.identity["RunIdentity"]["WorkflowRunAttempt"] = 2 + self._write_inputs() + self.subject["headRevision"] = "e" * 40 + self._write_json(self.subject_path, self.subject) + with self.assertRaises(observation.ObservationError): + self._build() + + def test_rejects_malformed_duplicate_and_oversized_inputs(self) -> None: + self.plan_path.write_bytes(b'{"Profile":{},"Profile":{}}') + with self.assertRaises(observation.ObservationError): + self._build() + + self.plan_path.write_bytes(b"x" * (observation.MAX_PLAN_BYTES + 1)) + with self.assertRaises(observation.ObservationError): + self._build() + + def test_rejects_symlinked_input_and_parent_paths(self) -> None: + target = self.root / "target.json" + target.write_bytes(self.plan_path.read_bytes()) + link = self.root / "linked-plan.json" + link.symlink_to(target) + with self.assertRaises(observation.ObservationError): + self._build(verified_plan_path=link) + + linked_parent = self.root / "linked-parent" + linked_parent.symlink_to(self.root, target_is_directory=True) + with self.assertRaises(observation.ObservationError): + self._build(verified_plan_path=linked_parent / self.plan_path.name) + + def test_rejects_missing_extra_linked_and_digest_mismatched_artifacts(self) -> None: + inputs = self._coverage_inputs() + self.artifacts_path.joinpath("cobertura.xml").unlink() + with self.assertRaises(observation.ObservationError): + self._build(**inputs) + + self._coverage_inputs() + (self.artifacts_path / "unexpected.bin").write_bytes(b"unexpected") + with self.assertRaises(observation.ObservationError): + self._build(**inputs) + + (self.artifacts_path / "unexpected.bin").unlink() + (self.artifacts_path / "cobertura.xml").unlink() + (self.artifacts_path / "cobertura.xml").symlink_to(self.artifacts_path / "gate-report.md") + with self.assertRaises(observation.ObservationError): + self._build(**inputs) + + self._coverage_inputs() + (self.artifacts_path / "cobertura.xml").write_bytes(b"changed bytes") + with self.assertRaises(observation.ObservationError): + self._build(**inputs) + + def test_cli_writes_new_output_and_fails_without_disclosing_paths(self) -> None: + command = [ + sys.executable, str(SCRIPT), + "--verified-plan", str(self.plan_path), + "--verifier-identity", str(self.identity_path), + "--subject-result", str(self.subject_path), + "--output", str(self.output_path), + ] + completed = subprocess.run(command, check=False, capture_output=True, text=True) + self.assertEqual(0, completed.returncode, completed.stderr) + self.assertEqual(b"\n", self.output_path.read_bytes()[-1:]) + self.assertIn(b'"claimEligible":false', self.output_path.read_bytes()) + + failed_output = self.root / "failed.json" + completed = subprocess.run(command[:-2] + ["--expected-image-digest", self.image_digest, "--output", str(failed_output)], check=False, capture_output=True, text=True) + self.assertEqual(2, completed.returncode) + self.assertNotIn(str(self.root), completed.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_policy_shadow.py b/scripts/tests/test_evidence_gate_policy_shadow.py new file mode 100644 index 000000000..a36dc0d54 --- /dev/null +++ b/scripts/tests/test_evidence_gate_policy_shadow.py @@ -0,0 +1,237 @@ +"""Synthetic Git-object tests for the trusted policy-shadow preparer.""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-policy-shadow.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_policy_shadow", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +policy_shadow = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = policy_shadow +SPEC.loader.exec_module(policy_shadow) + + +POLICY_PATH = ".appsurface/evidence/evidence.policy.json" +FIXTURES_PATH = "docs/fixtures/issue-777-policy-shadow/fixtures.json" + + +def run_git(repository: Path, *arguments: str) -> bytes: + result = subprocess.run( + ["git", *arguments], + cwd=repository, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + ) + return result.stdout + + +class EvidenceGatePolicyShadowTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory(prefix="evidence-gate-policy-shadow-tests-") + self.root = Path(self.temporary_directory.name).resolve() + self.protected_base = self.root / "protected-base" + self._write_file(self.protected_base, POLICY_PATH, b'{"protected":"policy"}\n') + self._write_file(self.protected_base, FIXTURES_PATH, b"[]\n") + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + @staticmethod + def _write_file(root: Path, relative_path: str, content: bytes) -> Path: + destination = root.joinpath(*relative_path.split("/")) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(content) + return destination + + def _new_worktree(self) -> tuple[Path, Path, Path]: + capture = self.root / "capture" + capture.mkdir() + worktree = self.root / "candidate" + worktree.mkdir() + run_git(worktree, "init") + run_git(worktree, "config", "user.name", "Policy Shadow Test") + run_git(worktree, "config", "user.email", "policy-shadow@example.invalid") + return capture, worktree, capture / "repository.git" + + def _commit(self, worktree: Path, message: str) -> str: + run_git(worktree, "add", "--all") + run_git(worktree, "commit", "--quiet", "-m", message) + return run_git(worktree, "rev-parse", "HEAD").decode("ascii").strip() + + @staticmethod + def _write_identity(capture: Path, head_revision: str) -> None: + identity = { + "BaseRevision": "a" * len(head_revision), + "HeadRepositoryId": 123, + "HeadRevision": head_revision, + "PullRequestNumber": 777, + "RepositoryId": 123, + "TargetBranch": "main", + "WorkflowRunAttempt": 1, + "WorkflowRunId": 456, + } + (capture / "pull-request-run-identity.json").write_text( + json.dumps(identity, separators=(",", ":")), + encoding="utf-8", + ) + + def _publish_bare_store(self, capture: Path, worktree: Path, repository: Path, head_revision: str) -> Path: + subprocess.run( + ["git", "clone", "--quiet", "--bare", str(worktree), str(repository)], + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + ) + self._write_identity(capture, head_revision) + return capture + + def _prepare(self, capture: Path, name: str = "prepared") -> Path: + output = self.root / name + return policy_shadow.prepare(capture, self.protected_base, output) + + def test_extracts_only_blobs_at_exact_captured_head(self) -> None: + capture, worktree, repository = self._new_worktree() + self._write_file(worktree, POLICY_PATH, b'{"revision":"initial"}\n') + self._write_file(worktree, FIXTURES_PATH, b'[{"id":"initial"}]\n') + self._commit(worktree, "initial candidate") + head_policy = b'{"revision":"captured-head"}\n' + head_fixtures = b'[{"id":"captured-head"}]\n' + self._write_file(worktree, POLICY_PATH, head_policy) + self._write_file(worktree, FIXTURES_PATH, head_fixtures) + captured_head = self._commit(worktree, "captured head") + self._write_file(worktree, POLICY_PATH, b'{"revision":"later-branch-tip"}\n') + self._write_file(worktree, FIXTURES_PATH, b'[{"id":"later-branch-tip"}]\n') + self._commit(worktree, "later branch tip") + self._publish_bare_store(capture, worktree, repository, captured_head) + + output = self._prepare(capture) + + self.assertEqual(head_policy, (output / POLICY_PATH).read_bytes()) + self.assertEqual(head_fixtures, (output / FIXTURES_PATH).read_bytes()) + + def test_changed_policy_is_copied_as_candidate_data(self) -> None: + capture, worktree, repository = self._new_worktree() + self._write_file(worktree, POLICY_PATH, b'{"policy":"candidate-change"}\n') + self._write_file(worktree, FIXTURES_PATH, b"[]\n") + head = self._commit(worktree, "candidate policy change") + self._publish_bare_store(capture, worktree, repository, head) + + output = self._prepare(capture) + + self.assertEqual(b'{"policy":"candidate-change"}\n', (output / POLICY_PATH).read_bytes()) + self.assertEqual(b'{"protected":"policy"}\n', (self.protected_base / POLICY_PATH).read_bytes()) + + def test_deleted_candidate_fixtures_remain_absent(self) -> None: + capture, worktree, repository = self._new_worktree() + self._write_file(worktree, POLICY_PATH, b'{"policy":"candidate"}\n') + self._write_file(worktree, FIXTURES_PATH, b'[{"id":"deleted-later"}]\n') + self._commit(worktree, "with candidate fixtures") + (worktree / FIXTURES_PATH).unlink() + head = self._commit(worktree, "delete candidate fixtures") + self._publish_bare_store(capture, worktree, repository, head) + + output = self._prepare(capture) + + self.assertTrue((output / POLICY_PATH).is_file()) + self.assertFalse((output / FIXTURES_PATH).exists()) + + def test_symbolic_link_mode_is_rejected(self) -> None: + capture, worktree, repository = self._new_worktree() + policy = worktree / POLICY_PATH + policy.parent.mkdir(parents=True, exist_ok=True) + policy.symlink_to("candidate-policy-target.json") + self._write_file(worktree, FIXTURES_PATH, b"[]\n") + head = self._commit(worktree, "symlink candidate policy") + self._publish_bare_store(capture, worktree, repository, head) + + output = self.root / "unsafe-output" + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "unsafe Git file mode"): + policy_shadow.prepare(capture, self.protected_base, output) + + self.assertFalse(output.exists()) + + def test_executable_blob_mode_is_rejected(self) -> None: + capture, worktree, repository = self._new_worktree() + run_git(worktree, "config", "core.filemode", "true") + policy = self._write_file(worktree, POLICY_PATH, b'{"policy":"executable"}\n') + os.chmod(policy, 0o755) + self._write_file(worktree, FIXTURES_PATH, b"[]\n") + head = self._commit(worktree, "executable candidate policy") + self._publish_bare_store(capture, worktree, repository, head) + + output = self.root / "executable-output" + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "unsafe Git file mode"): + policy_shadow.prepare(capture, self.protected_base, output) + + self.assertFalse(output.exists()) + + def test_missing_candidate_policy_fails_closed(self) -> None: + capture, worktree, repository = self._new_worktree() + self._write_file(worktree, FIXTURES_PATH, b"[]\n") + head = self._commit(worktree, "candidate policy missing") + self._publish_bare_store(capture, worktree, repository, head) + + output = self.root / "missing-policy-output" + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "missing its required candidate policy"): + policy_shadow.prepare(capture, self.protected_base, output) + + self.assertFalse(output.exists()) + + def test_oversized_candidate_blob_fails_closed_before_output_creation(self) -> None: + capture, worktree, repository = self._new_worktree() + self._write_file(worktree, POLICY_PATH, b"p" * (policy_shadow.MAX_FILE_BYTES + 1)) + self._write_file(worktree, FIXTURES_PATH, b"[]\n") + head = self._commit(worktree, "oversized candidate policy") + self._publish_bare_store(capture, worktree, repository, head) + + output = self.root / "oversized-output" + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "byte limit"): + policy_shadow.prepare(capture, self.protected_base, output) + + self.assertFalse(output.exists()) + + def test_invalid_head_revision_is_rejected_before_git_invocation(self) -> None: + capture, _worktree, _repository = self._new_worktree() + identity = { + "BaseRevision": "a" * 40, + "HeadRepositoryId": 123, + "HeadRevision": "A" * 40, + "PullRequestNumber": 777, + "RepositoryId": 123, + "TargetBranch": "main", + "WorkflowRunAttempt": 1, + "WorkflowRunId": 456, + } + (capture / "pull-request-run-identity.json").write_text(json.dumps(identity), encoding="utf-8") + + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "full lower-case Git object ID"): + policy_shadow.prepare(capture, self.protected_base, self.root / "invalid-revision-output") + + def test_nonregular_protected_input_is_rejected_without_blocking(self) -> None: + fixture_path = self.protected_base.joinpath(*FIXTURES_PATH.split("/")) + fixture_path.unlink() + os.mkfifo(fixture_path) + capture, _worktree, _repository = self._new_worktree() + + started = time.monotonic() + with self.assertRaisesRegex(policy_shadow.PolicyShadowPreparerError, "bounded regular file"): + policy_shadow.prepare(capture, self.protected_base, self.root / "nonregular-output") + + self.assertLess(time.monotonic() - started, 1.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_subject.py b/scripts/tests/test_evidence_gate_subject.py new file mode 100644 index 000000000..d669fcccf --- /dev/null +++ b/scripts/tests/test_evidence_gate_subject.py @@ -0,0 +1,1239 @@ +"""Focused isolation and failure-path tests for the subject OCI launcher.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import shutil +import signal +import stat +import sys +import tempfile +import threading +from types import SimpleNamespace +from typing import Callable +import unittest +from contextlib import redirect_stdout +from unittest import mock + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-subject.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_subject", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +subject = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = subject +SPEC.loader.exec_module(subject) + + +IMAGE = "ghcr.io/forge-trust/appsurface-subject@sha256:" + "a" * 64 +ARTIFACT_CONTENTS = ( + b"cobertura artifact\n", + b"coverage gate report\n", + b"coverage diagnostics\n", +) + + +class FakeExecutor: + """Return deterministic Podman JSON while retaining every fixed argv.""" + + def __init__(self, root: Path, image: str = IMAGE) -> None: + self.root = root + self.image = image + self.calls: list[tuple[list[str], dict[str, object]]] = [] + self.container_name: str | None = None + self.fail_start: BaseException | None = None + self.start_exit_code = 0 + self.start_stderr = b"" + self.fail_cleanup = False + self.fail_mount = False + self.fail_unmount = False + self.cleanup_order: list[str] = [] + self.mount_options: str | None = None + self.mount_target: str | None = None + self.result_export: bytes | None = self.successful_subject_record() + self.config_override: dict[str, object] | None = None + self.scratch_mount_override: dict[str, object] | None = None + self.labels_override: dict[str, str] | None = None + self.partial_mount_present = False + self.stopped_state: dict[str, object] = {"Running": False, "Status": "exited"} + self.artifact_mutation: Callable[[Path], None] | None = None + self.lifecycle: list[str] = [] + self.scratch_mountpoint: Path | None = None + self.container_started = False + self.inspect_count = 0 + + def __call__(self, arguments: list[str], **options: object) -> subject.CommandResult: + self.calls.append((list(arguments), dict(options))) + self.assert_execution_options(options) + command = arguments[1:] + if command == ["--remote=false", "info", "--format=json"]: + return self.result( + { + "host": { + "security": {"rootless": True}, + "cgroupVersion": "v2", + "cgroupControllers": ["cpu", "memory", "pids"], + } + } + ) + if command[:3] == ["--remote=false", "image", "exists"]: + return subject.CommandResult(0, b"", b"") + if command[:3] == ["--remote=false", "image", "inspect"]: + return self.result( + [ + { + "RepoDigests": [self.image], + "Config": {"Volumes": {}}, + } + ] + ) + if command[1] == "create": + name_value = next(value for value in command if value.startswith("--name=")) + self.container_name = name_value.partition("=")[2] + return subject.CommandResult(0, b"", b"") + if command[1:3] == ["inspect", "--format=json"]: + self.lifecycle.append("inspect") + self.inspect_count += 1 + return self.container_inspect() + if arguments[0] == subject.SUDO_PATH: + privileged_command = arguments[1:] + if privileged_command[:4] == ["-n", "mount", "-t", "tmpfs"]: + self.cleanup_order.append("mount") + self.mount_options = privileged_command[5] + self.mount_target = privileged_command[-1] + return subject.CommandResult(1 if self.fail_mount else 0, b"", b"") + if privileged_command[:3] == ["-n", "umount", "--"]: + self.cleanup_order.append("umount") + assert self.mount_target == privileged_command[-1] + return subject.CommandResult(1 if self.fail_unmount else 0, b"", b"") + if command[1] == "start": + if self.fail_start is not None: + raise self.fail_start + self.lifecycle.append("start") + self._write_scratch_artifacts() + self.container_started = True + return subject.CommandResult(self.start_exit_code, self.result_export or b"", self.start_stderr) + if command[1:3] == ["rm", "--force"]: + self.cleanup_order.append("container-remove") + self.lifecycle.append("container-remove") + return subject.CommandResult(1 if self.fail_cleanup else 0, b"", b"") + raise AssertionError(f"unexpected fixed engine argv: {arguments!r}") + + @staticmethod + def assert_execution_options(options: dict[str, object]) -> None: + assert options["timeout_seconds"] > 0 + assert options["maximum_output_bytes"] > 0 + assert options["environment"] == { + "PATH": subject.ENGINE_PATH, + "HOME": str(options["environment"]["HOME"]), + "XDG_RUNTIME_DIR": str(options["environment"]["XDG_RUNTIME_DIR"]), + "TMPDIR": str(options["environment"]["TMPDIR"]), + "REGISTRY_AUTH_FILE": "/dev/null", + } + assert isinstance(options["cancel_event"], threading.Event) + + @staticmethod + def result(value: object) -> subject.CommandResult: + return subject.CommandResult(0, json.dumps(value, separators=(",", ":")).encode(), b"") + + @staticmethod + def successful_subject_record() -> bytes: + steps = [ + { + "exitCode": 0, + "name": name, + "outputBytes": 0, + "stderrSha256": "0" * 64, + "stdoutSha256": "0" * 64, + } + for name in subject.SUBJECT_RESULT_STEP_NAMES + ] + value = { + "artifacts": [ + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": len(content), + "sha256": hashlib.sha256(content).hexdigest(), + } + for (logical_name, relative_path, _maximum_bytes), content in zip( + subject.SUBJECT_ARTIFACTS, ARTIFACT_CONTENTS, strict=True + ) + ], + "claimEligible": False, + "profileId": "code-coverage", + "schemaVersion": 1, + "status": "completed", + "steps": steps, + } + return (json.dumps(value, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii") + + def container_inspect(self) -> subject.CommandResult: + assert self.container_name is not None + create_call = next(call for call, _ in self.calls if len(call) > 2 and call[2] == "create") + mounts = [create_call[index + 1] for index, value in enumerate(create_call[:-1]) if value == "--mount"] + subject_mount = next(value for value in mounts if "dst=/subject," in value) + subject_source = next(value.split("=", 1)[1] for value in subject_mount.split(",") if value.startswith("src=")) + diff_mount = next(value for value in mounts if "dst=/source.diff," in value) + diff_source = next(value.partition("=")[2] for value in diff_mount.split(",") if value.startswith("src=")) + scratch_mount = next( + value for value in mounts if "dst=/scratch," in value + ) + scratch_source = next( + value.partition("=")[2] for value in scratch_mount.split(",") if value.startswith("src=") + ) + self.scratch_mountpoint = Path(scratch_source) + create_arguments = create_call + labels = { + key: value + for argument in create_arguments + if argument.startswith("--label=") + for key, separator, value in [argument[len("--label="):].partition("=")] + if separator + } + if self.labels_override is not None: + labels = dict(self.labels_override) + pids = int(next(value.partition("=")[2] for value in create_arguments if value.startswith("--pids-limit="))) + memory_mib = int(next(value.partition("=")[2][:-1] for value in create_arguments if value.startswith("--memory="))) + cpu_millis = round( + float(next(value.partition("=")[2] for value in create_arguments if value.startswith("--cpus="))) * 1000 + ) + environment = [value.partition("=")[2] for value in create_arguments if value.startswith("--env=")] + document = [ + { + "Config": { + "Entrypoint": [subject.CONTAINER_ENTRYPOINT], + "Cmd": create_call[create_call.index(self.image) + 1 :], + "User": "65532:65532", + "WorkingDir": "/subject", + "Env": environment, + "Labels": labels, + }, + "HostConfig": { + "ReadonlyRootfs": True, + "CapDrop": sorted(subject.PODMAN_DEFAULT_CAPABILITIES), + "SecurityOpt": ["no-new-privileges"], + "NetworkMode": "none", + "PidsLimit": pids, + "Memory": memory_mib * 1024 * 1024, + "NanoCpus": cpu_millis * 1_000_000, + "Privileged": False, + "Devices": [], + "PortBindings": {}, + "Tmpfs": {}, + "PidMode": "private", + "IpcMode": "private", + "UTSMode": "private", + "CgroupnsMode": None, + "UsernsMode": "private", + }, + "Mounts": [ + { + "Type": "bind", + "Source": subject_source, + "Destination": "/subject", + "RW": False, + "Propagation": "rprivate", + }, + { + "Type": "bind", + "Source": diff_source, + "Destination": "/source.diff", + "RW": False, + "Propagation": "rprivate", + }, + { + "Type": "bind", + "Source": scratch_source, + "Destination": "/scratch", + "RW": True, + "Propagation": "rprivate", + }, + ], + "State": ( + { + "Running": False, + "Status": "created", + "Paused": False, + "Restarting": False, + "OOMKilled": False, + "Dead": False, + "Pid": 0, + "ExitCode": 0, + "Error": "", + } + if not self.container_started + else dict( + { + "Running": False, + "Status": "exited", + "Paused": False, + "Restarting": False, + "OOMKilled": False, + "Dead": False, + "Pid": 0, + "ExitCode": self.start_exit_code, + "Error": "", + } + | self.stopped_state + ) + ), + } + ] + if self.config_override: + document[0]["HostConfig"].update(self.config_override) + if self.scratch_mount_override is not None: + scratch_mount_document = next( + mount for mount in document[0]["Mounts"] if mount["Destination"] == "/scratch" + ) + scratch_mount_document.update(self.scratch_mount_override) + return self.result(document) + + def _write_scratch_artifacts(self) -> None: + assert self.scratch_mountpoint is not None + root = self.scratch_mountpoint + for (_logical_name, relative_path, _maximum_bytes), content in zip( + subject.SUBJECT_ARTIFACTS, ARTIFACT_CONTENTS, strict=True + ): + source = root / relative_path + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(content) + if self.artifact_mutation is not None: + self.artifact_mutation(root) + + +class FakeCleanupSupervisor: + """Public launcher seam fake; cleanup actions remain owned by this fake supervisor.""" + + def __init__( + self, + executor: FakeExecutor, + environment: dict[str, str], + *, + ready: bool = True, + fail_alive: bool = False, + attestation: dict[str, object] | None = None, + ) -> None: + self.executor = executor + self.environment = environment + self.ready = ready + self.fail_alive = fail_alive + self.attestation = attestation + self.owner_token = "b" * 32 + self.session: subject.SupervisorSession | None = None + self.scratch_directory: Path | None = None + self.started = False + self.requested = False + self.request_observed_export = False + self.artifact_export_directory: Path | None = None + self.request_observed_artifact_directory = False + self.request_observed_artifact_names: tuple[str, ...] = () + self.lifecycle: list[str] = [] + + def start(self, **arguments: object) -> subject.SupervisorSession: + self.started = True + self.lifecycle.append("start") + self.scratch_directory = Path(str(arguments["scratch_directory"])) + if self.ready: + state = Path(str(arguments["runner_temp"])) / f"appsurface-subject-supervisor-{self.owner_token}" + self.session = subject.SupervisorSession( + owner_token=self.owner_token, + owner_label=subject.SUPERVISOR_OWNER_LABEL, + manifest_path=state / "supervisor.json", + state_directory=state, + supervisor_pid=12345, + supervisor_start_time=67890, + ready=True, + state_directory_device=-1, + state_directory_inode=-1, + ) + return self.session + return subject.SupervisorSession( + owner_token=self.owner_token, + owner_label=subject.SUPERVISOR_OWNER_LABEL, + manifest_path=Path("/unavailable/supervisor.json"), + state_directory=Path("/unavailable"), + supervisor_pid=12345, + supervisor_start_time=67890, + ready=False, + state_directory_device=-1, + state_directory_inode=-1, + ) + + def assert_alive(self, session: subject.SupervisorSession) -> None: + if not self.ready or self.fail_alive or session is not self.session: + raise subject.SubjectLauncherError("ASEGS017", "fake supervisor is not ready") + self.lifecycle.append("assert-alive") + + def request_and_wait(self, session: subject.SupervisorSession) -> dict[str, object]: + self.requested = True + self.lifecycle.append("request") + self.executor.lifecycle.append("supervisor-request") + if self.artifact_export_directory is not None: + self.request_observed_artifact_directory = self.artifact_export_directory.is_dir() + if self.request_observed_artifact_directory: + self.request_observed_artifact_names = tuple( + sorted(path.name for path in self.artifact_export_directory.iterdir()) + ) + if session is not self.session: + raise subject.SubjectLauncherError("ASEGS017", "fake supervisor session mismatch") + mount_call = next( + (call for call, _ in self.executor.calls if call[0] == subject.SUDO_PATH and call[2] == "mount"), + None, + ) + create_attempted = any(call[2] == "create" for call, _ in self.executor.calls) + container_status = "absent" + if create_attempted: + result = self.executor( + ["/usr/bin/podman", "--remote=false", "rm", "--force", "--ignore", self.executor.container_name or ""], + **self._command_options(), + ) + container_status = "removed" if result.returncode == 0 else "failed" + + mount_status = "absent" + mount_present = False + if mount_call is not None: + mount_present = ( + not self.executor.fail_mount + or subject._host_scratch_mount_is_present(Path(str(self.executor.mount_target))) + ) + if mount_call is not None and mount_present: + if container_status in {"removed", "absent"}: + result = self.executor( + [subject.SUDO_PATH, "-n", "umount", "--", str(self.executor.mount_target)], + **self._command_options(), + ) + mount_status = "unmounted" if result.returncode == 0 else "failed" + if result.returncode == 0: + shutil.rmtree(Path(str(self.executor.mount_target))) + else: + mount_status = "unverified" + elif mount_call is not None: + shutil.rmtree(Path(str(self.executor.mount_target))) + scratch_status = ( + "removed" + if container_status in {"removed", "absent"} and mount_status in {"unmounted", "absent"} + else "preserved" + ) + self.request_observed_export = ( + self.scratch_directory is not None + and (self.scratch_directory / subject.SUBJECT_RESULT_RELATIVE_PATH).is_file() + ) + complete = ( + container_status in {"removed", "absent"} + and mount_status in {"unmounted", "absent"} + and scratch_status == "removed" + ) + record: dict[str, object] = { + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "complete" if complete else "incomplete", + "trigger": "request", + "containerStatus": container_status, + "mountStatus": mount_status, + "scratchStatus": scratch_status, + "failureCode": "none" if complete else "resource-cleanup-incomplete", + "cleanupDeadlineSeconds": subject.SUPERVISOR_CLEANUP_DEADLINE_SECONDS, + } + return self.attestation or record + + def _command_options(self) -> dict[str, object]: + return { + "timeout_seconds": subject.CLEANUP_TIMEOUT_SECONDS, + "maximum_output_bytes": 4096, + "environment": { + "PATH": subject.ENGINE_PATH, + "HOME": self.environment["HOME"], + "XDG_RUNTIME_DIR": self.environment["XDG_RUNTIME_DIR"], + "TMPDIR": self.environment["RUNNER_TEMP"], + "REGISTRY_AUTH_FILE": "/dev/null", + }, + "cancel_event": threading.Event(), + } + + +class EvidenceGateSubjectTests(unittest.TestCase): + def setUp(self) -> None: + if os.geteuid() == 0: + self.skipTest("host context validation requires a non-root test process") + self.temporary_directory = tempfile.TemporaryDirectory(prefix="evidence-gate-subject-tests-") + self.root = Path(self.temporary_directory.name).resolve() + self.launch_count = 0 + self.subject_root = self.root / "trusted-subject-snapshot" + self.subject_root.mkdir() + self.source_diff = self.root / "source.diff" + self.source_diff.write_bytes(b"controller captured unified diff\n") + self.source_diff_sha256 = hashlib.sha256(self.source_diff.read_bytes()).hexdigest() + self.runner_temp = self.root / "runner-temp" + self.runner_temp.mkdir() + self.home = self.root / "runner-home" + self.home.mkdir() + self.runtime = self.root / "runtime" + self.runtime.mkdir(mode=0o700) + self.environment = { + "GITHUB_ACTIONS": "true", + "RUNNER_ENVIRONMENT": "github-hosted", + "GITHUB_RUN_ID": "123456", + "GITHUB_RUN_ATTEMPT": "2", + "RUNNER_TEMP": str(self.runner_temp), + "HOME": str(self.home), + "XDG_RUNTIME_DIR": str(self.runtime), + } + self.limits = subject.SubjectLimits( + timeout_seconds=60, + memory_mib=512, + cpu_millis=1000, + pids=64, + output_bytes=16 * 1024, + ) + self.executor = FakeExecutor(self.root) + self.supervisor = FakeCleanupSupervisor(self.executor, self.environment) + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + def test_completed_subject_result_requires_exact_bounded_artifact_index(self) -> None: + valid = json.loads(FakeExecutor.successful_subject_record()) + mutations = ( + lambda value: value.pop("artifacts"), + lambda value: value["artifacts"].__setitem__(1, dict(value["artifacts"][0])), + lambda value: value["artifacts"].reverse(), + lambda value: value["artifacts"][0].update(relativePath="../coverage.cobertura.xml"), + lambda value: value["artifacts"][2].update(byteCount=subject.MAX_GATE_JSON_ARTIFACT_BYTES + 1), + lambda value: value["artifacts"][1].update(sha256="A" * 64), + ) + for index, mutate in enumerate(mutations): + with self.subTest(mutation=index): + result = json.loads(json.dumps(valid)) + mutate(result) + content = (json.dumps(result, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii") + with self.assertRaises(subject.SubjectLauncherError) as caught: + subject._validate_subject_result_content(content, expected_status="completed") + self.assertEqual("ASEGS021", caught.exception.code) + + def test_failed_subject_result_cannot_carry_artifact_index(self) -> None: + result = json.loads(FakeExecutor.successful_subject_record()) + result["status"] = "failed" + result["diagnostic"] = {"code": "ASESE013", "message": "artifact missing"} + content = (json.dumps(result, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii") + with self.assertRaises(subject.SubjectLauncherError) as caught: + subject._validate_subject_result_content(content, expected_status="failed") + self.assertEqual("ASEGS018", caught.exception.code) + + def test_stopped_container_verification_requires_exited_state(self) -> None: + invalid_states = ( + {"Running": True, "Status": "running"}, + {"Running": False, "Status": "created"}, + {"Running": 0, "Status": "exited"}, + None, + ) + for state in invalid_states: + with self.subTest(state=state), self.assertRaises(subject.SubjectLauncherError) as caught: + subject._verify_container_stopped( + FakeExecutor.result([{"State": state}]).stdout + ) + self.assertEqual("ASEGS012", caught.exception.code) + + def launch(self, **overrides: object) -> subject.SubjectRunResult: + self.launch_count += 1 + export_directory = self.runner_temp / ( + "subject-artifact-export" + if self.launch_count == 1 + else f"subject-artifact-export-{self.launch_count}" + ) + arguments: dict[str, object] = { + "subject_checkout": self.subject_root, + "image_digest": IMAGE, + "scratch_directory": self.runner_temp / "subject-scratch", + "profile_id": "code-coverage", + "source_diff": self.source_diff, + "source_diff_sha256": self.source_diff_sha256, + "artifact_export_directory": export_directory, + "limits": self.limits, + "_environment": self.environment, + "_system_name": "Linux", + "_effective_uid": os.geteuid(), + "_engine_path": "/usr/bin/podman", + "_host_mount_verifier": self.verify_fake_host_mount, + "_command_executor": self.executor, + "supervisor_client": self.supervisor, + } + arguments.update(overrides) + if "supervisor_client" not in overrides: + self.supervisor = FakeCleanupSupervisor( + arguments["_command_executor"], # type: ignore[arg-type] + arguments["_environment"], # type: ignore[arg-type] + ) + arguments["supervisor_client"] = self.supervisor + return subject.launch_subject(**arguments) + + def verify_fake_host_mount(self, mountpoint: Path, *, host_uid: int, host_gid: int) -> None: + self.assertTrue(mountpoint.is_dir()) + self.assertEqual("quota-limited-scratch-" + mountpoint.name.rsplit("-", 1)[-1], mountpoint.name) + self.assertEqual(os.geteuid(), host_uid) + self.assertEqual(os.getegid(), host_gid) + + def test_success_uses_fixed_offline_argv_and_exact_container_envelope(self) -> None: + hostile_command = "--entrypoint=/bin/sh -c 'cat /runner/token'" + (self.subject_root / "subject-owned-command.txt").write_text(hostile_command, encoding="utf-8") + result = self.launch() + + self.assertEqual(0, result.exit_code) + self.assertEqual(b"", result.stdout) + self.assertFalse(result.claim_eligible) + self.assertEqual(IMAGE, result.envelope_observation["imageDigest"]) + self.assertEqual("none", result.envelope_observation["networkMode"]) + self.assertIs(True, result.envelope_observation["subjectAndDiffReadOnlyConfigured"]) + self.assertEqual(self.runner_temp / "subject-artifact-export", result.artifact_export_directory) + export = result.artifact_export_directory + assert export is not None + self.assertEqual(0o700, stat.S_IMODE(export.stat().st_mode)) + self.assertEqual( + tuple(sorted(subject.SUBJECT_ARTIFACT_EXPORT_NAMES)), + tuple(sorted(path.name for path in export.iterdir())), + ) + for export_name, content in zip(subject.SUBJECT_ARTIFACT_EXPORT_NAMES, ARTIFACT_CONTENTS, strict=True): + exported = export / export_name + self.assertEqual(content, exported.read_bytes()) + self.assertEqual(0o600, stat.S_IMODE(exported.stat().st_mode)) + self.assertEqual(2, self.executor.inspect_count) + self.assertLess(self.executor.lifecycle.index("start"), self.executor.lifecycle.index("inspect", 2)) + self.assertLess(self.executor.lifecycle.index("inspect", 2), self.executor.lifecycle.index("container-remove")) + self.assertEqual(0o700, stat.S_IMODE(result.scratch_directory.stat().st_mode)) + exported_result = result.scratch_directory / subject.SUBJECT_RESULT_RELATIVE_PATH + self.assertTrue(exported_result.is_file()) + self.assertFalse(json.loads(exported_result.read_bytes())["claimEligible"]) + self.assertEqual("completed", json.loads(exported_result.read_bytes())["status"]) + self.assertTrue(self.supervisor.requested) + self.assertTrue(self.supervisor.request_observed_export) + self.assertEqual("start", self.supervisor.lifecycle[0]) + self.assertEqual("request", self.supervisor.lifecycle[-1]) + + podman_calls = [call for call, _ in self.executor.calls if call[0] != subject.SUDO_PATH] + self.assertTrue(all(call[1] == "--remote=false" for call in podman_calls)) + create = next(call for call, _ in self.executor.calls if call[2] == "create") + self.assertEqual("none", next(value.partition("=")[2] for value in create if value.startswith("--network="))) + self.assertIn("--http-proxy=false", create) + self.assertIn("--read-only", create) + self.assertIn("--cap-drop=ALL", create) + self.assertIn("--security-opt=no-new-privileges", create) + self.assertIn("--userns=keep-id:uid=65532,gid=65532", create) + self.assertIn("--user=65532:65532", create) + self.assertIn("--pids-limit=64", create) + self.assertIn("--memory=512m", create) + self.assertIn("--cpus=1.000", create) + self.assertIn("--unsetenv-all", create) + self.assertIn(f"--entrypoint={subject.CONTAINER_ENTRYPOINT}", create) + self.assertIn(IMAGE, create) + self.assertIn("--profile-id=code-coverage", create) + self.assertIn(f"--diff-sha256={self.source_diff_sha256}", create) + self.assertNotIn(hostile_command, " ".join(create)) + self.assertNotIn("--entrypoint=/bin/sh", create) + self.assertNotIn("GITHUB_TOKEN", " ".join(create)) + self.assertNotIn("subject-owned-command.txt", " ".join(create)) + owner_label_argument = ( + f"--label={subject.SUPERVISOR_OWNER_LABEL}={self.supervisor.owner_token}" + ) + self.assertIn(owner_label_argument, create) + self.assertFalse( + any("token" in value.casefold() for value in create if value != owner_label_argument) + ) + self.assertFalse(any("socket" in value.casefold() for value in create)) + self.assertEqual(3, len([value for value in create if value == "--mount"])) + self.assertNotIn("--tmpfs", create) + mount_arguments = [create[index + 1] for index, value in enumerate(create[:-1]) if value == "--mount"] + self.assertIn("dst=/subject,ro=true,bind-propagation=rprivate", mount_arguments[0]) + diff_mount = next(value for value in mount_arguments if "dst=/source.diff," in value) + self.assertIn(f"src={self.source_diff}", diff_mount) + self.assertIn("dst=/source.diff,ro=true,bind-propagation=rprivate", diff_mount) + scratch_mount = next(value for value in mount_arguments if "dst=/scratch," in value) + self.assertIn("type=bind", scratch_mount) + self.assertIn("rw=true", scratch_mount) + self.assertIn("bind-propagation=rprivate", scratch_mount) + self.assertTrue(scratch_mount.startswith("type=bind,src=" + str(result.scratch_directory / "quota-limited-scratch-"))) + mount_call = next(call for call, _ in self.executor.calls if call[0] == subject.SUDO_PATH and call[2] == "mount") + self.assertEqual([subject.SUDO_PATH, "-n", "mount", "-t", "tmpfs"], mount_call[:5]) + self.assertEqual("-o", mount_call[5]) + self.assertEqual( + "rw,nosuid,nodev," + f"size={subject.MAX_PROFILE_SCRATCH_BYTES}," + f"nr_inodes={subject.MAX_PROFILE_SCRATCH_INODES}," + f"mode=0700,uid={os.geteuid()},gid={os.getegid()}", + mount_call[6], + ) + self.assertEqual(["tmpfs", mount_call[-1]], mount_call[-2:]) + unmount_call = next(call for call, _ in self.executor.calls if call[0] == subject.SUDO_PATH and call[2] == "umount") + self.assertEqual([subject.SUDO_PATH, "-n", "umount", "--", mount_call[-1]], unmount_call) + self.assertEqual(mount_call[-1], self.executor.mount_target) + self.assertFalse(Path(mount_call[-1]).exists()) + self.assertEqual(["mount", "container-remove", "umount"], self.executor.cleanup_order) + self.assertTrue((result.scratch_directory / subject.SUBJECT_RESULT_RELATIVE_PATH).is_file()) + self.assertFalse(any(mountpoint.iterdir() for mountpoint in result.scratch_directory.glob("quota-limited-scratch-*"))) + self.assertFalse(any(call[2] == "cp" for call, _ in self.executor.calls)) + start_options = next(options for call, options in self.executor.calls if call[2] == "start") + self.assertEqual( + self.limits.output_bytes + subject.MAX_SUBJECT_RESULT_BYTES, + start_options["maximum_output_bytes"], + ) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in self.executor.calls)) + self.assertTrue(all(options["maximum_output_bytes"] <= subject.MAX_ENGINE_OUTPUT_BYTES for _, options in self.executor.calls)) + + def test_resource_backed_profile_fails_before_engine_or_scratch(self) -> None: + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(profile_id="postgresql-integration") + self.assertEqual("ASEGS005", caught.exception.code) + self.assertIn("network envelope", caught.exception.message) + self.assertEqual([], self.executor.calls) + self.assertFalse((self.runner_temp / "subject-scratch").exists()) + + def test_unknown_or_documentation_profile_cannot_launch_subject(self) -> None: + for profile in ("documentation-only", "new-policy-command"): + with self.subTest(profile=profile): + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(profile_id=profile) + self.assertEqual("ASEGS005", caught.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_unpinned_image_unsafe_scratch_and_path_symlink(self) -> None: + with self.assertRaises(subject.SubjectLauncherError) as image_error: + self.launch(image_digest="ghcr.io/forge-trust/appsurface:latest") + self.assertEqual("ASEGS004", image_error.exception.code) + + with self.assertRaises(subject.SubjectLauncherError) as scratch_error: + self.launch(scratch_directory=self.subject_root / "scratch") + self.assertEqual("ASEGS002", scratch_error.exception.code) + + alias = self.root / "subject-alias" + alias.symlink_to(self.subject_root, target_is_directory=True) + with self.assertRaises(subject.SubjectLauncherError) as path_error: + self.launch(subject_checkout=alias) + self.assertEqual("ASEGS002", path_error.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_source_diff_digest_mismatch_before_engine_use(self) -> None: + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(source_diff_sha256="0" * 64) + self.assertEqual("ASEGS020", caught.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_source_diff_inside_subject_checkout_before_engine_use(self) -> None: + subject_diff = self.subject_root / "source.diff" + content = b"head-controlled diff\n" + subject_diff.write_bytes(content) + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch( + source_diff=subject_diff, + source_diff_sha256=hashlib.sha256(content).hexdigest(), + ) + self.assertEqual("ASEGS020", caught.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_missing_linked_and_oversized_source_diff_before_engine_use(self) -> None: + missing = self.root / "missing.diff" + linked = self.root / "linked.diff" + linked.symlink_to(self.source_diff) + for path in (missing, linked): + with self.subTest(path=path), self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(source_diff=path) + self.assertEqual("ASEGS002", caught.exception.code) + with mock.patch.object(subject, "MAX_SOURCE_DIFF_BYTES", 4): + with self.assertRaises(subject.SubjectLauncherError) as oversized: + self.launch() + self.assertEqual("ASEGS020", oversized.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_runner_capability_gaps_and_unbounded_limits(self) -> None: + with self.assertRaises(subject.SubjectLauncherError) as hosted_error: + self.launch(_environment={**self.environment, "RUNNER_ENVIRONMENT": "self-hosted"}) + self.assertEqual("ASEGS003", hosted_error.exception.code) + + with self.assertRaises(subject.SubjectLauncherError) as linux_error: + self.launch(_system_name="Darwin") + self.assertEqual("ASEGS003", linux_error.exception.code) + + with self.assertRaises(subject.SubjectLauncherError) as limit_error: + self.launch(limits=subject.SubjectLimits(60, 512, 1001, 64, 16384)) + self.assertEqual("ASEGS001", limit_error.exception.code) + self.assertEqual([], self.executor.calls) + + def test_rejects_missing_rootless_and_cgroup_capabilities(self) -> None: + original = self.executor.__call__ + + def no_rootless(arguments: list[str], **options: object) -> subject.CommandResult: + if arguments[1:4] == ["--remote=false", "info", "--format=json"]: + return FakeExecutor.result( + { + "host": { + "security": {"rootless": False}, + "cgroupVersion": "v1", + "cgroupControllers": ["cpu"], + } + } + ) + return original(arguments, **options) + + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(_command_executor=no_rootless) + self.assertEqual("ASEGS009", caught.exception.code) + self.assertFalse((self.runner_temp / "subject-scratch").exists()) + + def test_container_configuration_mismatch_is_removed_and_never_claimed(self) -> None: + self.executor.config_override = {"NetworkMode": "bridge"} + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + self.assertEqual("ASEGS012", caught.exception.code) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in self.executor.calls)) + self.assertFalse(any(call[2] == "start" for call, _ in self.executor.calls)) + + def test_podman_capability_presentation_requires_every_default_drop_and_no_additions(self) -> None: + # The native Podman 4.9 pilot expands --cap-drop=ALL into a list of + # default capabilities, rather than retaining the literal ALL value. + self.assertEqual(0, self.launch().exit_code) + + invalid_presentations = ( + {"CapDrop": sorted(subject.PODMAN_DEFAULT_CAPABILITIES - {"CAP_CHOWN"})}, + {"CapDrop": sorted(subject.PODMAN_DEFAULT_CAPABILITIES) + ["CAP_CHOWN"]}, + {"CapAdd": ["CAP_CHOWN"]}, + ) + for index, override in enumerate(invalid_presentations): + with self.subTest(override=override): + executor = FakeExecutor(self.root) + executor.config_override = override + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch( + scratch_directory=self.runner_temp / f"scratch-invalid-cap-{index}", + _command_executor=executor, + ) + self.assertEqual("ASEGS012", caught.exception.code) + self.assertFalse(any(call[2] == "start" for call, _ in executor.calls)) + + literal_executor = FakeExecutor(self.root) + literal_executor.config_override = {"CapDrop": ["ALL"]} + self.assertEqual( + 0, + self.launch( + scratch_directory=self.runner_temp / "scratch-literal-cap-drop", + _command_executor=literal_executor, + ).exit_code, + ) + + def test_scratch_bind_inspection_rejects_untrusted_source_access_and_propagation(self) -> None: + overrides = ( + {"Source": str(self.runner_temp)}, + {"RW": False}, + {"Propagation": "rshared"}, + {"Type": "tmpfs"}, + ) + for index, override in enumerate(overrides): + with self.subTest(override=override): + executor = FakeExecutor(self.root) + executor.scratch_mount_override = override + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch( + scratch_directory=self.runner_temp / f"scratch-invalid-{index}", + _command_executor=executor, + ) + self.assertEqual("ASEGS012", caught.exception.code) + self.assertFalse(any(call[2] == "start" for call, _ in executor.calls)) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in executor.calls)) + + executor = FakeExecutor(self.root) + executor.config_override = {"Tmpfs": {"/scratch": "unexpected"}} + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(scratch_directory=self.runner_temp / "scratch-unexpected-tmpfs", _command_executor=executor) + self.assertEqual("ASEGS012", caught.exception.code) + self.assertFalse(any(call[2] == "start" for call, _ in executor.calls)) + + def test_successful_subject_requires_a_bounded_nonclaiming_result_export(self) -> None: + self.executor.result_export = b'{"claimEligible":true,"profileId":"code-coverage","schemaVersion":1,"status":"completed","steps":[]}\n' + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + self.assertEqual("ASEGS018", caught.exception.code) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in self.executor.calls)) + + executor = FakeExecutor(self.root) + executor.result_export = b"x" * (subject.MAX_SUBJECT_RESULT_BYTES + 1) + with self.assertRaises(subject.SubjectLauncherError) as oversized_error: + self.launch(scratch_directory=self.runner_temp / "scratch-export-oversized", _command_executor=executor) + self.assertEqual("ASEGS018", oversized_error.exception.code) + self.assertFalse( + (self.runner_temp / "scratch-export-oversized" / subject.SUBJECT_RESULT_RELATIVE_PATH).exists() + ) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in executor.calls)) + + executor = FakeExecutor(self.root) + executor.result_export = None + with self.assertRaises(subject.SubjectLauncherError) as missing_error: + self.launch(scratch_directory=self.runner_temp / "scratch-export-missing", _command_executor=executor) + self.assertEqual("ASEGS018", missing_error.exception.code) + self.assertFalse( + (self.runner_temp / "scratch-export-missing" / subject.SUBJECT_RESULT_RELATIVE_PATH).exists() + ) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in executor.calls)) + + def test_artifact_export_rejects_unsafe_or_changed_source_and_removes_partial_copy(self) -> None: + def mutate_missing(root: Path) -> None: + (root / subject.SUBJECT_ARTIFACTS[0][1]).unlink() + + def mutate_symlink(root: Path) -> None: + artifact = root / subject.SUBJECT_ARTIFACTS[0][1] + saved = artifact.with_name("original.xml") + artifact.rename(saved) + artifact.symlink_to(saved.name) + + def mutate_hardlink(root: Path) -> None: + artifact = root / subject.SUBJECT_ARTIFACTS[0][1] + os.link(artifact, artifact.with_name("second-link.xml")) + + def mutate_digest(root: Path) -> None: + artifact = root / subject.SUBJECT_ARTIFACTS[1][1] + artifact.write_bytes(b"x" * len(ARTIFACT_CONTENTS[1])) + + def mutate_oversized(root: Path) -> None: + artifact = root / subject.SUBJECT_ARTIFACTS[2][1] + with artifact.open("r+b") as output: + output.truncate(subject.MAX_GATE_JSON_ARTIFACT_BYTES + 1) + + for index, mutation in enumerate( + (mutate_missing, mutate_symlink, mutate_hardlink, mutate_digest, mutate_oversized) + ): + with self.subTest(mutation=mutation.__name__): + executor = FakeExecutor(self.root) + executor.artifact_mutation = mutation + exported = self.runner_temp / f"unsafe-export-{index}" + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch( + scratch_directory=self.runner_temp / f"unsafe-scratch-{index}", + artifact_export_directory=exported, + _command_executor=executor, + ) + self.assertEqual("ASEGS021", caught.exception.code) + self.assertFalse(exported.exists()) + self.assertTrue(self.supervisor.requested) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in executor.calls)) + + def test_successful_subject_requires_every_fixed_zero_exit_step(self) -> None: + valid = json.loads(FakeExecutor.successful_subject_record()) + mutations = ( + lambda value: value.update(steps=[]), + lambda value: value["steps"].pop(), + lambda value: value["steps"][2].update(name="unexpected-step"), + lambda value: value["steps"][2].update(exitCode=1), + lambda value: value["steps"][0].update(stdoutSha256="not-a-digest"), + lambda value: value["steps"][0].update(outputBytes=True), + lambda value: value["steps"][0].update(unexpected=True), + ) + for index, mutate in enumerate(mutations): + with self.subTest(mutation=index): + value = json.loads(json.dumps(valid)) + mutate(value) + executor = FakeExecutor(self.root) + executor.result_export = ( + json.dumps(value, separators=(",", ":"), sort_keys=True) + "\n" + ).encode("ascii") + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch( + scratch_directory=self.runner_temp / f"scratch-step-proof-{index}", + _command_executor=executor, + ) + self.assertEqual("ASEGS018", caught.exception.code) + + def test_failed_subject_exports_its_typed_nonclaiming_result_record(self) -> None: + self.executor.start_exit_code = 2 + self.executor.result_export = ( + b'{"claimEligible":false,"diagnostic":{"code":"ASESE010","message":"coverage unavailable"},' + b'"profileId":"code-coverage","schemaVersion":1,"status":"failed","steps":[]}\n' + ) + result = self.launch() + + self.assertEqual(2, result.exit_code) + self.assertFalse(result.claim_eligible) + record = json.loads((result.scratch_directory / subject.SUBJECT_RESULT_RELATIVE_PATH).read_bytes()) + self.assertEqual("failed", record["status"]) + self.assertEqual("ASESE010", record["diagnostic"]["code"]) + + def test_cancellation_during_subject_process_still_cleans_container(self) -> None: + self.executor.fail_start = subject._ProcessCancelled() + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + self.assertEqual("ASEGS013", caught.exception.code) + cleanup = next(call for call, _ in self.executor.calls if call[2] == "rm") + self.assertIn("--force", cleanup) + + def test_pre_cancelled_request_starts_no_engine_process(self) -> None: + cancelled = threading.Event() + cancelled.set() + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(cancel_event=cancelled) + self.assertEqual("ASEGS013", caught.exception.code) + self.assertEqual([], self.executor.calls) + + def test_cleanup_failure_invalidates_even_a_zero_exit_run(self) -> None: + self.executor.fail_cleanup = True + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + self.assertEqual("ASEGS017", caught.exception.code) + self.assertEqual(["mount", "container-remove"], self.executor.cleanup_order) + self.assertTrue(Path(self.executor.mount_target or "").is_dir()) + + def test_unready_supervisor_stops_before_mount_or_container_creation(self) -> None: + self.supervisor = FakeCleanupSupervisor(self.executor, self.environment, ready=False) + + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(supervisor_client=self.supervisor) + + self.assertEqual("ASEGS017", caught.exception.code) + self.assertTrue(self.supervisor.started) + self.assertFalse(self.supervisor.requested) + self.assertFalse(any(call[0] == subject.SUDO_PATH for call, _ in self.executor.calls)) + self.assertFalse(any(len(call) > 2 and call[2] == "create" for call, _ in self.executor.calls)) + + def test_missing_container_owner_label_fails_before_start_and_still_requests_cleanup(self) -> None: + self.executor.labels_override = {} + + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + + self.assertEqual("ASEGS012", caught.exception.code) + self.assertTrue(self.supervisor.requested) + self.assertFalse(any(len(call) > 2 and call[2] == "start" for call, _ in self.executor.calls)) + + def test_incomplete_supervisor_attestation_invalidates_zero_exit_execution(self) -> None: + self.supervisor = FakeCleanupSupervisor( + self.executor, + self.environment, + attestation={ + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "incomplete", + "trigger": "request", + "containerStatus": "removed", + "mountStatus": "unmounted", + "scratchStatus": "preserved", + "failureCode": "resource-cleanup-incomplete", + "cleanupDeadlineSeconds": subject.SUPERVISOR_CLEANUP_DEADLINE_SECONDS, + }, + ) + + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch(supervisor_client=self.supervisor) + + self.assertEqual("ASEGS017", caught.exception.code) + self.assertTrue(self.supervisor.requested) + self.assertTrue(self.supervisor.request_observed_export) + + def test_host_tmpfs_mount_failure_stops_before_container_creation(self) -> None: + self.executor.fail_mount = True + + with mock.patch.object(subject, "_host_scratch_mount_is_present", return_value=False): + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + + self.assertEqual("ASEGS019", caught.exception.code) + self.assertEqual(["mount"], self.executor.cleanup_order) + self.assertFalse(any(call[2] == "create" for call, _ in self.executor.calls)) + self.assertFalse(Path(self.executor.mount_target or "").exists()) + + partial_executor = FakeExecutor(self.root) + partial_executor.fail_mount = True + with mock.patch.object(subject, "_host_scratch_mount_is_present", return_value=True): + with self.assertRaises(subject.SubjectLauncherError) as partial_failure: + self.launch( + scratch_directory=self.runner_temp / "scratch-partial-mount", + _command_executor=partial_executor, + ) + + self.assertEqual("ASEGS019", partial_failure.exception.code) + self.assertEqual(["mount", "umount"], partial_executor.cleanup_order) + self.assertFalse(any(call[2] == "create" for call, _ in partial_executor.calls)) + self.assertFalse(Path(partial_executor.mount_target or "").exists()) + + def test_host_tmpfs_unmount_failure_invalidates_run_and_keeps_mountpoint(self) -> None: + self.executor.fail_unmount = True + + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + + self.assertEqual("ASEGS017", caught.exception.code) + self.assertEqual(["mount", "container-remove", "umount"], self.executor.cleanup_order) + mountpoint = Path(self.executor.mount_target or "") + self.assertTrue(mountpoint.is_dir()) + self.assertTrue((mountpoint.parent / subject.SUBJECT_RESULT_RELATIVE_PATH).is_file()) + + def test_mountinfo_parser_decodes_mountpoint_and_checks_live_tmpfs_limits(self) -> None: + mountpoint = self.root / "scratch mount" + mountpoint.mkdir(mode=0o700) + os.chmod(mountpoint, 0o700) + mountinfo_path = self.root / "mountinfo" + escaped_mountpoint = str(mountpoint).replace(" ", r"\040") + + def write_mountinfo(*, inode_limit: int = subject.MAX_PROFILE_SCRATCH_INODES) -> None: + mountinfo_path.write_text( + "41 25 0:38 / " + f"{escaped_mountpoint} rw,nosuid,nodev - tmpfs tmpfs " + f"rw,nosuid,nodev,size={subject.MAX_PROFILE_SCRATCH_BYTES}," + f"nr_inodes={inode_limit},mode=700,uid={os.geteuid()},gid={os.getegid()}\n", + encoding="utf-8", + ) + + filesystem_stats = SimpleNamespace( + f_blocks=subject.MAX_PROFILE_SCRATCH_BYTES // 4096, + f_frsize=4096, + f_files=subject.MAX_PROFILE_SCRATCH_INODES, + ) + with mock.patch.object(subject, "MOUNTINFO_PATH", mountinfo_path): + with mock.patch.object(subject.os, "statvfs", return_value=filesystem_stats): + write_mountinfo() + self.assertTrue(subject._host_scratch_mount_is_present(mountpoint)) + subject._verify_host_scratch_mount( + mountpoint, + host_uid=os.geteuid(), + host_gid=os.getegid(), + ) + + write_mountinfo(inode_limit=subject.MAX_PROFILE_SCRATCH_INODES + 1) + with self.assertRaises(subject.SubjectLauncherError) as caught: + subject._verify_host_scratch_mount( + mountpoint, + host_uid=os.geteuid(), + host_gid=os.getegid(), + ) + self.assertEqual("ASEGS019", caught.exception.code) + + mountinfo_path.write_text("malformed mountinfo\n", encoding="utf-8") + with self.assertRaises(subject.SubjectLauncherError) as malformed: + subject._host_scratch_mount_is_present(mountpoint) + self.assertEqual("ASEGS019", malformed.exception.code) + + def test_bounded_output_rejection_is_preserved_and_container_is_cleaned(self) -> None: + self.executor.fail_start = subject._ProcessOutputExceeded() + with self.assertRaises(subject.SubjectLauncherError) as caught: + self.launch() + self.assertEqual("ASEGS015", caught.exception.code) + self.assertTrue(any(call[2] == "rm" for call, _ in self.executor.calls)) + + executor = FakeExecutor(self.root) + executor.start_stderr = b"x" * (self.limits.output_bytes + 1) + with self.assertRaises(subject.SubjectLauncherError) as stderr_error: + self.launch(scratch_directory=self.runner_temp / "scratch-stderr-overflow", _command_executor=executor) + self.assertEqual("ASEGS015", stderr_error.exception.code) + self.assertTrue(any(call[2:4] == ["rm", "--force"] for call, _ in executor.calls)) + + def test_process_executor_uses_argv_and_kills_process_group_on_cancellation(self) -> None: + class FakeProcess: + pid = 43210 + + def __init__(self) -> None: + stdout_read, stdout_write = os.pipe() + stderr_read, stderr_write = os.pipe() + os.close(stdout_write) + os.close(stderr_write) + self.stdout = os.fdopen(stdout_read, "rb", buffering=0) + self.stderr = os.fdopen(stderr_read, "rb", buffering=0) + self.returncode: int | None = None + + def poll(self) -> int | None: + return self.returncode + + def wait(self, timeout: float) -> int: + self.returncode = -15 + return self.returncode + + def terminate(self) -> None: + self.returncode = -15 + + def kill(self) -> None: + self.returncode = -9 + + process = FakeProcess() + cancellation = threading.Event() + cancellation.set() + with mock.patch.object(subject.subprocess, "Popen", return_value=process) as popen: + with mock.patch.object(subject.os, "killpg") as kill_group: + with self.assertRaises(subject._ProcessCancelled): + subject._run_command( + ["/usr/bin/podman", "--remote=false", "start", "--attach", "fixed-id"], + timeout_seconds=10, + maximum_output_bytes=4096, + environment={"PATH": subject.ENGINE_PATH}, + cancel_event=cancellation, + ) + self.assertEqual([signal.SIGTERM, signal.SIGKILL], [call.args[1] for call in kill_group.call_args_list]) + self.assertEqual(["/usr/bin/podman", "--remote=false", "start", "--attach", "fixed-id"], popen.call_args.args[0]) + self.assertFalse(popen.call_args.kwargs["shell"]) + self.assertTrue(popen.call_args.kwargs["start_new_session"]) + self.assertEqual("/", popen.call_args.kwargs["cwd"]) + + def test_process_executor_enforces_combined_output_budget(self) -> None: + class FakeProcess: + pid = 54321 + + def __init__(self) -> None: + stdout_read, stdout_write = os.pipe() + stderr_read, stderr_write = os.pipe() + os.write(stdout_write, b"12345") + os.close(stdout_write) + os.close(stderr_write) + self.stdout = os.fdopen(stdout_read, "rb", buffering=0) + self.stderr = os.fdopen(stderr_read, "rb", buffering=0) + self.returncode: int | None = None + + def poll(self) -> int | None: + return self.returncode + + def wait(self, timeout: float) -> int: + self.returncode = -15 + return self.returncode + + def terminate(self) -> None: + self.returncode = -15 + + def kill(self) -> None: + self.returncode = -9 + + process = FakeProcess() + with mock.patch.object(subject.subprocess, "Popen", return_value=process): + with mock.patch.object(subject.os, "killpg") as kill_group: + with self.assertRaises(subject._ProcessOutputExceeded): + subject._run_command( + ["/usr/bin/podman", "inspect"], + timeout_seconds=10, + maximum_output_bytes=4, + environment={"PATH": subject.ENGINE_PATH}, + cancel_event=threading.Event(), + ) + self.assertTrue(kill_group.called) + + def test_cli_never_returns_a_green_gate_status_for_a_zero_exit_subject(self) -> None: + completed = subject.SubjectRunResult(0, b"", b"", self.runner_temp) + output = io.StringIO() + with mock.patch.object(subject, "launch_subject", return_value=completed): + with redirect_stdout(output): + status = subject.main( + [ + "--subject-checkout", str(self.subject_root), + "--image-digest", IMAGE, + "--scratch-directory", str(self.runner_temp / "cli-scratch"), + "--profile-id", "code-coverage", + "--source-diff", str(self.source_diff), + "--source-diff-sha256", self.source_diff_sha256, + "--artifact-export-directory", str(self.runner_temp / "cli-artifact-export"), + "--timeout-seconds", "60", + "--memory-mib", "512", + "--cpu-millis", "1000", + "--pids", "64", + "--output-bytes", "16384", + ] + ) + self.assertEqual(2, status) + self.assertFalse(json.loads(output.getvalue())["claimEligible"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_subject_entrypoint.py b/scripts/tests/test_evidence_gate_subject_entrypoint.py new file mode 100644 index 000000000..b17b0a1b3 --- /dev/null +++ b/scripts/tests/test_evidence_gate_subject_entrypoint.py @@ -0,0 +1,735 @@ +"""Failure-focused tests for the fixed offline subject entrypoint.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from unittest import mock + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-subject-entrypoint.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_subject_entrypoint", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +entrypoint = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = entrypoint +SPEC.loader.exec_module(entrypoint) + + +def process_result(exit_code: int = 0, stdout: bytes = b"ok", stderr: bytes = b"") -> entrypoint.ProcessResult: + return entrypoint.ProcessResult(exit_code, stdout, stderr) + + +class FixedOfflineSubjectEntrypointTests(unittest.TestCase): + def invocation(self) -> entrypoint.Invocation: + return entrypoint.Invocation( + entrypoint.FIXED_PROFILE_ID, + entrypoint.SUBJECT_ROOT, + entrypoint.SCRATCH_ROOT, + entrypoint.DEPENDENCY_SOURCE, + entrypoint.PATCH_DIFF_PATH, + hashlib.sha256(b"captured unified diff\n").hexdigest(), + True, + ) + + @staticmethod + def mountinfo(subject: Path, scratch: Path, dependencies: Path, *, diff_options: str = "ro") -> str: + return "\n".join( + ( + f"1 0 0:1 / {subject} ro - bind none ro", + f"2 0 0:2 / {scratch} rw - bind none rw", + f"3 0 0:3 / {dependencies} ro - bind none ro", + f"4 0 0:4 / {entrypoint.PATCH_DIFF_PATH} {diff_options} - bind none {diff_options}", + ) + ) + + @staticmethod + def make_subject( + root: Path, + *, + include_lock: bool = True, + runtime_identifier_lock: bool = False, + ) -> None: + project = root / "Cli/ForgeTrust.AppSurface.Cli" + project.mkdir(parents=True) + (root / "ForgeTrust.AppSurface.slnx").write_text( + '', + encoding="utf-8", + ) + project_file = project / "ForgeTrust.AppSurface.Cli.csproj" + project_file.write_text( + "" + "packages.$(NETCoreSdkRuntimeIdentifier).lock.json" + "" + if runtime_identifier_lock + else "", + encoding="utf-8", + ) + if include_lock: + lock_name = "packages.linux-x64.lock.json" if runtime_identifier_lock else "packages.lock.json" + (project / lock_name).write_text( + '{"version":1,"dependencies":{"net10.0":{"Example.Package":{"type":"Direct","resolved":"1.0.0","contentHash":"x"}}}}', + encoding="utf-8", + ) + (root / "subject.txt").write_text("fixed source", encoding="utf-8") + + @staticmethod + def make_feed(root: Path) -> None: + root.mkdir(parents=True) + (root / "example.package.1.0.0.nupkg").write_bytes(b"locked-package-payload") + + def patch_paths(self, subject: Path, scratch: Path, feed: Path) -> mock._patch: + diff_path = subject.parent / "source.diff" + diff_path.write_bytes(b"captured unified diff\n") + combined = mock.patch.multiple( + entrypoint, + SUBJECT_ROOT=subject, + SCRATCH_ROOT=scratch, + DEPENDENCY_SOURCE=feed, + PATCH_DIFF_PATH=diff_path, + FIXED_SUBJECT_ARGUMENT=f"--subject-root={subject}", + FIXED_SCRATCH_ARGUMENT=f"--scratch-root={scratch}", + FIXED_DEPENDENCY_ARGUMENT=f"--dependency-source={feed}", + ) + return combined + + def prepared_roots(self, parent: Path) -> tuple[Path, Path, Path]: + subject = parent / "subject" + scratch = parent / "scratch" + feed = parent / "locked-dependencies" + subject.mkdir() + scratch.mkdir(mode=0o700) + scratch.chmod(0o700) + self.make_feed(feed) + return subject, scratch, feed + + @staticmethod + def make_coverage_artifacts(scratch: Path, *, omit: str | None = None) -> None: + for logical_name, relative_path, _maximum_bytes in entrypoint.REQUIRED_ARTIFACTS: + if logical_name == omit: + continue + path = scratch / relative_path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(f"artifact:{logical_name}\n".encode("ascii")) + + def test_invocation_accepts_only_the_launcher_fixed_contract(self) -> None: + digest = hashlib.sha256(b"captured unified diff\n").hexdigest() + invocation = entrypoint.parse_invocation( + [ + "--profile-id=code-coverage", + "--subject-root=/subject", + "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", + "--diff-file=/source.diff", + f"--diff-sha256={digest}", + "--offline", + ] + ) + self.assertEqual("code-coverage", invocation.profile_id) + self.assertEqual(digest, invocation.diff_sha256) + self.assertEqual(Path("/source.diff"), invocation.diff_file) + self.assertTrue(invocation.offline) + with self.assertRaises(entrypoint.EntrypointError): + entrypoint.parse_invocation( + [ + "--profile-id=code-coverage", "--subject-root=/subject", "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", "--diff-file=/source.diff", + f"--diff-sha256={digest}\\Z", "--offline", + ] + ) + for invalid in ( + [ + "--profile-id=code-coverage", "--subject-root=/tmp/subject", "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", "--diff-file=/source.diff", + f"--diff-sha256={digest}", "--offline", + ], + [ + "--profile-id=code-coverage", "--subject-root=/subject", "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", "--diff-file=/source.diff", + f"--diff-sha256={digest}", + ], + [ + "--profile-id=code-coverage", "--subject-root=/subject", "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", "--diff-file=/source.diff", + f"--diff-sha256={digest}", "--offline", "dotnet", "restore", + ], + ): + with self.subTest(argv=invalid), self.assertRaises(SystemExit): + entrypoint.parse_invocation(invalid) + with self.assertRaises(entrypoint.EntrypointError): + entrypoint.parse_invocation( + [ + "--profile-id=code-coverage", "--subject-root=/subject", "--scratch-root=/scratch", + "--dependency-source=/opt/appsurface/locked-dependencies", "--diff-file=/source.diff", + "--diff-sha256=" + "z" * 64, "--offline", + ] + ) + + def test_mount_validation_rejects_writable_subject_and_public_scratch(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + subject, scratch, feed = self.prepared_roots(Path(temporary).resolve()) + self.make_subject(subject) + with self.patch_paths(subject, scratch, feed): + invocation = self.invocation() + cases = ( + (self.mountinfo(subject, scratch, feed).replace(f"{subject} ro", f"{subject} rw"), "read-only"), + (self.mountinfo(subject, scratch, feed, diff_options="rw"), "source diff mount is not read-only"), + ) + for mountinfo, message in cases: + with self.subTest(message=message), self.assertRaisesRegex(entrypoint.EntrypointError, message): + entrypoint.validate_mounts( + subject, + scratch, + feed, + invocation.diff_file, + invocation.diff_sha256, + mountinfo_text=mountinfo, + effective_uid=os.geteuid(), + ) + scratch.chmod(0o755) + with self.assertRaisesRegex(entrypoint.EntrypointError, "scratch directory is not private"): + entrypoint.validate_mounts( + subject, + scratch, + feed, + invocation.diff_file, + invocation.diff_sha256, + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + ) + + def test_mount_validation_rejects_source_diff_digest_mismatch(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + subject, scratch, feed = self.prepared_roots(Path(temporary).resolve()) + self.make_subject(subject) + with self.patch_paths(subject, scratch, feed): + invocation = self.invocation() + invocation.diff_file.write_bytes(b"different captured diff\n") + with self.assertRaises(entrypoint.EntrypointError) as failure: + entrypoint.validate_mounts( + subject, + scratch, + feed, + invocation.diff_file, + invocation.diff_sha256, + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + ) + self.assertEqual("ASESE012", failure.exception.code) + + def test_mount_validation_rejects_missing_source_diff(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + subject, scratch, feed = self.prepared_roots(Path(temporary).resolve()) + self.make_subject(subject) + with self.patch_paths(subject, scratch, feed): + invocation = self.invocation() + invocation.diff_file.unlink() + with self.assertRaises(entrypoint.EntrypointError) as failure: + entrypoint.validate_mounts( + subject, + scratch, + feed, + invocation.diff_file, + invocation.diff_sha256, + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + ) + self.assertEqual("ASESE012", failure.exception.code) + + def test_missing_offline_package_feed_writes_bounded_failure_without_running_dotnet(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + (feed / "example.package.1.0.0.nupkg").unlink() + scratch.rmdir() + scratch.mkdir(mode=0o700) + scratch.chmod(0o700) + runner = mock.Mock(side_effect=AssertionError("runtime must not start")) + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + self.assertEqual(2, code) + runner.assert_not_called() + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["status"]) + self.assertEqual("ASESE002", result["diagnostic"]["code"]) + self.assertLess((scratch / entrypoint.RESULT_RELATIVE_PATH).stat().st_size, entrypoint.MAX_RESULT_BYTES) + + def test_dependency_feed_scans_every_entry_after_first_package(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + feed = Path(temporary).resolve() / "locked-dependencies" + self.make_feed(feed) + nested = feed / "nested" + nested.mkdir() + (nested / "second.1.0.0.nupkg").write_bytes(b"second locked package") + + entrypoint._validate_dependency_feed(feed) + + (nested / "unsafe-link").symlink_to(feed / "example.package.1.0.0.nupkg") + with self.assertRaises(entrypoint.EntrypointError) as failure: + entrypoint._validate_dependency_feed(feed) + self.assertEqual("ASESE002", failure.exception.code) + + def test_unlocked_solution_project_fails_before_restore(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject, include_lock=False) + calls: list[list[str]] = [] + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + calls.append(arguments) + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/usr/share/dotnet/shared/Microsoft.NETCore.App]\n") + self.fail(f"Unexpected command before lock validation: {arguments!r}") + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + self.assertEqual(2, code) + self.assertEqual([["dotnet", "--version"], ["dotnet", "--list-runtimes"]], calls) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertEqual("ASESE002", result["diagnostic"]["code"]) + self.assertFalse(result["claimEligible"]) + + def test_subject_nuget_configuration_is_rejected_before_restore(self) -> None: + for relative_path in ("NuGet.Config", "nested/nuget.config"): + with self.subTest(relative_path=relative_path), tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + controlled_config = subject / relative_path + controlled_config.parent.mkdir(parents=True, exist_ok=True) + controlled_config.write_text("", encoding="utf-8") + calls: list[list[str]] = [] + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + calls.append(arguments) + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/dotnet]\n") + self.fail(f"Restore must not run with subject NuGet configuration: {arguments!r}") + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + + self.assertEqual(2, code) + self.assertEqual([["dotnet", "--version"], ["dotnet", "--list-runtimes"]], calls) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertEqual("ASESE003", result["diagnostic"]["code"]) + self.assertFalse(result["claimEligible"]) + + def test_project_declared_linux_runtime_lock_is_used(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + staged = parent / "staged" + staged.mkdir() + self.make_subject(staged, runtime_identifier_lock=True) + + entrypoint._validate_solution_locks(staged) + + project = staged / "Cli/ForgeTrust.AppSurface.Cli/ForgeTrust.AppSurface.Cli.csproj" + self.assertEqual( + project.parent / "packages.linux-x64.lock.json", + entrypoint._project_lock_path(project), + ) + + def test_project_declared_missing_runtime_lock_fails_closed(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + staged = Path(temporary).resolve() / "staged" + staged.mkdir() + self.make_subject(staged, include_lock=False, runtime_identifier_lock=True) + + with self.assertRaisesRegex(entrypoint.EntrypointError, "dependency lock"): + entrypoint._validate_solution_locks(staged) + + def test_container_dependent_solution_fails_before_coverage(self) -> None: + for relative_project in entrypoint.OFFLINE_UNSUPPORTED_TEST_PROJECTS: + with self.subTest(project=relative_project), tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + unsupported_project = subject / relative_project + unsupported_project.parent.mkdir(parents=True) + unsupported_project.write_text("", encoding="utf-8") + calls: list[list[str]] = [] + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + calls.append(arguments) + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/dotnet]\n") + if len(arguments) > 1 and arguments[1] == "restore": + return process_result() + self.fail(f"Coverage must not run for an unsupported offline profile: {arguments!r}") + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + + self.assertEqual(2, code) + self.assertEqual(3, len(calls)) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["status"]) + self.assertEqual("ASESE010", result["diagnostic"]["code"]) + self.assertEqual( + ["dotnet-sdk-version", "dotnet-runtime-list", "offline-locked-restore"], + [step["name"] for step in result["steps"]], + ) + + def test_mocked_fixed_command_flow_restores_offline_and_keeps_result_nonclaiming(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + calls: list[tuple[list[str], dict[str, object]]] = [] + + def runner(arguments: list[str], **options: object) -> entrypoint.ProcessResult: + calls.append((arguments, options)) + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/usr/share/dotnet/shared/Microsoft.NETCore.App]\n") + if "coverage" in arguments and "gate" in arguments: + self.make_coverage_artifacts(scratch) + return process_result() + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + self.assertEqual(0, code) + commands = [arguments for arguments, _ in calls] + restore = next(command for command in commands if len(command) > 1 and command[1] == "restore") + self.assertIn("--locked-mode", restore) + self.assertIn("--configfile", restore) + self.assertIn("--source", restore) + self.assertEqual(str(feed), restore[restore.index("--source") + 1]) + offline_config = Path(restore[restore.index("--configfile") + 1]).read_text(encoding="utf-8") + self.assertIn("", offline_config) + self.assertIn(f'', offline_config) + user_config = scratch / "dotnet-home/.nuget/NuGet/NuGet.Config" + self.assertEqual(offline_config, user_config.read_text(encoding="utf-8")) + self.assertEqual(0o600, stat.S_IMODE(user_config.stat().st_mode)) + coverage_run, coverage_gate = entrypoint._coverage_commands( + scratch / entrypoint.STAGED_SUBJECT_RELATIVE_PATH, + scratch, + parent / "source.diff", + ) + self.assertIn(coverage_run, commands) + self.assertIn(coverage_gate, commands) + self.assertEqual("95", coverage_gate[coverage_gate.index("--min-patch-line") + 1]) + self.assertEqual("85", coverage_gate[coverage_gate.index("--min-patch-branch") + 1]) + self.assertEqual("codecov", coverage_gate[coverage_gate.index("--patch-line-mode") + 1]) + self.assertEqual(str(parent / "source.diff"), coverage_gate[coverage_gate.index("--diff-file") + 1]) + self.assertEqual("--exclusive-test-project", coverage_run[coverage_run.index("--exclusive-test-project")]) + self.assertNotIn("--build", coverage_run) + result_bytes = (scratch / entrypoint.RESULT_RELATIVE_PATH).read_bytes() + result = json.loads(result_bytes) + self.assertFalse(result["claimEligible"]) + self.assertEqual("completed", result["status"]) + self.assertEqual( + ["dotnet-sdk-version", "dotnet-runtime-list", "offline-locked-restore", "coverage-run", "coverage-gate"], + [step["name"] for step in result["steps"]], + ) + self.assertEqual( + [ + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": len(f"artifact:{logical_name}\n".encode("ascii")), + "sha256": hashlib.sha256(f"artifact:{logical_name}\n".encode("ascii")).hexdigest(), + } + for logical_name, relative_path, _maximum_bytes in entrypoint.REQUIRED_ARTIFACTS + ], + result["artifacts"], + ) + self.assertLessEqual(len(result_bytes), entrypoint.MAX_RESULT_BYTES) + + def test_missing_required_coverage_artifact_fails_without_artifact_success(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/dotnet]\n") + if "coverage" in arguments and "gate" in arguments: + self.make_coverage_artifacts(scratch, omit="diagnostics") + return process_result() + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertEqual(2, code) + self.assertEqual("failed", result["status"]) + self.assertFalse(result["claimEligible"]) + self.assertNotIn("artifacts", result) + self.assertEqual("ASESE013", result["diagnostic"]["code"]) + + def test_artifact_index_rejects_symlink_oversize_and_concurrent_mutation(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + scratch = Path(temporary).resolve() + self.make_coverage_artifacts(scratch) + + symlink_name, symlink_relative, _ = entrypoint.REQUIRED_ARTIFACTS[0] + symlink_path = scratch / symlink_relative + target = scratch / "trusted-target.xml" + target.write_bytes(b"target\n") + symlink_path.unlink() + symlink_path.symlink_to(target) + with self.assertRaises(entrypoint.EntrypointError) as symlink_failure: + entrypoint._build_artifact_index(scratch, deadline=time.monotonic() + 5) + self.assertEqual("ASESE013", symlink_failure.exception.code) + + symlink_path.unlink() + symlink_path.write_bytes(b"x" * (entrypoint.MAX_COBERTURA_ARTIFACT_BYTES + 1)) + with self.assertRaises(entrypoint.EntrypointError) as oversized_failure: + entrypoint._build_artifact_index(scratch, deadline=time.monotonic() + 5) + self.assertEqual("ASESE013", oversized_failure.exception.code) + + symlink_path.write_bytes(b"stable content\n") + original_read = entrypoint.os.read + changed = False + + def mutate_during_read(descriptor: int, count: int) -> bytes: + nonlocal changed + data = original_read(descriptor, count) + info = os.fstat(descriptor) + if not changed and (info.st_dev, info.st_ino) == (symlink_path.stat().st_dev, symlink_path.stat().st_ino): + changed = True + symlink_path.write_bytes(b"mutant content\n") + return data + + with mock.patch.object(entrypoint.os, "read", side_effect=mutate_during_read): + with self.assertRaises(entrypoint.EntrypointError) as mutation_failure: + entrypoint._build_artifact_index(scratch, deadline=time.monotonic() + 5) + self.assertTrue(changed) + self.assertEqual("ASESE013", mutation_failure.exception.code) + + def test_restore_failure_does_not_claim_coverage_or_run_coverage_commands(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + calls: list[list[str]] = [] + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + calls.append(arguments) + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"10.0.100\n") + if arguments == ["dotnet", "--list-runtimes"]: + return process_result(stdout=b"Microsoft.NETCore.App 10.0.2 [/dotnet]\n") + if len(arguments) > 1 and arguments[1] == "restore": + return process_result(exit_code=1, stderr=b"untrusted oversized restore detail") + self.fail("coverage must not run after a failed restore") + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + self.assertEqual(2, code) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertFalse(result["claimEligible"]) + self.assertEqual("failed", result["status"]) + self.assertEqual("ASESE008", result["diagnostic"]["code"]) + self.assertNotIn("untrusted oversized restore detail", json.dumps(result)) + self.assertEqual(["dotnet-sdk-version", "dotnet-runtime-list", "offline-locked-restore"], [step["name"] for step in result["steps"]]) + + def test_runtime_version_mismatch_fails_closed(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + subject, scratch, feed = self.prepared_roots(parent) + self.make_subject(subject) + + def runner(arguments: list[str], **_options: object) -> entrypoint.ProcessResult: + if arguments == ["dotnet", "--version"]: + return process_result(stdout=b"9.0.999\n") + self.fail("runtime inventory must not run after an SDK version mismatch") + + with self.patch_paths(subject, scratch, feed): + code = entrypoint.execute( + self.invocation(), + mountinfo_text=self.mountinfo(subject, scratch, feed), + effective_uid=os.geteuid(), + runner=runner, + ) + self.assertEqual(2, code) + result = json.loads((scratch / entrypoint.RESULT_RELATIVE_PATH).read_text(encoding="ascii")) + self.assertEqual("ASESE004", result["diagnostic"]["code"]) + self.assertFalse(result["claimEligible"]) + + def test_copy_refuses_links_and_copies_regular_files_into_scratch(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + parent = Path(temporary).resolve() + source = parent / "source" + source.mkdir() + (source / "safe.txt").write_text("source bytes", encoding="utf-8") + staged = parent / "staged" + files, copied_bytes = entrypoint._copy_subject_tree(source, staged, deadline=time.monotonic() + 2) + self.assertEqual(1, files) + self.assertEqual(len(b"source bytes"), copied_bytes) + self.assertEqual("source bytes", (staged / "safe.txt").read_text(encoding="utf-8")) + (source / "link").symlink_to(staged / "safe.txt") + with self.assertRaises(entrypoint.EntrypointError): + entrypoint._copy_subject_tree(source, parent / "linked-copy", deadline=time.monotonic() + 2) + + def test_process_output_limit_and_deadline_terminate_child(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary).resolve() + environment = {"PATH": os.environ["PATH"]} + output_budget = entrypoint.OutputBudget(32) + with self.assertRaisesRegex(entrypoint.EntrypointError, "output exceeded"): + entrypoint.run_bounded_process( + [sys.executable, "-c", "import os,time; os.write(1, b'x' * 4096); time.sleep(3)"], + working_directory=root, + environment=environment, + deadline=time.monotonic() + 5, + output_budget=output_budget, + ) + with self.assertRaisesRegex(entrypoint.EntrypointError, "deadline expired"): + entrypoint.run_bounded_process( + [sys.executable, "-c", "import time; time.sleep(3)"], + working_directory=root, + environment=environment, + deadline=time.monotonic() + 0.05, + output_budget=entrypoint.OutputBudget(128), + ) + with self.assertRaisesRegex(entrypoint.EntrypointError, "deadline expired"): + entrypoint.run_bounded_process( + [sys.executable, "-c", "import os,time; os.close(1); os.close(2); time.sleep(3)"], + working_directory=root, + environment=environment, + deadline=time.monotonic() + 0.05, + output_budget=entrypoint.OutputBudget(128), + ) + + def test_result_schema_is_canonical_and_diagnostic_is_bounded(self) -> None: + diagnostic = ("ASESE002", "dependency unavailable") + first = entrypoint._make_result("failed", [], diagnostic=diagnostic) + second = entrypoint._make_result("failed", [], diagnostic=diagnostic) + self.assertEqual(first, second) + self.assertTrue(first.endswith(b"\n")) + self.assertEqual(first, (json.dumps(json.loads(first), ensure_ascii=True, separators=(",", ":"), sort_keys=True) + "\n").encode("ascii")) + + def test_main_streams_the_bounded_result_record_for_attached_launcher_capture(self) -> None: + class CapturedStdout: + def __init__(self) -> None: + self.buffer = io.BytesIO() + + for status, exit_code, diagnostic in ( + ("completed", 0, None), + ("failed", 2, ("ASESE010", "coverage unavailable")), + ): + with self.subTest(status=status), tempfile.TemporaryDirectory() as temporary: + scratch = Path(temporary).resolve() + invocation = entrypoint.Invocation( + entrypoint.FIXED_PROFILE_ID, + entrypoint.SUBJECT_ROOT, + scratch, + entrypoint.DEPENDENCY_SOURCE, + entrypoint.PATCH_DIFF_PATH, + hashlib.sha256(b"captured unified diff\n").hexdigest(), + True, + ) + artifacts = [ + { + "logicalName": logical_name, + "relativePath": relative_path, + "byteCount": 1, + "sha256": "a" * 64, + } + for logical_name, relative_path, _maximum_bytes in entrypoint.REQUIRED_ARTIFACTS + ] if status == "completed" else None + expected = entrypoint._make_result(status, [], artifacts=artifacts, diagnostic=diagnostic) + captured = CapturedStdout() + + def write_record(_invocation: entrypoint.Invocation) -> int: + entrypoint._write_result(scratch, expected) + return exit_code + + with ( + mock.patch.object(entrypoint, "parse_invocation", return_value=invocation), + mock.patch.object(entrypoint, "execute", side_effect=write_record), + mock.patch("sys.stdout", captured), + ): + self.assertEqual(exit_code, entrypoint.main([])) + + self.assertEqual(expected, captured.buffer.getvalue()) + + def test_result_transport_rejects_oversized_or_symlinked_record(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + scratch = Path(temporary).resolve() + oversized = scratch / entrypoint.RESULT_RELATIVE_PATH + oversized.write_bytes(b"x" * (entrypoint.MAX_RESULT_BYTES + 1)) + with self.assertRaisesRegex(entrypoint.EntrypointError, "bounded") as oversized_failure: + entrypoint._result_for_transport(scratch) + self.assertEqual("ASESE009", oversized_failure.exception.code) + + oversized.unlink() + target = scratch / "target" + target.write_bytes(b"{}") + (scratch / entrypoint.RESULT_RELATIVE_PATH).symlink_to(target) + with self.assertRaises(entrypoint.EntrypointError) as symlink_failure: + entrypoint._result_for_transport(scratch) + self.assertEqual("ASESE009", symlink_failure.exception.code) + + def test_process_cleanup_fails_closed_when_group_cannot_be_reaped(self) -> None: + process = mock.Mock(pid=12345) + process.wait.side_effect = subprocess.TimeoutExpired("fixture", 2) + with mock.patch.object(entrypoint.os, "killpg") as kill_group: + with self.assertRaisesRegex(entrypoint.EntrypointError, "could not be reaped") as failure: + entrypoint._terminate_process_group(process) + self.assertEqual("ASESE011", failure.exception.code) + kill_group.assert_called_once_with(12345, entrypoint.signal.SIGKILL) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_subject_supervisor.py b/scripts/tests/test_evidence_gate_subject_supervisor.py new file mode 100644 index 000000000..2322214ca --- /dev/null +++ b/scripts/tests/test_evidence_gate_subject_supervisor.py @@ -0,0 +1,531 @@ +"""Safety and forced-parent-loss tests for the OCI subject cleanup supervisor.""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import signal +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +from types import SimpleNamespace +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-subject-supervisor.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_subject_supervisor", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +supervisor = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = supervisor +SPEC.loader.exec_module(supervisor) + + +class FakeExecutor: + def __init__(self, *, token: str, container_name: str, mountpoint: Path) -> None: + self.token = token + self.container_name = container_name + self.mountpoint = mountpoint + self.calls: list[list[str]] = [] + self.container_present = True + self.owned = True + self.fail_remove = False + self.unmount_succeeds = True + self.mount_is_present = True + self.events: list[str] = [] + + def __call__(self, arguments: list[str], **options: object) -> supervisor.CommandResult: + self.calls.append(list(arguments)) + self.assert_options(options) + command = arguments[1:] + if command == ["--remote=false", "ps", "--all", "--no-trunc", "--format=json"]: + items = [{"Names": [self.container_name]}] if self.container_present else [] + return self.result(items) + if command == ["--remote=false", "inspect", "--format=json", self.container_name]: + labels = {supervisor.OWNER_LABEL: self.token} if self.owned else {} + return self.result( + [ + { + "Id": "a" * 64, + "Name": f"/{self.container_name}", + "Config": {"Labels": labels}, + "Mounts": [ + { + "Type": "bind", + "Source": str(self.mountpoint), + "Destination": "/scratch", + } + ], + } + ] + ) + if command == ["--remote=false", "rm", "--force", "--ignore", "a" * 64]: + self.events.append("container-remove") + if self.fail_remove: + return supervisor.CommandResult(1, b"", b"not removed") + self.container_present = False + return supervisor.CommandResult(0, b"", b"") + if arguments == [supervisor.SUDO_PATH, "-n", "umount", "--", str(self.mountpoint)]: + self.events.append("umount") + if self.unmount_succeeds: + self.mount_is_present = False + return supervisor.CommandResult(0, b"", b"") + return supervisor.CommandResult(1, b"", b"still mounted") + raise AssertionError(f"unexpected command: {arguments!r}") + + @staticmethod + def assert_options(options: dict[str, object]) -> None: + assert 0 < options["timeout_seconds"] <= supervisor.MAX_COMMAND_SECONDS + assert options["maximum_output_bytes"] > 0 + assert options["environment"]["REGISTRY_AUTH_FILE"] == "/dev/null" + assert set(options["environment"]) == { + "PATH", "HOME", "XDG_RUNTIME_DIR", "TMPDIR", "REGISTRY_AUTH_FILE" + } + + @staticmethod + def result(value: object) -> supervisor.CommandResult: + return supervisor.CommandResult( + 0, json.dumps(value, separators=(",", ":")).encode("utf-8"), b"" + ) + + +class SubjectSupervisorTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix="subject-supervisor-tests-") + self.root = Path(self.temporary.name).resolve() + self.uid = os.geteuid() + self.gid = os.getegid() + self.runner_temp = self.root / "runner-temp" + self.runner_temp.mkdir(mode=0o700) + self.home = self.root / "home" + self.home.mkdir(mode=0o700) + self.runtime = self.root / "runtime" + self.runtime.mkdir(mode=0o700) + self.scratch = self.runner_temp / "subject-scratch" + self.scratch.mkdir(mode=0o700) + self.mountpoint = self.scratch / "quota-limited-scratch-0123456789abcdef" + self.mountpoint.mkdir(mode=0o700) + os.chown(self.mountpoint, self.uid, self.gid) + self.token = "b" * 32 + self.container_name = "ase-subject-123456-2-0123456789ab" + self.state_directory = self.runner_temp / f"appsurface-subject-supervisor-{self.token}" + self.state_directory.mkdir(mode=0o700) + self.manifest_path = self.state_directory / supervisor.MANIFEST_NAME + self.parent_pid = 424_242 + self.parent_start_time = 123_456 + self._write_manifest() + self.environment = { + "RUNNER_TEMP": str(self.runner_temp), + "HOME": str(self.home), + "XDG_RUNTIME_DIR": str(self.runtime), + } + self.executor = FakeExecutor( + token=self.token, container_name=self.container_name, mountpoint=self.mountpoint + ) + self.mountinfo_text = self._mountinfo() + self.fake_statvfs = SimpleNamespace( + f_blocks=supervisor.TMPFS_BYTES // 4096, + f_frsize=4096, + f_files=supervisor.TMPFS_INODES, + ) + + def tearDown(self) -> None: + self.temporary.cleanup() + + def _write_manifest(self, **overrides: object) -> None: + document: dict[str, object] = { + "schemaVersion": 1, + "ownerToken": self.token, + "containerName": self.container_name, + "scratchDirectory": str(self.scratch), + "mountpoint": str(self.mountpoint), + "parentPid": self.parent_pid, + "parentStartTime": self.parent_start_time, + "scratchDevice": self.scratch.stat().st_dev, + "scratchInode": self.scratch.stat().st_ino, + "mountpointDevice": self.mountpoint.lstat().st_dev, + "mountpointInode": self.mountpoint.lstat().st_ino, + } + document.update(overrides) + payload = (json.dumps(document, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + if self.manifest_path.exists(): + self.manifest_path.unlink() + supervisor._write_new_file(self.state_directory, supervisor.MANIFEST_NAME, payload) + + def _mountinfo(self) -> str: + options = ( + f"rw,nosuid,nodev,size={supervisor.TMPFS_BYTES}," + f"nr_inodes={supervisor.TMPFS_INODES},mode=700,uid={self.uid},gid={self.gid}" + ) + return f"21 1 0:42 / {self.mountpoint} rw,relatime - tmpfs tmpfs {options}\n" + + def _run_cleanup(self, *, deadline: float = 10_000) -> dict[str, str]: + return supervisor._cleanup( + supervisor.Manifest( + self.token, + self.container_name, + self.scratch, + self.mountpoint, + self.parent_pid, + self.parent_start_time, + self.scratch.stat().st_dev, + self.scratch.stat().st_ino, + self.mountpoint.lstat().st_dev, + self.mountpoint.lstat().st_ino, + ), + home=self.home, + runtime=self.runtime, + runner_temp=self.runner_temp, + uid=self.uid, + gid=self.gid, + executor=self.executor, + mountinfo_reader=lambda: self.mountinfo_text if self.executor.mount_is_present else "", + statvfs=lambda _path: self.fake_statvfs, + monotonic=lambda: 0.0, + sleep=lambda _seconds: None, + cleanup_deadline=deadline, + ) + + def test_cleanup_removes_owned_container_before_unmounting_exact_tmpfs(self) -> None: + result = self._run_cleanup() + + self.assertEqual( + {"containerStatus": "removed", "mountStatus": "unmounted", "scratchStatus": "removed"}, + result, + ) + self.assertEqual(["container-remove", "umount"], self.executor.events) + self.assertFalse(self.mountpoint.exists()) + + def test_unowned_container_is_never_removed_and_its_mount_is_preserved(self) -> None: + self.executor.owned = False + + result = self._run_cleanup() + + self.assertEqual("unverified", result["containerStatus"]) + self.assertTrue(self.executor.mount_is_present) + self.assertFalse(any(" rm " in f" {' '.join(call)} " for call in self.executor.calls)) + self.assertNotIn("umount", self.executor.events) + + def test_container_removal_failure_preserves_mountpoint_and_tmpfs(self) -> None: + self.executor.fail_remove = True + + result = self._run_cleanup() + + self.assertEqual("failed", result["containerStatus"]) + self.assertTrue(self.executor.mount_is_present) + self.assertTrue(self.mountpoint.is_dir()) + self.assertNotIn("umount", self.executor.events) + + def test_unmount_failure_preserves_mountpoint(self) -> None: + self.executor.unmount_succeeds = False + + result = self._run_cleanup() + + self.assertEqual("failed", result["mountStatus"]) + self.assertEqual("preserved", result["scratchStatus"]) + self.assertTrue(self.mountpoint.is_dir()) + + def test_foreign_or_wrong_quota_mount_is_never_unmounted(self) -> None: + self.mountinfo_text = self._mountinfo().replace("size=4294967296", "size=4294967295") + + result = self._run_cleanup() + + self.assertEqual("unverified", result["mountStatus"]) + self.assertTrue(self.executor.mount_is_present) + self.assertNotIn("umount", self.executor.events) + + def test_subject_export_is_removed_but_unexpected_scratch_is_preserved(self) -> None: + subject_result = self.scratch / supervisor.SUBJECT_RESULT_NAME + subject_result.write_bytes(b"{}\n") + os.chmod(subject_result, 0o600) + + result = self._run_cleanup() + + self.assertEqual("removed", result["scratchStatus"]) + self.assertFalse(subject_result.exists()) + self.assertFalse(self.scratch.exists()) + + def test_unexpected_scratch_entry_is_never_deleted(self) -> None: + unexpected = self.scratch / "subject-created-output.bin" + unexpected.write_bytes(b"keep") + + result = self._run_cleanup() + + self.assertEqual("preserved", result["scratchStatus"]) + self.assertEqual(b"keep", unexpected.read_bytes()) + self.assertTrue(self.scratch.is_dir()) + + def test_symlinked_mountpoint_is_rejected_before_commands(self) -> None: + moved = self.scratch / "real-mountpoint" + self.mountpoint.rename(moved) + self.mountpoint.symlink_to(moved, target_is_directory=True) + + result = self._run_cleanup() + + self.assertEqual("unverified", result["containerStatus"]) + self.assertEqual([], self.executor.calls) + self.assertTrue(moved.is_dir()) + + def test_manifest_rejects_path_traversal_and_symlinked_state(self) -> None: + for value in (str(self.runner_temp / ".." / "outside"), str(self.root / "elsewhere")): + with self.subTest(value=value): + self._write_manifest(mountpoint=value) + with self.assertRaises(supervisor.SupervisorError): + supervisor._read_manifest( + self.manifest_path, + environment=self.environment, + uid=self.uid, + gid=self.gid, + ) + self._write_manifest() + moved = self.runner_temp / f"moved-{self.token}" + self.state_directory.rename(moved) + self.state_directory.symlink_to(moved, target_is_directory=True) + with self.assertRaises(supervisor.SupervisorError): + supervisor._read_manifest( + self.manifest_path, + environment=self.environment, + uid=self.uid, + gid=self.gid, + ) + + def test_attestation_is_bounded_and_always_non_claiming(self) -> None: + record = supervisor._attestation( + trigger="parent-exit", + statuses={ + "containerStatus": "removed", + "mountStatus": "unmounted", + "scratchStatus": "removed", + }, + failure_code="none", + ) + encoded = json.dumps(record, separators=(",", ":")).encode("ascii") + + self.assertLessEqual(len(encoded), supervisor.MAX_ATTESTATION_BYTES) + self.assertFalse(record["claimEligible"]) + self.assertFalse(record["published"]) + self.assertEqual("complete", record["status"]) + + def test_request_requires_matching_token_and_is_private(self) -> None: + with self.assertRaises(supervisor.SupervisorError): + supervisor._request_cleanup( + self.manifest_path, + "c" * 32, + environment=self.environment, + ) + + supervisor._request_cleanup( + self.manifest_path, + self.token, + environment=self.environment, + ) + request = self.state_directory / supervisor.REQUEST_NAME + self.assertEqual(0o600, stat.S_IMODE(request.stat().st_mode)) + self.assertEqual( + {"ownerToken": self.token, "schemaVersion": 1}, + json.loads(request.read_text(encoding="ascii")), + ) + + def test_supervisor_triggers_when_fake_parent_proc_identity_disappears(self) -> None: + fake_proc = self.root / "proc" + parent_directory = fake_proc / str(self.parent_pid) + parent_directory.mkdir(parents=True) + stat_fields = ["S"] + ["0"] * 19 + stat_fields[19] = str(self.parent_start_time) + (parent_directory / "stat").write_text( + f"{self.parent_pid} (test parent) {' '.join(stat_fields)}\n", encoding="ascii" + ) + clock = [0.0] + + def sleep(_seconds: float) -> None: + clock[0] += 0.1 + (parent_directory / "stat").unlink(missing_ok=True) + try: + parent_directory.rmdir() + except FileNotFoundError: + pass + + exit_code = supervisor.run_supervisor( + self.manifest_path, + environment=self.environment, + effective_uid=self.uid, + effective_gid=self.gid, + proc_root=fake_proc, + mountinfo_reader=lambda: self._mountinfo() if self.executor.mount_is_present else "", + executor=self.executor, + statvfs=lambda _path: self.fake_statvfs, + monotonic=lambda: clock[0], + sleep=sleep, + ) + + record = json.loads((self.state_directory / supervisor.ATTESTATION_NAME).read_text(encoding="ascii")) + self.assertEqual(0, exit_code, record) + self.assertEqual("parent-exit", record["trigger"]) + self.assertEqual("complete", record["status"]) + self.assertFalse(record["claimEligible"]) + + +class ForcedParentKillIntegrationTests(unittest.TestCase): + def test_detached_supervisor_reaps_fake_resources_after_launcher_sigkill(self) -> None: + """Exercise real process independence with fake Podman and mount operations.""" + with tempfile.TemporaryDirectory(prefix="subject-supervisor-kill-") as temporary: + root = Path(temporary).resolve() + runner_temp = root / "runner-temp" + runner_temp.mkdir(mode=0o700) + home = root / "home" + home.mkdir(mode=0o700) + runtime = root / "runtime" + runtime.mkdir(mode=0o700) + scratch = runner_temp / "subject-scratch" + scratch.mkdir(mode=0o700) + mountpoint = scratch / "quota-limited-scratch-0123456789abcdef" + mountpoint.mkdir(mode=0o700) + uid = os.geteuid() + gid = os.getegid() + os.chown(mountpoint, uid, gid) + token = "d" * 32 + container_name = "ase-subject-123456-2-fedcba987654" + state = runner_temp / f"appsurface-subject-supervisor-{token}" + state.mkdir(mode=0o700) + manifest_path = state / supervisor.MANIFEST_NAME + ready_path = root / "launcher-ready" + fake_proc = root / "fake-proc" + resources_path = root / "fake-resource-state.json" + event_path = root / "events.json" + resources_path.write_text( + json.dumps({"containerPresent": True, "mountPresent": True}), + encoding="ascii", + ) + + supervisor_code = textwrap.dedent( + """ + import importlib.util, json, os, sys, time + from pathlib import Path + from types import SimpleNamespace + spec = importlib.util.spec_from_file_location('egss', sys.argv[1]) + module = importlib.util.module_from_spec(spec); sys.modules[spec.name] = module; spec.loader.exec_module(module) + manifest_path, state_path, events_path, mountpoint = map(Path, sys.argv[2:6]) + token, container_name = sys.argv[6:8] + proc_root = Path(sys.argv[8]) + manifest = json.loads(manifest_path.read_text(encoding='ascii')) + parent_pid = manifest['parentPid'] + parent_start = manifest['parentStartTime'] + state = json.loads(state_path.read_text(encoding='ascii')) + class Executor: + def __call__(self, arguments, **options): + command = arguments[1:] + events = json.loads(events_path.read_text(encoding='ascii')) if events_path.exists() else [] + if command[:2] == ['--remote=false', 'ps']: + value = [{'Names':[container_name]}] if state['containerPresent'] else [] + result = module.CommandResult(0, json.dumps(value).encode(), b'') + elif command[:2] == ['--remote=false', 'inspect']: + value = [{'Id':'a'*64,'Name':'/'+container_name,'Config':{'Labels':{module.OWNER_LABEL:token}},'Mounts':[{'Type':'bind','Source':str(mountpoint),'Destination':'/scratch'}]}] + result = module.CommandResult(0, json.dumps(value).encode(), b'') + elif command[:2] == ['--remote=false', 'rm']: + events.append('container-remove'); state['containerPresent'] = False + state_path.write_text(json.dumps(state), encoding='ascii') + result = module.CommandResult(0,b'',b'') + elif arguments[:3] == [module.SUDO_PATH, '-n', 'umount']: + events.append('umount'); state['mountPresent'] = False + state_path.write_text(json.dumps(state), encoding='ascii') + result = module.CommandResult(0,b'',b'') + else: raise AssertionError(arguments) + events_path.write_text(json.dumps(events), encoding='ascii') + return result + def mountinfo(): + if not state['mountPresent']: return '' + options = f'rw,nosuid,nodev,size={module.TMPFS_BYTES},nr_inodes={module.TMPFS_INODES},mode=700,uid={os.geteuid()},gid={os.getegid()}' + return f'21 1 0:42 / {mountpoint} rw,relatime - tmpfs tmpfs {options}' + chr(10) + fake_statvfs = SimpleNamespace(f_blocks=module.TMPFS_BYTES//4096, f_frsize=4096, f_files=module.TMPFS_INODES) + def parent_identity(pid): + try: os.kill(pid, 0) + except ProcessLookupError: return (parent_start, 'Z') + return (parent_start, 'S') + environment = {'RUNNER_TEMP':str(Path(manifest_path).parent.parent),'HOME':os.environ['HOME'],'XDG_RUNTIME_DIR':os.environ['XDG_RUNTIME_DIR']} + sys.exit(module.run_supervisor(manifest_path, environment=environment, proc_root=proc_root, proc_identity_reader=parent_identity, executor=Executor(), mountinfo_reader=mountinfo, statvfs=lambda _:fake_statvfs)) + """ + ) + launcher_code = textwrap.dedent( + """ + import importlib.util, json, os, subprocess, sys, time + from pathlib import Path + spec = importlib.util.spec_from_file_location('egss', sys.argv[1]) + module = importlib.util.module_from_spec(spec); sys.modules[spec.name] = module; spec.loader.exec_module(module) + manifest_path, supervisor_code, ready_path, state_path, events_path, mountpoint = map(str, sys.argv[2:8]) + proc_root = Path(sys.argv[8]) + document = {'schemaVersion':1,'ownerToken':'d'*32,'containerName':'ase-subject-123456-2-fedcba987654','scratchDirectory':str(Path(mountpoint).parent),'mountpoint':mountpoint,'parentPid':os.getpid(),'parentStartTime':987654321} + scratch_info = Path(mountpoint).parent.stat(); mount_info = Path(mountpoint).lstat() + document.update({'scratchDevice':scratch_info.st_dev,'scratchInode':scratch_info.st_ino,'mountpointDevice':mount_info.st_dev,'mountpointInode':mount_info.st_ino}) + Path(manifest_path).write_text(json.dumps(document,sort_keys=True,separators=(',',':'))+chr(10),encoding='ascii') + os.chmod(manifest_path,0o600) + (proc_root / str(os.getpid())).mkdir(parents=True,mode=0o700) + command = [sys.executable,'-c',supervisor_code,sys.argv[1],manifest_path,state_path,events_path,mountpoint,'d'*32,'ase-subject-123456-2-fedcba987654',str(proc_root)] + child_environment = {'PATH':'/usr/bin:/bin','HOME':os.environ['HOME'],'XDG_RUNTIME_DIR':os.environ['XDG_RUNTIME_DIR'],'RUNNER_TEMP':str(Path(manifest_path).parent.parent)} + subprocess.Popen(command,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True,close_fds=True,cwd='/',env=child_environment) + Path(ready_path).write_text('ready',encoding='ascii') + while True: time.sleep(60) + """ + ) + launcher_environment = dict(os.environ) + launcher_environment.update( + {"RUNNER_TEMP": str(runner_temp), "HOME": str(home), "XDG_RUNTIME_DIR": str(runtime)} + ) + launcher = subprocess.Popen( + [ + sys.executable, + "-c", + launcher_code, + str(SCRIPT), + str(manifest_path), + supervisor_code, + str(ready_path), + str(resources_path), + str(event_path), + str(mountpoint), + str(fake_proc), + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + start_new_session=True, + env=launcher_environment, + ) + try: + deadline = time.monotonic() + 10 + while not ready_path.exists() and time.monotonic() < deadline: + if launcher.poll() is not None: + stderr = launcher.stderr.read().decode("utf-8", errors="replace") if launcher.stderr else "" + self.fail(f"launcher exited before starting supervisor: {stderr}") + time.sleep(0.02) + self.assertTrue(ready_path.exists(), "launcher did not start detached supervisor") + os.kill(launcher.pid, signal.SIGKILL) + launcher.wait(timeout=5) + + attestation_path = state / supervisor.ATTESTATION_NAME + deadline = time.monotonic() + 15 + while not attestation_path.exists() and time.monotonic() < deadline: + time.sleep(0.05) + self.assertTrue(attestation_path.exists(), "detached supervisor did not attest cleanup") + attestation = json.loads(attestation_path.read_text(encoding="ascii")) + resources = json.loads(resources_path.read_text(encoding="ascii")) + events = json.loads(event_path.read_text(encoding="ascii")) + self.assertEqual("complete", attestation["status"]) + self.assertFalse(attestation["claimEligible"]) + self.assertEqual({"containerPresent": False, "mountPresent": False}, resources) + self.assertEqual(["container-remove", "umount"], events) + self.assertFalse(mountpoint.exists()) + self.assertFalse(scratch.exists()) + finally: + if launcher.poll() is None: + launcher.kill() + launcher.wait(timeout=5) + if launcher.stderr is not None: + launcher.stderr.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_verifier_context.py b/scripts/tests/test_evidence_gate_verifier_context.py new file mode 100644 index 000000000..d4cff7386 --- /dev/null +++ b/scripts/tests/test_evidence_gate_verifier_context.py @@ -0,0 +1,199 @@ +"""Tests for base-owned workflow and subject-job identity resolution.""" + +from __future__ import annotations + +from contextlib import redirect_stdout +import importlib.util +import io +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-verifier-context.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_verifier_context", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +context = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = context +SPEC.loader.exec_module(context) + + +class VerifierContextTests(unittest.TestCase): + def setUp(self) -> None: + self.identity = { + "BaseRevision": "a" * 40, + "HeadRevision": "b" * 40, + "HeadRepositoryId": 321, + "PullRequestNumber": 777, + "RepositoryId": 321, + "TargetBranch": "main", + "WorkflowRunAttempt": 2, + "WorkflowRunId": 654321, + } + self.environment = { + "GITHUB_REPOSITORY": "forge-trust/AppSurface", + "GITHUB_REPOSITORY_ID": "321", + "GITHUB_RUN_ID": "654321", + "GITHUB_RUN_ATTEMPT": "2", + "GITHUB_EVENT_NAME": "pull_request_target", + } + self.prefix = "repos/forge-trust/AppSurface/actions/runs/654321/attempts/2" + self.workflow = { + "id": 654321, + "run_attempt": 2, + "workflow_id": 1234, + "event": "pull_request_target", + "repository": {"id": 321, "full_name": "forge-trust/AppSurface"}, + } + self.jobs = { + "total_count": 2, + "jobs": [ + {"id": 5555, "run_id": 654321, "name": "Evidence gate controller capture (non-claiming)", "status": "completed", "conclusion": "success"}, + {"id": 5678, "run_id": 654321, "name": context.SUBJECT_JOB_NAME, "status": "completed", "conclusion": "success"}, + ], + } + + def _api(self, path: str) -> dict[str, object]: + if path == self.prefix: + return self.workflow + if path == self.prefix + "/jobs?per_page=100": + return self.jobs + self.fail(f"Unexpected API path: {path}") + + def test_resolves_attempt_specific_identity_without_job_attempt_field(self) -> None: + expected = context.resolve_identity(self.identity, self.environment, self._api) + + self.assertEqual("1234", expected["WorkflowId"]) + self.assertEqual("5678", expected["SubjectJobId"]) + self.assertEqual("pull_request_target", expected["EventName"]) + self.assertEqual( + {key: self.identity[key] for key in context.EXPECTED_RUN_IDENTITY_KEYS}, + expected["RunIdentity"], + ) + self.assertEqual( + b'{"EventName":"pull_request_target","Repository":"forge-trust/AppSurface","RunIdentity":{"HeadRepositoryId":321,"PullRequestNumber":777,"RepositoryId":321,"TargetBranch":"main","WorkflowRunAttempt":2,"WorkflowRunId":654321},"SubjectJobId":"5678","WorkflowId":"1234"}', + context._canonical(expected), + ) + + def test_rejects_missing_or_malformed_captured_revisions(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-verifier-context-revisions-") as temporary: + path = Path(temporary) / "identity.json" + for base, head in ((None, "b" * 40), ("a" * 40, "B" * 40), ("a" * 40, "b" * 64)): + with self.subTest(base=base, head=head): + identity = dict(self.identity) + if base is None: + del identity["BaseRevision"] + else: + identity["BaseRevision"] = base + identity["HeadRevision"] = head + path.write_bytes(context._canonical(identity)) + with self.assertRaises(context.VerifierContextError): + context._read_identity(path) + + def test_rejects_stale_or_wrong_workflow_context_before_job_lookup(self) -> None: + for field, value in ( + ("GITHUB_REPOSITORY_ID", "322"), + ("GITHUB_RUN_ATTEMPT", "1"), + ("GITHUB_EVENT_NAME", "pull_request"), + ): + with self.subTest(field=field): + environment = dict(self.environment, **{field: value}) + with self.assertRaises(context.VerifierContextError): + context.resolve_identity(self.identity, environment, self._api) + + def test_rejects_wrong_attempt_or_workflow_repository(self) -> None: + for key, value in (("run_attempt", 1), ("id", 654322), ("event", "push")): + with self.subTest(key=key): + workflow = dict(self.workflow, **{key: value}) + with self.assertRaises(context.VerifierContextError): + context.resolve_identity(self.identity, self.environment, lambda path: workflow if path == self.prefix else self.jobs) + workflow = dict(self.workflow, repository={"id": 322, "full_name": "forge-trust/AppSurface"}) + with self.assertRaises(context.VerifierContextError): + context.resolve_identity(self.identity, self.environment, lambda path: workflow if path == self.prefix else self.jobs) + + def test_rejects_ambiguous_failed_or_wrong_run_subject_job(self) -> None: + variants = [ + {"total_count": 3, "jobs": [*self.jobs["jobs"], dict(self.jobs["jobs"][1], id=9999)]}, + {"total_count": 2, "jobs": [self.jobs["jobs"][0], dict(self.jobs["jobs"][1], conclusion="failure")]}, + {"total_count": 2, "jobs": [self.jobs["jobs"][0], dict(self.jobs["jobs"][1], run_id=654322)]}, + {"total_count": 2, "jobs": [self.jobs["jobs"][0], dict(self.jobs["jobs"][1], run_attempt=1)]}, + {"total_count": 3, "jobs": self.jobs["jobs"]}, + ] + for jobs in variants: + with self.subTest(jobs=jobs): + with self.assertRaises(context.VerifierContextError): + context.resolve_identity(self.identity, self.environment, lambda path: self.workflow if path == self.prefix else jobs) + + def test_accepts_matching_optional_job_attempt(self) -> None: + self.jobs["jobs"][1]["run_attempt"] = 2 + self.assertEqual("5678", context.resolve_identity(self.identity, self.environment, self._api)["SubjectJobId"]) + + def test_reads_only_canonical_regular_controller_identity(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-verifier-context-") as temporary: + root = Path(temporary) + identity = root / "identity.json" + identity.write_bytes(context._canonical(self.identity)) + self.assertEqual(self.identity, context._read_identity(identity)) + + identity.write_bytes(json.dumps(self.identity, indent=2).encode("utf-8")) + with self.assertRaises(context.VerifierContextError): + context._read_identity(identity) + + identity.write_bytes(context._canonical(self.identity)) + link = root / "link.json" + link.symlink_to(identity) + with self.assertRaises(context.VerifierContextError): + context._read_identity(link) + + def test_writes_new_identity_without_replacing_existing_file(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-verifier-context-") as temporary: + output = Path(temporary) / "expected.json" + expected = context.resolve_identity(self.identity, self.environment, self._api) + context.write_new_identity(output, expected) + self.assertEqual(expected, json.loads(output.read_bytes())) + with self.assertRaises(context.VerifierContextError): + context.write_new_identity(output, expected) + + def test_main_reads_fresh_identity_and_writes_expected_identity(self) -> None: + with tempfile.TemporaryDirectory(prefix="evidence-verifier-context-") as temporary: + root = Path(temporary) + capture = root / "capture.json" + output = root / "expected.json" + capture.write_bytes(context._canonical(self.identity)) + environment = dict(self.environment, GITHUB_TOKEN="test-token", GITHUB_API_URL="https://api.github.com") + with patch.dict(os.environ, environment), patch.object(context, "_read_api", side_effect=lambda path, **_kwargs: self._api(path)): + with redirect_stdout(io.StringIO()): + self.assertEqual(0, context.main(["--fresh-identity", str(capture), "--output", str(output)])) + self.assertEqual("5678", json.loads(output.read_bytes())["SubjectJobId"]) + + def test_api_reader_rejects_oversized_or_malformed_responses(self) -> None: + class Response(io.BytesIO): + def __init__(self, body: bytes, content_length: str | None = None) -> None: + super().__init__(body) + self.status = 200 + self.headers = {} if content_length is None else {"Content-Length": content_length} + + class Opener: + def __init__(self, response: Response) -> None: + self.response = response + + def open(self, _request: object, timeout: int) -> Response: + assert timeout == context.API_TIMEOUT_SECONDS + return self.response + + with patch.object(context, "build_opener", return_value=Opener(Response(b'{"id":1}'))): + self.assertEqual({"id": 1}, context._read_api("repos/example/repo", api_base="https://api.github.com", token="test")) + with patch.object(context, "build_opener", return_value=Opener(Response(b"{}", str(context.MAX_API_BYTES + 1)))): + with self.assertRaises(context.VerifierContextError): + context._read_api("repos/example/repo", api_base="https://api.github.com", token="test") + with patch.object(context, "build_opener", return_value=Opener(Response(b"{"))): + with self.assertRaises(context.VerifierContextError): + context._read_api("repos/example/repo", api_base="https://api.github.com", token="test") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_evidence_gate_verify_cleanup.py b/scripts/tests/test_evidence_gate_verify_cleanup.py new file mode 100644 index 000000000..d1fe3a425 --- /dev/null +++ b/scripts/tests/test_evidence_gate_verify_cleanup.py @@ -0,0 +1,190 @@ +"""Trusted verifier checks for the subject cleanup handoff.""" + +from __future__ import annotations + +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "evidence-gate-verify-cleanup.py" +SPEC = importlib.util.spec_from_file_location("evidence_gate_verify_cleanup", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +verifier = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(verifier) + + +class TrustedCleanupVerificationTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory(prefix="trusted-cleanup-verifier-") + self.root = Path(self.temporary.name).resolve() + self.plan = self.root / "evidence-plan.json" + self.attestation = self.root / "evidence-gate-cleanup-attestation.json" + self.record = self._complete_record() + self._profile("code-coverage") + + def tearDown(self) -> None: + self.temporary.cleanup() + + def _profile(self, profile_id: str) -> None: + self.plan.write_text(json.dumps({"Profile": {"Id": profile_id}}), encoding="ascii") + + def _record(self) -> None: + self.attestation.write_bytes( + (json.dumps(self.record, sort_keys=True, separators=(",", ":")) + "\n").encode("ascii") + ) + + @staticmethod + def _complete_record() -> dict[str, object]: + return { + "schemaVersion": 1, + "claimEligible": False, + "published": False, + "status": "complete", + "trigger": "request", + "containerStatus": "removed", + "mountStatus": "unmounted", + "scratchStatus": "removed", + "failureCode": "none", + "cleanupDeadlineSeconds": 600, + } + + def test_coverage_requires_complete_canonical_cleanup_record(self) -> None: + self._record() + verifier.verify_cleanup(self.plan, self.attestation) + + self.record["trigger"] = "parent-exit" + self.record["containerStatus"] = "absent" + self.record["mountStatus"] = "absent" + self.record["scratchStatus"] = "absent" + self._record() + verifier.verify_cleanup(self.plan, self.attestation) + + def test_empty_documentation_profile_rejects_unexpected_cleanup_artifact(self) -> None: + self._profile("documentation-only") + verifier.verify_cleanup(self.plan, self.attestation) + + self._record() + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC004"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_coverage_rejects_missing_unsafe_and_incomplete_records(self) -> None: + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + target = self.root / "target.json" + target.write_bytes(b"{}\n") + self.attestation.symlink_to(target) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + self.attestation.unlink() + + self.record["status"] = "incomplete" + self._record() + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC003"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_coverage_rejects_duplicate_extra_and_noncanonical_json(self) -> None: + self.attestation.write_bytes(b'{"status":"complete","status":"complete"}\n') + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + self.record["subjectOwnedClaim"] = True + self._record() + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + del self.record["subjectOwnedClaim"] + + self.attestation.write_bytes(json.dumps(self.record).encode("ascii")) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_coverage_rejects_each_incomplete_cleanup_condition(self) -> None: + invalid_values = { + "schemaVersion": [True, 2], + "claimEligible": [True], + "published": [True], + "status": ["incomplete"], + "trigger": ["unknown"], + "containerStatus": ["failed"], + "mountStatus": ["mounted"], + "scratchStatus": ["present"], + "failureCode": ["resource-cleanup-incomplete"], + "cleanupDeadlineSeconds": [True, 601], + } + for field, values in invalid_values.items(): + for value in values: + with self.subTest(field=field, value=value): + self.record[field] = value + self._record() + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC003"): + verifier.verify_cleanup(self.plan, self.attestation) + self.record[field] = self._complete_record()[field] + + def test_rejects_oversized_record_and_unsupported_profile(self) -> None: + self.attestation.write_bytes(b"x" * (verifier.MAX_ATTESTATION_BYTES + 1)) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + self._profile("postgresql-integration") + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC004"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_rejects_symlinked_parent_and_malformed_plan(self) -> None: + self._record() + linked_parent = self.root / "linked-parent" + linked_parent.symlink_to(self.root, target_is_directory=True) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, linked_parent / self.attestation.name) + + self.plan.write_bytes(b'{"Profile":{"Id":"code-coverage"},"Profile":{}}') + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC001"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_rejects_hardlinked_record_and_nonregular_plan(self) -> None: + self._record() + self.attestation.unlink() + target = self.root / "linked-record.json" + target.write_bytes(b"{}\n") + os.link(target, self.attestation) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + self.attestation.unlink() + self.plan.unlink() + self.plan.mkdir() + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC001"): + verifier.verify_cleanup(self.plan, self.attestation) + + @unittest.skipUnless(hasattr(os, "mkfifo"), "requires POSIX FIFOs") + def test_rejects_fifo_without_waiting_for_a_writer(self) -> None: + os.mkfifo(self.attestation) + with self.assertRaisesRegex(verifier.CleanupVerificationError, "ASEGC002"): + verifier.verify_cleanup(self.plan, self.attestation) + + def test_cli_exits_nonzero_without_disclosing_record_bytes(self) -> None: + self._record() + arguments = [ + sys.executable, + str(SCRIPT), + "--plan", str(self.plan), + "--attestation", str(self.attestation), + ] + complete = subprocess.run(arguments, capture_output=True, text=True, check=False) + self.assertEqual(0, complete.returncode) + + secret_marker = "SUBJECT-RAW-SECRET-MARKER" + self.attestation.write_text(secret_marker, encoding="ascii") + rejected = subprocess.run(arguments, capture_output=True, text=True, check=False) + self.assertEqual(2, rejected.returncode) + self.assertIn("ASEGC002", rejected.stderr) + self.assertNotIn(secret_marker, rejected.stdout + rejected.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/start-here/evidencehost.md b/start-here/evidencehost.md index 54fc9c555..e7e33089f 100644 --- a/start-here/evidencehost.md +++ b/start-here/evidencehost.md @@ -6,6 +6,8 @@ It is not a replacement for a test framework, coverage collector, GitHub Actions ## The first five minutes +To rehearse exact base/head planning against an immutable Git bundle, follow the [docs-only gate fixture](../docs/fixtures/issue-777-docs-only/README.md). It runs `explain`, the first-party host, and local `verify`; the [rollout record](../docs/evidence-gate-rollout.md) covers the separate live GitHub check proof. + Install the [AppSurface CLI](../Cli/ForgeTrust.AppSurface.Cli/README.md), then create the deliberately small policy starter: ```bash @@ -74,6 +76,8 @@ Similarly, v1 validates a registered release envelope but labels it `ValidatedNo ## Read next - [EvidenceHost cookbook](../guides/evidencehost-cookbook.md) +- [AppSurface issue #777 policy and producer matrix](../docs/evidence-gate-policy-matrix.md) explains which first-party PR profiles have real producers and which currently fail incomplete. +- [Evidence gate rollout record](../docs/evidence-gate-rollout.md) tracks the live proof needed before a required status check can be enabled. The current `pull_request_target` pilot is deliberately non-claiming. - [CLI evidence command reference](../Cli/ForgeTrust.AppSurface.Cli/README.md#appsurface-evidence) - [Evidence contract reference](../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md) - [Aspire lifecycle reference](../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/README.md) diff --git a/tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateResultRendererTests.cs b/tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateResultRendererTests.cs new file mode 100644 index 000000000..92e107ee9 --- /dev/null +++ b/tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateResultRendererTests.cs @@ -0,0 +1,109 @@ +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.EvidenceGate.Tests; + +public sealed class EvidenceGateResultRendererTests +{ + [Fact] + public void RendererKeepsTerminalMachineSummaryAndMarkdownOnOneBoundedVerdict() + { + var summary = new EvidencePullRequestGateSummary( + "code;coverage", "matched-policy-rules", + [new EvidencePullRequestGateRuleSummary("code-rule", "src/[malicious]`