gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9af07ece9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre9af07ece/lib/api.hl

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

Branches

Latest commits

  • 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
  • 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
  • a81abdc9gitoria#34: org page via function route, member-reachable orgs, selects, reportmre
  • 17f031f0gitoria#34: private repos, organizations, members, move tool, gatemre
  • 71b69343gitoria#23: the sidebar's Repositories link was a 404 after any in-page navigation (static menu re-evaluated publicUrl in the browser); the menu is an instance property now; gate taps it after a tab, folder, filemre
  • 90b4f728gitoria#25: restore the homepage cache and the parsed-blocks cache (they store data under immutable keys, no HTML); the page key, the framework readme key and the textHash key stay removedmre
  • a487248cgitoria#25: remove every cache that hid the page build (page key, Markdown render key, homepage cache, parsed-blocks cache) and the gate that only tested themmre
  • 12f2f4fegitoria: re-vendor Hybriel set-day27b, a startup fault in on Error exits 1mre
  • c21c084egitoria: write the standby service out in full so the boot gate can read the main servicemre