gitoria
All repositories: gitoria
6.9 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.// * 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).// * No hook: pull requests and releases are read from the commits when their page is built.// 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 { repoDir, tmpDir } from './git.hl'import { notifyPush } from './tickets.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 ' + 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 ' + service.slice(4) + ' --stateless-rpc "$1" > "$3"' : 'exec git ' + 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'])userId = pw != null ? userOfToken(pw) : null// 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 || !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 (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 (!mayPush(userId, repo)) { return plain(403, 'only the owner or a member of this repository can push to it') }}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) }}return new Response(out, { headers = headers })}
Branches
Latest commits
- 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
- e307d69agitoria: say what is per process during the hand-overmre
- f0cbe6a6gitoria: standby service on port 45014 and a deploy that hands over through it without a gapmre
- 727cd083gitoria#25: README: vendor notes for Hybriel c1b1010f and the page cachemre
- 61b72dedgitoria#25: re-vendor Hybriel master c1b1010f (W149 page cache), key the repo Readme page by slug and main commit, extend the readme-cache gatemre
- 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
- bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
- 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
- 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
- 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
- 2a2fdd77gs: C2 check before cookie experimentsmre
- 76e0587aWIP gs 2mre
- a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
- 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre