gitoria
All repositories: gitoria
9.4 KB
// lib/transport.hl — CLONE, FETCH AND PUSH OVER HTTPS (ticket gitoria#7; docs/git-backend.md). Git's "smart HTTP" protocol,// answered by this app itself with the `git` binary: on a repo address `<slug>.<domain>` the paths// /<slug>.git/info/refs?service=git-upload-pack | git-receive-pack (what a client asks first)// /<slug>.git/git-upload-pack (fetch / clone) /<slug>.git/git-receive-pack (push)// spawn `git upload-pack | receive-pack --stateless-rpc` and hand the request body over and the answer back.// The clone URL is https://<slug>.<domain>/<slug>.git — the folder git makes is named like the repo.// * 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.// * 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.// * WRITE (push) needs a token as the password (tokens.hl) of THE REPO'S OWNER — nobody else may push (decision below).// * The body travels through temp files, byte for byte (a String here holds raw bytes; hl:fs writes and reads them as// they are): hl:proc run() has no stdin, so the child reads `< body` and writes `> answer` in a tiny `sh -c` with// the paths as positional arguments (no user text in the script). A gzip body (git compresses big requests) is// unpacked first. Git protocol v2 is passed through (`Git-Protocol` → GIT_PROTOCOL, digits only).// * 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// (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).// The checks, the plain answers and the pkt-line are in transport-helpers.hl.import { Response } from 'hl:http1'import { run } from 'hl:proc'import { readFile, writeFile, remove, exists } from 'hl:fs'import { randomBytes } from 'hl:crypto'import { NL, slugOfHost, publicUrl } from './util.hl'import { repoBySlug, mayPush, mayRead } from './repos.hl'import { orgBySlug } from './orgs.hl'import { forwardOf } from './forwards.hl'import { userOfToken } from './tokens.hl'import { appOfToken } from './app-auth.hl'import { check as identCheck } from './ident-access.hl'import { ensureUser, userRecord, setUserName } from './users.hl'import { repoDir, tmpDir } from './git.hl'import { notifyPush } from './tickets.hl'import { ensurePulls } from './pullsync.hl'import { syncAndRaise } from './events.hl'import { passwordOf, plain, protocolEnv, pktLine } from './transport-helpers.hl'static seconds = 300 // one upload-pack / receive-pack callstatic maxBody = 500000000 // a push or fetch request above this is refused (bytes)// 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)static callGit = (slug, service, advertise, req) => {dir = tmpDir()name = dir + '/' + randomBytes(12, 'hex')inFile = name + '.in'outFile = name + '.out'let zipped = falselet script = 'exec git -c receive.hideRefs=refs/pull ' + service.slice(4) + ' --stateless-rpc --advertise-refs "$1" > "$3"'if (!advertise) {body = req.body == null ? '' : req.bodywriteFile(inFile, body, 384)enc = req.headers['content-encoding']zipped = enc != null && hlTypeName(enc) == 'String' && (enc.toLowerCase() == 'gzip' || enc.toLowerCase() == 'x-gzip')script = zipped ? 'gzip -dc < "$2" | git -c receive.hideRefs=refs/pull ' + service.slice(4) + ' --stateless-rpc "$1" > "$3"' : 'exec git -c receive.hideRefs=refs/pull ' + service.slice(4) + ' --stateless-rpc "$1" < "$2" > "$3"'}r = run(['sh', '-c', script, 'sh', repoDir(slug), inFile, outFile], { timeout = seconds env = protocolEnv(req) })out = exists(outFile) ? readFile(outFile) : nullif (exists(inFile)) { remove(inFile) }if (exists(outFile)) { remove(outFile) }// 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 doesif (out == null || (out == '' && (r == null || r.exit != 0))) { return null }return out}// THE ROUTE (project.hl, a function route): `/:repo/info/refs`, `/:repo/git-upload-pack`, `/:repo/git-receive-pack`static gitTransport = (route, req) => {hostHeader = req.headers['host']label = slugOfHost(hostHeader == null ? '' : hostHeader.split(':')[0])repoName = route.params.repo// the name the client asked for: <label>/<repoName> inside an organization, else <label>; a moved repo is served from its new placelet asked = ''if (label != '' && repoName.endsWith('.git')) {short = repoName.slice(0, repoName.length - 4)asked = orgBySlug(label) != null ? label + '/' + short : (short == label ? label : '')}if (asked == '') { return plain(404, 'no such repository') }let repo = repoBySlug(asked)if (repo == null && forwardOf(asked) != null) { repo = repoBySlug(forwardOf(asked)) }// WHO IS ASKING: a token as the password of a Basic header (private repos are read and pushed with it)pw = passwordOf(req.headers['authorization'])// 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// 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.let userId = nulllet keyAccess = nulllet appToken = falselet appRead = falseif (pw != null && pw.startsWith('idt_')) {who = identCheck(req)if (!who.ok) { return plain(who.status, who.error, who.status == 401 ? { 'WWW-Authenticate' = 'Basic realm="gitoria"' } : null) }let u = ensureUser(who.identity)if (u == null) { return plain(500, 'could not store the user') }if (u.name == '' && who.name != null && who.name != '') {setUserName(u.id, who.name)u = userRecord(u.id)}userId = u.idkeyAccess = who.access} else if (pw != null && pw.startsWith('gat_')) {// an APP's token (gitoria#42): READ of its one repo, never a push; for any other repo it is as good as no credentialfound = appOfToken(pw)appToken = found != nullappRead = found != null && repo != null && found.repoId == repo.id} else if (pw != null) {userId = userOfToken(pw)}// 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// 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.if (repo == null || !(appRead || mayRead(userId, repo))) {if (pw == null) { return plain(401, 'this repository needs a token: use it as the password', { 'WWW-Authenticate' = 'Basic realm="gitoria"' }) }return plain(404, 'no such repository')}slug = repo.sluglast = req.path.slice(req.path.lastIndexOf('/') + 1)advertise = last == 'refs'service = advertise ? (req.query != null ? req.query.service : null) : lastif (service != 'git-upload-pack' && service != 'git-receive-pack') { return plain(403, 'only the smart git protocol is served here: use git clone / fetch / push') }if (advertise && req.method != 'GET') { return plain(405, 'GET only') }if (!advertise && req.method != 'POST') { return plain(405, 'POST only') }if (req.body != null && req.body.length > maxBody) { return plain(413, 'that request is too big') }if (service == 'git-receive-pack') {realm = { 'WWW-Authenticate' = 'Basic realm="gitoria"' }if (appToken) { return plain(403, 'an app token is read-only: it can clone and fetch, not push') }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) }if (userId == null) { return plain(401, 'that token is not valid (removed, or mistyped)', realm) }if (keyAccess == 'read') { return plain(403, 'this ident access key is read-only: it can clone and fetch, not push') }if (!mayPush(userId, repo)) { return plain(403, 'only the owner or a member of this repository can push to it') }}// 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)if (service == 'git-receive-pack' && !advertise) { ensurePulls(slug) }let out = callGit(slug, service, advertise, req)if (out == null) { return plain(500, 'git gave no answer') }let headers = { 'Cache-Control' = 'no-cache, max-age=0, must-revalidate' 'Pragma' = 'no-cache' 'X-Content-Type-Options' = 'nosniff' }if (advertise) {headers['Content-Type'] = 'application/x-' + service + '-advertisement'// protocol v2 answers without the service banner; v0/v1 starts with it (as git http-backend does)v2 = protocolEnv(req).GIT_PROTOCOL != null && protocolEnv(req).GIT_PROTOCOL.includes('version=2')if (!v2) { out = pktLine('# service=' + service + NL) + '0000' + out }} else {headers['Content-Type'] = 'application/x-' + service + '-result'// a push arrived: tell the connected tickets project about commits naming a ticket (tickets.hl; never fails the push)if (service == 'git-receive-pack') {notifyPush(slug, false)// the pull request records follow the refs (numbers, refs/pull/N/head, the changes → pull-changes.log until gitoria#43)syncAndRaise(slug, userId)}}return new Response(out, { headers = headers })}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 34143d2cgitoria#46: closing brace of appComments lost in the mergemre
- 54927c9cgitoria#46: PR statuses and required checks before merge (merge w46-status)mre
- 187e1871gitoria#46: badges without decorative bordersmre
- 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
- 26a140e3gitoria#44: reviews, inline threads, replies, conversation for apps (merge w44-reviews)mre
- 888dbf87gitoria#44: unknown API paths answer the contract's JSON 404 and sit above the page routesmre
- ea587d90gitoria#44: reviews with inline threads, replies, resolve and the PR conversation for apps (lib/reviews.hl, tests/reviews.mjs)mre
- 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