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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions docs/distinct-github-apps.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions extension/branches/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -1337,15 +1337,15 @@ 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;
const paths = [...new Set(unmerged.split('\0').filter(Boolean).map(entry => entry.slice(entry.indexOf('\t') + 1)))];
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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions extension/branches/sync-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
33 changes: 30 additions & 3 deletions extension/github/app-identity.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 };
30 changes: 22 additions & 8 deletions extension/merge/lindsey-conflicts.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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);
}
Expand Down Expand Up @@ -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.
Expand All @@ -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',
Expand Down Expand Up @@ -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 };
57 changes: 57 additions & 0 deletions extension/merge/lindsey-resolver-auth.js
Original file line number Diff line number Diff line change
@@ -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 };
9 changes: 6 additions & 3 deletions extension/merge/sync-review.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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.');
Expand All @@ -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' },
Expand All @@ -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({
Expand Down
2 changes: 2 additions & 0 deletions scripts/ci/ci-test-groups.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
10 changes: 8 additions & 2 deletions tests/branches/routine-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
16 changes: 15 additions & 1 deletion tests/branches/sync/review.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 10 additions & 0 deletions tests/lindsey/conflicts.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 }); }
});
Expand Down
Loading
Loading