Files
stack/packages/organization/tests/repo-remote.test.mjs
jason.woltje 90245765f2 feat(bus): copy revoke CB4, lifecycle events fence and revoke bound copies (#1873)
Every lifecycle event that ends a copy's authority (unbind, emergency
revoke, slot removal or expiry, role change, fire, collision, shadowing,
archive, delete and recreate) now closes admissions, drains in-flight
uses, stops runs with a confirmed ack, removes the slot and revokes the
Gitea token through the org admin slot. The binding moves through a
durable revoking state, so a restart resumes the same op and never
resurrects authority; an uncertain outcome stays fenced.
2026-11-12 16:08:07 -06:00

360 lines
27 KiB
JavaScript

// #1873 P1-6 and P1-7: the remote URL rules, the ls-remote check, and repo set.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { createServer as createTcpServer } from 'node:net';
import { execFileSync } from 'node:child_process';
import { chmodSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { tmpdir } from 'node:os';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { parseRepoRemote, checkRemote, classifyCheck, summarizeGitError, CHECK_SSH_COMMAND, NEEDS_CREDENTIAL_MESSAGE, SSH_HOST_UNVERIFIED, repoRemoteTestSeam } from '../src/repo-remote.mjs';
import { createOrg, templateRender, projectRepoInit, projectRepoShow, projectRepoSet, queueInit, showOrg, updateOrg } from '../src/org-service.mjs';
import { loadBusiness } from '../src/organization-config.mjs';
import { REPO_ROLES } from './helpers.mjs';
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const seam = repoRemoteTestSeam;
const gitEnv = { PATH: process.env.PATH, HOME: '/nonexistent', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', LC_ALL: 'C' };
const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], { env: gitEnv, encoding: 'utf8' }).trim();
function bare() { const dir = mkdtempSync(join(tmpdir(), 'bare-')); git(dir, 'init', '--quiet', '--bare', '--template='); return dir; }
function context() { const root = mkdtempSync(join(tmpdir(), 'repo-remote-')); const configDir = join(root, 'config'), dataRoot = join(root, 'data'); mkdirSync(configDir, { mode: 0o700 }); mkdirSync(dataRoot, { mode: 0o700 }); return { configDir, dataRoot, instance: 'test', principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } }; }
const listen = (server) => new Promise((r) => server.listen(0, '127.0.0.1', () => r(server.address().port)));
test('remote URL rules: https and ssh only, nothing git could read as an option, helper, path or credential', () => {
for (const ok of ['https://git.example.com/owner/repo', 'https://git.example.com/owner/repo.git', 'https://git.example.com:8443/o/r',
'ssh://[email protected]/owner/repo.git', 'ssh://git.example.com:2222/srv/git/repo.git', '[email protected]:owner/repo.git', '[email protected]:/srv/repo']) {
assert.equal(parseRepoRemote(ok).ok, true, ok);
}
const refused = {
'ext::sh -c touch% /tmp/pwned': 'transport', 'fd::17': 'transport', 'file:///srv/repo.git': 'local', 'FILE:///srv/r': 'local',
'/srv/repo.git': 'local', './repo': 'local', '../repo': 'local', '~/repo': 'local', 'repo/sub:x': 'local', 'plainword': 'local',
'--upload-pack=touch /tmp/x': 'option', '-oProxyCommand=x': 'option',
'https://user:[email protected]/o/r': 'credentials', 'https://[email protected]/o/r': 'credentials',
'ssh://git:[email protected]/o/r': 'credentials', 'git:[email protected]:o/r': 'credentials',
'http://git.example.com/o/r': 'scheme', 'git://git.example.com/o/r': 'scheme', 'ftp://x/o/r': 'scheme', 'ssh+git://x/o/r': 'scheme',
'https://git.example.com/o/r?x=1': 'https', 'https://git.example.com/o/../r': 'https', 'https://git.example.com/o': 'https', 'HTTPS://git.example.com/o/r': 'https',
'ssh://-oProxyCommand=x/o/r': 'ssh', 'ssh://git@-host/o/r': 'ssh', 'ssh://-user@host/o/r': 'ssh', 'ssh://host/../etc': 'ssh',
'ssh://host:0/r': 'ssh', 'ssh://host:65536/r': 'ssh', 'ssh://host/-r': 'ssh', 'git@host:-r': 'ssh', 'git@host:a/../b': 'ssh', 'host:repo': 'ssh',
'ssh://host/a b': 'form', 'https://x/o/r\n': 'form', '': 'form',
};
for (const [value, problem] of Object.entries(refused)) {
const result = parseRepoRemote(value);
assert.equal(result.ok, false, value); assert.equal(result.problem, problem, value); assert.ok(result.message.length > 0);
}
assert.equal(parseRepoRemote(42).ok, false); assert.equal(parseRepoRemote('x'.repeat(600)).ok, false);
});
test('check outcomes are classified from git\'s own messages', () => {
assert.equal(classifyCheck({ code: 0, stderr: '' }).result, 'reachable');
assert.equal(classifyCheck({ code: 128, stderr: "fatal: could not read Username for 'https://git.example.com': terminal prompts disabled\n" }).result, 'needs-credential');
// An ssh remote that wants a key: the line says the check sent none and promises no binding,
// because copy credential bindings cover https Gitea remotes only (#1873 review F1).
assert.deepEqual(classifyCheck({ code: 128, stderr: '[email protected]: Permission denied (publickey,password).\nfatal: Could not read from remote repository.\n' }),
{ result: 'needs-credential', message: 'the repository needs a credential; this check uses none' });
assert.equal(classifyCheck({ code: 128, stderr: "fatal: unable to access 'https://h/o/r/': The requested URL returned error: 403\n" }).result, 'needs-credential');
const dns = classifyCheck({ code: 128, stderr: "fatal: unable to access 'https://git.example.invalid/o/r.git/': Could not resolve host: git.example.invalid\n" });
assert.deepEqual(dns, { result: 'unreachable', message: "unable to access 'https://git.example.invalid/o/r.git/': Could not resolve host: git.example.invalid" });
const ssh = classifyCheck({ code: 128, stderr: 'ssh: Could not resolve hostname git.example.invalid: Name or service not known\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\n' });
assert.equal(ssh.message, 'ssh: Could not resolve hostname git.example.invalid: Name or service not known');
assert.equal(classifyCheck({ timedOut: true, stderr: '' }).message, 'no answer before the check timed out');
assert.equal(classifyCheck({ spawnError: true }).result, 'unreachable');
assert.equal(summarizeGitError(`fatal: ${'x'.repeat(400)}\u001b[31m`).length, 200);
assert.equal(summarizeGitError(''), 'git gave no reason');
});
test('the ssh client for the check reads no config, key, agent or proxy', () => {
for (const option of ['-F /dev/null', 'BatchMode=yes', 'IdentityFile=none', 'IdentitiesOnly=yes', 'IdentityAgent=none', 'PasswordAuthentication=no',
'KbdInteractiveAuthentication=no', 'ProxyCommand=none', 'ProxyJump=none', 'ControlPath=none', 'PermitLocalCommand=no', 'ForwardAgent=no', 'UserKnownHostsFile=/dev/null']) {
assert.ok(CHECK_SSH_COMMAND.includes(option), option);
}
});
test('production check refuses local and helper URLs without running git, and file is not an allowed transport', async () => {
const repo = bare();
for (const url of [`file://${repo}`, repo, 'ext::sh -c id', '--upload-pack=id']) assert.equal((await checkRemote(url)).result, 'unreachable', url);
// The production protocol list, through the seam: git itself refuses the file transport.
const refused = await seam.lsRemote(`file://${repo}`, { protocols: 'https:ssh' });
assert.equal(refused.result, 'unreachable'); assert.match(refused.message, /transport 'file' not allowed/);
assert.equal((await seam.lsRemote(`file://${repo}`, { protocols: 'file' })).result, 'reachable');
});
test('the check ignores the caller\'s git config and environment', async () => {
const repo = bare(); const home = mkdtempSync(join(tmpdir(), 'home-'));
// A user config that would rewrite the URL to the local repository, and a credential helper.
writeFileSync(join(home, '.gitconfig'), `[url "file://${repo}"]\n\tinsteadOf = https://git.example.invalid/o/r\n[credential]\n\thelper = !echo username=x; echo password=y\n`);
const saved = { HOME: process.env.HOME, GIT_CONFIG_PARAMETERS: process.env.GIT_CONFIG_PARAMETERS, GIT_CONFIG_GLOBAL: process.env.GIT_CONFIG_GLOBAL };
process.env.HOME = home; process.env.GIT_CONFIG_GLOBAL = join(home, '.gitconfig'); process.env.GIT_CONFIG_PARAMETERS = `'url.file://${repo}.insteadof'='https://git.example.invalid/o/r'`;
try {
const result = await seam.lsRemote('https://git.example.invalid/o/r', { protocols: 'https:ssh:file', timeoutMs: 10000 });
assert.equal(result.result, 'unreachable'); assert.match(result.message, /git\.example\.invalid/);
} finally { for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v; }
});
test('a 401 is needs-credential and no credential is sent', async () => {
const seen = [];
const server = createServer((req, res) => { seen.push(req.headers.authorization ?? null); res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="git"' }); res.end(); });
const port = await listen(server);
try {
const result = await seam.lsRemote(`http://127.0.0.1:${port}/o/r.git`, { protocols: 'http' });
assert.equal(result.result, 'needs-credential'); assert.equal(result.message, NEEDS_CREDENTIAL_MESSAGE); assert.doesNotMatch(result.message, /binding/);
assert.ok(seen.length >= 1); assert.deepEqual(seen.filter(Boolean), []);
} finally { server.close(); }
});
test('a redirect is not followed, so the check reaches only the named URL', async () => {
let elsewhere = 0;
const other = createServer((req, res) => { elsewhere++; res.writeHead(404); res.end(); });
const otherPort = await listen(other);
const server = createServer((req, res) => { res.writeHead(302, { Location: `http://127.0.0.1:${otherPort}${req.url}` }); res.end(); });
const port = await listen(server);
try {
const result = await seam.lsRemote(`http://127.0.0.1:${port}/o/r.git`, { protocols: 'http' });
assert.equal(result.result, 'unreachable'); assert.match(result.message, /302/); assert.equal(elsewhere, 0);
} finally { server.close(); other.close(); }
});
test('a silent server times out and the check reports it', async () => {
const sockets = []; const server = createTcpServer((s) => sockets.push(s)); const port = await listen(server);
try {
const started = Date.now();
const result = await seam.lsRemote(`http://127.0.0.1:${port}/o/r.git`, { protocols: 'http', timeoutMs: 600 });
assert.deepEqual(result, { result: 'unreachable', message: 'no answer before the check timed out' }); assert.ok(Date.now() - started < 5000);
} finally { for (const s of sockets) s.destroy(); server.close(); }
});
test('no production source reaches the test seam', () => {
const offenders = [];
for (const pkg of readdirSync(join(repoRoot, 'packages'))) {
const walk = (dir) => { let entries; try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const e of entries) { const p = join(dir, e.name); if (e.isDirectory()) { if (e.name !== 'node_modules') walk(p); } else if (/\.(m?js|cjs)$/.test(e.name) && readFileSync(p, 'utf8').includes('repoRemoteTestSeam') && !p.endsWith(join('organization', 'src', 'repo-remote.mjs'))) offenders.push(p); } };
walk(join(repoRoot, 'packages', pkg, 'src'));
}
assert.deepEqual(offenders, []);
});
// #1873 security review P2: the ssh check accepts any host key, so an ssh answer cannot say the
// named host answered. Every ssh outcome that came from an answer says the key was not verified;
// https and an unreachable ssh host do not carry the note.
test('an ssh answer says the host key was not verified; https does not', async () => {
const answer = { reachable: { result: 'reachable', message: 'the repository answered' }, needs: { result: 'needs-credential', message: NEEDS_CREDENTIAL_MESSAGE }, down: { result: 'unreachable', message: 'ssh: Could not resolve hostname h.invalid' } };
try {
for (const url of ['[email protected]:team/work.git', 'ssh://[email protected]:2222/team/work.git']) {
seam.useCheck(async () => answer.reachable);
assert.deepEqual(await checkRemote(url), { result: 'reachable', message: `the repository answered; ${SSH_HOST_UNVERIFIED}`, url });
seam.useCheck(async () => answer.needs);
assert.equal((await checkRemote(url)).message, `${NEEDS_CREDENTIAL_MESSAGE}; ${SSH_HOST_UNVERIFIED}`);
seam.useCheck(async () => answer.down);
assert.equal((await checkRemote(url)).message, answer.down.message);
}
seam.useCheck(async () => answer.reachable);
assert.equal((await checkRemote('https://git.example.com/team/work.git')).message, 'the repository answered');
} finally { seam.useCheck(null); }
});
async function orgWithRepo(c, opts = { mode: 'local-only', acceptLocalLossRisk: true }) {
await createOrg(c, 'alpha', await templateRender('alpha')); return projectRepoInit(c, 'alpha', 'work', opts);
}
test('remote init sets origin and records the check; nothing is pushed', async () => {
const c = context(); const repo = bare(); const url = 'https://git.example.com/team/work.git';
seam.useCheck((u) => { assert.equal(u, url); return seam.lsRemote(`file://${repo}`, { protocols: 'file' }); });
try {
const r = await orgWithRepo(c, { mode: 'remote', remote: url });
assert.equal(r.origin, url); assert.deepEqual(r.check, { result: 'reachable', message: 'the repository answered', url });
assert.equal(git(r.root, 'remote', '-v'), `origin\t${url} (fetch)\norigin\t${url} (push)`);
assert.equal(git(repo, 'for-each-ref').length, 0, 'nothing pushed');
const shown = await projectRepoShow(c, 'alpha', 'work');
assert.deepEqual(shown.current, { mode: 'remote', remote: url, origin: url, revision: shown.current.revision, check: r.check });
} finally { seam.useCheck(null); }
});
test('repo set switches remote to local-only and back, with receipts and the revision fence', async () => {
const c = context(); const r = await orgWithRepo(c);
assert.equal(git(r.root, 'remote', '-v'), '');
let rev = (await showOrg(c, 'alpha')).revision;
seam.useCheck(async () => ({ result: 'needs-credential', message: NEEDS_CREDENTIAL_MESSAGE }));
try {
const ssh = '[email protected]:team/work.git';
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: ssh, ifRevision: rev + 1 }), { code: 'revision-conflict' });
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: ssh }), { code: 'org-invalid' });
const set = await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: ssh, ifRevision: rev });
assert.equal(set.op, 'org.project.repo.set'); assert.equal(set.revision, rev + 1); assert.deepEqual(set.previous, { mode: 'local-only' });
assert.equal(set.check.result, 'needs-credential'); assert.equal(set.check.url, ssh); assert.equal(git(r.root, 'remote', 'get-url', 'origin'), ssh);
assert.deepEqual(loadBusiness('alpha', { dir: c.configDir, rolesDir: REPO_ROLES }).projects.work.git, { mode: 'remote', remote: ssh });
rev = set.revision;
const https = 'https://git.example.com/team/work';
const moved = await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: https, ifRevision: rev });
assert.equal(git(r.root, 'remote', 'get-url', 'origin'), https); assert.equal(moved.revision, rev + 1); rev = moved.revision;
// The same URL again re-checks and repairs origin without a new revision.
git(r.root, 'remote', 'set-url', 'origin', 'https://elsewhere.example/x/y');
const again = await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: https, ifRevision: rev });
assert.equal(again.revision, rev); assert.equal(git(r.root, 'remote', 'get-url', 'origin'), https);
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'local-only', ifRevision: rev }), { code: 'org-risk' });
const local = await projectRepoSet(c, 'alpha', 'work', { mode: 'local-only', acceptLocalLossRisk: true, ifRevision: rev });
assert.equal(local.revision, rev + 1); assert.equal(local.check, undefined); assert.equal(git(r.root, 'remote', '-v'), '');
const shown = await projectRepoShow(c, 'alpha', 'work');
assert.deepEqual(shown.current, { mode: 'local-only', origin: null, revision: local.revision, changedAt: local.at });
const ops = readFileSync(join(r.root, '../../receipts.jsonl'), 'utf8').trim().split('\n').map((l) => JSON.parse(l).op);
assert.deepEqual(ops.filter((o) => o.startsWith('org.project.repo')), ['org.project.repo.init', 'org.project.repo.set', 'org.project.repo.set', 'org.project.repo.set', 'org.project.repo.set']);
// A whole-document update still can't change the binding.
const current = await showOrg(c, 'alpha'); const doc = structuredClone(current.doc); doc.projects.work.git = { mode: 'remote', remote: https };
await assert.rejects(updateOrg(c, 'alpha', doc, { ifRevision: current.revision }), { code: 'org-invalid' });
} finally { seam.useCheck(null); }
});
// #1873 review F2: origin is set before the document is written. When that write fails, the
// checkout's origin and the recorded binding differ; show reports both as they are, keeps the
// last check only for the URL it ran against, and the same set again repairs it.
test('a set whose document write fails leaves origin ahead of the record, and show says so', async () => {
const c = context(); const r = await orgWithRepo(c);
seam.useCheck(async () => ({ result: 'reachable', message: 'the repository answered' }));
const businesses = join(c.configDir, 'businesses');
try {
let rev = (await showOrg(c, 'alpha')).revision;
const a = 'https://git.example.com/team/a', b = 'https://git.example.com/team/b';
rev = (await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: a, ifRevision: rev })).revision;
chmodSync(businesses, 0o500);
try { await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: b, ifRevision: rev })); }
finally { chmodSync(businesses, 0o700); }
assert.equal(git(r.root, 'remote', 'get-url', 'origin'), b);
let shown = (await projectRepoShow(c, 'alpha', 'work')).current;
assert.deepEqual(shown, { mode: 'remote', remote: a, origin: b, revision: rev, check: { result: 'reachable', message: 'the repository answered', url: a }, changedAt: shown.changedAt });
// Repeating the recorded URL repairs origin.
await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: a, ifRevision: rev });
shown = (await projectRepoShow(c, 'alpha', 'work')).current;
assert.equal(shown.origin, a); assert.equal(shown.check.url, a);
// A recorded check for another URL is not lent to the current one.
const receipts = join(r.root, '../../receipts.jsonl');
const lines = readFileSync(receipts, 'utf8').trim().split('\n').map((l) => JSON.parse(l));
lines.at(-1).check.url = b; writeFileSync(receipts, lines.map((l) => JSON.stringify(l)).join('\n') + '\n');
shown = (await projectRepoShow(c, 'alpha', 'work')).current;
assert.equal(shown.check, undefined); assert.equal(shown.remote, a);
} finally { seam.useCheck(null); chmodSync(businesses, 0o700); }
});
// #1873 F7: a copy binding grants the repositories its projects' remotes name when a credential is
// issued, and its decision records only project names. While a binding that names the project is
// approved (pending) or active (bound), repo set refuses before any check or origin change, and
// names the next step. An unbound (revoked) binding, or none, leaves repo set as it was.
// Bindings are seeded into the document directly, as the CB1 writer would leave them; the registry
// digest is updated so the read fences accept the document.
function seedBindings(c, bindings) {
const file = join(c.configDir, 'businesses', 'alpha.json');
const doc = JSON.parse(readFileSync(file, 'utf8')); doc.copyBindings = bindings;
const raw = JSON.stringify(doc, null, 2) + '\n'; writeFileSync(file, raw, { mode: 0o600 });
const registryFile = join(c.configDir, 'org-runtime.json'); const registry = JSON.parse(readFileSync(registryFile, 'utf8'));
registry.orgs.alpha.digest = createHash('sha256').update(raw).digest('hex'); writeFileSync(registryFile, JSON.stringify(registry, null, 2) + '\n', { mode: 0o600 });
}
function binding(instance, state, { project = null, projects = ['work'], n = 1 } = {}) {
const name = project ? instance.slice(0, -(project.length + 1)) : instance;
const gitea = { slot: 'self', scopes: ['read:repository'], resources: { projects } };
if (state === 'bound') Object.assign(gitea, { rotateBy: '2099-01-01', grantId: `gitea:5:${n}`, grantGeneration: 1 });
return { copyId: String(n).repeat(32), orgIncarnation: 'a'.repeat(32),
source: { level: project ? 'project' : 'root', name, project }, definition: { ref: 'reviewer', rev: null, sha256: 'b'.repeat(64) },
generation: 1, state, services: state === 'unbound' ? {} : { gitea }, decision: `1111111${n}-1111-4111-8111-111111111111` };
}
async function refusedUnderBinding(bindings, expect) {
const c = context(); const r = await orgWithRepo(c);
const before = readFileSync(join(r.root, '../../receipts.jsonl'), 'utf8');
seedBindings(c, bindings);
let checks = 0; seam.useCheck(async () => { checks++; return { result: 'reachable', message: 'the repository answered' }; });
try {
const rev = (await showOrg(c, 'alpha')).revision;
for (const selection of [{ mode: 'remote', remote: 'https://git.example.com/team/other' }, { mode: 'local-only', acceptLocalLossRisk: true }]) {
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { ...selection, ifRevision: rev }), (e) => {
assert.equal(e.code, 'project-repo-bound');
for (const text of expect) assert.ok(e.message.includes(text), `${text} in ${e.message}`);
assert.match(e.message, /Revoke that copy binding first .*then set the repository, then ask the chief to raise a new binding decision/);
return true;
});
}
assert.equal(checks, 0, 'no check ran'); assert.equal(git(r.root, 'remote', '-v'), '', 'origin unchanged');
assert.equal((await showOrg(c, 'alpha')).revision, rev); assert.equal(readFileSync(join(r.root, '../../receipts.jsonl'), 'utf8'), before, 'no receipt');
assert.deepEqual(loadBusiness('alpha', { dir: c.configDir, rolesDir: REPO_ROLES }).projects.work.git, { mode: 'local-only' });
} finally { seam.useCheck(null); }
}
test('repo set is refused while an approved (pending) copy binding names the project', async () => {
await refusedUnderBinding({ 'rev.work': binding('rev.work', 'pending', { project: 'work' }) }, ['rev.work (approved, not yet verified)']);
});
test('repo set is refused while an active (bound) copy binding names the project', async () => {
// A root copy whose gitea resources name the project, beside a binding for another project that does not count.
await refusedUnderBinding({ rev: binding('rev', 'bound', { projects: ['other', 'work'] }), dev: binding('dev', 'bound', { projects: ['other'], n: 2 }) },
['rev (active)']);
await refusedUnderBinding({ rev: binding('rev', 'bound', { projects: ['work'] }), 'qa.work': binding('qa.work', 'pending', { project: 'work', n: 2 }) },
['qa.work (approved, not yet verified), rev (active)']);
});
test('repo set is refused while a copy binding naming the project is still revoking (CB4)', async () => {
// The revoking record keeps its services until the revoke finishes, so the project stays granted.
const revoking = { ...binding('rev.work', 'bound', { project: 'work' }), state: 'revoking',
revoke: { id: '22222222-2222-4222-8222-222222222222', cause: 'revoke', at: '2026-11-12T00:00:00.000Z', failed: ['remote'] } };
await refusedUnderBinding({ 'rev.work': revoking }, ['rev.work (being revoked)']);
});
test('repo set is allowed after the binding is revoked (unbound)', async () => {
const c = context(); const r = await orgWithRepo(c);
seam.useCheck(async () => ({ result: 'reachable', message: 'the repository answered' }));
try {
const url = 'https://git.example.com/team/other';
seedBindings(c, { 'rev.work': binding('rev.work', 'bound', { project: 'work' }) });
const rev = (await showOrg(c, 'alpha')).revision;
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: url, ifRevision: rev }), { code: 'project-repo-bound' });
// The unbind leaves the tombstone; a binding for another project does not count.
const revoked = { 'rev.work': binding('rev.work', 'unbound', { project: 'work' }), dev: binding('dev', 'bound', { projects: ['other'], n: 2 }) };
seedBindings(c, revoked);
const set = await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: url, ifRevision: rev });
assert.equal(set.op, 'org.project.repo.set'); assert.equal(set.revision, rev + 1); assert.equal(git(r.root, 'remote', 'get-url', 'origin'), url);
assert.deepEqual(loadBusiness('alpha', { dir: c.configDir, rolesDir: REPO_ROLES }).copyBindings, revoked, 'bindings untouched');
} finally { seam.useCheck(null); }
});
// Unchanged behaviour: it passes on a source that never refuses, and guards against refusing too much.
test('repo set is allowed with no copy binding', async () => {
const c = context(); const r = await orgWithRepo(c);
seam.useCheck(async () => ({ result: 'reachable', message: 'the repository answered' }));
try {
const rev = (await showOrg(c, 'alpha')).revision; const url = 'https://git.example.com/team/other';
const set = await projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: url, ifRevision: rev });
assert.equal(set.revision, rev + 1); assert.equal(git(r.root, 'remote', 'get-url', 'origin'), url);
} finally { seam.useCheck(null); }
});
test('repo set refuses bad URLs before any check, and needs an initialized repository', async () => {
const c = context(); await createOrg(c, 'alpha', await templateRender('alpha'));
let checks = 0; seam.useCheck(async () => { checks++; return { result: 'reachable', message: 'x' }; });
try {
const rev = (await showOrg(c, 'alpha')).revision;
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote: 'https://git.example.com/o/r', ifRevision: rev }), { code: 'org-unavailable' });
await projectRepoInit(c, 'alpha', 'work', { mode: 'local-only', acceptLocalLossRisk: true });
const rev2 = (await showOrg(c, 'alpha')).revision;
for (const remote of ['ext::sh -c id', `file://${bare()}`, '/srv/x', '--upload-pack=id', 'https://u:[email protected]/o/r', 'http://git.example.com/o/r']) {
await assert.rejects(projectRepoSet(c, 'alpha', 'work', { mode: 'remote', remote, ifRevision: rev2 }), { code: 'org-invalid' }, remote);
await assert.rejects(projectRepoInit(c, 'alpha', 'other', { mode: 'remote', remote }), { code: 'org-invalid' }, remote);
}
assert.equal(checks, 0);
} finally { seam.useCheck(null); }
});
test('queue init with a remote also sets origin', async () => {
const c = context(); await createOrg(c, 'alpha', await templateRender('alpha'));
seam.useCheck(async () => ({ result: 'unreachable', message: 'Could not resolve host: git.example.invalid' }));
try {
const q = await queueInit(c, 'alpha', { mode: 'remote', remote: 'ssh://[email protected]/team/queue.git' });
assert.equal(git(q.root, 'remote', 'get-url', 'origin'), 'ssh://[email protected]/team/queue.git'); assert.equal(q.check.result, 'unreachable');
} finally { seam.useCheck(null); }
});
test('the loader accepts an ssh git remote and refuses a helper URL', async () => {
const c = context(); await createOrg(c, 'alpha', await templateRender('alpha'));
const file = join(c.configDir, 'businesses', 'alpha.json');
const doc = JSON.parse(readFileSync(file, 'utf8'));
const { validateOrg } = await import('../src/org-service.mjs');
doc.projects.work.git = { mode: 'remote', remote: '[email protected]:team/work.git' };
assert.deepEqual(await validateOrg(doc), { ok: true, errors: [] });
doc.projects.work.git = { mode: 'remote', remote: 'ext::sh -c id' };
assert.equal((await validateOrg(doc)).ok, false);
});