diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 82f3d2c7..f54194e2 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -297,6 +297,7 @@ jobs: node tests/kefania/github-app-settings.js node tests/kefania/app-environment.js node tests/lindsey/bulk-merge.js + node tests/lindsey/resolver-auth.js packaged-runtime: name: Installed extension imports (ubuntu-latest) diff --git a/docs/distinct-github-apps.md b/docs/distinct-github-apps.md index b8b8248d..0f531f8b 100644 --- a/docs/distinct-github-apps.md +++ b/docs/distinct-github-apps.md @@ -64,6 +64,14 @@ and use **Check comment permissions** to verify the saved installation. This check covers Issues and Pull requests write access alongside the existing read-only checks, and does not post a comment, submit a review, or merge code. +**Resolve and sync with Lindsey** uses the same saved GitHub App key. Sweetiebot +discovers the resolver from the App's HTTPS `/webhook` URL and authenticates +before starting the merge. The resolver verifies the signed request and the +publishing repository's installation before processing the conflicting files. +This requires a compatible local `lindsey-sync` checkout and server deployment. +If the server and Sweetiebot use different keys for the App, the server must +also trust the public key corresponding to the saved Sweetiebot key. + The connection is still the **Lindsey GitHub App**: its installation token is the author of automated review and merge comments, not the GitHub user signed in to Sweetiebot. The shortcut does not introduce a second credential store or a diff --git a/extension/branches/actions.js b/extension/branches/actions.js index d7606415..417fad13 100644 --- a/extension/branches/actions.js +++ b/extension/branches/actions.js @@ -1320,7 +1320,7 @@ async function syncBranch(repository, { branch, defaultBranch, remote, strategy const targetSha = await git(['rev-parse', target]); const approved = await reviewConflicts(repository, { branch, defaultBranch, remote, strategy, targetRef: target, head: headBefore, target: targetSha, - appIdentity: Boolean(publish) + publishingRepository: publish?.repository }); if (!approved) return false; conflictChoice = approved; @@ -1337,7 +1337,7 @@ async function syncBranch(repository, { branch, defaultBranch, remote, strategy const merge = async (args, headBefore, expectedTree) => { try { await git(args); } catch (error) { - if (expectedTree !== null || conflictChoice !== 'lindsey' || !publish + if (expectedTree !== null || !conflictChoice?.lindsey || !publish || typeof resolveConflicts !== 'function') throw error; const unmerged = await git(['ls-files', '-u', '-z']); if (!unmerged) throw error; @@ -1345,7 +1345,7 @@ async function syncBranch(repository, { branch, defaultBranch, remote, strategy if (!paths.every(safeRelative)) throw Error('Unsupported sync conflict paths.'); const index = await git(['ls-files', '--stage', '-z']); const targetSha = await git(['rev-parse', target]); - const proposal = await resolveConflicts(repository); + const proposal = await resolveConflicts(repository, conflictChoice.lindsey); if (!proposal) return false; await checkBranch(); if (await git(['rev-parse', 'HEAD']) !== headBefore @@ -1577,8 +1577,8 @@ function registerBranchCommands(vscode, context) { } : {}), ...(command === 'sweetiebot.syncBranch' && vscode.window ? { reviewConflicts: (repo, details) => reviewSyncConflicts(vscode, repo, details), - resolveConflicts: async repo => { - try { return await generatePreview(vscode, repo, { sync: true }); } + resolveConflicts: async (repo, lindsey) => { + try { return await generatePreview(vscode, repo, { sync: true, lindsey }); } catch (error) { // Do not replace a failed Lindsey launch with the generic // conflict picker: that hides the reason Sync stopped. diff --git a/extension/branches/sync-main.js b/extension/branches/sync-main.js index 7991ebb4..2da3c0f4 100644 --- a/extension/branches/sync-main.js +++ b/extension/branches/sync-main.js @@ -79,6 +79,7 @@ async function syncPublisher(root, remote, { enabled = separateAppsEnabled, tran GIT_TERMINAL_PROMPT: '0', GH_PROMPT_DISABLED: '1', GIT_ASKPASS: '', SSH_ASKPASS: '' } }); } catch (error) { throw gitFailure(error, ['push']); } }; + publish.repository = repo; publish.commit = async message => { try { await run('git', ['commit', '-m', message], { cwd: root, timeout: 120000, diff --git a/extension/github/app-identity.js b/extension/github/app-identity.js index a7e1cff5..1cf91cd6 100644 --- a/extension/github/app-identity.js +++ b/extension/github/app-identity.js @@ -74,8 +74,7 @@ async function getRoleInstallationToken(role, repository, { if (!separateAppsEnabled(env)) throw new Error('Distinct GitHub App mode is not enabled.'); if (!REPOSITORY.test(repository || '')) throw new Error('Invalid GitHub repository for GitHub App authorization.'); const config = roleSettings(role, env); - const key = config.keychain ? await keychainKey(role) : config.keyFile - ? await readKey(config.keyFile, 'utf8') : config.inlineKey.replace(/\\n/g, '\n'); + const key = await appPrivateKey(role, config, readKey, keychainKey); const jwt = signAppJwt(config.id, key, now()); const request = async (endpoint, authorization, method = 'GET', body) => { let response; @@ -144,5 +143,33 @@ async function getRoleInstallationToken(role, repository, { return { token: authorized.token, login: config.slug + '[bot]', expiresAt: authorized.expires_at }; } +function appPrivateKey(role, config, readKey, keychainKey) { + return config.keychain ? keychainKey(role) : config.keyFile + ? readKey(config.keyFile, 'utf8') : config.inlineKey.replace(/\\n/g, '\n'); +} + +async function createLindseyResolverIdentity({ env = process.env, fetchImpl = globalThis.fetch, + readKey = readFile, keychainKey = readKeychainKey, now = Date.now } = {}) { + const role = 'lindsey'; + const config = roleSettings(role, env); + const key = await appPrivateKey(role, config, readKey, keychainKey); + let webhook; + if (!env.LINDSEY_RESOLVE_URL) { + try { + const response = await fetchImpl(API + '/app/hook/config', { + headers: { Authorization: 'Bearer ' + signAppJwt(config.id, key, now()), + Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }, + redirect: 'error', signal: AbortSignal.timeout(15000) + }); + if (response.ok) webhook = (await response.json()).url; + } catch { /* Report a setup error without printing the App configuration. */ } + if (!webhook) throw Error('Could not discover the Lindsey resolver from the GitHub App webhook. Check the App webhook configuration.'); + } + return { + appId: config.id, webhook, + sign: payload => createSign('RSA-SHA256').update(payload).sign(key, 'base64url') + }; +} + module.exports = { separateAppsEnabled, roleSettings, workflowBotLogin, - stripAppSecrets, getRoleInstallationToken }; + stripAppSecrets, getRoleInstallationToken, createLindseyResolverIdentity }; diff --git a/extension/merge/lindsey-conflicts.js b/extension/merge/lindsey-conflicts.js index 2b7c7644..21a423c7 100644 --- a/extension/merge/lindsey-conflicts.js +++ b/extension/merge/lindsey-conflicts.js @@ -7,6 +7,8 @@ const fs = require('node:fs/promises'); const os = require('node:os'); const path = require('node:path'); const { promisify } = require('node:util'); +const { pathToFileURL } = require('node:url'); +const { connectLindseyResolver } = require('./lindsey-resolver-auth'); const exec = promisify(execFile); const sha256 = data => createHash('sha256').update(data).digest('hex'); @@ -27,6 +29,16 @@ function lindseyScript(repoRoot, folders = [], configured = process.env.LINDSEY_ throw new Error('Lindsey Sync is not available locally. Open the lindsey-sync repository in this VS Code workspace, keep it under ~/GitHub/pony-factor or ~/GitHub, put it beside this repository, or set LINDSEY_SYNC_REPO.'); } +async function checkLindseyResolver(vscode, root, repository) { + const script = lindseyScript(root, vscode.workspace?.workspaceFolders || []); + const { prepareConflictPreview } = await import(pathToFileURL(script).href); + if (typeof prepareConflictPreview !== 'function') { + throw Error('Update the local lindsey-sync checkout to a version that supports the saved Lindsey App connection.'); + } + const requestResolution = await connectLindseyResolver(repository); + return (repo, output) => prepareConflictPreview(repo, output, requestResolution); +} + function isConflictState(repository) { return Boolean(repository.state?.mergeChanges?.length); } @@ -107,19 +119,22 @@ async function applyPreview(repository, temporary, manifest) { return files.length; } -async function generatePreview(vscode, repository, { sync = false, run = exec, findScript = lindseyScript } = {}) { +async function generatePreview(vscode, repository, { sync = false, lindsey, run = exec, findScript = lindseyScript } = {}) { const root = repository.rootUri?.fsPath; if (!root) throw new Error('No local Git repository selected.'); - const script = findScript(root, vscode.workspace?.workspaceFolders || []); const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'sweetiebot-lindsey-')); try { - let stdout; - try { - ({ stdout } = await run(process.execPath, + let manifest; + if (lindsey) { + manifest = await lindsey(root, temporary); + } else try { + const script = findScript(root, vscode.workspace?.workspaceFolders || []); + const { stdout } = await run(process.execPath, [script, '--repo', root, '--output', temporary], { cwd: root, timeout: 180000, maxBuffer: 1024 * 1024, env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', GIT_TERMINAL_PROMPT: '0' } - })); + }); + manifest = JSON.parse(stdout); } catch (error) { // Never send provider output through the Git error formatter, which // mistakes the resolver's filename for an ordinary merge failure. @@ -129,7 +144,6 @@ async function generatePreview(vscode, repository, { sync = false, run = exec, f ? 'Lindsey conflict resolution service is not configured. Configure LINDSEY_RESOLVE_URL and LINDSEY_RESOLVE_SECRET in the local VS Code environment, then retry. No resolutions were applied.' : 'Lindsey could not prepare conflict proposals. Check the local resolution service and retry. No resolutions were applied.'); } - const manifest = JSON.parse(stdout); const files = await inspectPreview(repository, temporary, manifest); for (const file of files) { await vscode.commands.executeCommand('vscode.diff', @@ -172,5 +186,5 @@ async function offerConflictRecoveryOptions(vscode, repository, propose = genera return undefined; } -module.exports = { isConflictState, lindseyScript, safeRelative, inspectPreview, +module.exports = { isConflictState, lindseyScript, checkLindseyResolver, safeRelative, inspectPreview, applyPreview, generatePreview, offerConflictRecoveryOptions }; diff --git a/extension/merge/lindsey-resolver-auth.js b/extension/merge/lindsey-resolver-auth.js new file mode 100644 index 00000000..ed8b791d --- /dev/null +++ b/extension/merge/lindsey-resolver-auth.js @@ -0,0 +1,57 @@ +'use strict'; + +const { createHash, randomUUID } = require('node:crypto'); +const { createLindseyResolverIdentity } = require('../github/app-identity'); + +function resolverEndpoint(override, webhook) { + let url; + try { url = new URL(override || webhook); } catch { /* Use a sanitized error below. */ } + if (!url || url.username || url.password || url.search || url.hash || + !(url.protocol === 'https:' || (override && url.protocol === 'http:' && + ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) || + url.pathname !== (override ? '/resolve-conflicts' : '/webhook')) { + throw Error('Lindsey needs an HTTPS /webhook URL on its GitHub App or an explicit /resolve-conflicts URL.'); + } + url.pathname = '/resolve-conflicts'; + return url; +} + +async function connectLindseyResolver(repository, { env = process.env, fetchImpl = globalThis.fetch, + identity = createLindseyResolverIdentity, now = Date.now } = {}) { + if (!/^[\w.-]+\/[\w.-]+$/.test(repository || '')) throw Error('Lindsey needs a GitHub repository to resolve conflicts.'); + const { appId, webhook, sign } = await identity({ env, fetchImpl, now }); + const endpoint = resolverEndpoint(env.LINDSEY_RESOLVE_URL, webhook); + const send = async (method, body = '') => { + const time = String(Math.floor(now() / 1000)); + const nonce = randomUUID(); + const digest = createHash('sha256').update(body).digest('hex'); + const proof = sign(['lindsey-resolver-v1', method, appId, repository, time, nonce, digest].join('\n')); + let response; + try { + response = await fetchImpl(endpoint, { + method, redirect: 'error', signal: AbortSignal.timeout(method === 'GET' ? 20000 : 120000), + headers: { 'X-Lindsey-App': appId, 'X-Lindsey-Repository': repository, 'X-Lindsey-Time': time, + 'X-Lindsey-Nonce': nonce, 'X-Lindsey-Proof': proof, + ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}) }, + ...(method === 'POST' ? { body } : {}) + }); + } catch { throw Error('Could not reach the Lindsey resolver configured for the GitHub App.'); } + if (response.status === 401 || response.status === 403) { + throw Error('The Lindsey resolver could not verify this App key or repository installation.'); + } + if (response.status === 404 || response.status === 405) { + throw Error('The deployed Lindsey resolver does not support App authentication yet.'); + } + if (!response.ok) throw Error('The Lindsey resolver request failed (HTTP ' + response.status + ').'); + let result; + try { result = await response.json(); } catch { /* Invalid response. */ } + if (!result?.ok || (method === 'GET' && result.authentication !== 'lindsey-app-v1')) { + throw Error('The Lindsey resolver returned an unexpected response. Check the resolver deployment.'); + } + return result; + }; + await send('GET'); + return request => send('POST', JSON.stringify(request)); +} + +module.exports = { connectLindseyResolver }; diff --git a/extension/merge/sync-review.js b/extension/merge/sync-review.js index c1d78be3..87304d04 100644 --- a/extension/merge/sync-review.js +++ b/extension/merge/sync-review.js @@ -4,6 +4,7 @@ const { promisify } = require('node:util'); const { existsSync } = require('node:fs'); const fs = require('node:fs/promises'); const path = require('node:path'); +const { checkLindseyResolver } = require('./lindsey-conflicts'); const exec = promisify(execFile); const SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i; const gh = ['/opt/homebrew/bin/gh', '/usr/local/bin/gh'].find(existsSync) || 'gh'; @@ -16,7 +17,7 @@ function githubRepository(url) { const found = String(url || '').match(/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i); return found ? found[1] + '/' + found[2] : null; } -async function reviewSyncConflicts(vscode, repository, details) { +async function reviewSyncConflicts(vscode, repository, details, { connect = checkLindseyResolver } = {}) { const { branch, defaultBranch, remote, head, target, strategy } = details; const root = repository.rootUri?.fsPath; if (!root || !SHA.test(head) || !SHA.test(target)) throw Error('Missing verified sync revisions.'); @@ -32,7 +33,7 @@ async function reviewSyncConflicts(vscode, repository, details) { await unchanged(); for (;;) { const choice = await vscode.window.showQuickPick([ - ...(details.appIdentity ? [{ id: 'lindsey', label: '$(sparkle) Resolve and sync with Lindsey', description: 'Review conflict proposals, then commit and publish with the configured App' }] : []), + ...(details.publishingRepository ? [{ id: 'lindsey', label: '$(sparkle) Resolve and sync with Lindsey', description: 'Review conflict proposals, then commit and publish with the configured App' }] : []), { id: 'inspect', label: '$(diff) Inspect conflict preview', description: 'Read Git conflict details; no files are changed' }, { id: 'resolve', label: '$(tools) Start conflict resolution', description: 'Proceed to Git merge editor without auto-committing' }, { id: 'own', label: '$(git-commit) Make my own commit first', description: 'Prefill an editable commit title and cancel this sync' }, @@ -41,7 +42,9 @@ async function reviewSyncConflicts(vscode, repository, details) { placeHolder: 'Git cannot automatically reconcile this ' + strategy + ' sync', ignoreFocusOut: true }); if (!choice || choice.id === 'cancel') return false; await unchanged(); - if (choice.id === 'lindsey') return 'lindsey'; + if (choice.id === 'lindsey') { + return { lindsey: await connect(vscode, root, details.publishingRepository) }; + } if (choice.id === 'own') { const suggested = '🛠️ Prepare ' + branch + ' for synchronization with ' + defaultBranch; const input = await vscode.window.showInputBox({ diff --git a/scripts/ci/ci-test-groups.json b/scripts/ci/ci-test-groups.json index 57726bda..a3b44c55 100644 --- a/scripts/ci/ci-test-groups.json +++ b/scripts/ci/ci-test-groups.json @@ -245,6 +245,7 @@ "lindsey/bulk-merge.js", "lindsey/transport.js", "lindsey/conflicts.js", + "lindsey/resolver-auth.js", "merge/keep-awake.js", "merge/order.js", "merge/handoff-page.js", @@ -274,6 +275,7 @@ "syntax": [ "extension/merge/lindsey-bulk-merge.js", "extension/merge/lindsey-transport.js", + "extension/merge/lindsey-resolver-auth.js", "extension/github/app-commit-identity.js", "extension/commits/git-failure.js", "extension/merge/parallel-merge-batch.js", diff --git a/tests/branches/routine-sync.js b/tests/branches/routine-sync.js index 11a29bea..ba46effd 100644 --- a/tests/branches/routine-sync.js +++ b/tests/branches/routine-sync.js @@ -78,9 +78,15 @@ async function run() { return exec(command, args, opts); } }); + const preparePreview = () => { throw Error('Preview generation is mocked by resolveConflicts'); }; const result = syncBranch(repository, { ...options, strategy, createPublisher, - reviewConflicts: async (_, details) => { assert.equal(details.appIdentity, true); return 'lindsey'; }, - resolveConflicts: async () => { + reviewConflicts: async (_, details) => { + assert.equal(details.publishingRepository, 'owner/repo'); + return { lindsey: preparePreview }; + }, + resolveConflicts: async (checkout, preview) => { + assert.equal(checkout, repository); + assert.equal(preview, preparePreview, 'The approved resolver is forwarded to conflict resolution'); proposed++; assert(git('ls-files', '-u'), 'Resolver receives the actual conflicting index'); if (scenario === 'cancel') return undefined; diff --git a/tests/branches/sync/review.js b/tests/branches/sync/review.js index f85ae732..05fff809 100644 --- a/tests/branches/sync/review.js +++ b/tests/branches/sync/review.js @@ -120,8 +120,22 @@ async function run() { assert.equal(await reviewSyncConflicts(vscode, repository, review), false); choices = ['resolve']; assert.equal(await reviewSyncConflicts(vscode, repository, review), true); + const lindsey = { ...review, publishingRepository: 'owner/publishing-fork' }; choices = ['lindsey']; - assert.equal(await reviewSyncConflicts(vscode, repository, { ...review, appIdentity: true }), 'lindsey'); + await assert.rejects(reviewSyncConflicts(vscode, repository, lindsey, { + connect: async () => { throw Error('Resolver unavailable'); } + }), /Resolver unavailable/); + assert.equal(git('status', '--porcelain'), '', 'Setup errors leave the topic checkout clean'); + choices = ['lindsey']; + const prepare = () => {}; + assert.deepEqual(await reviewSyncConflicts(vscode, repository, lindsey, { + connect: async (host, checkout, targetRepo) => { + assert.equal(host, vscode); + assert.equal(checkout, root); + assert.equal(targetRepo, 'owner/publishing-fork'); + return prepare; + } + }), { lindsey: prepare }); await assert.rejects(reviewSyncConflicts(vscode, repository, { ...review, head: before }), /revisions or working files changed/); } finally { diff --git a/tests/lindsey/conflicts.js b/tests/lindsey/conflicts.js index 692b4d8a..20cf65de 100644 --- a/tests/lindsey/conflicts.js +++ b/tests/lindsey/conflicts.js @@ -93,6 +93,16 @@ async function run() { path: 'file.txt', sha256: createHash('sha256').update('merged\n').digest('hex') }] }); assert(git('ls-files', '-u'), 'Preview returns reviewed bytes to the sync coordinator before staging'); + fs.writeFileSync(path.join(root, 'file.txt'), original); + assert.deepEqual(await generatePreview(syncUI, mockRepo, { + sync: true, + lindsey: async (checkout, output) => { + assert.equal(checkout, root); + fs.writeFileSync(path.join(output, candidate), 'merged\n'); + return manifest; + }, + run: async () => { assert.fail('App-authenticated sync should not invoke the shared-secret CLI'); } + }), { files: [{ path: 'file.txt', sha256: createHash('sha256').update('merged\n').digest('hex') }] }); const failedPreview = stderr => generatePreview(syncUI, mockRepo, { ...previewOptions, run: async () => { throw Object.assign(new Error('Command failed'), { stderr }); } }); diff --git a/tests/lindsey/resolver-auth.js b/tests/lindsey/resolver-auth.js new file mode 100644 index 00000000..9f2e2738 --- /dev/null +++ b/tests/lindsey/resolver-auth.js @@ -0,0 +1,39 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { createHash, generateKeyPairSync, verify } = require('node:crypto'); +const { connectLindseyResolver } = require('../../extension/merge/lindsey-resolver-auth'); + +async function run() { + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const env = { SWEETIEBOT_LINDSEY_APP_ID: '42', SWEETIEBOT_LINDSEY_APP_SLUG: 'lindsey', + SWEETIEBOT_LINDSEY_APP_PRIVATE_KEY: privateKey.export({ type: 'pkcs8', format: 'pem' }) }; + const requested = []; + const fetchImpl = async (url, options) => { + requested.push(String(url)); + assert.equal(options.redirect, 'error'); + if (String(url) === 'https://api.github.com/app/hook/config') { + assert.match(options.headers.Authorization, /^Bearer .*\..*\..*$/); + return Response.json({ url: 'https://lindsey.example.invalid/webhook' }); + } + const h = options.headers; + assert.equal(h.Authorization, undefined); + assert.equal(h['X-Lindsey-Repository'], 'owner/repo'); + const digest = createHash('sha256').update(options.body ?? '').digest('hex'); + const message = ['lindsey-resolver-v1', options.method, '42', 'owner/repo', h['X-Lindsey-Time'], + h['X-Lindsey-Nonce'], digest].join('\n'); + assert(verify('RSA-SHA256', Buffer.from(message), publicKey, Buffer.from(h['X-Lindsey-Proof'], 'base64url'))); + return options.method === 'GET' ? Response.json({ ok: true, authentication: 'lindsey-app-v1' }) + : Response.json({ ok: true, resolutions: [] }); + }; + const resolve = await connectLindseyResolver('owner/repo', { env, fetchImpl }); + assert.equal(requested.length, 2, 'The preflight sends no conflict body'); + await resolve({ files: [{ path: 'fixture.txt' }] }); + assert.deepEqual(requested, ['https://api.github.com/app/hook/config', + 'https://lindsey.example.invalid/resolve-conflicts', 'https://lindsey.example.invalid/resolve-conflicts']); + await assert.rejects(connectLindseyResolver('owner/repo', { env, fetchImpl: async url => + String(url).startsWith('https://api.github.com/') ? Response.json({ url: 'https://lindsey.example.invalid/webhook' }) + : new Response('', { status: 401 }) }), /could not verify this App key/); +} + +run().catch(error => { console.error(error); process.exitCode = 1; });