gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7e8aabea7e8aabeareport: W51b pull source verificationmre7e8aabea/tests/ssh.mjs

25.0 KB

  1. // tests/ssh.mjs — THE GATE OF GIT OVER SSH (ticket gitoria#7): the REAL sshd container (docker/sshd, built here) + the real ssh and git clients
  2. // against this app; keys pasted in Chrome. (tests/push.mjs is the HTTPS gate; this is a copy of its set-up.)
  3. // was: tests/push.mjs — THE GATE OF PUSH AND PULL (ticket gitoria#7). Its own gitoria server + its own ident (copy, mail sink),
  4. // a real Chrome for everything visible (create a repo, the "add code" box, access tokens), and the REAL `git` binary for
  5. // clone / push / fetch over HTTP against the repo address <slug>.gitoria.test (git's http.curloptResolve maps it to 127.0.0.1).
  6. // node tests/push.mjs (GITORIA_GATE_PORT 8700, GITORIA_GATE_IDENT_PORT 8701, GITORIA_GATE_CHROME "8703-8707")
  7. import { spawn, spawnSync } from 'node:child_process';
  8. import { request as httpRequest, createServer } from 'node:http';
  9. import { rmSync, mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
  10. import { dirname, join, resolve } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { randomBytes } from 'node:crypto';
  13. import { launchBrowser } from './cdp.mjs';
  14. import { startIdent } from './identkit.mjs';
  15. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  16. const HERE = dirname(fileURLToPath(import.meta.url));
  17. const APP = resolve(HERE, '..');
  18. const BIN = join(APP, 'bin/hybriel');
  19. const PORT = Number(process.env.GITORIA_GATE_PORT || 8700);
  20. const IDENT_PORT = Number(process.env.GITORIA_GATE_IDENT_PORT || 8701);
  21. const PROXY = Number(process.env.GITORIA_GATE_PROXY || 8702);
  22. const SSHPORT = Number(process.env.GITORIA_GATE_SSH_PORT || 8708);
  23. const TUNNEL_PORT = Number(process.env.GITORIA_GATE_TUNNEL_PORT || 8709); // the gate's own ssh -L forward
  24. const SECRET = 'gate-secret-' + Math.random().toString(16).slice(2);
  25. const CONTAINER = 'gitoria-sshd-gate'; // stands in for nginx: buffers a chunked request body and sends it with a length
  26. const [CH_FROM, CH_TO] = (process.env.GITORIA_GATE_CHROME || '8703-8707').split('-').map(Number);
  27. const API = `http://127.0.0.1:${PORT}`;
  28. const BASE = `http://gitoria.test:${PORT}`;
  29. const IDENT_B = `http://ident.gitoria.test:${IDENT_PORT}`;
  30. const REPO = (slug) => `http://${slug}.gitoria.test:${PORT}`;
  31. const hreq = (method, path, host, headers = {}, body = null) => new Promise((res, rej) => {
  32. const rq = httpRequest({ host: '127.0.0.1', port: PORT, path, method, headers: { host, ...headers } }, (r) => { let b = ''; r.setEncoding('utf8'); r.on('data', d => b += d); r.on('end', () => res({ status: r.statusCode, headers: r.headers, body: b })); });
  33. rq.on('error', rej); if (body) { rq.setHeader('content-length', Buffer.byteLength(body)); rq.write(body); } rq.end();
  34. });
  35. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.gitoria.test 127.0.0.1, MAP gitoria.test 127.0.0.1';
  36. const SCRATCH = join(APP, '.scratch');
  37. const STORE = join(SCRATCH, 'ssh-store');
  38. const WORK = join(STORE, 'work');
  39. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  40. rmSync(STORE, { recursive: true, force: true });
  41. mkdirSync(WORK, { recursive: true });
  42. const J2 = JSON.stringify;
  43. const sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  44. async function shClick(page, inner, name = null) {
  45. const find = `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; const el = ${name === null ? `r.querySelector(${J2(inner)})` : `[...r.querySelectorAll(${J2(inner)})].find(b => b.textContent === ${J2(name)})`}; if (!el) return null; const b = el.getBoundingClientRect(); return b.width > 0 ? { x: b.x + b.width / 2, y: b.y + b.height / 2 } : null; })()`;
  46. const box = await page.waitFor(find, { label: 'selector ' + inner });
  47. const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  48. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });
  49. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });
  50. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });
  51. }
  52. // the header's selector (the only sign-in): choose the first identity
  53. async function selectorLogin(page) {
  54. await shClick(page, '#choose');
  55. await page.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });
  56. await shClick(page, '[part~="identity"]', 'Default');
  57. }
  58. let failures = 0, passes = 0;
  59. function check(label, ok, detail = '') {
  60. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  61. if (ok) passes++; else failures++;
  62. }
  63. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  64. const J = JSON.stringify;
  65. let pageA = null;
  66. let log = '', server = null, ident = null, proxy = null;
  67. function startProxy() {
  68. proxy = createServer((req, res) => {
  69. const parts = []; req.on('data', d => parts.push(d));
  70. req.on('end', () => {
  71. const body = Buffer.concat(parts);
  72. const headers = { ...req.headers }; delete headers['transfer-encoding']; headers['content-length'] = String(body.length);
  73. const up = httpRequest({ host: '127.0.0.1', port: PORT, path: req.url, method: req.method, headers }, (r) => { res.writeHead(r.statusCode, r.headers); r.pipe(res); });
  74. up.on('error', () => { res.writeHead(502); res.end(); });
  75. up.end(body);
  76. });
  77. });
  78. proxy.listen(PROXY, '127.0.0.1');
  79. }
  80. const browsers = [];
  81. function startServer(extraEnv = {}) {
  82. server = spawn(BIN, ['project.hl'], {
  83. cwd: APP,
  84. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),
  85. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, GITORIA_TICKETS_URL: 'http://127.0.0.1:1', ...extraEnv },
  86. stdio: ['ignore', 'pipe', 'pipe'],
  87. });
  88. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  89. }
  90. async function serverUp() {
  91. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/api/repos'); if (r.ok) return; } catch {} await sleep(250); }
  92. throw new Error('gitoria did not come up\n' + log);
  93. }
  94. async function stopServer() {
  95. if (!server) return;
  96. try { server.kill('SIGTERM'); } catch {}
  97. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  98. server = null;
  99. }
  100. function patient(page) {
  101. const waitFor = page.waitFor.bind(page);
  102. page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * 3 });
  103. const goto = page.goto.bind(page);
  104. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * 3 });
  105. return page;
  106. }
  107. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  108. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  109. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  110. // THE SHELL (gitoria#23, the theme's header): "Log out" sits in the user menu's dropdown, on a phone "Log in with ident" in the
  111. // ident dropdown — a person opens it first; a target that already shows is clicked straight away (as tests/browser.mjs)
  112. async function clickInMenu(page, sel, toggle) {
  113. const shows = `(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`;
  114. await page.waitForSelector(sel);
  115. if (!(await page.evaluate(shows)) && await has(page, toggle)) { await page.click(toggle); await page.waitFor(shows, { label: 'menu open for ' + sel }); }
  116. await page.click(sel);
  117. }
  118. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  119. // the real git client. HOST = the repo address mapped to 127.0.0.1; credentials in the URL when given
  120. const GIT_ENV = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', HOME: WORK, LC_ALL: 'C' };
  121. function git(cwd, args, slug, extra = {}) {
  122. const pre = slug ? ['-c', `http.curloptResolve=${slug}.gitoria.test:${extra.port || PROXY}:127.0.0.1`] : [];
  123. const { port: _p, ...envExtra } = extra;
  124. // async: the proxy of this gate lives in this process, a blocking spawnSync would starve it
  125. return new Promise((res) => {
  126. const c = spawn('git', [...pre, '-c', 'user.name=Gate', '-c', '[email protected]', '-c', 'init.defaultBranch=main', ...args], { cwd, env: { ...GIT_ENV, ...envExtra } });
  127. let out = ''; c.stdout.on('data', d => out += d); c.stderr.on('data', d => out += d);
  128. const t = setTimeout(() => c.kill('SIGKILL'), 120000);
  129. c.on('close', (code) => { clearTimeout(t); res({ code, out }); });
  130. });
  131. }
  132. const urlOf = (slug, user, pass, port = PROXY) => `http://${user ? `${user}:${pass}@` : ''}${slug}.gitoria.test:${port}/${slug}.git`;
  133. const KEYDIR = join(STORE, 'keys');
  134. mkdirSync(KEYDIR, { recursive: true });
  135. const newKey = (name, type = 'ed25519', extra = []) => {
  136. spawnSync('ssh-keygen', ['-q', '-t', type, ...extra, '-N', '', '-C', name + '@gate', '-f', join(KEYDIR, name)]);
  137. return { file: join(KEYDIR, name), pub: readFileSync(join(KEYDIR, name + '.pub'), 'utf8').trim() };
  138. };
  139. const sshCmd = (key) => `ssh -i ${key.file} -p ${SSHPORT} -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o LogLevel=ERROR`;
  140. const sgit = (cwd, args, key) => git(cwd, args, null, { GIT_SSH_COMMAND: sshCmd(key) });
  141. const sshRaw = (key, cmd) => new Promise((res) => {
  142. const c = spawn('sh', ['-c', `${sshCmd(key)} [email protected] ${cmd}`]);
  143. let out = ''; c.stdout.on('data', d => out += d); c.stderr.on('data', d => out += d);
  144. const t = setTimeout(() => c.kill('SIGKILL'), 30000);
  145. c.on('close', (code) => { clearTimeout(t); res({ code, out }); });
  146. });
  147. const SURL = (slug) => `ssh://[email protected]:${SSHPORT}/${slug}.git`;
  148. async function addKeyInChrome(A, name, pub) {
  149. await A.evaluate(`(() => { const n = document.querySelector('#keyname'); n.value = ${J(name)}; n.dispatchEvent(new Event('input', { bubbles: true })); const t = document.querySelector('#keytext'); t.value = ${J(pub)}; t.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  150. await A.click('#keysave');
  151. }
  152. try {
  153. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  154. const alice = await ident.signIn('[email protected]');
  155. const bob = await ident.signIn('[email protected]');
  156. const APPKEY = await ident.registerApp(alice, 'gitoria (ssh gate)', [BASE]);
  157. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, GITORIA_SSH_SECRET: SECRET, GITORIA_SSH_PORT: String(SSHPORT) });
  158. await serverUp();
  159. // the sshd container: host network (reaches the app on 127.0.0.1), repos = this store's git folder
  160. mkdirSync(join(STORE, 'git'), { recursive: true });
  161. spawnSync('docker', ['rm', '-f', CONTAINER]);
  162. const built = spawnSync('docker', ['build', '-q', '-t', 'gitoria-sshd-gate', join(APP, 'docker/sshd')], { encoding: 'utf8' });
  163. check('sshd image builds', built.status === 0, built.stderr);
  164. const started = spawnSync('docker', ['run', '-d', '--rm', '--name', CONTAINER, '--network', 'host', '-e', 'GITORIA_SSH_SECRET=' + SECRET, '-e', 'GITORIA_SSH_PORT=' + SSHPORT, '-e', 'GITORIA_URL=' + API, '-v', join(STORE, 'git') + ':/repos', 'gitoria-sshd-gate'], { encoding: 'utf8' });
  165. check('sshd container starts', started.status === 0, started.stderr);
  166. for (let i = 0; i < 40; i++) { const r = spawnSync('sh', ['-c', `ssh-keyscan -p ${SSHPORT} 127.0.0.1 2>/dev/null | grep -c ssh-`], { encoding: 'utf8' }); if (Number(r.stdout) > 0) break; await sleep(250); }
  167. // ---- the internal endpoints: only with the secret, never through the proxy ------------------------------------
  168. const H = `gitoria.test:${PORT}`;
  169. check('internal: /__git/keys without the secret is 403', (await hreq('GET', '/__git/keys?type=ssh-ed25519&key=AAAAC3NzaC1lZDI1NTE5AAAAIx', H)).status === 403);
  170. check('internal: /__git/keys with a wrong secret is 403', (await hreq('GET', '/__git/keys?type=ssh-ed25519&key=AAAAC3NzaC1lZDI1NTE5AAAAIx', H, { 'x-gitoria-secret': 'nope' })).status === 403);
  171. check('internal: with the secret but through a proxy (X-Forwarded-For) is 403', (await hreq('GET', '/__git/access?user=x&slug=y&write=0', H, { 'x-gitoria-secret': SECRET, 'x-forwarded-for': '1.2.3.4' })).status === 403);
  172. check('internal: an unknown key gets an empty answer', (await hreq('GET', '/__git/keys?type=ssh-ed25519&key=AAAAC3NzaC1lZDI1NTE5AAAAIx', H, { 'x-gitoria-secret': SECRET })).body === '');
  173. // ---- alice in Chrome: log in, name, create a repo, add keys -----------------------------------------------------
  174. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  175. browsers.push(b);
  176. const A = patient(await b.newPage());
  177. pageA = A;
  178. const [ck, cv] = alice.cookie.split('=');
  179. await A.send('Network.enable');
  180. await A.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });
  181. await A.goto(BASE + '/');
  182. await A.waitForSelector('#selector');
  183. await hydrated(A);
  184. check('keys: signed out, the main page offers no key form', !(await has(A, '#keyform')));
  185. await selectorLogin(A);
  186. await A.waitForSelector('#nameform');
  187. await hydrated(A);
  188. await A.type('#displayname', 'alice');
  189. await A.click('#namesave');
  190. await A.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#createform")', { label: 'named' });
  191. await A.type('#slug', 'gamma');
  192. await A.click('#createsave');
  193. await A.waitForSelector('#created');
  194. await A.waitFor('!!document.querySelector("#keyform")', { label: 'key form' });
  195. check('keys: logged in, "You have no SSH keys yet"', await has(A, '#nokeys'));
  196. const k1 = newKey('laptop');
  197. await addKeyInChrome(A, 'laptop', 'this is not a key');
  198. await A.waitFor('document.querySelector("#keyerror").textContent.length > 0', { label: 'error' });
  199. check('keys: text that is not a key is refused with a reason', /not a public key/.test(await txt(A, '#keyerror')), await txt(A, '#keyerror'));
  200. await addKeyInChrome(A, 'laptop', readFileSync(k1.file, 'utf8').split('\n').slice(0, 2).join('\n'));
  201. await A.waitFor('/PRIVATE/.test(document.querySelector("#keyerror").textContent)', { label: 'private key error' });
  202. check('keys: a PRIVATE key is refused and never stored', true);
  203. await addKeyInChrome(A, 'laptop', 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIabc broken');
  204. await A.waitFor('/not valid/.test(document.querySelector("#keyerror").textContent)', { label: 'invalid error' });
  205. check('keys: a key with a broken body is refused', true);
  206. const weak = newKey('weak', 'rsa', ['-b', '1024']);
  207. await addKeyInChrome(A, 'weak', weak.pub);
  208. await A.waitFor('/2048|not valid/.test(document.querySelector("#keyerror").textContent)', { label: 'weak error' });
  209. check('keys: a 1024-bit RSA key is refused', true);
  210. await addKeyInChrome(A, 'laptop', k1.pub);
  211. await A.waitFor('document.querySelectorAll("#keylist li").length === 1', { label: 'key added' });
  212. await sleep(400);
  213. check('keys: the key is added and listed with name and SHA256 fingerprint', /laptop/.test(await txt(A, '#keylist')) && /SHA256:/.test(await txt(A, '#keylist')) && !(await txt(A, '#keyerror')), (await txt(A, '#keylist')) + ' / error: ' + (await txt(A, '#keyerror')));
  214. const fp = spawnSync('ssh-keygen', ['-l', '-f', k1.file + '.pub'], { encoding: 'utf8' }).stdout.split(' ')[1];
  215. check('keys: the shown fingerprint is the real one', (await txt(A, '#keylist')).includes(fp), fp);
  216. await addKeyInChrome(A, 'again', k1.pub);
  217. await A.waitFor('/already/.test(document.querySelector("#keyerror").textContent)', { label: 'dup' });
  218. check('keys: the same key twice is refused', true);
  219. const rsa = newKey('rsa', 'rsa', ['-b', '3072']);
  220. await A.evaluate('document.querySelector("#keyerror").textContent = ""');
  221. await addKeyInChrome(A, 'old-rsa', rsa.pub);
  222. await A.waitFor('document.querySelectorAll("#keylist li").length === 2', { label: 'rsa added' });
  223. check('keys: a 3072-bit RSA key is accepted', true);
  224. // ---- the box on the (empty) repo's Code page (gitoria#20) ---------------------------------------------------------
  225. await A.goto(REPO('gamma') + '/code');
  226. await A.waitFor('!!document.querySelector("#addcode")');
  227. check('box: the ssh clone command is on the repo page', (await txt(A, '#sshclonecommand')) === `git clone ssh://[email protected]:${SSHPORT}/gamma.git`, await txt(A, '#sshclonecommand'));
  228. check('box: it links to the SSH keys on the main address', (await A.evaluate('document.querySelector("#tosshkeys").getAttribute("href")')) === BASE + '/#sshkeys');
  229. // ---- real ssh + git ------------------------------------------------------------------------------------------------
  230. const W = (n) => join(WORK, n);
  231. let g = await sgit(WORK, ['clone', SURL('gamma'), 'first'], k1);
  232. check('ssh git: cloning the empty repo works', g.code === 0 && /empty repository/.test(g.out), g.out);
  233. writeFileSync(join(W('first'), 'README.md'), '# gamma\n\nPushed over **ssh**.\n');
  234. writeFileSync(join(W('first'), 'big.bin'), randomBytes(3000000));
  235. await git(W('first'), ['add', '.']); await git(W('first'), ['commit', '-qm', 'first over ssh']);
  236. g = await sgit(W('first'), ['push', 'origin', 'main'], k1);
  237. check('ssh git: the owner pushes (3 MB) with the key', g.code === 0 && /main -> main/.test(g.out), g.out);
  238. g = await sgit(WORK, ['clone', SURL('gamma'), 'second'], rsa);
  239. check('ssh git: the owner\'s RSA key clones the pushed commit', g.code === 0 && readFileSync(join(W('second'), 'big.bin')).equals(readFileSync(join(W('first'), 'big.bin'))), g.out);
  240. writeFileSync(join(W('second'), 'more.txt'), 'more\n'); await git(W('second'), ['add', '.']); await git(W('second'), ['commit', '-qm', 'second']);
  241. g = await sgit(W('second'), ['push', 'origin', 'main'], rsa);
  242. check('ssh git: a push with the second key (fast-forward) works', g.code === 0, g.out);
  243. g = await sgit(W('first'), ['pull', '--no-rebase', '--no-edit', 'origin', 'main'], k1);
  244. check('ssh git: pull brings the new commit', g.code === 0 && existsSync(join(W('first'), 'more.txt')), g.out);
  245. await A.goto(REPO('gamma') + '/');
  246. await A.waitFor('/Pushed over/.test((document.querySelector("#homepage") || {}).textContent || "")', { label: 'readme after ssh push' });
  247. check('pushed code: the Readme page shows what was pushed over ssh', true);
  248. const bare = await git(WORK, ['--git-dir', join(STORE, 'git', 'gamma.git'), 'log', '--format=%s']);
  249. check('pushed code: the bare repo holds both commits', bare.out.trim().split('\n').join(',') === 'second,first over ssh', bare.out);
  250. // ---- what must NOT work ------------------------------------------------------------------------------------------
  251. const stranger = newKey('stranger');
  252. g = await sgit(WORK, ['clone', SURL('gamma'), 'nokey'], stranger);
  253. check('ssh git: a key nobody added is refused', g.code !== 0 && /Permission denied|publickey/.test(g.out), g.out);
  254. let r = await sshRaw(k1, 'ls /');
  255. check('ssh: no shell — any other command is refused', r.code !== 0 && /only git clone, fetch and push/.test(r.out), J(r));
  256. r = await sshRaw(k1, '');
  257. check('ssh: an interactive login is refused too', r.code !== 0 && !/repos|bin/.test(r.out), J(r));
  258. r = await sshRaw(k1, "\"git-upload-pack '../../etc'\"");
  259. check('ssh: a path outside the repos is refused', r.code !== 0 && /no such repository/.test(r.out), J(r));
  260. r = await sshRaw(k1, "\"git-upload-pack 'nope.git'\"");
  261. check('ssh: an unknown repo is refused', r.code !== 0 && /no such repository/.test(r.out), J(r));
  262. r = await sshRaw(k1, "\"git-upload-pack 'gamma.git; id'\"");
  263. check('ssh: a command smuggled behind the repo name is refused', r.code !== 0 && !/uid=/.test(r.out), J(r));
  264. const fwd = spawn('sh', ['-c', `${sshCmd(k1)} -o ExitOnForwardFailure=no -L ${TUNNEL_PORT}:127.0.0.1:${PORT} -N [email protected]`]);
  265. await sleep(1500);
  266. const viaTunnel = spawnSync('curl', ['-s', '-m', '5', '-o', '/dev/null', '-w', '%{http_code}', 'http://127.0.0.1:' + TUNNEL_PORT + '/api/repos'], { encoding: 'utf8' }).stdout;
  267. fwd.kill();
  268. check('ssh: no port forwarding through a key', viaTunnel !== '200', 'tunnel answered ' + viaTunnel);
  269. // bob: a key of his own may read but not push to alice's repo
  270. const bobCode = await ident.selectorCode(bob, APPKEY, BASE);
  271. const bl = await fetch(API + '/login/callback?ident_code=' + bobCode, { redirect: 'manual' });
  272. const bobCookie = (bl.headers.get('set-cookie') || '').split(';')[0];
  273. await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie: bobCookie }, body: J({ t: 'emit', i: 1, event: 'gitoriaSaveName', payload: ['bob'] }) });
  274. const bobKey = newKey('bob');
  275. const bk = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie: bobCookie }, body: J({ t: 'emit', i: 2, event: 'gitoriaAddKey', payload: ['bobs', bobKey.pub] }) });
  276. const bkt = await bk.text();
  277. check('keys: bob adds his own key (a face, own session)', !!(JSON.parse(bkt).value || {}).row, bkt);
  278. g = await sgit(WORK, ['clone', SURL('gamma'), 'bobs'], bobKey);
  279. check('ssh git: another user\'s key may read (public repo)', g.code === 0 && existsSync(join(W('bobs'), 'more.txt')), g.out);
  280. writeFileSync(join(W('bobs'), 'evil.txt'), 'x\n'); await git(W('bobs'), ['add', '.']); await git(W('bobs'), ['commit', '-qm', 'evil']);
  281. g = await sgit(W('bobs'), ['push', 'origin', 'main'], bobKey);
  282. check('ssh git: another user\'s key may not push — only the owner may', g.code !== 0 && /only the owner/.test(g.out), g.out);
  283. const bd = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie: bobCookie }, body: J({ t: 'emit', i: 3, event: 'gitoriaAddKey', payload: ['stolen', k1.pub] }) });
  284. const bdt = await bd.text();
  285. check('keys: alice\'s key cannot be added again by bob', /already/.test(bdt), bdt);
  286. const fk = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 4, event: 'gitoriaAddKey', payload: ['x', stranger.pub, { user: { id: 'y' } }] }) });
  287. const fkt = await fk.text();
  288. const fkr = await sgit(WORK, ['ls-remote', SURL('gamma')], stranger);
  289. check('keys: a forged session argument adds no key', fkr.code !== 0, fkt);
  290. // remove a key: stops at once; the other one still works
  291. await A.goto(BASE + '/');
  292. await A.waitFor('document.querySelectorAll("#keylist li").length === 2', { label: 'keys after reload' });
  293. await hydrated(A);
  294. check('keys: the list survives a reload', (await txt(A, '#keylist')).includes('laptop'));
  295. await A.evaluate('document.querySelector("#keylist li .removekey").click()');
  296. await A.waitFor('document.querySelectorAll("#keylist li").length === 1', { label: 'one removed' });
  297. const left = (await txt(A, '#keylist')).includes('laptop') ? 'laptop' : 'old-rsa';
  298. g = await sgit(W('first'), ['ls-remote', 'origin'], rsa);
  299. const g2 = await sgit(W('first'), ['ls-remote', 'origin'], k1);
  300. check('keys: a removed key stops working at once, the other one still works', left === 'laptop' && g.code !== 0 && g2.code === 0, `left=${left} rsa=${g.code} laptop=${g2.code}`);
  301. await clickInMenu(A, '#logout', 'button.user-toggle');
  302. await A.waitFor('!document.querySelector("#keyform")', { label: 'key form gone at logout' });
  303. check('keys: logout hides the key form', !(await has(A, '#keyform')) && !(await has(A, '.removekey')));
  304. for (const [w, name] of [[390, 'phone'], [1280, 'wide']]) {
  305. await A.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: w < 600 });
  306. await A.goto(REPO('gamma') + '/code');
  307. await A.waitFor('!!document.querySelector("#crumbs")');
  308. check(`layout ${w}px: the pushed repo's code page has no horizontal overflow`, await noOverflow(A));
  309. const { data } = await A.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  310. writeFileSync(join(SCRATCH, `ssh-${name}.png`), Buffer.from(data, 'base64'));
  311. }
  312. const problems = A.problems().filter(m => !/favicon|ERR_|Failed to load resource/.test(m.text));
  313. check('browser: no console errors', problems.length === 0, problems.map(m => m.text).join(' | '));
  314. check('server log: no error other than absorbed ones', !/error(?!: absorbed)/i.test(log.replace(/error absorbed[^\n]*/g, '')), log.split('\n').filter(l => /error/i.test(l)).slice(0, 5).join(' | '));
  315. } catch (e) {
  316. failures++;
  317. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  318. if (pageA) { try { console.log('DOM: ' + (await pageA.evaluate('document.querySelector("#sshkeys") ? document.querySelector("#sshkeys").outerHTML.slice(0, 1500) : location.href'))); } catch {} }
  319. console.log('sshd log: ' + spawnSync('docker', ['logs', '--tail', '30', CONTAINER], { encoding: 'utf8' }).stderr);
  320. } finally {
  321. for (const b of browsers) { try { await b.close(); } catch {} }
  322. spawnSync('docker', ['rm', '-f', CONTAINER]);
  323. await stopServer();
  324. if (ident) await ident.stop();
  325. writeFileSync(join(SCRATCH, 'ssh-server.log'), log);
  326. console.log(`${passes} passed, ${failures} failed`);
  327. process.exit(failures ? 1 : 0);
  328. }

Branches

Latest commits

  • 7e8aabeareport: W51b pull source verificationmre
  • 6c18de76fix: preserve pull sources across containing branchesmre
  • fc36fa2elog: W51b pull source bugmre
  • 56bc1220log: v1.5.1 livemre
  • 845fc0aareport: W51mre
  • 83127391fix: return v1.5.1 app and merge error detailsmre
  • b07d0e97log: W51 v1.5.1 startedmre
  • 0b417d06docs: apps-api v1.5 user tokens (#48, W49)mre
  • d046940alog: vinzenz contract note sentmre
  • db443456log: vinzenz note retry 2mre
  • 802f229alog: kunibert repo ping provenmre
  • 2d2eaa92log: Kunibert connected to kunibert repomre
  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre