gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9364fb169364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre9364fb16/lib/api.hl

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

Branches

Latest commits

  • 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
  • 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
  • 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
  • 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