gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6b0227986b022798gitoria#46: tests/status.mjs in GATESmre6b022798/lib/api.hl

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

Branches

Latest commits

  • 6b022798gitoria#46: tests/status.mjs in GATESmre
  • c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmre
  • e5a0b64egitoria#46: PUT statuses/<sha>, required contexts block the merge on the servermre
  • 49533a50gitoria#43: signed events to connected apps (merge w43-events)mre
  • 1a1e87d5gitoria#43: the sender never writes the apps row; Settings shows the newest deliverymre
  • cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
  • 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
  • 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
  • 15e01e94gitoria#43: tests/events.mjs and its probemre
  • 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)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