gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2f2959c52f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre2f2959c5/lib/transport.hl

9.5 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. // * An APP token (`gat_…`, app-tokens.hl, gitoria#42) as the password is READ of its one repo; a push with it is a 403; another repo: no access.
  9. // * WRITE (push) needs a token as the password (tokens.hl) of THE REPO'S OWNER — nobody else may push (decision below).
  10. // * The body travels through temp files, byte for byte (a String here holds raw bytes; hl:fs writes and reads them as
  11. // they are): hl:proc run() has no stdin, so the child reads `< body` and writes `> answer` in a tiny `sh -c` with
  12. // the paths as positional arguments (no user text in the script). A gzip body (git compresses big requests) is
  13. // unpacked first. Git protocol v2 is passed through (`Git-Protocol` → GIT_PROTOCOL, digits only).
  14. // * refs/pull/* (a pull request's head, pullsync.hl) is gitoria's own: receive.hideRefs=refs/pull makes git-receive-pack refuse a push to it
  15. // (and not advertise it to a pusher; fetch still gets it). After a push git is asked to be compared with the pull request records (pullsync.hl syncPulls, then the apps hear of every change: events.hl syncAndRaise).
  16. // The checks, the plain answers and the pkt-line are in transport-helpers.hl.
  17. import { Response } from 'hl:http1'
  18. import { run } from 'hl:proc'
  19. import { readFile, writeFile, remove, exists } from 'hl:fs'
  20. import { randomBytes } from 'hl:crypto'
  21. import { NL, slugOfHost, publicUrl } from './util.hl'
  22. import { repoBySlug, mayPush, mayRead } from './repos.hl'
  23. import { orgBySlug } from './orgs.hl'
  24. import { forwardOf } from './forwards.hl'
  25. import { userOfToken } from './tokens.hl'
  26. import { appOfToken } from './app-auth.hl'
  27. import { check as identCheck } from './ident-access.hl'
  28. import { ensureUser, userRecord, setUserName } from './users.hl'
  29. import { repoDir, tmpDir, hooksDir } from './git.hl'
  30. import { notifyPush } from './tickets.hl'
  31. import { ensurePulls } from './pullsync.hl'
  32. import { syncAndRaise } from './events.hl'
  33. import { passwordOf, plain, protocolEnv, pktLine } from './transport-helpers.hl'
  34. static seconds = 300 // one upload-pack / receive-pack call
  35. static maxBody = 500000000 // a push or fetch request above this is refused (bytes)
  36. // 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)
  37. static callGit = (slug, service, advertise, req) => {
  38. dir = tmpDir()
  39. name = dir + '/' + randomBytes(12, 'hex')
  40. inFile = name + '.in'
  41. outFile = name + '.out'
  42. let zipped = false
  43. let script = 'exec git -c receive.hideRefs=refs/pull -c core.hooksPath="$4" ' + service.slice(4) + ' --stateless-rpc --advertise-refs "$1" > "$3"'
  44. if (!advertise) {
  45. body = req.body == null ? '' : req.body
  46. writeFile(inFile, body, 384)
  47. enc = req.headers['content-encoding']
  48. zipped = enc != null && hlTypeName(enc) == 'String' && (enc.toLowerCase() == 'gzip' || enc.toLowerCase() == 'x-gzip')
  49. script = zipped ? 'gzip -dc < "$2" | git -c receive.hideRefs=refs/pull -c core.hooksPath="$4" ' + service.slice(4) + ' --stateless-rpc "$1" > "$3"' : 'exec git -c receive.hideRefs=refs/pull -c core.hooksPath="$4" ' + service.slice(4) + ' --stateless-rpc "$1" < "$2" > "$3"'
  50. }
  51. r = run(['sh', '-c', script, 'sh', repoDir(slug), inFile, outFile, hooksDir], { timeout = seconds env = protocolEnv(req) })
  52. out = exists(outFile) ? readFile(outFile) : null
  53. if (exists(inFile)) { remove(inFile) }
  54. if (exists(outFile)) { remove(outFile) }
  55. // 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
  56. if (out == null || (out == '' && (r == null || r.exit != 0))) { return null }
  57. return out
  58. }
  59. // THE ROUTE (project.hl, a function route): `/:repo/info/refs`, `/:repo/git-upload-pack`, `/:repo/git-receive-pack`
  60. static gitTransport = (route, req) => {
  61. hostHeader = req.headers['host']
  62. label = slugOfHost(hostHeader == null ? '' : hostHeader.split(':')[0])
  63. repoName = route.params.repo
  64. // the name the client asked for: <label>/<repoName> inside an organization, else <label>; a moved repo is served from its new place
  65. let asked = ''
  66. if (label != '' && repoName.endsWith('.git')) {
  67. short = repoName.slice(0, repoName.length - 4)
  68. asked = orgBySlug(label) != null ? label + '/' + short : (short == label ? label : '')
  69. }
  70. if (asked == '') { return plain(404, 'no such repository') }
  71. let repo = repoBySlug(asked)
  72. if (repo == null && forwardOf(asked) != null) { repo = repoBySlug(forwardOf(asked)) }
  73. // WHO IS ASKING: a token as the password of a Basic header (private repos are read and pushed with it)
  74. pw = passwordOf(req.headers['authorization'])
  75. // 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
  76. // 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.
  77. let userId = null
  78. let keyAccess = null
  79. let appToken = false
  80. let appRead = false
  81. if (pw != null && pw.startsWith('idt_')) {
  82. who = identCheck(req)
  83. if (!who.ok) { return plain(who.status, who.error, who.status == 401 ? { 'WWW-Authenticate' = 'Basic realm="gitoria"' } : null) }
  84. let u = ensureUser(who.identity)
  85. if (u == null) { return plain(500, 'could not store the user') }
  86. if (u.name == '' && who.name != null && who.name != '') {
  87. setUserName(u.id, who.name)
  88. u = userRecord(u.id)
  89. }
  90. userId = u.id
  91. keyAccess = who.access
  92. } else if (pw != null && pw.startsWith('gat_')) {
  93. // an APP's token (gitoria#42): READ of its one repo, never a push; for any other repo it is as good as no credential
  94. found = appOfToken(pw)
  95. appToken = found != null
  96. appRead = found != null && repo != null && found.repoId == repo.id
  97. } else if (pw != null) {
  98. userId = userOfToken(pw)
  99. }
  100. // 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
  101. // 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.
  102. if (repo == null || !(appRead || mayRead(userId, repo))) {
  103. if (pw == null) { return plain(401, 'this repository needs a token: use it as the password', { 'WWW-Authenticate' = 'Basic realm="gitoria"' }) }
  104. return plain(404, 'no such repository')
  105. }
  106. slug = repo.slug
  107. last = req.path.slice(req.path.lastIndexOf('/') + 1)
  108. advertise = last == 'refs'
  109. service = advertise ? (req.query != null ? req.query.service : null) : last
  110. 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') }
  111. if (advertise && req.method != 'GET') { return plain(405, 'GET only') }
  112. if (!advertise && req.method != 'POST') { return plain(405, 'POST only') }
  113. if (req.body != null && req.body.length > maxBody) { return plain(413, 'that request is too big') }
  114. if (service == 'git-receive-pack') {
  115. realm = { 'WWW-Authenticate' = 'Basic realm="gitoria"' }
  116. if (appToken) { return plain(403, 'an app token is read-only: it can clone and fetch, not push') }
  117. 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) }
  118. if (userId == null) { return plain(401, 'that token is not valid (removed, or mistyped)', realm) }
  119. if (keyAccess == 'read') { return plain(403, 'this ident access key is read-only: it can clone and fetch, not push') }
  120. if (!mayPush(userId, repo)) { return plain(403, 'only the owner or a member of this repository can push to it') }
  121. }
  122. // the pull requests a repo already has get their numbers BEFORE the push lands, so that only the new ones are "opened" (once per repo)
  123. if (service == 'git-receive-pack' && !advertise) { ensurePulls(slug) }
  124. let out = callGit(slug, service, advertise, req)
  125. if (out == null) { return plain(500, 'git gave no answer') }
  126. let headers = { 'Cache-Control' = 'no-cache, max-age=0, must-revalidate' 'Pragma' = 'no-cache' 'X-Content-Type-Options' = 'nosniff' }
  127. if (advertise) {
  128. headers['Content-Type'] = 'application/x-' + service + '-advertisement'
  129. // protocol v2 answers without the service banner; v0/v1 starts with it (as git http-backend does)
  130. v2 = protocolEnv(req).GIT_PROTOCOL != null && protocolEnv(req).GIT_PROTOCOL.includes('version=2')
  131. if (!v2) { out = pktLine('# service=' + service + NL) + '0000' + out }
  132. } else {
  133. headers['Content-Type'] = 'application/x-' + service + '-result'
  134. // a push arrived: tell the connected tickets project about commits naming a ticket (tickets.hl; never fails the push)
  135. if (service == 'git-receive-pack') {
  136. notifyPush(slug, false)
  137. // the pull request records follow the refs (numbers, refs/pull/N/head, the changes → pull-changes.log until gitoria#43)
  138. syncAndRaise(slug, userId)
  139. }
  140. }
  141. return new Response(out, { headers = headers })
  142. }

Branches

Latest commits

  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria
  • a002ecb7|||PR records: HL25 report, heap helper, logmre
  • 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
  • fefaedd2log: tracker PR-only, HL25 startedmre
  • 21aa57calog: parkmre
  • e9f950a8reports: G25c soakmre
  • a7783686log: deploy 9f41ffcmre
  • 9f41ffc1log: W30b mergedmre
  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre
  • 01b71c2edocs: neutral wording in missions, reports and logmre
  • 3eeea733log: 2026-11-09 PR flow plan and membersmre