credential-helper.test.ts
This file
Path
apps/cli/test/local/credential-helper.test.ts
479 lines · 14.1 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
1import { NodeHttpServer, NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Client } from "@repo/protocol/contracts";5import { gitOk, spawn } from "@repo/testkit/git";6import { httpBackend } from "@repo/testkit/http-backend";7import {8 ConfigProvider,9 Context,10 Effect,11 Exit,12 FileSystem,13 Layer,14 Option,15 Path,16 Predicate,17 Queue,18 Redacted,19 Ref,20 Schema,21 Sink,22 Stdio,23 Stream,24 Terminal,25} from "effect";26import type { Cause } from "effect";27import { CliOutput } from "effect/cli";28import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";29import type { ChildProcessSpawner } from "effect/process";30import { TestConsole } from "effect/testing";3132import { credentialHelper, currentEnv } from "../../src/credential-helper.ts";33import { Credentials, CredentialsFile } from "../../src/credentials.ts";34import type { Profile } from "../../src/credentials.ts";35import { program } from "../../src/main.ts";36import { OutputPlain } from "../../src/output.ts";3738const SLUG = Brand.slug.toUpperCase();3940const token = "t0ken-0123456789abcdefghijklmnopqrstuvwxyz";4142const platform: Profile = {43 token: Redacted.make(token),44 url: "https://platform.test",45};4647const asked = (host: string, protocol = "https") =>48 `protocol=${protocol}\nhost=${host}\npath=datekit--fix-week--alice.git\n\n`;4950const pi = { AI_AGENT: "pi", PI_MODEL: "kimi-k3" };5152const encoder = new TextEncoder();5354const decoder = new TextDecoder();5556const credentialsIn = (env: Record<string, string>) =>57 CredentialsFile.pipe(58 Layer.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))59 );6061const storedIn = (profiles: Readonly<Record<string, Profile>>) =>62 Effect.gen(function* () {63 const fs = yield* FileSystem.FileSystem;64 const dir = yield* fs.makeTempDirectoryScoped();65 const env = { HOME: "/nonexistent", XDG_CONFIG_HOME: dir };6667 const credentials = yield* Effect.provide(68 Effect.service(Credentials),69 credentialsIn(env)70 );7172 for (const [name, profile] of Object.entries(profiles)) {73 yield* credentials.put(name, profile);74 }7576 return env;77 });7879const noTerminal = Layer.succeed(80 Terminal.Terminal,81 Terminal.make({82 columns: Effect.die("the helper read the terminal's width"),83 display: () => Effect.die("the helper wrote to the terminal"),84 readInput: Effect.die("the helper read the terminal"),85 readLine: Effect.die("the helper prompted on the terminal"),86 rows: Effect.die("the helper read the terminal's height"),87 })88);8990const helper = (91 op: string,92 stdin: Stream.Stream<Uint8Array>,93 env: Record<string, string>94) =>95 Effect.gen(function* () {96 const written = yield* Queue.unbounded<string | Uint8Array, Cause.Done>();9798 const stdio = Stdio.layerTest({99 stdin,100 stdout: () => Sink.fromQueue(written),101 });102103 const exit = yield* Effect.exit(104 program(["credential", op]).pipe(105 Effect.provide(106 // The test stdio and terminal come last, so they stand in for Node's.107 Layer.mergeAll(108 Layer.mergeAll(109 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),110 Layer.mock(Client)({}),111 OutputPlain,112 credentialsIn(env),113 ConfigProvider.layer(ConfigProvider.fromEnv({ env }))114 ).pipe(Layer.provideMerge(NodeServices.layer)),115 stdio,116 noTerminal117 )118 )119 )120 );121122 const stderr = (yield* TestConsole.errorLines).map(String);123124 const stdout = (yield* Queue.clear(written))125 .map((chunk) =>126 Predicate.isString(chunk) ? chunk : decoder.decode(chunk)127 )128 .join("");129130 return { ok: Exit.isSuccess(exit), stderr, stdout };131 }).pipe(Effect.provide(TestConsole.layer));132133const input = (text: string) => Stream.make(encoder.encode(text));134135describe(`${Brand.cli} credential, git's credential helper`, () => {136 it.live(137 "hands git the stored token for the platform's host, with the harness as audit metadata in the username",138 () =>139 Effect.gen(function* () {140 const env = yield* storedIn({ default: platform });141142 const ran = yield* helper("get", input(asked("platform.test")), {143 ...env,144 ...pi,145 });146147 expect(ran).toStrictEqual({148 ok: true,149 stderr: [],150 stdout: `username=audit;harness=pi&model=kimi-k3\npassword=${token}\n`,151 });152 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))153 );154155 it.live("says nothing for another host, so git asks its next helper", () =>156 Effect.gen(function* () {157 const env = yield* storedIn({ default: platform });158159 const ran = yield* helper("get", input(asked("github.com")), {160 ...env,161 ...pi,162 });163164 expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });165 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))166 );167168 it.live("never hands the token to the platform's host over plain http", () =>169 Effect.gen(function* () {170 const env = yield* storedIn({ default: platform });171172 const ran = yield* helper(173 "get",174 input(asked("platform.test", "http")),175 env176 );177178 expect(ran.ok).toBeTruthy();179 expect(ran.stdout).toBe("");180 expect(ran.stderr.join("\n")).not.toContain(token);181 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))182 );183184 it.live(185 "with no login, says nothing to git and one line to the person naming login",186 () =>187 Effect.gen(function* () {188 const env = yield* storedIn({});189190 const ran = yield* helper("get", input(asked("platform.test")), env);191192 expect(ran.ok).toBeTruthy();193 expect(ran.stdout).toBe("");194 expect(ran.stderr).toHaveLength(1);195 expect(ran.stderr[0]).toContain(`${Brand.cli} login`);196 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))197 );198199 it.live(200 "under a named profile, answers only as that person, never with another profile's token on the host",201 () =>202 Effect.gen(function* () {203 const bob: Profile = {204 token: Redacted.make("bob-token-0123456789abcdefghijklmnopqrstuv"),205 url: "https://elsewhere.test",206 };207208 const env = yield* storedIn({ alice: platform, bob });209210 const asBob = yield* helper("get", input(asked("platform.test")), {211 ...env,212 [`${SLUG}_PROFILE`]: "bob",213 });214215 const asCarol = yield* helper("get", input(asked("platform.test")), {216 ...env,217 [`${SLUG}_PROFILE`]: "carol",218 });219220 expect({ asBob, asCarol: asCarol.stdout }).toStrictEqual({221 asBob: { ok: true, stderr: [], stdout: "" },222 asCarol: "",223 });224 expect(asCarol.stderr).toHaveLength(1);225 expect(asCarol.stderr[0]).toContain(226 `${Brand.cli} login --profile carol`227 );228 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))229 );230231 it.live.each(["store", "erase"])(232 "%s reads what git sends, prints nothing and keeps the stored token",233 (op) =>234 Effect.gen(function* () {235 const env = yield* storedIn({ default: platform });236237 const ran = yield* helper(238 op,239 input(`${asked("platform.test")}username=x\npassword=${token}\n\n`),240 env241 );242243 expect(ran).toStrictEqual({ ok: true, stderr: [], stdout: "" });244245 const kept = yield* Effect.provide(246 Effect.flatMap(247 Effect.service(Credentials),248 (stored) => stored.current249 ),250 credentialsIn(env)251 );252253 expect(254 Option.map(kept, (profile) => Redacted.value(profile.token))255 ).toStrictEqual(Option.some(token));256 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))257 );258259 it.live(260 "answers at the blank line without reading further, even if stdin never ends",261 () =>262 Effect.gen(function* () {263 const env = yield* storedIn({ default: platform });264265 const endless = Stream.concat(266 input(asked("platform.test")),267 Stream.never268 );269270 const pastTheEnd = Stream.concat(271 input(asked("platform.test")),272 Stream.die("the helper read past the blank line")273 );274275 for (const stdin of [endless, pastTheEnd]) {276 const ran = yield* helper("get", stdin, env);277278 expect(ran.stdout).toBe(`username=audit;\npassword=${token}\n`);279 }280 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))281 );282});283284describe(credentialHelper, () => {285 it.live(286 "names no harness when none runs it, and answers from the profile on the asked host",287 () =>288 Effect.gen(function* () {289 const env = yield* storedIn({290 default: {291 token: Redacted.make("other-token"),292 url: "https://x.test",293 },294 platform,295 });296297 const stdout = yield* credentialHelper(298 "get",299 asked("platform.test"),300 {}301 ).pipe(Effect.provide(credentialsIn(env)));302303 expect(stdout).toBe(`username=audit;\npassword=${token}\n`);304 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))305 );306});307308describe("the env the CLI sees", () => {309 it.effect(310 "reads the env in a bounded walk, even with a huge number in a name",311 () =>312 Effect.gen(function* () {313 const source = ConfigProvider.fromEnv({314 env: { AI_AGENT: "pi", RUN_0: "first", RUN_100000: "far" },315 });316317 const reads = yield* Ref.make(0);318319 const counted = ConfigProvider.make((at) =>320 Effect.andThen(321 Ref.update(reads, (n) => n + 1),322 source.load(at)323 )324 );325326 const read = yield* currentEnv.pipe(327 Effect.provideService(ConfigProvider.ConfigProvider, counted)328 );329330 expect(read).toStrictEqual({ AI_AGENT: "pi", RUN_0: "first" });331 expect(yield* Ref.get(reads)).toBeLessThan(2000);332 })333 );334});335336const Basic = /^Basic (?<encoded>\S+)$/u;337338const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);339340// A request without credentials gets the 401 that makes git ask its helper.341const guarded = (root: string) =>342 Effect.gen(function* () {343 const spawner =344 yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();345346 const seen = yield* Ref.make<readonly { user: string; password: string }[]>(347 []348 );349350 const backend = httpBackend(root);351352 const app = Effect.gen(function* () {353 const request = yield* HttpServerRequest.toWeb(354 yield* HttpServerRequest.HttpServerRequest355 );356357 const pair = Option.fromNullishOr(358 Basic.exec(request.headers.get("authorization") ?? "")?.groups?.encoded359 ).pipe(Option.flatMap(fromBase64));360361 if (Option.isNone(pair)) {362 return HttpServerResponse.text("sign in", {363 headers: { "www-authenticate": 'Basic realm="test"' },364 status: 401,365 });366 }367368 const colon = pair.value.indexOf(":");369370 yield* Ref.update(seen, (all) => [371 ...all,372 {373 password: pair.value.slice(colon + 1),374 user: pair.value.slice(0, colon),375 },376 ]);377378 return HttpServerResponse.fromWeb(379 yield* Effect.scoped(backend(request)).pipe(Effect.provide(spawner))380 );381 }).pipe(Effect.orDie);382383 const server = yield* Layer.build(384 HttpServer.serve(app).pipe(Layer.provideMerge(NodeHttpServer.layerTest))385 ).pipe(Effect.orDie);386387 const { address } = Context.get(server, HttpServer.HttpServer);388389 const origin =390 "port" in address391 ? `http://127.0.0.1:${address.port}`392 : yield* Effect.die("the test server listens on a socket, not a port");393394 return { origin, seen: Ref.get(seen) };395 });396397describe("real git with the helper", () => {398 it.live(399 "git ls-remote sends the stored token as the basic-auth password, with no token in the url",400 () =>401 Effect.gen(function* () {402 const fs = yield* FileSystem.FileSystem;403 const path = yield* Path.Path;404 const root = yield* fs.makeTempDirectoryScoped();405 const work = yield* fs.makeTempDirectoryScoped();406407 yield* gitOk(408 root,409 "init",410 "--quiet",411 "--bare",412 "-b",413 "main",414 "demo.git"415 );416 yield* gitOk(work, "init", "--quiet", "-b", "main");417 yield* gitOk(work, "commit", "--quiet", "--allow-empty", "-m", "first");418 yield* gitOk(419 work,420 "push",421 "--quiet",422 path.join(root, "demo.git"),423 "main"424 );425426 const head = yield* gitOk(work, "rev-parse", "HEAD");427 const server = yield* guarded(root);428429 const env = yield* storedIn({430 default: { token: Redacted.make(token), url: server.origin },431 });432433 const bin = yield* path.fromFileUrl(434 new URL("../../src/bin.ts", import.meta.url)435 );436437 const child = yield* spawn(438 "git",439 [440 "-c",441 "credential.helper=",442 "-c",443 `credential.helper=!bun '${bin}' credential`,444 "ls-remote",445 `${server.origin}/demo.git`,446 ],447 {448 cwd: work,449 env: {450 ...env,451 ...pi,452 [`${SLUG}_PROFILE`]: "",453 [`${SLUG}_TOKEN`]: "",454 [`${SLUG}_URL`]: "",455 PI_PROVIDER: "",456 PI_SESSION_ID: "",457 },458 }459 );460461 const [stdout, stderr, exitCode] = yield* Effect.all(462 [463 child.stdout.pipe(Stream.decodeText(), Stream.mkString),464 child.stderr.pipe(Stream.decodeText(), Stream.mkString),465 child.exitCode,466 ],467 { concurrency: "unbounded" }468 );469470 expect({ exitCode, stderr }).toStrictEqual({ exitCode: 0, stderr: "" });471 expect(stdout).toBe(`${head}\tHEAD\n${head}\trefs/heads/main\n`);472 expect(yield* server.seen).toContainEqual({473 password: token,474 user: "audit;harness=pi&model=kimi-k3",475 });476 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),477 30_000478 );479});