git.ts
This file
Path
apps/platform/src/git.ts
272 lines · 7.9 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–3why, one step back1import { Brand } from "@repo/brand";2import { Custody } from "@repo/git/custody";3import { gateway, gitRoute, plain } from "@repo/git/gateway";Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 4why, one step back4import type { GitRoute } from "@repo/git/gateway";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 5–34why, one step back5import { concat, packetAt, pkt, utf8 } from "@repo/git/pkt-line";6import { readUpload } from "@repo/git/upload-pack";7import type { UploadRequest } from "@repo/git/upload-pack";8import { Upstream } from "@repo/git/upstream";9import type { Projects } from "@repo/project/projects";10import type { LayerAccess } from "@repo/project/visibility-port";11import { Anonymous, Principal } from "@repo/protocol/principal";12import { Effect, Option, Ref } from "effect";1314import {15 custodyFor,16 layerCustodyFor,17 layerRead,18 refuseAll,19} from "./adapters/custody.ts";20import { auditOf, credentialOf } from "./credential.ts";21import { LayerGate } from "./layer-gate.ts";22import type { LayerReach } from "./layer-gate.ts";23import { repoKind, RepoKind } from "./repo-names.ts";24import { Sessions } from "./sessions.ts";2526export type GitServices = Sessions | Projects | Upstream;2728const writes = (endpoint: string, url: URL) =>29 endpoint === "git-receive-pack" ||30 (endpoint === "info/refs" &&31 url.searchParams.get("service") === "git-receive-pack");3233const RESULT = "application/x-git-receive-pack-result";34Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 35why, one step back35// git asks its credential helper for a password only after a 401 that names Basic.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 36–120why, one step back36const signIn = (reason: string) =>37 plain(401, `${reason}; sign in with ${Brand.cli} login`, {38 "www-authenticate": `Basic realm="${Brand.name}"`,39 });4041const notFound = (name: string) => plain(404, `no repo ${name}`);4243const principalOf = (headers: Headers) =>44 Option.match(credentialOf(headers), {45 onNone: () => Effect.succeedSome<Principal>(Anonymous.make({})),46 onSome: (token) =>47 Sessions.use(({ verify }) => verify(token)).pipe(48 Effect.map(Option.map((person): Principal => person))49 ),50 });5152const mayRead = (principal: Principal, kind: RepoKind) =>53 RepoKind.$is("Canonical")(kind) || Principal.guards.Person(principal);5455const withNotices = (response: Response, notices: readonly string[]) =>56 Effect.gen(function* () {57 if (58 notices.length === 0 ||59 response.status !== 200 ||60 response.headers.get("content-type") !== RESULT61 ) {62 return response;63 }6465 const read = yield* Effect.option(66 Effect.tryPromise(() => response.arrayBuffer())67 );6869 if (Option.isNone(read)) {70 return plain(502, "the push's report was cut off");71 }7273 const reply = new Uint8Array(read.value);7475 const first = Option.flatten(Option.liftThrowable(packetAt)(reply, 0));7677 const banded = Option.exists(78 first,79 ({ packet }) =>80 packet !== "Flush" && packet[0] !== undefined && packet[0] <= 381 );8283 const body = banded84 ? concat([85 ...notices.map((line) =>86 pkt(concat([Uint8Array.of(2), utf8(`${line}\n`)]))87 ),88 reply,89 ])90 : reply;9192 return new Response(body, {93 headers: response.headers,94 status: response.status,95 });96 });9798const REACH = {99 none: 0,100 read: 1,101 write: 2,102} as const satisfies Record<LayerAccess, number>;103104const inflated = (bytes: Uint8Array, encoding: string | null) => {105 if (encoding === null) {106 return Effect.succeedSome(bytes);107 }108109 return encoding === "gzip"110 ? Effect.tryPromise(() =>111 new Response(112 new Response(bytes).body?.pipeThrough(new DecompressionStream("gzip"))113 ).arrayBuffer()114 ).pipe(115 Effect.map((read) => new Uint8Array(read)),116 Effect.option117 )118 : Effect.succeedNone;119};120Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 121–122why, one step back121// Read whole for the read log and sent on unchanged. A body in an encoding git never122// sends still counts as a read, so the log errs toward a read.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 123–152why, one step back123const uploadOf = (request: Request) =>124 Effect.gen(function* () {125 const read = yield* Effect.option(126 Effect.tryPromise(() => request.arrayBuffer())127 );128129 if (Option.isNone(read)) {130 return Option.none();131 }132133 const bytes = new Uint8Array(read.value);134135 const upload = Option.match(136 yield* inflated(bytes, request.headers.get("content-encoding")),137 {138 onNone: (): UploadRequest => ({ reads: true, want: Option.none() }),139 onSome: readUpload,140 }141 );142143 return Option.some({144 request: new Request(request.url, {145 body: bytes,146 headers: request.headers,147 method: request.method,148 }),149 upload,150 });151 });152Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 153–154why, one step back153// Every upload-pack request answered 200 is logged as a read, except a v2 `ls-refs`,154// which reads nothing, so a clone is one read.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 155–206why, one step back155const serveLayer = (156 request: Request,157 route: { readonly endpoint: string; readonly name: string },158 principal: Principal,159 { access, target }: LayerReach160) =>161 Effect.gen(function* () {162 const gate = yield* LayerGate;163 const pushing = writes(route.endpoint, new URL(request.url));164165 if (!Principal.guards.Person(principal)) {166 return signIn("a layer is read by its readers");167 }168169 if (REACH[access] < REACH[pushing ? "write" : "read"]) {170 return plain(171 403,172 `${principal.handle} may not ${pushing ? "push to" : "read"} ${route.name}`173 );174 }175176 const custody =177 route.endpoint === "git-receive-pack"178 ? yield* layerCustodyFor(principal, target)179 : refuseAll;180181 const served = (sent: Request) =>182 gateway(sent).pipe(183 Effect.provideService(Custody, custody),184 Effect.provideService(Upstream, gate.upstream)185 );186187 if (route.endpoint !== "git-upload-pack" || request.method !== "POST") {188 return yield* served(request);189 }190191 const fetched = yield* uploadOf(request);192193 if (Option.isNone(fetched)) {194 return plain(400, "the request could not be read");195 }196197 const { upload } = fetched.value;198 const response = yield* served(fetched.value.request);199200 if (upload.reads && response.status === 200) {201 yield* layerRead(principal, target, upload.want);202 }203204 return response;205 });206Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 207why, one step back207const serve = (request: Request, route: GitRoute, principal: Principal) =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 208why, one step back208 Effect.gen(function* () {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 209–211why, one step back209 if (Option.isNone(route.repo)) {210 return notFound(route.name);211 }Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
line 212why, one step back212Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 213–215why, one step back213 const repo = route.repo.value;214 const kind = repoKind(repo);215Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 216–217why, one step back216 if (RepoKind.$is("Unknown")(kind)) {217 const layer = yield* LayerGate.use((gate) =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 218why, one step back218 gate.classify(repo, principal)Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 219–248why, one step back219 );220221 return yield* Option.match(layer, {222 onNone: () => Effect.succeed(notFound(route.name)),223 onSome: (reach) => serveLayer(request, route, principal, reach),224 });225 }226227 const pushing = writes(route.endpoint, new URL(request.url));228229 if (pushing && !Principal.guards.Person(principal)) {230 return signIn("a push needs a signed-in person");231 }232233 if (!mayRead(principal, kind)) {234 return signIn("a fork is read by signed-in people");235 }236237 const notices = yield* Ref.make<readonly string[]>([]);238239 const custody =240 route.endpoint === "git-receive-pack"241 ? yield* custodyFor(242 principal,243 kind,244 (line) => Ref.update(notices, (said) => [...said, line]),245 auditOf(request.headers)246 )247 : refuseAll;248Merge observability into mainoscabrielbefore adoption1985111
line 249why, one step back249 const served = gateway(request).pipe(Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 250–251why, one step back250 Effect.provideService(Custody, custody)251 );Merge observability into mainoscabrielbefore adoption1985111
lines 252–257why, one step back252253 const response = yield* route.endpoint === "git-receive-pack"254 ? served.pipe(255 Effect.withSpan("Gateway.push", { attributes: { target: kind._tag } })256 )257 : served;Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 258–264why, one step back258259 return yield* withNotices(response, yield* Ref.get(notices));260 });261262export const serveGit = (263 request: Request264): Option.Option<Effect.Effect<Response, never, GitServices>> =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 265why, one step back265 Option.map(gitRoute(new URL(request.url).pathname), (route) =>Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 266–268why, one step back266 Effect.flatMap(principalOf(request.headers), (principal) =>267 Option.match(principal, {268 onNone: () => Effect.succeed(signIn("that token is not one we know")),Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 269why, one step back269 onSome: (known) => serve(request, route, known),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 270–272why, one step back270 })271 )272 );