gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5a996ea85a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre5a996ea8/lib/api.hl

16.7 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (project.hl wires them): thin wrappers — check the request and the session, call the
  2. // topic, answer. The plumbing (JSON / Markdown / plain answers, redirects, the ssh guard, `?next=`) is lib/api-helpers.hl.
  3. // /api/repos, /api/repos/:slug the public reads (repos.hl; Accept: text/markdown → the Markdown read view)
  4. // /login/callback the login button's return (users.hl)
  5. // /settings/connect, /settings/connected connecting a repo to a tickets project (tickets.hl)
  6. // /api/apps/token an app trades its key for a one-hour token (app-tokens.hl, gitoria#42)
  7. // /settings/apps/connect, /settings/apps/confirm, /api/apps/exchange connecting an app to a repo (apps.hl, gitoria#41)
  8. // /__git/keys, /__git/access what the sshd container asks (sshkeys.hl, repos.hl)
  9. // (The git protocol's routes are lib/transport.hl gitTransport.)
  10. // A route that WRITES THE SESSION gets the request and the framework's session store BY REFERENCE (`&req`, `&sessions`,
  11. // from project.hl): copied into a second call, the session inside `req` would be a copy too and the write would be lost.
  12. import { Response } from 'hl:http1'
  13. import { randomBytes } from 'hl:crypto'
  14. import { NL, px, slugOfHost } from './util.hl'
  15. import { userOfLoginCode } from './users.hl'
  16. import { repoRows, repoRow, repoBySlug, repoFor, orgFor, ownsRepo, mayPush, mayRead } from './repos.hl'
  17. import { fullNameError, repoDocument, listDocument } from './repos-helpers.hl'
  18. import { forwardOf } from './forwards.hl'
  19. import { userIdOfSession } from './users.hl'
  20. import { connectHref, finishConnect } from './tickets.hl'
  21. import { keyLine } from './sshkeys.hl'
  22. import { urlAllowed, withQuery, formFields } from './apps-helpers.hl'
  23. import { nameError, makeCode, exchangeCode, appOfKey } from './apps.hl'
  24. import { issueToken } from './app-tokens.hl'
  25. import { bearerOf, unauthorized, notFound } from './app-auth.hl'
  26. import { reply, fail, apiError, wantsMarkdown, markdownReply, textReply, goTo, sshGuard, repoOfRequest, safeNext } from './api-helpers.hl'
  27. import { ensurePulls, syncPulls } from './pullsync.hl'
  28. import { notifyPush } from './tickets.hl'
  29. // ---- the API: reads are public (creating a repo is a web action for now) ------------------------
  30. static apiRepos = (route, req) => {
  31. if (req.method != 'GET') { return fail(405, 'GET only') }
  32. rows = repoRows(userIdOfSession(req.session))
  33. if (wantsMarkdown(req)) { return markdownReply(listDocument(rows)) }
  34. return reply(200, { repos = rows })
  35. }
  36. static apiRepo = (route, req) => {
  37. if (req.method != 'GET') { return fail(405, 'GET only') }
  38. row = repoRow(route.params.slug, userIdOfSession(req.session))
  39. if (row == null) { return fail(404, 'no such repository') }
  40. if (wantsMarkdown(req)) { return markdownReply(repoDocument(row)) }
  41. return reply(200, row)
  42. }
  43. // ---- NOTHING ELSE (mission MG, as ident's notFoundPage): the last route of project.hl answers a path no route knows with the
  44. // shell's 404 page (components/notfound.hl) — status 404, the page rendered by the framework with the request's session and host
  45. static notFoundPage = (route, req, &srv, pageComponent) => {
  46. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }
  47. res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))
  48. res.status = 404
  49. return res
  50. }
  51. // `/: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:
  52. // a stray single-segment path on any other address keeps its real 404 status — /.env, /host.js, a private organization's /x)
  53. static orgRepoPage = (route, req, &srv, pageComponent, missingComponent) => {
  54. h = req.headers['host']
  55. label = slugOfHost(h == null ? '' : h.split(':')[0])
  56. if (label == '' || orgFor(label, userIdOfSession(req.session)) == null) { return notFoundPage(route, req, &srv, missingComponent) }
  57. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = req.path.slice(1) } path = req.path }
  58. return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))
  59. }
  60. static notFoundApi = (route, req) => { return fail(404, 'no such endpoint') }
  61. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------
  62. // ident sends the browser back with ?ident_code= (and our ?next=); the code is exchanged here (users.hl userOfLoginCode),
  63. // the user goes into THIS browser's session (`req.session`, the cookie's — hybriel #11; minted when it brought none),
  64. // then → `?next=` (api-helpers.hl safeNext). A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked
  65. // in the session, then → /login/failed.
  66. static loginFailed = (&req, &sessions, why) => {
  67. let s = req.session
  68. fresh = s == null
  69. if (fresh) { s = sessions.mint() }
  70. s.data.loginError = why
  71. sessions.save(s)
  72. 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' } })
  73. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  74. return res
  75. }
  76. static loginCallback = (route, &req, &sessions) => {
  77. if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }
  78. q = req.query != null ? req.query : {}
  79. code = q.ident_code
  80. if (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }
  81. x = userOfLoginCode(code)
  82. if (x.error != null) { return loginFailed(&req, &sessions, x.error) }
  83. // 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
  84. // app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted here
  85. let s = req.session
  86. if (s == null) { s = sessions.mint() }
  87. s.user = { id = x.user.id }
  88. s.data.tag = randomBytes(16)
  89. s.data.loginError = null
  90. sessions.save(s)
  91. 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) } })
  92. return res
  93. }
  94. // ---- ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS ---------------------------------------------------------------------
  95. // Nothing here: hl:web (batch 20) does it. The session cookie carries `Domain=.<host>` (project.hl sessionDomain); among several gitoriasid
  96. // 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
  97. // 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".
  98. // ---- CONNECT A REPO TO A TICKETS PROJECT (gitoria#18; tickets.hl, components/settings.hl) ----------------------------
  99. // /settings/connect: the owner's click → a fresh nonce parked in the session (bound to the repo) → tickets' /connect.
  100. // /settings/connected: tickets' return with ?code&state → tickets.hl finishConnect (nonce, exchange, key stored per
  101. // repo) → back to /settings. A failure is a note on the settings page.
  102. static connectStart = (route, &req, &sessions) => {
  103. if (req.method != 'GET') { return fail(405, 'GET only') }
  104. repo = repoOfRequest(route, req)
  105. if (repo == null) { return fail(404, 'no such repository') }
  106. s = req.session
  107. if (s == null || !ownsRepo(repo.slug, s)) { return goTo(px(repo.slug) + '/settings') }
  108. nonce = randomBytes(16)
  109. s.data.connectState = repo.slug + '.' + nonce
  110. s.data.connectNote = null
  111. sessions.save(s)
  112. return goTo(connectHref(repo.slug, nonce))
  113. }
  114. // One log line for every end of the connect flow (docker logs of the gitoria container): "connect-back <slug> <outcome> ..." and
  115. // never the code, the state value or a key. `state` only says whether tickets brought one.
  116. static connectLog = (slug, outcome, hasState) => {
  117. console.log('connect-back ' + slug + ' ' + outcome + ' state=' + (hasState ? 'present' : 'absent'))
  118. }
  119. 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.'
  120. static connectBack = (route, &req, &sessions) => {
  121. if (req.method != 'GET') { return fail(405, 'GET only') }
  122. repo = repoOfRequest(route, req)
  123. if (repo == null) { return fail(404, 'no such repository') }
  124. q = req.query != null ? req.query : {}
  125. hasState = q.state != null
  126. let s = req.session
  127. if (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) {
  128. // nothing is exchanged; the code is dropped. The browser is told why on the settings page: a session-less browser gets a fresh
  129. // session that carries the note (like loginFailed), a session that exists keeps itself and gets the note
  130. why = s == null ? 'no-session' : (userIdOfSession(s) == null ? 'session-not-signed-in' : 'not-owner')
  131. connectLog(repo.slug, 'refused reason=' + why, hasState)
  132. fresh = s == null
  133. if (fresh) { s = sessions.mint() }
  134. s.data.connectNote = notSignedInNote
  135. sessions.save(s)
  136. res = goTo(px(repo.slug) + '/settings')
  137. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  138. return res
  139. }
  140. want = s.data.connectState
  141. s.data.connectState = null
  142. note = finishConnect(repo.slug, want, q)
  143. s.data.connectNote = note == '' ? null : note
  144. sessions.save(s)
  145. if (note == '') {
  146. connectLog(repo.slug, 'connected', hasState)
  147. } else if (q.error != null && q.code == null) {
  148. connectLog(repo.slug, 'tickets-error', hasState)
  149. } else if (want == null || want != repo.slug + '.' + q.state) {
  150. connectLog(repo.slug, 'state-mismatch', hasState)
  151. } else {
  152. connectLog(repo.slug, 'exchange-failed', hasState)
  153. }
  154. return goTo(px(repo.slug) + '/settings')
  155. }
  156. // ---- WHAT THE SSHD CONTAINER ASKS (ticket gitoria#7; docker/sshd) — only with the shared secret (api-helpers.hl sshGuard)
  157. // GET /__git/keys?type=<ssh-ed25519>&key=<base64> sshd AuthorizedKeysCommand: the authorized_keys line for a known key
  158. // (sshkeys.hl keyLine), empty for an unknown one
  159. // GET /__git/access?user=<id>&slug=<slug>&write=0|1 gitoria-shell before it starts git: `ok` or 403. Read = every repo (public);
  160. // write = the repo's owner only (repos.hl mayPush — the same rule as the token on HTTPS, transport.hl)
  161. static gitKeys = (route, req) => {
  162. no = sshGuard(req)
  163. if (no != null) { return no }
  164. q = req.query != null ? req.query : {}
  165. return textReply(200, keyLine(q.type, q.key))
  166. }
  167. // GET /__git/pushed?user=<id>&slug=<slug>&phase=before|after gitoria-shell around a push over ssh (what transport.hl does for HTTPS):
  168. // 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.
  169. static gitPushed = (route, req) => {
  170. no = sshGuard(req)
  171. if (no != null) { return no }
  172. q = req.query != null ? req.query : {}
  173. slug = q.slug
  174. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  175. let repo = repoBySlug(slug)
  176. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  177. if (repo == null || !mayPush(q.user, repo)) { return textReply(403, 'not allowed' + NL) }
  178. if (q.phase == 'before') { ensurePulls(repo.slug) }
  179. else if (q.phase == 'after') {
  180. notifyPush(repo.slug, false)
  181. syncPulls(repo.slug, q.user)
  182. } else { return textReply(400, 'phase is before or after' + NL) }
  183. return textReply(200, 'ok' + NL)
  184. }
  185. static gitAccess = (route, req) => {
  186. no = sshGuard(req)
  187. if (no != null) { return no }
  188. q = req.query != null ? req.query : {}
  189. slug = q.slug
  190. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  191. let repo = repoBySlug(slug)
  192. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  193. // the asker is the key's user: a repo they may not see does not exist for them (404, as over HTTPS)
  194. if (repo == null || !mayRead(q.user, repo)) { return textReply(404, 'no such repository' + NL) }
  195. 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) }
  196. // the sshd container runs git in the repo's real folder: tell it the name (it differs after a move)
  197. return textReply(200, 'ok ' + repo.slug + NL)
  198. }
  199. // ---- CONNECT AN APP TO A REPO (gitoria#41; apps.hl, docs/apps-api.md §1 flow A) ----------------------------------------------------
  200. // /settings/apps/connect?app&hook&return&state: the app sends the owner's browser here. The four values are checked (the URL allow-list:
  201. // 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
  202. // (the same session goes on after the login) and, for the owner, shows "Connect <app> to <repo>?" with a Yes / No form.
  203. // /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).
  204. static appConnectStart = (route, &req, &sessions) => {
  205. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  206. repo = repoOfRequest(route, req)
  207. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  208. q = req.query != null ? req.query : {}
  209. if (!urlAllowed(q.hook)) { return apiError(400, 'invalid_url', 'hook is not an allowed receiver address', { field = 'hook' }) }
  210. if (!urlAllowed(q['return'])) { return apiError(400, 'invalid_url', 'return is not an allowed address', { field = 'return' }) }
  211. bad = nameError(q.app)
  212. if (bad != null) { return apiError(422, 'invalid', bad, { field = 'app' }) }
  213. 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' }) }
  214. let s = req.session
  215. fresh = s == null
  216. if (fresh) { s = sessions.mint() }
  217. s.data.appConnect = { slug = repo.slug app = ('' + q.app).trim() hook = q.hook ret = q['return'] state = q.state nonce = randomBytes(16) }
  218. sessions.save(s)
  219. res = goTo(px(repo.slug) + '/settings')
  220. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  221. return res
  222. }
  223. static appConnectConfirm = (route, &req, &sessions) => {
  224. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  225. repo = repoOfRequest(route, req)
  226. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  227. home = px(repo.slug) + '/settings'
  228. let s = req.session
  229. if (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) { return goTo(home) }
  230. p = s.data.appConnect
  231. f = formFields(req.body)
  232. if (p == null || p.slug != repo.slug || f.nonce == null || f.nonce != p.nonce) { return goTo(home) }
  233. // one try: the parked request goes whatever the answer is
  234. s.data.appConnect = null
  235. sessions.save(s)
  236. if (f.decision != 'yes') { return goTo(withQuery(p.ret, { error = 'denied' state = p.state })) }
  237. code = makeCode(repo, p.app, p.hook, userIdOfSession(s))
  238. if (code == null) { return goTo(home) }
  239. return goTo(withQuery(p.ret, { code = code state = p.state }))
  240. }
  241. // POST /api/apps/exchange {"code"} (no auth): the app's server trades the code → { key, secret, api, repo, app } (apps.hl exchangeCode)
  242. static appExchange = (route, req) => {
  243. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  244. repo = repoOfRequest(route, req)
  245. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  246. // 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 here
  247. t = req.body == null ? '' : req.body.trim()
  248. j = t.startsWith('{') && t.endsWith('}') ? JSON.parse(t) : null
  249. if (j == null || hlTypeName(j) != 'Hybrid') { return apiError(400, 'invalid_json', 'the body must be JSON: {"code":"…"}', null) }
  250. x = exchangeCode(repo, j.code)
  251. if (x.notFound == true) { return apiError(404, 'not_found', 'unknown, used or expired code', null) }
  252. return reply(200, x.body)
  253. }
  254. // POST {api}/apps/token Authorization: Bearer gak_… → 200 { token, expires } (app-tokens.hl); the key must be the key of the repo the address names
  255. static appToken = (route, req) => {
  256. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  257. app = appOfKey(bearerOf(req))
  258. if (app == null) { return unauthorized() }
  259. repo = repoOfRequest(route, req)
  260. if (repo == null || repo.id != app.repo) { return notFound() }
  261. t = issueToken(app)
  262. if (t.error != null) { return apiError(500, 'internal', 'could not make a token', null) }
  263. return reply(200, { token = t.token expires = t.expires })
  264. }

Branches

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