Skip to content
Myr

upstream.test.ts

This file

Path

packages/git/test/upstream.test.ts

275 lines · 7.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take 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–275why, one step back
1import { describe, expect, it } from "@effect/vitest";
2import { Fetch, FetchFailed } from "@repo/artifacts/fetch";3import { RepoHost, RepoName, RepoNotFound } from "@repo/artifacts/repo-host";4import type { TokenScope } from "@repo/artifacts/repo-host";5import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";6import {7 DateTime,8 Duration,9 Effect,10 Layer,11 Redacted,12 Ref,13 Stream,14} from "effect";15import { TestClock } from "effect/testing";1617import { Exchange, Upstream, UpstreamFailure } from "../src/upstream.ts";18import { UpstreamRepoHost } from "../src/upstream/repo-host.ts";1920const repo = RepoName.make("demo");2122interface Minted {23 readonly scope: TokenScope;24 readonly secret: string;25 readonly expiresAt: DateTime.Utc;26}2728interface Seen {29 readonly requests: Ref.Ref<readonly Request[]>;30 readonly minted: Ref.Ref<readonly Minted[]>;31}3233const store = (minted: Seen["minted"]) =>34 Layer.effect(35 RepoHost,36 Effect.gen(function* () {37 const host = yield* RepoHost;3839 return RepoHost.of({40 ...host,41 mintToken: (name, scope, ttl) =>42 Effect.gen(function* () {43 const token = yield* host.mintToken(name, scope, ttl);44 const secret = Redacted.value(token.secret);4546 yield* Ref.update(minted, (all) => [47 ...all,48 { expiresAt: token.expiresAt, scope, secret },49 ]);5051 return {52 ...token,53 secret: Redacted.make(54 `${secret}?expires=${DateTime.toEpochMillis(token.expiresAt) / 1000}`55 ),56 };57 }),58 });59 })60 ).pipe(Layer.provide(RepoHostMemory));6162const recording = (requests: Seen["requests"]) =>63 Layer.succeed(64 Fetch,65 Fetch.of({66 fetch: (request) =>67 Ref.update(requests, (all) => [...all, request]).pipe(68 Effect.as(new Response("upstream"))69 ),70 })71 );7273const world = (seen: Seen) =>74 UpstreamRepoHost.pipe(75 Layer.provideMerge(76 Layer.mergeAll(store(seen.minted), recording(seen.requests))77 )78 );7980const advertise = Exchange.Advertise({81 headers: new Headers({ "git-protocol": "version=2" }),82 service: "git-upload-pack",83});8485const withUpstream = <A, E>(86 body: (seen: Seen) => Effect.Effect<A, E, Upstream | RepoHost>87) =>88 Effect.gen(function* () {89 const seen: Seen = {90 minted: yield* Ref.make<readonly Minted[]>([]),91 requests: yield* Ref.make<readonly Request[]>([]),92 };9394 return yield* Effect.gen(function* () {95 yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);9697 return yield* body(seen);98 }).pipe(Effect.provide(world(seen)));99 });100101const basic = (secret: string) => `Basic ${btoa(`x:${secret}`)}`;102103const sent = (request: Request) => ({104 authorization: request.headers.get("authorization"),105 method: request.method,106 protocol: request.headers.get("git-protocol"),107 url: request.url,108});109110describe("the upstream over RepoHost", () => {111 it.effect(112 "advertises refs at the repo's remote with a minted read token",113 () =>114 withUpstream((seen) =>115 Effect.gen(function* () {116 const upstream = yield* Upstream;117 const response = yield* upstream.exchange(repo, advertise);118 const remote = yield* RepoHost.use((host) => host.remote(repo));119 const minted = yield* Ref.get(seen.minted);120121 expect(yield* Effect.promise(() => response.text())).toBe("upstream");122 expect({123 requests: (yield* Ref.get(seen.requests)).map(sent),124 scopes: minted.map(({ scope }) => scope),125 }).toStrictEqual({126 requests: [127 {128 authorization: basic(minted[0]?.secret ?? ""),129 method: "GET",130 protocol: "version=2",131 url: `${remote}/info/refs?service=git-upload-pack`,132 },133 ],134 scopes: ["read"],135 });136 })137 )138 );139140 it.effect("posts a receive-pack call with a write token", () =>141 withUpstream((seen) =>142 Effect.gen(function* () {143 const upstream = yield* Upstream;144 const remote = yield* RepoHost.use((host) => host.remote(repo));145146 yield* upstream.exchange(147 repo,148 Exchange.Call({149 body: Stream.toReadableStream(150 Stream.make(new TextEncoder().encode("0000"))151 ),152 headers: new Headers({153 "content-type": "application/x-git-receive-pack-request",154 }),155 service: "git-receive-pack",156 })157 );158159 const [request] = yield* Ref.get(seen.requests);160 const minted = yield* Ref.get(seen.minted);161162 expect({163 request: request === undefined ? undefined : sent(request),164 scopes: minted.map(({ scope }) => scope),165 }).toStrictEqual({166 request: {167 authorization: basic(minted[0]?.secret ?? ""),168 method: "POST",169 protocol: null,170 url: `${remote}/git-receive-pack`,171 },172 scopes: ["write"],173 });174 expect(175 yield* Effect.promise(() => request?.text() ?? Promise.resolve(""))176 ).toBe("0000");177 })178 )179 );180181 it.effect(182 "mints once while the token lasts, and again a minute before it expires",183 () =>184 withUpstream((seen) =>185 Effect.gen(function* () {186 const upstream = yield* Upstream;187188 yield* upstream.exchange(repo, advertise);189 yield* upstream.exchange(repo, advertise);190191 const first = yield* Ref.get(seen.minted);192193 expect(first).toHaveLength(1);194195 const lasts = Duration.subtract(196 DateTime.distance(197 yield* DateTime.now,198 first[0]?.expiresAt ?? DateTime.makeUnsafe(0)199 ),200 Duration.seconds(60)201 );202203 yield* TestClock.adjust(204 Duration.subtract(lasts, Duration.seconds(1))205 );206 yield* upstream.exchange(repo, advertise);207208 expect(yield* Ref.get(seen.minted)).toHaveLength(1);209210 yield* TestClock.adjust(Duration.seconds(1));211 yield* upstream.exchange(repo, advertise);212213 const minted = yield* Ref.get(seen.minted);214 const requests = yield* Ref.get(seen.requests);215216 expect(minted).toHaveLength(2);217 expect(requests.at(-1)?.headers.get("authorization")).toBe(218 basic(minted[1]?.secret ?? "")219 );220 })221 )222 );223224 it.effect("calls a request that got no response an UpstreamFailure", () =>225 Effect.gen(function* () {226 const unreachable = Layer.succeed(227 Fetch,228 Fetch.of({229 fetch: (request) =>230 Effect.fail(231 new FetchFailed({ reason: "connection reset", url: request.url })232 ),233 })234 );235236 const minted = yield* Ref.make<readonly Minted[]>([]);237238 const failure = yield* Effect.gen(function* () {239 yield* RepoHost.use((host) => host.create(repo)).pipe(Effect.orDie);240241 return yield* Upstream.use((upstream) =>242 upstream.exchange(repo, advertise)243 ).pipe(Effect.flip);244 }).pipe(245 Effect.provide(246 UpstreamRepoHost.pipe(247 Layer.provideMerge(Layer.mergeAll(store(minted), unreachable))248 )249 )250 );251252 expect(failure).toStrictEqual(253 new UpstreamFailure({ reason: "connection reset", repo })254 );255 })256 );257258 it.effect("passes RepoNotFound through for a repo the store lacks", () =>259 withUpstream(() =>260 Effect.gen(function* () {261 const upstream = yield* Upstream;262 const missing = RepoName.make("missing");263264 expect(265 yield* upstream.exchange(missing, advertise).pipe(266 Effect.match({267 onFailure: (error) => error,268 onSuccess: () => "forwarded",269 })270 )271 ).toStrictEqual(new RepoNotFound({ name: missing }));272 })273 )274 );275});