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/transport.hl

8.0 KB

  1. // lib/transport.hl — CLONE, FETCH AND PUSH OVER HTTPS (ticket gitoria#7; docs/git-backend.md). Git's "smart HTTP" protocol,
  2. // answered by this app itself with the `git` binary: on a repo address `<slug>.<domain>` the paths
  3. // /<slug>.git/info/refs?service=git-upload-pack | git-receive-pack (what a client asks first)
  4. // /<slug>.git/git-upload-pack (fetch / clone) /<slug>.git/git-receive-pack (push)
  5. // spawn `git upload-pack | receive-pack --stateless-rpc` and hand the request body over and the answer back.
  6. // The clone URL is https://<slug>.<domain>/<slug>.git — the folder git makes is named like the repo.
  7. // * READ (clone, fetch) needs no login for a public repo; a private one (GO34) answers 404 unless the token (password) is its owner's or a member's.
  8. // * WRITE (push) needs a token as the password (tokens.hl) of THE REPO'S OWNER — nobody else may push (decision below).
  9. // * The body travels through temp files, byte for byte (a String here holds raw bytes; hl:fs writes and reads them as
  10. // they are): hl:proc run() has no stdin, so the child reads `< body` and writes `> answer` in a tiny `sh -c` with
  11. // the paths as positional arguments (no user text in the script). A gzip body (git compresses big requests) is
  12. // unpacked first. Git protocol v2 is passed through (`Git-Protocol` → GIT_PROTOCOL, digits only).
  13. // * No hook: pull requests and releases are read from the commits when their page is built.
  14. // The checks, the plain answers and the pkt-line are in transport-helpers.hl.
  15. import { Response } from 'hl:http1'
  16. import { run } from 'hl:proc'
  17. import { readFile, writeFile, remove, exists } from 'hl:fs'
  18. import { randomBytes } from 'hl:crypto'
  19. import { NL, slugOfHost, publicUrl } from './util.hl'
  20. import { repoBySlug, mayPush, mayRead } from './repos.hl'
  21. import { orgBySlug } from './orgs.hl'
  22. import { forwardOf } from './forwards.hl'
  23. import { userOfToken } from './tokens.hl'
  24. import { check as identCheck } from './ident-access.hl'
  25. import { ensureUser, userRecord, setUserName } from './users.hl'
  26. import { repoDir, tmpDir } from './git.hl'
  27. import { notifyPush } from './tickets.hl'
  28. import { passwordOf, plain, protocolEnv, pktLine } from './transport-helpers.hl'
  29. static seconds = 300 // one upload-pack / receive-pack call
  30. static maxBody = 500000000 // a push or fetch request above this is refused (bytes)
  31. // ONE GIT CALL: the request body (or none) in, the answer out. → the answer's bytes as a String, or null (git failed and said nothing)
  32. static callGit = (slug, service, advertise, req) => {
  33. dir = tmpDir()
  34. name = dir + '/' + randomBytes(12, 'hex')
  35. inFile = name + '.in'
  36. outFile = name + '.out'
  37. let zipped = false
  38. let script = 'exec git ' + service.slice(4) + ' --stateless-rpc --advertise-refs "$1" > "$3"'
  39. if (!advertise) {
  40. body = req.body == null ? '' : req.body
  41. writeFile(inFile, body, 384)
  42. enc = req.headers['content-encoding']
  43. zipped = enc != null && hlTypeName(enc) == 'String' && (enc.toLowerCase() == 'gzip' || enc.toLowerCase() == 'x-gzip')
  44. script = zipped ? 'gzip -dc < "$2" | git ' + service.slice(4) + ' --stateless-rpc "$1" > "$3"' : 'exec git ' + service.slice(4) + ' --stateless-rpc "$1" < "$2" > "$3"'
  45. }
  46. r = run(['sh', '-c', script, 'sh', repoDir(slug), inFile, outFile], { timeout = seconds env = protocolEnv(req) })
  47. out = exists(outFile) ? readFile(outFile) : null
  48. if (exists(inFile)) { remove(inFile) }
  49. if (exists(outFile)) { remove(outFile) }
  50. // git answers nothing to the client's "0000" probe of a big push (exit 0): that is a 200 with an empty body, as git http-backend does
  51. if (out == null || (out == '' && (r == null || r.exit != 0))) { return null }
  52. return out
  53. }
  54. // THE ROUTE (project.hl, a function route): `/:repo/info/refs`, `/:repo/git-upload-pack`, `/:repo/git-receive-pack`
  55. static gitTransport = (route, req) => {
  56. hostHeader = req.headers['host']
  57. label = slugOfHost(hostHeader == null ? '' : hostHeader.split(':')[0])
  58. repoName = route.params.repo
  59. // the name the client asked for: <label>/<repoName> inside an organization, else <label>; a moved repo is served from its new place
  60. let asked = ''
  61. if (label != '' && repoName.endsWith('.git')) {
  62. short = repoName.slice(0, repoName.length - 4)
  63. asked = orgBySlug(label) != null ? label + '/' + short : (short == label ? label : '')
  64. }
  65. if (asked == '') { return plain(404, 'no such repository') }
  66. let repo = repoBySlug(asked)
  67. if (repo == null && forwardOf(asked) != null) { repo = repoBySlug(forwardOf(asked)) }
  68. // WHO IS ASKING: a token as the password of a Basic header (private repos are read and pushed with it)
  69. pw = passwordOf(req.headers['authorization'])
  70. // an ident access key (idt_…, ident#27) as the password: ident says who it is and what it may do (read or write); the identity's gitoria user is the one
  71. // its login made (made here at the first use, named as ident names it). A bad, revoked or foreign key is a 401 (git asks again), ident not answering a 503.
  72. let userId = null
  73. let keyAccess = null
  74. if (pw != null && pw.startsWith('idt_')) {
  75. who = identCheck(req)
  76. if (!who.ok) { return plain(who.status, who.error, who.status == 401 ? { 'WWW-Authenticate' = 'Basic realm="gitoria"' } : null) }
  77. let u = ensureUser(who.identity)
  78. if (u == null) { return plain(500, 'could not store the user') }
  79. if (u.name == '' && who.name != null && who.name != '') {
  80. setUserName(u.id, who.name)
  81. u = userRecord(u.id)
  82. }
  83. userId = u.id
  84. keyAccess = who.access
  85. } else if (pw != null) {
  86. userId = userOfToken(pw)
  87. }
  88. // A REPO THE ASKER MAY NOT SEE ANSWERS AS ONE THAT DOES NOT EXIST, so its name does not leak. Git sends no credentials before it is challenged, so an
  89. // ANONYMOUS ask for a private repo and for a name nobody made gets the same 401 (asking for a token); with a token that gives no access: 404.
  90. if (repo == null || !mayRead(userId, repo)) {
  91. if (pw == null) { return plain(401, 'this repository needs a token: use it as the password', { 'WWW-Authenticate' = 'Basic realm="gitoria"' }) }
  92. return plain(404, 'no such repository')
  93. }
  94. slug = repo.slug
  95. last = req.path.slice(req.path.lastIndexOf('/') + 1)
  96. advertise = last == 'refs'
  97. service = advertise ? (req.query != null ? req.query.service : null) : last
  98. if (service != 'git-upload-pack' && service != 'git-receive-pack') { return plain(403, 'only the smart git protocol is served here: use git clone / fetch / push') }
  99. if (advertise && req.method != 'GET') { return plain(405, 'GET only') }
  100. if (!advertise && req.method != 'POST') { return plain(405, 'POST only') }
  101. if (req.body != null && req.body.length > maxBody) { return plain(413, 'that request is too big') }
  102. if (service == 'git-receive-pack') {
  103. realm = { 'WWW-Authenticate' = 'Basic realm="gitoria"' }
  104. if (pw == null) { return plain(401, 'pushing needs a token: log in at ' + publicUrl + ', make one under "Access tokens", and use it as the password', realm) }
  105. if (userId == null) { return plain(401, 'that token is not valid (removed, or mistyped)', realm) }
  106. if (keyAccess == 'read') { return plain(403, 'this ident access key is read-only: it can clone and fetch, not push') }
  107. if (!mayPush(userId, repo)) { return plain(403, 'only the owner or a member of this repository can push to it') }
  108. }
  109. let out = callGit(slug, service, advertise, req)
  110. if (out == null) { return plain(500, 'git gave no answer') }
  111. let headers = { 'Cache-Control' = 'no-cache, max-age=0, must-revalidate' 'Pragma' = 'no-cache' 'X-Content-Type-Options' = 'nosniff' }
  112. if (advertise) {
  113. headers['Content-Type'] = 'application/x-' + service + '-advertisement'
  114. // protocol v2 answers without the service banner; v0/v1 starts with it (as git http-backend does)
  115. v2 = protocolEnv(req).GIT_PROTOCOL != null && protocolEnv(req).GIT_PROTOCOL.includes('version=2')
  116. if (!v2) { out = pktLine('# service=' + service + NL) + '0000' + out }
  117. } else {
  118. headers['Content-Type'] = 'application/x-' + service + '-result'
  119. // a push arrived: tell the connected tickets project about commits naming a ticket (tickets.hl; never fails the push)
  120. if (service == 'git-receive-pack') { notifyPush(slug, false) }
  121. }
  122. return new Response(out, { headers = headers })
  123. }

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