gitoria
All repositories: gitoria
16.7 KB
// lib/api.hl — THE FUNCTION ROUTES (project.hl wires them): thin wrappers — check the request and the session, call the// topic, answer. The plumbing (JSON / Markdown / plain answers, redirects, the ssh guard, `?next=`) is lib/api-helpers.hl.// /api/repos, /api/repos/:slug the public reads (repos.hl; Accept: text/markdown → the Markdown read view)// /login/callback the login button's return (users.hl)// /settings/connect, /settings/connected connecting a repo to a tickets project (tickets.hl)// /api/apps/token an app trades its key for a one-hour token (app-tokens.hl, gitoria#42)// /settings/apps/connect, /settings/apps/confirm, /api/apps/exchange connecting an app to a repo (apps.hl, gitoria#41)// /__git/keys, /__git/access what the sshd container asks (sshkeys.hl, repos.hl)// (The git protocol's routes are lib/transport.hl gitTransport.)// A route that WRITES THE SESSION gets the request and the framework's session store BY REFERENCE (`&req`, `&sessions`,// from project.hl): copied into a second call, the session inside `req` would be a copy too and the write would be lost.import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { NL, px, slugOfHost } from './util.hl'import { userOfLoginCode } from './users.hl'import { repoRows, repoRow, repoBySlug, repoFor, orgFor, ownsRepo, mayPush, mayRead } from './repos.hl'import { fullNameError, repoDocument, listDocument } from './repos-helpers.hl'import { forwardOf } from './forwards.hl'import { userIdOfSession } from './users.hl'import { connectHref, finishConnect } from './tickets.hl'import { keyLine } from './sshkeys.hl'import { urlAllowed, withQuery, formFields } from './apps-helpers.hl'import { nameError, makeCode, exchangeCode, appOfKey } from './apps.hl'import { issueToken } from './app-tokens.hl'import { bearerOf, unauthorized, notFound } from './app-auth.hl'import { reply, fail, apiError, wantsMarkdown, markdownReply, textReply, goTo, sshGuard, repoOfRequest, safeNext } from './api-helpers.hl'import { ensurePulls, syncPulls } from './pullsync.hl'import { notifyPush } from './tickets.hl'// ---- the API: reads are public (creating a repo is a web action for now) ------------------------static apiRepos = (route, req) => {if (req.method != 'GET') { return fail(405, 'GET only') }rows = repoRows(userIdOfSession(req.session))if (wantsMarkdown(req)) { return markdownReply(listDocument(rows)) }return reply(200, { repos = rows })}static apiRepo = (route, req) => {if (req.method != 'GET') { return fail(405, 'GET only') }row = repoRow(route.params.slug, userIdOfSession(req.session))if (row == null) { return fail(404, 'no such repository') }if (wantsMarkdown(req)) { return markdownReply(repoDocument(row)) }return reply(200, row)}// ---- NOTHING ELSE (mission MG, as ident's notFoundPage): the last route of project.hl answers a path no route knows with the// shell's 404 page (components/notfound.hl) — status 404, the page rendered by the framework with the request's session and hoststatic notFoundPage = (route, req, &srv, pageComponent) => {m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))res.status = 404return res}// `/:orepo` (GO34): on an organization's address (one the viewer may see) the first segment is a repo's Readme page, rendered like the 404 page is (a function route:// a stray single-segment path on any other address keeps its real 404 status — /.env, /host.js, a private organization's /x)static orgRepoPage = (route, req, &srv, pageComponent, missingComponent) => {h = req.headers['host']label = slugOfHost(h == null ? '' : h.split(':')[0])if (label == '' || orgFor(label, userIdOfSession(req.session)) == null) { return notFoundPage(route, req, &srv, missingComponent) }m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = req.path.slice(1) } path = req.path }return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))}static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------// ident sends the browser back with ?ident_code= (and our ?next=); the code is exchanged here (users.hl userOfLoginCode),// the user goes into THIS browser's session (`req.session`, the cookie's — hybriel #11; minted when it brought none),// then → `?next=` (api-helpers.hl safeNext). A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked// in the session, then → /login/failed.static loginFailed = (&req, &sessions, why) => {let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.loginError = whysessions.save(s)res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}static loginCallback = (route, &req, &sessions) => {if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }q = req.query != null ? req.query : {}code = q.ident_codeif (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }x = userOfLoginCode(code)if (x.error != null) { return loginFailed(&req, &sessions, x.error) }// THE SAME SESSION, NEVER SIGNED OUT (ident#28): a good code signs the session the browser already has in (a second tab or an installed// app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted herelet s = req.sessionif (s == null) { s = sessions.mint() }s.user = { id = x.user.id }s.data.tag = randomBytes(16)s.data.loginError = nullsessions.save(s)res = new Response('logged in', { status = 302 headers = { 'Location' = safeNext(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' 'Set-Cookie' = sessions.cookieHeader(s.id) } })return res}// ---- ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS ---------------------------------------------------------------------// Nothing here: hl:web (batch 20) does it. The session cookie carries `Domain=.<host>` (project.hl sessionDomain); among several gitoriasid// cookies the signed-in one wins and is re-issued with the Domain (the stray host-only copy expires), and a signed-in cookie is re-issued when its// attributes change (a login from before the Domain was set moves to it on its next request) and otherwise once a day. Gate: tests/browser.mjs "gitoria#24".// ---- CONNECT A REPO TO A TICKETS PROJECT (gitoria#18; tickets.hl, components/settings.hl) ----------------------------// /settings/connect: the owner's click → a fresh nonce parked in the session (bound to the repo) → tickets' /connect.// /settings/connected: tickets' return with ?code&state → tickets.hl finishConnect (nonce, exchange, key stored per// repo) → back to /settings. A failure is a note on the settings page.static connectStart = (route, &req, &sessions) => {if (req.method != 'GET') { return fail(405, 'GET only') }repo = repoOfRequest(route, req)if (repo == null) { return fail(404, 'no such repository') }s = req.sessionif (s == null || !ownsRepo(repo.slug, s)) { return goTo(px(repo.slug) + '/settings') }nonce = randomBytes(16)s.data.connectState = repo.slug + '.' + nonces.data.connectNote = nullsessions.save(s)return goTo(connectHref(repo.slug, nonce))}// One log line for every end of the connect flow (docker logs of the gitoria container): "connect-back <slug> <outcome> ..." and// never the code, the state value or a key. `state` only says whether tickets brought one.static connectLog = (slug, outcome, hasState) => {console.log('connect-back ' + slug + ' ' + outcome + ' state=' + (hasState ? 'present' : 'absent'))}static notSignedInNote = 'The connection to tickets did not finish: this browser is not signed in to gitoria as the repo owner. Sign in and press Connect again.'static connectBack = (route, &req, &sessions) => {if (req.method != 'GET') { return fail(405, 'GET only') }repo = repoOfRequest(route, req)if (repo == null) { return fail(404, 'no such repository') }q = req.query != null ? req.query : {}hasState = q.state != nulllet s = req.sessionif (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) {// nothing is exchanged; the code is dropped. The browser is told why on the settings page: a session-less browser gets a fresh// session that carries the note (like loginFailed), a session that exists keeps itself and gets the notewhy = s == null ? 'no-session' : (userIdOfSession(s) == null ? 'session-not-signed-in' : 'not-owner')connectLog(repo.slug, 'refused reason=' + why, hasState)fresh = s == nullif (fresh) { s = sessions.mint() }s.data.connectNote = notSignedInNotesessions.save(s)res = goTo(px(repo.slug) + '/settings')if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}want = s.data.connectStates.data.connectState = nullnote = finishConnect(repo.slug, want, q)s.data.connectNote = note == '' ? null : notesessions.save(s)if (note == '') {connectLog(repo.slug, 'connected', hasState)} else if (q.error != null && q.code == null) {connectLog(repo.slug, 'tickets-error', hasState)} else if (want == null || want != repo.slug + '.' + q.state) {connectLog(repo.slug, 'state-mismatch', hasState)} else {connectLog(repo.slug, 'exchange-failed', hasState)}return goTo(px(repo.slug) + '/settings')}// ---- WHAT THE SSHD CONTAINER ASKS (ticket gitoria#7; docker/sshd) — only with the shared secret (api-helpers.hl sshGuard)// GET /__git/keys?type=<ssh-ed25519>&key=<base64> sshd AuthorizedKeysCommand: the authorized_keys line for a known key// (sshkeys.hl keyLine), empty for an unknown one// GET /__git/access?user=<id>&slug=<slug>&write=0|1 gitoria-shell before it starts git: `ok` or 403. Read = every repo (public);// write = the repo's owner only (repos.hl mayPush — the same rule as the token on HTTPS, transport.hl)static gitKeys = (route, req) => {no = sshGuard(req)if (no != null) { return no }q = req.query != null ? req.query : {}return textReply(200, keyLine(q.type, q.key))}// GET /__git/pushed?user=<id>&slug=<slug>&phase=before|after gitoria-shell around a push over ssh (what transport.hl does for HTTPS):// before → the repo's existing pull requests are numbered (ensurePulls); after (git exited 0) → notifyPush + syncPulls for that user. `ok`; never an error for the push.static gitPushed = (route, req) => {no = sshGuard(req)if (no != null) { return no }q = req.query != null ? req.query : {}slug = q.slugif (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }let repo = repoBySlug(slug)if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }if (repo == null || !mayPush(q.user, repo)) { return textReply(403, 'not allowed' + NL) }if (q.phase == 'before') { ensurePulls(repo.slug) }else if (q.phase == 'after') {notifyPush(repo.slug, false)syncPulls(repo.slug, q.user)} else { return textReply(400, 'phase is before or after' + NL) }return textReply(200, 'ok' + NL)}static gitAccess = (route, req) => {no = sshGuard(req)if (no != null) { return no }q = req.query != null ? req.query : {}slug = q.slugif (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }let repo = repoBySlug(slug)if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }// the asker is the key's user: a repo they may not see does not exist for them (404, as over HTTPS)if (repo == null || !mayRead(q.user, repo)) { return textReply(404, 'no such repository' + NL) }if (q.write == '1' && !mayPush(q.user, repo)) { return textReply(403, 'only the owner or a member of this repository can push to it' + NL) }// the sshd container runs git in the repo's real folder: tell it the name (it differs after a move)return textReply(200, 'ok ' + repo.slug + NL)}// ---- CONNECT AN APP TO A REPO (gitoria#41; apps.hl, docs/apps-api.md §1 flow A) ----------------------------------------------------// /settings/apps/connect?app&hook&return&state: the app sends the owner's browser here. The four values are checked (the URL allow-list:// anything else is 400 invalid_url) and PARKED in the session with a nonce; then → the repo's settings page, which asks the person to sign in// (the same session goes on after the login) and, for the owner, shows "Connect <app> to <repo>?" with a Yes / No form.// /settings/apps/confirm (POST): the form's answer → the owner check, the nonce, a one-time code → redirect to return?code&state (No: return?error=denied&state).static appConnectStart = (route, &req, &sessions) => {if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }repo = repoOfRequest(route, req)if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }q = req.query != null ? req.query : {}if (!urlAllowed(q.hook)) { return apiError(400, 'invalid_url', 'hook is not an allowed receiver address', { field = 'hook' }) }if (!urlAllowed(q['return'])) { return apiError(400, 'invalid_url', 'return is not an allowed address', { field = 'return' }) }bad = nameError(q.app)if (bad != null) { return apiError(422, 'invalid', bad, { field = 'app' }) }if (q.state == null || hlTypeName(q.state) != 'String' || q.state.length == 0 || q.state.length > 200) { return apiError(422, 'invalid', 'state is missing or too long', { field = 'state' }) }let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.appConnect = { slug = repo.slug app = ('' + q.app).trim() hook = q.hook ret = q['return'] state = q.state nonce = randomBytes(16) }sessions.save(s)res = goTo(px(repo.slug) + '/settings')if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}static appConnectConfirm = (route, &req, &sessions) => {if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }repo = repoOfRequest(route, req)if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }home = px(repo.slug) + '/settings'let s = req.sessionif (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) { return goTo(home) }p = s.data.appConnectf = formFields(req.body)if (p == null || p.slug != repo.slug || f.nonce == null || f.nonce != p.nonce) { return goTo(home) }// one try: the parked request goes whatever the answer iss.data.appConnect = nullsessions.save(s)if (f.decision != 'yes') { return goTo(withQuery(p.ret, { error = 'denied' state = p.state })) }code = makeCode(repo, p.app, p.hook, userIdOfSession(s))if (code == null) { return goTo(home) }return goTo(withQuery(p.ret, { code = code state = p.state }))}// POST /api/apps/exchange {"code"} (no auth): the app's server trades the code → { key, secret, api, repo, app } (apps.hl exchangeCode)static appExchange = (route, req) => {if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }repo = repoOfRequest(route, req)if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }// DOCS/GAP: JSON.parse of broken JSON is a located error that ends the request (500), there is no safe parse; only a body that is not even shaped like an object gets the 400 heret = req.body == null ? '' : req.body.trim()j = t.startsWith('{') && t.endsWith('}') ? JSON.parse(t) : nullif (j == null || hlTypeName(j) != 'Hybrid') { return apiError(400, 'invalid_json', 'the body must be JSON: {"code":"…"}', null) }x = exchangeCode(repo, j.code)if (x.notFound == true) { return apiError(404, 'not_found', 'unknown, used or expired code', null) }return reply(200, x.body)}// POST {api}/apps/token Authorization: Bearer gak_… → 200 { token, expires } (app-tokens.hl); the key must be the key of the repo the address namesstatic appToken = (route, req) => {if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }app = appOfKey(bearerOf(req))if (app == null) { return unauthorized() }repo = repoOfRequest(route, req)if (repo == null || repo.id != app.repo) { return notFound() }t = issueToken(app)if (t.error != null) { return apiError(500, 'internal', 'could not make a token', null) }return reply(200, { token = t.token expires = t.expires })}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
Latest commits
- 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
- b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
- 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
- 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
- fdb9ed28gitoria#41: repo owners can connect an app (merge w41-apps-connect)mre
- 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
- 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
- b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
- 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
- 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre
- c4175e6dgitoria: a startup error prints its message before exit 1 (hybriel#247)mre
- c50d17efKeep function-route not-found style in shared stylesheetmre
- e42d78d3Preserve ticket state CSS and document function-route style gapmre
- c6b7154eWIP gitoria#26: move styles into nested component blocksmre
- 77a2c31cgitoria#31: plain declarations instead of needless let in lib/ and tools/ (103 let removed, 137 kept because reassigned); no other changemre
- 4b98ab62gitoria: an ident access key (idt_) works as the git password; read key clones only, bad key 401, ident down 503 (ident#27); gate tests/ident-access-gitoria.mjs in deploy.shmre
- 1185f686gitoria#36: a failed return from tickets shows a note on the settings page and leaves one log line per outcome; no code is exchangedmre
- 5d2c385agitoria: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 71+5 failing → 76 passed; deploy.sh runs tests/private.mjs toomre
- 241ef3f9deploy.sh: rebuild the sshd image before up -d (GO34c)mre
- 821cdbb1gitoria#34b: styles, create-repo tool, docs, push/ssh gates sign in through the selector, shots scriptmre