gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit0f39e1810f39e181Merge branch 'w64-org-slash' into mainGitoria0f39e181/tests/ssh.mjs

24.9 KB

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

Branches

Latest commits

  • 0f39e181Merge branch 'w64-org-slash' into mainGitoria
  • 9c72d0bf|||PR org repo addresses work with a trailing slashmre
  • a4a33081Merge branch 'w63-force-push' into mainGitoria
  • 52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mre
  • 5a7b3e68|||PR a force push keeps the same pull request (#56)mre
  • cc1be2d6Merge branch 'w62-pr-close' into mainGitoria
  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre