Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 66 additions & 4 deletions .github/workflows/integrity-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,19 @@ permissions:
checks: write
statuses: write

env:
CODECOV_TOKEN: '2f2eb890-30e2-4724-83eb-7633832cf0de'

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
# Same-run artifact actions use the workflow artifact runtime; keep GITHUB_TOKEN scopes minimal.
tests:
name: Tests
runs-on: ubuntu-latest
outputs:
coverage-artifact-id: ${{ steps.coverage-artifact.outputs.artifact-id }}
permissions:
contents: read
Comment thread
wallstop marked this conversation as resolved.
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
- name: Install package manager (from package.json)
Expand Down Expand Up @@ -49,14 +51,74 @@ jobs:
case "$(yarn --version)" in 1.*) echo 'expected up-to-date yarn version'; exit 1 ;; esac
yarn install --immutable
- run: yarn lint
- run: yarn test:workflow-policy
- run: node scripts/verify-resource-cleanup-contract.mjs .
- run: yarn test:ci --coverage
- run: bash <(curl -s https://codecov.io/bash)
- name: Preserve coverage for isolated upload
id: coverage-artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: coverage-report
path: ./coverage/lcov.info
if-no-files-found: error
retention-days: 1
- name: Verify generated distribution
run: |
yarn build || { echo "build command should always succeed"; exit 61; }
git diff --exit-code -- dist || { echo "generated dist is stale"; exit 62; }

upload-trusted-coverage:
name: Upload trusted coverage
if: >-
always() && needs.tests.outputs.coverage-artifact-id != '' &&
((github.event_name == 'push' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == github.repository &&
github.event.pull_request.user.login != 'dependabot[bot]'))
needs: tests
Comment thread
cursor[bot] marked this conversation as resolved.
runs-on: ubuntu-latest
permissions:
id-token: write
steps:
- name: Download coverage
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: coverage-report
path: coverage
- name: Upload coverage to Codecov with OIDC
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
with:
disable_search: true
fail_ci_if_error: true
files: ./coverage/lcov.info
use_oidc: true

upload-tokenless-pr-coverage:
name: Upload fork and Dependabot coverage without a token
if: >-
always() && needs.tests.outputs.coverage-artifact-id != '' &&
github.event_name == 'pull_request' &&
(github.event.pull_request.head.repo.full_name != github.repository ||
github.event.pull_request.user.login == 'dependabot[bot]')
needs: tests
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Download coverage
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: coverage-report
path: coverage
- name: Upload unprotected fork or Dependabot coverage without a token
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
with:
disable_search: true
fail_ci_if_error: true
files: ./coverage/lcov.info
override_branch: pr${{ github.event.pull_request.number }}:${{ github.event.pull_request.head.ref }}
use_oidc: false

orchestrator-integration:
name: Orchestrator Integration
if: >-
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"test": "node scripts/ensure-husky.mjs && vitest run",
"test:watch": "vitest",
"test:ci": "vitest run",
"test:workflow-policy": "node --test scripts/workflow-credential-policy.test.mjs",
"coverage": "vitest run --coverage",
"lint": "yarn oxlint --report-unused-disable-directives",
"format": "oxfmt --write",
Expand Down
119 changes: 118 additions & 1 deletion scripts/verify-resource-cleanup-contract.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { parse } from 'yaml';
import {
findCredentialShapedEnvLiterals,
renderCredentialFinding,
} from './workflow-credential-policy.mjs';

const root = path.resolve(process.argv[2] || '.');
const failures = [];
Expand Down Expand Up @@ -247,6 +251,119 @@ if (orchestratorWorkflow.includes('secrets.UNITY_'))
if (existsSync(path.join(root, '.github/workflows/sync-secrets.yml')))
failures.push('RC016: cross-repository secret synchronization must remain removed');

const integrityWorkflow = parse(read('.github/workflows/integrity-check.yml'));
const integrityTests = integrityWorkflow.jobs?.tests;
const integrityTestSteps = integrityTests?.steps || [];
const coverageGenerationStepIndex = integrityTestSteps.findIndex(
(step) => step.run === 'yarn test:ci --coverage',
);
const coverageArtifactStepIndex = integrityTestSteps.findIndex(
(step) => step.name === 'Preserve coverage for isolated upload',
);
const distVerificationStepIndex = integrityTestSteps.findIndex(
(step) => step.name === 'Verify generated distribution',
);
const coverageGenerationStep = integrityTestSteps[coverageGenerationStepIndex];
const coverageArtifactStep = integrityTestSteps[coverageArtifactStepIndex];
const hasExplicitConditionOrFailureOverride = (step) =>
Object.hasOwn(step || {}, 'if') || Object.hasOwn(step || {}, 'continue-on-error');
const trustedCoverageJob = integrityWorkflow.jobs?.['upload-trusted-coverage'];
const tokenlessPrCoverageJob = integrityWorkflow.jobs?.['upload-tokenless-pr-coverage'];
const trustedCoverageCondition =
"always() && needs.tests.outputs.coverage-artifact-id != '' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]'))";
const tokenlessPrCoverageCondition =
"always() && needs.tests.outputs.coverage-artifact-id != '' && github.event_name == 'pull_request' && (github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')";
const expectedTrustedSteps = [
{
name: 'Download coverage',
uses: 'actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c',
with: { name: 'coverage-report', path: 'coverage' },
},
{
name: 'Upload coverage to Codecov with OIDC',
uses: 'codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f',
with: {
disable_search: true,
fail_ci_if_error: true,
files: './coverage/lcov.info',
use_oidc: true,
},
},
];
const expectedPrSteps = [
expectedTrustedSteps[0],
{
name: 'Upload unprotected fork or Dependabot coverage without a token',
uses: 'codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f',
with: {
disable_search: true,
fail_ci_if_error: true,
files: './coverage/lcov.info',
override_branch:
'pr${{ github.event.pull_request.number }}:${{ github.event.pull_request.head.ref }}',
use_oidc: false,
},
},
];
const uploadJobUsesCheckout = (job) =>
(job?.steps || []).some((step) => String(step.uses || '').startsWith('actions/checkout@'));
if (
integrityTests?.permissions?.contents !== 'read' ||
Object.keys(integrityTests?.permissions || {}).length !== 1 ||
Object.hasOwn(integrityTests?.permissions || {}, 'id-token') ||
integrityTestSteps.some((step) => String(step.uses || '').startsWith('codecov/')) ||
integrityTests?.outputs?.['coverage-artifact-id'] !==
'${{ steps.coverage-artifact.outputs.artifact-id }}' ||
coverageGenerationStepIndex < 0 ||
coverageArtifactStepIndex <= coverageGenerationStepIndex ||
distVerificationStepIndex <= coverageArtifactStepIndex ||
hasExplicitConditionOrFailureOverride(coverageGenerationStep) ||
hasExplicitConditionOrFailureOverride(coverageArtifactStep) ||
coverageArtifactStep?.id !== 'coverage-artifact' ||
coverageArtifactStep?.uses !==
'actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a' ||
coverageArtifactStep?.with?.name !== 'coverage-report' ||
coverageArtifactStep?.with?.path !== './coverage/lcov.info' ||
coverageArtifactStep?.with?.['if-no-files-found'] !== 'error' ||
coverageArtifactStep?.with?.['retention-days'] !== 1 ||
trustedCoverageJob?.if !== trustedCoverageCondition ||
trustedCoverageJob?.needs !== 'tests' ||
trustedCoverageJob?.permissions?.['id-token'] !== 'write' ||
Object.keys(trustedCoverageJob?.permissions || {}).length !== 1 ||
uploadJobUsesCheckout(trustedCoverageJob) ||
JSON.stringify(trustedCoverageJob?.steps) !== JSON.stringify(expectedTrustedSteps) ||
tokenlessPrCoverageJob?.if !== tokenlessPrCoverageCondition ||
tokenlessPrCoverageJob?.needs !== 'tests' ||
tokenlessPrCoverageJob?.permissions?.contents !== 'read' ||
Object.keys(tokenlessPrCoverageJob?.permissions || {}).length !== 1 ||
Object.hasOwn(tokenlessPrCoverageJob?.permissions || {}, 'id-token') ||
uploadJobUsesCheckout(tokenlessPrCoverageJob) ||
JSON.stringify(tokenlessPrCoverageJob?.steps) !== JSON.stringify(expectedPrSteps) ||
JSON.stringify(integrityWorkflow).includes('secrets.CODECOV')
)
failures.push(
'RC019: coverage must cross an artifact boundary into exact isolated pinned OIDC and fork/Dependabot tokenless upload jobs',
);

const pendingWorkflowDirectories = [path.join(root, '.github')];
while (pendingWorkflowDirectories.length > 0) {
const directory = pendingWorkflowDirectories.pop();
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const absolute = path.join(directory, entry.name);
if (entry.isDirectory()) {
pendingWorkflowDirectories.push(absolute);
continue;
}
if (!entry.isFile() || (!entry.name.endsWith('.yml') && !entry.name.endsWith('.yaml')))
continue;
const fileName = path.relative(path.join(root, '.github'), absolute).replaceAll('\\', '/');
const workflow = parse(read(path.relative(root, absolute)));
for (const finding of findCredentialShapedEnvLiterals(workflow, fileName)) {
failures.push(`RC018: ${renderCredentialFinding(finding)}`);
}
}
}

for (const fileName of readdirSync(path.join(root, '.github/workflows'))) {
if (!fileName.endsWith('.yml') && !fileName.endsWith('.yaml')) continue;
const workflow = parse(read(`.github/workflows/${fileName}`));
Expand All @@ -272,4 +389,4 @@ if (failures.length) {
console.error(failures.join('\n'));
process.exit(1);
}
console.log('Resource cleanup contract verified (RC001-RC017).');
console.log('Resource cleanup contract verified (RC001-RC019).');
75 changes: 75 additions & 0 deletions scripts/workflow-credential-policy.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { parse } from 'yaml';

const credentialNamePattern =
/(?:^|_)(?:API_KEY|ACCESS_KEY|CREDENTIAL|PASSWORD|PASSWD|PRIVATE_KEY|SECRET|TOKEN)(?:_|$)/i;
const credentialValuePatterns = [
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
/^(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,})$/,
/^(?:AKIA|ASIA)[A-Z0-9]{16}$/,
/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
/^-----BEGIN [A-Z0-9 ]+ PRIVATE KEY-----/,
/^(?=.{32,}$)(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9+/=_-]+$/,
];

function isCredentialShapedLiteral(name, value) {
if (!credentialNamePattern.test(name) || typeof value !== 'string') return false;

const scalar = value.trim();
if (!scalar) return false;
if (/^\$\{\{\s*(?:secrets\.[A-Za-z_][A-Za-z0-9_]*|github\.token)\s*\}\}$/.test(scalar)) {
return false;
}
if (scalar.includes('${{')) return true;

return credentialValuePatterns.some((pattern) => pattern.test(scalar));
}

