gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5b0b4b9e5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre5b0b4b9e/tests/ssh.mjs

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

Branches

Latest commits

  • 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
  • bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
  • 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
  • 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
  • 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
  • 2a2fdd77gs: C2 check before cookie experimentsmre
  • 76e0587aWIP gs 2mre
  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG