From 9f1d44ec148f914d5a8569808b36f9f6a1c456f6 Mon Sep 17 00:00:00 2001 From: Chris Date: Fri, 27 Nov 2026 15:01:54 -0800 Subject: [PATCH] fix(deps): require lockfiles for Buddy manifest updates --- src/git/github-provider.ts | 127 ++++++++++++----------- src/utils/lock-file.ts | 56 +++++----- test/github-provider-api.test.ts | 66 ++++++++++++ test/workflow-permission-refusal.test.ts | 40 ++++++- 4 files changed, 195 insertions(+), 94 deletions(-) diff --git a/src/git/github-provider.ts b/src/git/github-provider.ts index e6fbc344..3eee4357 100644 --- a/src/git/github-provider.ts +++ b/src/git/github-provider.ts @@ -8,7 +8,7 @@ import { getGitHubApiUrl } from '../utils/endpoints' import { formatError, GitHubApiError } from '../utils/errors' import { assertUpdateTargetsExist, FileChangeValidationError, normalizeRepositoryPath } from '../utils/file-changes' import { fetchWithTimeout } from '../utils/http' -import { detectRequiredPackageManagers, getAllLockFilePaths, nestedLockProjects, regenerateLockFile } from '../utils/lock-file' +import { detectRequiredPackageManagers, getAllLockFilePaths, isLockfileManifest, missingLockFiles, nestedLockProjects, regenerateLockFile } from '../utils/lock-file' import { getDefaultLogger } from '../utils/logger' import { isBuddyBranch } from '../utils/branches' @@ -391,12 +391,14 @@ export class GitHubProvider implements GitProvider { } }) + const updatedPaths: string[] = [] + const isTestEnv = process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test' // Apply file changes for (const file of files) { const cleanPath = normalizeRepositoryPath(file.path) // Safety check: prevent writing to sensitive files during tests - if (process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test') { + if (isTestEnv) { const sensitiveFiles = ['package.json', 'bun.lock', 'bun.lockb', 'package-lock.json', 'yarn.lock'] if (sensitiveFiles.includes(cleanPath) && file.content === '{"name":"x"}') { this.logger.warn(`⚠️ Skipping test file write to ${cleanPath} to prevent overwriting project files`) @@ -407,6 +409,7 @@ export class GitHubProvider implements GitProvider { if (file.type === 'delete') { try { await this.runCommand('git', ['rm', cleanPath]) + updatedPaths.push(cleanPath) } catch { // File might not exist, that's ok for delete operations @@ -416,69 +419,62 @@ export class GitHubProvider implements GitProvider { // Bun.write creates parent directories automatically and is async await Bun.write(cleanPath, file.content) await this.runCommand('git', ['add', cleanPath]) + updatedPaths.push(cleanPath) } } - // Regenerate lock files after manifest changes (skip in test environments). - // We HARD-FAIL if regeneration fails for any required manager: a PR with an - // updated manifest but stale lockfile is a correctness bug — consumers will - // install the wrong versions. Fail loudly so the caller can retry or - // investigate instead of silently opening a broken PR. - const isTestEnv = process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test' - if (!isTestEnv) { - const updatedPaths = files.map(f => f.path.replace(/^\.\//, '').replace(/^\/+/, '')) - const requiredManagers = detectRequiredPackageManagers(updatedPaths) + // Real writes require matching locks even when the process uses a test environment. + const requiredManagers = detectRequiredPackageManagers(updatedPaths) - if (requiredManagers.length > 0) { - this.logger.info(`🔒 Regenerating lock files for: ${requiredManagers.join(', ')}`) - const cwd = process.cwd() - const failures: string[] = [] + if (requiredManagers.length > 0) { + this.logger.info(`🔒 Regenerating lock files for: ${requiredManagers.join(', ')}`) + const cwd = process.cwd() + const failures: string[] = [] - for (const manager of requiredManagers) { - try { - const result = await regenerateLockFile(manager, cwd) - if (result.success) { - // Stage any regenerated lock files - for (const lockFile of getAllLockFilePaths()) { - try { - await this.runCommand('git', ['add', lockFile]) - } - catch { - // Lock file may not exist for this manager, that's fine - } + for (const manager of requiredManagers) { + try { + const result = await regenerateLockFile(manager, cwd) + if (result.success) { + // Stage any regenerated lock files + for (const lockFile of getAllLockFilePaths()) { + try { + await this.runCommand('git', ['add', lockFile]) + } + catch { + // Lock file may not exist for this manager, that's fine } - } - else { - failures.push(`${manager}: ${result.message}`) } } - catch (lockError) { - failures.push(`${manager}: ${lockError instanceof Error ? lockError.message : String(lockError)}`) + else { + failures.push(`${manager}: ${result.message}`) } } - - // Projects with a lock file of their own beside a changed manifest - // are separate installs; the root install does not touch them. - for (const project of nestedLockProjects(updatedPaths, cwd)) { - try { - const result = await regenerateLockFile(project.manager, `${cwd}/${project.dir}`) - if (result.success) - await this.runCommand('git', ['add', project.lockFile]) - else - failures.push(`${project.dir} (${project.manager}): ${result.message}`) - } - catch (lockError) { - failures.push(`${project.dir} (${project.manager}): ${lockError instanceof Error ? lockError.message : String(lockError)}`) - } + catch (lockError) { + failures.push(`${manager}: ${lockError instanceof Error ? lockError.message : String(lockError)}`) } + } - if (failures.length > 0) { - const detail = failures.map(f => ` - ${f}`).join('\n') - throw new LockfileRegenerationError( - `Lock file regeneration failed; refusing to open PR with stale lockfiles.\n${detail}`, - ) + // Projects with a lock file of their own beside a changed manifest + // are separate installs; the root install does not touch them. + for (const project of nestedLockProjects(updatedPaths, cwd)) { + try { + const result = await regenerateLockFile(project.manager, `${cwd}/${project.dir}`) + if (result.success) + await this.runCommand('git', ['add', project.lockFile]) + else + failures.push(`${project.dir} (${project.manager}): ${result.message}`) + } + catch (lockError) { + failures.push(`${project.dir} (${project.manager}): ${lockError instanceof Error ? lockError.message : String(lockError)}`) } } + + if (failures.length > 0) { + const detail = failures.map(f => ` - ${f}`).join('\n') + throw new LockfileRegenerationError( + `Lock file regeneration failed; refusing to open PR with stale lockfiles.\n${detail}`, + ) + } } // Check if there are changes to commit against the current branch tip @@ -542,16 +538,6 @@ export class GitHubProvider implements GitProvider { this.logger.info(`✅ Including ${workflowFiles.length} workflow file(s) with elevated permissions`) } - // Note: Lock files cannot be regenerated when committing via the API path - // because there is no local filesystem to run install commands against. - const hasManifestFiles = files.some(f => - f.path.endsWith('package.json') || f.path.endsWith('composer.json'), - ) - if (hasManifestFiles) { - this.logger.warn(`⚠️ Committing manifest files via API — lock files will not be updated.`) - this.logger.warn(` Lock file regeneration requires the Git CLI commit path (local filesystem).`) - } - // Renovate-style: base the new commit on the base branch (e.g. main), not the PR branch. // This recreates the branch from scratch, eliminating any merge conflicts. this.logger.info(`🔄 Recreating ${branchName} from ${baseBranch} via API (Renovate-style)...`) @@ -565,7 +551,7 @@ export class GitHubProvider implements GitProvider { await assertUpdateTargetsExist(files, async (cleanPath) => { const encodedPath = cleanPath.split('/').map(segment => encodeURIComponent(segment)).join('/') try { - await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodedPath}?ref=${encodeURIComponent(baseBranch)}`) + await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodedPath}?ref=${encodeURIComponent(baseSha)}`) return true } catch (error: any) { @@ -575,6 +561,23 @@ export class GitHubProvider implements GitProvider { } }) + // The API cannot run the package managers. Check the exact base tree so + // a failed Git commit cannot discard the regenerated files on fallback. + const changedPaths = files + .filter(file => file.type !== 'delete' || isLockfileManifest(normalizeRepositoryPath(file.path))) + .map(file => normalizeRepositoryPath(file.path)) + if (changedPaths.some(isLockfileManifest)) { + const baseTree: { truncated: boolean, tree: { path: string, type: string }[] } + = await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/trees/${baseTreeSha}?recursive=1`) + if (baseTree.truncated || !Array.isArray(baseTree.tree)) + throw new LockfileRegenerationError('The base tree is incomplete; use Git to verify and regenerate its lockfiles before publishing.') + + const tracked = new Set(baseTree.tree.filter(entry => entry.type === 'blob').map(entry => entry.path)) + const missing = missingLockFiles(changedPaths, '.', path => tracked.has(normalizeRepositoryPath(path))) + if (missing.length > 0) + throw new LockfileRegenerationError(`Refusing to publish dependency manifests without updated lockfiles: ${missing.join(', ')}. Use Git to regenerate them and retry.`) + } + // Create new tree with file changes const tree = [] for (const file of files) { diff --git a/src/utils/lock-file.ts b/src/utils/lock-file.ts index c93632ef..80d4b02c 100644 --- a/src/utils/lock-file.ts +++ b/src/utils/lock-file.ts @@ -1,7 +1,7 @@ import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' +import { join } from 'node:path' import process from 'node:process' -import { detectPackageManager } from './helpers' import { getDefaultLogger } from './logger' export type PackageManagerType = 'bun' | 'npm' | 'yarn' | 'pnpm' | 'composer' | 'pantry' @@ -149,6 +149,14 @@ export async function regenerateLockFile( * Pantry's own manifests. A change to one of these only reaches `pantry.lock`. */ const PANTRY_MANIFESTS = new Set(['deps.yaml', 'deps.yml', 'pantry.jsonc', 'pantry.json', 'pantry.toml']) +const JS_PACKAGE_MANAGERS = ['bun', 'pnpm', 'yarn', 'npm'] as const +type FileExists = (path: string) => boolean + +/** Whether changing this manifest can invalidate a dependency lockfile. */ +export function isLockfileManifest(path: string): boolean { + const name = path.split('/').at(-1) ?? '' + return name === 'package.json' || name === 'composer.json' || PANTRY_MANIFESTS.has(name) +} /** * Examine which manifest files were updated to determine which package managers @@ -163,7 +171,7 @@ const PANTRY_MANIFESTS = new Set(['deps.yaml', 'deps.yml', 'pantry.jsonc', 'pant * @param updatedFilePaths - List of file paths that were updated * @param cwd - Project root whose lock files decide the managers */ -export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: string = process.cwd()): PackageManagerType[] { +export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): PackageManagerType[] { const managers: Set = new Set() let pantryInputChanged = false @@ -172,7 +180,7 @@ export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: s if (fileName === 'package.json') { // Detect the JS package manager from lock files on disk - managers.add(detectPackageManager(cwd)) + managers.add(JS_PACKAGE_MANAGERS.find(manager => lockFileFor(manager, cwd, exists)) ?? 'bun') pantryInputChanged = true } @@ -184,7 +192,7 @@ export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: s pantryInputChanged = true } - if (pantryInputChanged && hasLockFile('pantry', cwd)) + if (pantryInputChanged && lockFileFor('pantry', cwd, exists)) managers.add('pantry') return Array.from(managers) @@ -212,7 +220,7 @@ export interface NestedLockProject { * @param updatedFilePaths - Paths a change touches, relative to the root * @param cwd - Repository root */ -export function nestedLockProjects(updatedFilePaths: string[], cwd: string = process.cwd()): NestedLockProject[] { +export function nestedLockProjects(updatedFilePaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): NestedLockProject[] { const projects = new Map() for (const filePath of updatedFilePaths) { const clean = filePath.replace(/^\.\//, '') @@ -221,11 +229,11 @@ export function nestedLockProjects(updatedFilePaths: string[], cwd: string = pro const dir = clean.slice(0, clean.lastIndexOf('/')) if (projects.has(dir)) continue - const absolute = `${cwd}/${dir}` - const manager = (['bun', 'pnpm', 'yarn', 'npm'] as const).find(candidate => hasLockFile(candidate, absolute)) + const absolute = join(cwd, dir) + const manager = JS_PACKAGE_MANAGERS.find(candidate => lockFileFor(candidate, absolute, exists)) if (!manager) continue - const lockFile = lockFileFor(manager, absolute) + const lockFile = lockFileFor(manager, absolute, exists) if (lockFile) projects.set(dir, { dir, manager, lockFile: `${dir}/${lockFile}` }) } @@ -235,7 +243,7 @@ export function nestedLockProjects(updatedFilePaths: string[], cwd: string = pro /** * The lock file a manager writes in this project, or null when it has none. */ -export function lockFileFor(packageManager: PackageManagerType, cwd: string): string | null { +export function lockFileFor(packageManager: PackageManagerType, cwd: string, exists: FileExists = existsSync): string | null { const candidates: Record = { bun: ['bun.lock', 'bun.lockb'], npm: ['package-lock.json'], @@ -244,7 +252,7 @@ export function lockFileFor(packageManager: PackageManagerType, cwd: string): st composer: ['composer.lock'], pantry: ['pantry.lock'], } - return candidates[packageManager].find(name => existsSync(`${cwd}/${name}`)) ?? null + return candidates[packageManager].find(name => exists(join(cwd, name))) ?? null } /** @@ -258,14 +266,15 @@ export function lockFileFor(packageManager: PackageManagerType, cwd: string): st * @param changedPaths - Paths the pull request changes * @param cwd - Project root whose lock files decide what is expected */ -export function missingLockFiles(changedPaths: string[], cwd: string = process.cwd()): string[] { +export function missingLockFiles(changedPaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): string[] { const changed = new Set(changedPaths.map(path => path.replace(/^\.\//, ''))) - const nestedDirs = new Set(nestedLockProjects(changedPaths, cwd).map(project => project.dir)) + const nested = nestedLockProjects(changedPaths, cwd, exists) + const nestedDirs = new Set(nested.map(project => project.dir)) // A manifest inside a nested project needs only that project's lock file. const rootPaths = changedPaths.filter(path => !nestedDirs.has(path.replace(/^\.\//, '').replace(/\/package\.json$/, ''))) - const rootLocks = detectRequiredPackageManagers(rootPaths, cwd) - .map(manager => lockFileFor(manager, cwd)) - const nestedLocks = nestedLockProjects(changedPaths, cwd).map(project => project.lockFile) + const rootLocks = detectRequiredPackageManagers(rootPaths, cwd, exists) + .map(manager => lockFileFor(manager, cwd, exists)) + const nestedLocks = nested.map(project => project.lockFile) return [...rootLocks, ...nestedLocks] .filter((lockFile): lockFile is string => lockFile !== null && !changed.has(lockFile)) } @@ -274,20 +283,5 @@ export function missingLockFiles(changedPaths: string[], cwd: string = process.c * Check if a lock file exists for a given package manager in the working directory */ export function hasLockFile(packageManager: PackageManagerType, cwd: string): boolean { - const path = require('node:path') - - switch (packageManager) { - case 'bun': - return existsSync(path.join(cwd, 'bun.lock')) || existsSync(path.join(cwd, 'bun.lockb')) - case 'npm': - return existsSync(path.join(cwd, 'package-lock.json')) - case 'yarn': - return existsSync(path.join(cwd, 'yarn.lock')) - case 'pnpm': - return existsSync(path.join(cwd, 'pnpm-lock.yaml')) - case 'composer': - return existsSync(path.join(cwd, 'composer.lock')) - case 'pantry': - return existsSync(path.join(cwd, 'pantry.lock')) - } + return lockFileFor(packageManager, cwd) !== null } diff --git a/test/github-provider-api.test.ts b/test/github-provider-api.test.ts index ac55a089..b92e0f3c 100644 --- a/test/github-provider-api.test.ts +++ b/test/github-provider-api.test.ts @@ -604,6 +604,72 @@ describe('gitHubProvider API surface', () => { }) describe('commitChanges via API', () => { + function writableApiCommit(paths: string[], truncated = false) { + const prov = github() + ;(prov as any).runCommand = async () => { throw new Error('git unavailable') } + const calls = stubFetch((call) => { + if (call.url.includes('/git/ref/heads/')) + return json({ object: { sha: 'base-sha' } }) + if (call.method === 'GET' && call.url.includes('/git/commits/')) + return json({ tree: { sha: 'tree-sha' } }) + if (call.method === 'GET' && call.url.includes('/git/trees/tree-sha')) + return json({ truncated, tree: paths.map(path => ({ path, type: 'blob' })) }) + return json({ sha: 'written-sha' }) + }) + return { prov, calls } + } + + it('does not write a manifest without the tracked Bun and Pantry locks', async () => { + const { prov, calls } = writableApiCommit(['package.json', 'bun.lock', 'pantry.lock']) + + const error = await prov.commitChanges('buddy/x', 'msg', [ + { path: 'package.json', content: '{"dependencies":{"stacks":"0.75.711"}}', type: 'update' }, + ]).catch((e: unknown) => e) + + expect((error as Error)?.message).toContain('bun.lock, pantry.lock') + expect(calls.filter(call => call.method !== 'GET')).toEqual([]) + }) + + it('allows a standalone nested update with its own supplied lock', async () => { + const { prov, calls } = writableApiCommit(['bun.lock', 'docs/package.json', 'docs/pnpm-lock.yaml']) + + await prov.commitChanges('buddy/x', 'msg', [ + { path: 'docs/package.json', content: '{"dependencies":{"docs":"1.1.0"}}', type: 'update' }, + { path: 'docs/pnpm-lock.yaml', content: 'updated lock', type: 'update' }, + ]) + + expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1) + }) + + it('allows an API manifest update in a repository without lockfiles', async () => { + const { prov, calls } = writableApiCommit(['package.json']) + + await prov.commitChanges('buddy/x', 'msg', [ + { path: 'package.json', content: '{"dependencies":{"stacks":"0.75.711"}}', type: 'update' }, + ]) + + expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1) + }) + + it('does not count a deleted lock as a regenerated lock', async () => { + const { prov, calls } = writableApiCommit(['package.json', 'bun.lock']) + + await expect(prov.commitChanges('buddy/x', 'msg', [ + { path: 'package.json', content: '{}', type: 'update' }, + { path: 'bun.lock', content: '', type: 'delete' }, + ])).rejects.toThrow('without updated lockfiles: bun.lock') + expect(calls.filter(call => call.method !== 'GET')).toEqual([]) + }) + + it('does not write a manifest if the base tree is incomplete', async () => { + const { prov, calls } = writableApiCommit(['package.json'], true) + + await expect(prov.commitChanges('buddy/x', 'msg', [ + { path: 'package.json', content: '{}', type: 'update' }, + ])).rejects.toThrow('The base tree is incomplete') + expect(calls.filter(call => call.method !== 'GET')).toEqual([]) + }) + function providerForCommit(contentsError: Error): { prov: GitHubProvider, endpoints: string[] } { const prov = github() ;(prov as any).runCommand = async () => { diff --git a/test/workflow-permission-refusal.test.ts b/test/workflow-permission-refusal.test.ts index ae19ba34..5b48256e 100644 --- a/test/workflow-permission-refusal.test.ts +++ b/test/workflow-permission-refusal.test.ts @@ -1,11 +1,12 @@ import type { FileChange } from '../src/types' import { describe, expect, it, spyOn } from 'bun:test' import { Buffer } from 'node:buffer' -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import process from 'node:process' import { gitAuthConfigArgs, GitHubProvider, isWorkflowPermissionRefusal, WorkflowPermissionError } from '../src/git/github-provider' +import { Logger } from '../src/utils/logger' /** * A token can exist and still be refused for `.github/workflows/`: a GitHub @@ -104,3 +105,40 @@ describe('git authentication for an override token', () => { } }) }) + +it('regenerates locks for real manifest writes in a test-labelled process', async () => { + const cwd = process.cwd() + const dir = mkdtempSync(join(tmpdir(), 'buddy-lock-write-')) + const previous = process.env.NODE_ENV + process.env.NODE_ENV = 'test' + try { + for (const [folder, version] of [['before', '1.0.0'], ['after', '2.0.0']]) { + mkdirSync(join(dir, folder)) + writeFileSync(join(dir, folder, 'package.json'), JSON.stringify({ name: 'fixture', version })) + } + const manifest = (folder: string): string => JSON.stringify({ name: 'lock-test', dependencies: { fixture: `file:./${folder}` } }) + writeFileSync(join(dir, 'package.json'), manifest('before')) + const bun = (...args: string[]) => Bun.spawnSync([process.execPath, 'install', '--ignore-scripts', ...args], { cwd: dir }) + expect(bun().exitCode).toBe(0) + process.chdir(dir) + + const provider = new GitHubProvider('token', 'owner', 'repo', false, undefined, 'https://api.github.test', Logger.silent()) + const staged: string[] = [] + provider.runCommand = async (_command, args) => { + if (args[0] === 'add') staged.push(args[1]!) + return '' + } + await provider.commitChanges('buddy/update', 'chore(deps): update fixture', [ + { path: 'package.json', type: 'update', content: manifest('after') }, + ]) + + expect(bun('--frozen-lockfile').exitCode).toBe(0) + expect(staged).toContain('bun.lock') + } + finally { + process.chdir(cwd) + if (previous === undefined) delete process.env.NODE_ENV + else process.env.NODE_ENV = previous + rmSync(dir, { recursive: true, force: true }) + } +})