function findCredentialShapedEnvLiterals(document, fileName = '<workflow>') {
const findings = [];

function visit(value, nodePath) {
if (Array.isArray(value)) {
value.forEach((entry, index) => visit(entry, [...nodePath, String(index)]));
return;
}
if (!value || typeof value !== 'object') return;

for (const [key, child] of Object.entries(value)) {
const childPath = [...nodePath, key];
if (key === 'env' && child && typeof child === 'object' && !Array.isArray(child)) {
for (const [name, envValue] of Object.entries(child)) {
if (isCredentialShapedLiteral(name, envValue)) {
findings.push({ fileName, name, path: [...childPath, name].join('.') });
}
}
}
visit(child, childPath);
}
}

visit(document, []);
return findings;
}

function renderDiagnosticComponent(value) {
return JSON.stringify(String(value))
.replaceAll(':', '\\u003a')
.replaceAll('\u2028', '\\u2028')
.replaceAll('\u2029', '\\u2029');
}

function renderCredentialFinding(finding) {
return `${renderDiagnosticComponent(finding.fileName)} has a credential-shaped literal at ${renderDiagnosticComponent(finding.path)}; use OIDC or a GitHub secret reference`;
}

function auditWorkflowCredentialLiterals(source, fileName = '<workflow>') {
return findCredentialShapedEnvLiterals(parse(source), fileName);
}

export {
auditWorkflowCredentialLiterals,
findCredentialShapedEnvLiterals,
isCredentialShapedLiteral,
renderCredentialFinding,
renderDiagnosticComponent,
};
Loading
Loading