Skip to content
Myr

Answer git only as the profile it names, and log a named profile in only where it says

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Review of 412 against its issue and AGENTS.md; each finding fixed test-first at the issue's seams. - credential-helper.ts: under `<SLUG>_PROFILE` only that profile answers. `forHost` falls back to any profile on the host, so a swarm agent run as bob (bob on another platform) or carol (no login) was handed alice's token and pushed as alice. The helper now fails closed for a named person and its stderr line names `login --profile <name>`; without `<SLUG>_PROFILE`, `forHost` still picks the profile on the host. - credential-helper.ts: `currentEnv` reads at most 1,024 indices under one all-numeric level. The config provider reports such a level by its largest index only, so an env name like `RUN_2000000` cost every helper call 7.6 s (measured) and `X_4294967294` hung. No harness marker ends in a number, and the binary's git child still gets the whole process env. - login.ts: `login --profile <other>` with no `--url` asked the platform of the current profile; it now asks for `--url` unless the profile named is the current one (`Credentials` reads back only that one). - login.ts: `--json` carries `gitConfig` (the lines) and `gitConfigSet` even under `--no-git-config`, where it had sent `[]` while the text listed the lines to run. - login.ts: logout unsets every `useHttpPath` value (`--unset-all`; `--unset` exits 5 on two, which read as already gone); printed shell lines escape `'`. - Tests added: credential-helper.test.ts (a named profile never answers with another's token, and a missing one gets the login note; the env walk is bounded with `RUN_100000` set); login.test.ts (re-login of the current profile without --url, another profile asked for --url; --no-git-config leaves git alone and returns the lines in --json; useHttpPath set twice is removed; a quote in the url is escaped in the printed lines). Each was red by assertion first. The browser test now reads `opened` after the join, not racing the open. - Left as judgement calls (issue Comments 16): the callback query and git's request are read with URLSearchParams and a line split rather than a Schema; SLUG and test helpers repeat across files the territory keeps apart. - bun run fix && bun run verify green: cli 69 tests; debt at baseline.

authored by oscabriel · committed by oscabriel · parent 150cedd · Browse files · 4 files+246 added−46 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+246 added−46 removed

  • tests:+177 added−27 removed
  • other:+69 added−19 removed

4 files+246 added−46 removed

modified:apps/cli/src/local/login.ts+22 added-7 removed
204 unmodified lines
205 if (arg === "") {206 return '""';207 }208209 return /^[\w./:@=-]+$/u.test(arg) ? arg : `'${arg}'`;209 return /^[\w./:@=-]+$/u.test(arg)210 ? arg211 : `'${arg.replaceAll("'", String.raw`'\''`)}'`;212 })213 .join(" ");214215/** Runs one `git config` argv list; `allowed` are the exit codes that mean done. */
47 unmodified lines
263 onSome: ({ origin }) => Effect.succeed(origin),264 }265 );266265/** The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's own. */267/**268 * The platform to log in to: `--url`, else `<SLUG>_URL`, else the profile's269 * own. `Credentials` reads back only the current profile, so another270 * profile named by `--profile` needs `--url`: it is never logged in to the271 * current profile's platform by default.272 */273const platformOf = (274 flag: Option.Option<string>,275 profile: Option.Option<string>,276 env: Readonly<Record<string, string>>277) =>278 Effect.gen(function* () {279 const named = Option.orElse(flag, () =>
3 unmodified lines
283 if (Option.isSome(named)) {284 return yield* originOf(named.value);285 }286279 const current = yield* (yield* Credentials).current;287 const name = profileName(profile, env);288289 const current =290 name === profileName(Option.none(), env)291 ? yield* (yield* Credentials).current292 : Option.none<Profile>();293294 if (Option.isSome(current)) {295 return yield* originOf(current.value.url);296 }297298 return yield* new LoginUsage({286 reason: `no platform to log in to: run ${Brand.cli} login --url https://<platform host>`,299 reason: `no platform to log in to for profile ${name}: run ${Brand.cli} login --url https://<platform host>${Option.isSome(profile) ? ` --profile ${name}` : ""}`,300 });301 });302303// --- The token, by one of two ways.
283 unmodified lines
587 const output = yield* Output;588 const credentials = yield* Credentials;589 const env = yield* currentEnv;590 const name = profileName(given.profile, env);578 const url = yield* platformOf(given.url, env);591 const url = yield* platformOf(given.url, given.profile, env);592593 const token = given.tokenStdin594 ? yield* tokenFromStdin595 : yield* tokenFromBrowser(
26 unmodified lines
622623 yield* output.success({624 command: "login",625 data: {613 gitConfig: given.noGitConfig ? [] : commands,626 // The lines, set or not: under --no-git-config they are what to run.627 gitConfig: commands,628 gitConfigSet: !given.noGitConfig,629 ...Option.match(handle, {630 onNone: () => ({}),631 onSome: (known) => ({ handle: known }),632 }),
17 unmodified lines
650651/** The `git config --global` lines that undo `gitHelperConfig(url)`; exit 5 means already gone. */652const gitHelperUnset = (url: string): readonly (readonly string[])[] => [653 ["git", "config", "--global", "--unset-all", `credential.${url}.helper`],639 ["git", "config", "--global", "--unset", `credential.${url}.useHttpPath`],654 ["git", "config", "--global", "--unset-all", `credential.${url}.useHttpPath`],655];656657const HELPER_KEY = /^credential\.(?<url>.+)\.helper$/u;658
79 unmodified lines
modified:apps/cli/src/credential-helper.ts+47 added-12 removed
35 unmodified lines
3637/** The env, by name: what `detectHarness` reads. */38export type Env = Readonly<Record<string, string | undefined>>;3940/**41 * The most indices the walk reads under one name. The config provider tells42 * an all-numeric level only its largest index, so a name like43 * `RUN_4294967294` would have the walk count to four billion on every git44 * call; names with an index past this are not read. No harness marker ends45 * in a number, and the binary's git child gets the process env whole.46 */47const INDEX_LIMIT = 1024;4849/** The env-name parts below `path` and their values, from the CLI's config provider. */50const namesBelow = (51 provider: ConfigProvider.ConfigProvider,52 path: ConfigProvider.Path
11 unmodified lines
64 : [];6566 const children = Match.valueTags(node, {67 Array: ({ length }) =>59 Array.from({ length }, (_, at) => String(at)),68 Array.from({ length: Math.min(length, INDEX_LIMIT) }, (_, at) =>69 String(at)70 ),71 Record: ({ keys }) => [...keys],72 Value: () => [],73 });74
38 unmodified lines
113114 return fields;115};116106/** `url`'s scheme without its colon, if it is a URL. */107const schemeOf = Option.liftThrowable((url: string) =>108 new URL(url).protocol.replace(/:$/u, "")109);117/** The env names the CLI reads, spelled from the brand: `<SLUG>_PROFILE`. */118const SLUG = Brand.slug.toUpperCase();119120/** `url`'s scheme without its colon, and its `host[:port]` in lowercase, if it is a URL. */121const placeOf = Option.liftThrowable((url: string) => {122 const { host, protocol } = new URL(url);123124 return { host: host.toLowerCase(), scheme: protocol.replace(/:$/u, "") };125});126127/** A value git's credential protocol can carry: one line, no NUL. */128const fitsOneLine = (value: string) => !/[\n\r\0]/u.test(value);129130/** What the helper prints: for git on stdout, and maybe a line for a person on stderr. */
5 unmodified lines
136const silent: Answer = { note: Option.none(), stdout: "" };137138/**139 * The helper's answer to `op` with git's `input`. `get` answers only for a124 * host a profile is on, over that profile's scheme; with no login at all it125 * also says, once, how to log in. `store` and `erase` do nothing: the stored126 * token changes only through `login` and `logout`.140 * host a profile is on, over that profile's scheme. Under `<SLUG>_PROFILE`141 * only that profile may answer: it names the person git acts for, so the142 * helper never hands over another person's token for the same host. With no143 * login for the profile in use, it also says, once, how to log in. `store`144 * and `erase` do nothing: the stored token changes only through `login`145 * and `logout`.146 */147const answer = (op: Operation, input: string, env: Env) =>148 Effect.gen(function* () {149 if (op !== "get") {
9 unmodified lines
159 }160161 const credentials = yield* Credentials;162163 const named = Option.filter(164 Option.fromNullishOr(env[`${SLUG}_PROFILE`]),165 (name) => name !== ""166 );167168 const candidate = Option.isSome(named)169 ? yield* credentials.current170 : yield* credentials.forHost(host);171172 const profile = Option.filter(145 yield* credentials.forHost(host),173 candidate,174 ({ token, url }) =>147 Option.contains(schemeOf(url), protocol) &&148 fitsOneLine(Redacted.value(token))175 Option.exists(176 placeOf(url),177 (at) => at.scheme === protocol && at.host === host.toLowerCase()178 ) && fitsOneLine(Redacted.value(token))179 );180181 if (Option.isSome(profile)) {182 return {
1 unmodified line
184 stdout: `username=${auditUser(detectHarness(env))}\npassword=${Redacted.value(profile.value.token)}\n`,185 } satisfies Answer;186 }187188 const flag = Option.match(named, {189 onNone: () => "",190 onSome: (name) => ` --profile ${name}`,191 });192193 return Option.isNone(yield* credentials.current)194 ? {195 note: Option.some(161 `no ${Brand.cli} login for ${host}: run ${Brand.cli} login --url ${protocol}://${host}`196 `no ${Brand.cli} login for ${host}: run ${Brand.cli} login${flag} --url ${protocol}://${host}`197 ),198 stdout: "",199 }200 : silent;
63 unmodified lines
modified:apps/cli/test/local/credential-helper.test.ts+61 added-1 removed
27 unmodified lines
28import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";29import type { ChildProcessSpawner } from "effect/process";30import { TestConsole } from "effect/testing";3132import { credentialHelper } from "../../src/credential-helper.ts";32import { 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";
172 unmodified lines
209 expect(ran.stderr[0]).toContain(`${Brand.cli} login`);210 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))211 );212213 it.live(214 "under a named profile, answers only as that person, never with another profile's token on the host",215 () =>216 Effect.gen(function* () {217 const bob: Profile = {218 token: Redacted.make("bob-token-0123456789abcdefghijklmnopqrstuv"),219 url: "https://elsewhere.test",220 };221222 const env = yield* storedIn({ alice: platform, bob });223224 const asBob = yield* helper("get", input(asked("platform.test")), {225 ...env,226 [`${SLUG}_PROFILE`]: "bob",227 });228229 const asCarol = yield* helper("get", input(asked("platform.test")), {230 ...env,231 [`${SLUG}_PROFILE`]: "carol",232 });233234 expect({ asBob, asCarol: asCarol.stdout }).toStrictEqual({235 asBob: { ok: true, stderr: [], stdout: "" },236 asCarol: "",237 });238 expect(asCarol.stderr).toHaveLength(1);239 expect(asCarol.stderr[0]).toContain(240 `${Brand.cli} login --profile carol`241 );242 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))243 );244245 it.live.each(["store", "erase"])(246 "%s reads what git sends, prints nothing and keeps the stored token",247 (op) =>248 Effect.gen(function* () {
69 unmodified lines
318 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))319 );320});321322describe("the env the CLI sees", () => {323 it.effect(324 "reads the env in a bounded walk, even with a huge number in a name",325 () =>326 Effect.gen(function* () {327 const source = ConfigProvider.fromEnv({328 env: { AI_AGENT: "pi", RUN_0: "first", RUN_100000: "far" },329 });330331 const reads = yield* Ref.make(0);332333 const counted = ConfigProvider.make((at) =>334 Effect.andThen(335 Ref.update(reads, (n) => n + 1),336 source.load(at)337 )338 );339340 const read = yield* currentEnv.pipe(341 Effect.provideService(ConfigProvider.ConfigProvider, counted)342 );343344 expect(read).toStrictEqual({ AI_AGENT: "pi", RUN_0: "first" });345 expect(yield* Ref.get(reads)).toBeLessThan(2000);346 })347 );348});349350const Basic = /^Basic (?<encoded>\S+)$/u;351352const fromBase64 = Schema.decodeOption(Schema.StringFromBase64);353
144 unmodified lines
modified:apps/cli/test/local/login.test.ts+116 added-26 removed
55 unmodified lines
56 `git config --global --add credential.${at}.helper ${Brand.slug}`,57 `git config --global credential.${at}.useHttpPath true`,58];5960/** The same three, as the argv lists `--json` carries. */61const helperArgv = (at: string) => [62 ["git", "config", "--global", "--replace-all", `credential.${at}.helper`, ""],63 ["git", "config", "--global", "--add", `credential.${at}.helper`, Brand.slug],64 ["git", "config", "--global", `credential.${at}.useHttpPath`, "true"],65];6667/** A temp HOME with its own global git config: a person's shell, for the CLI and git. */68const home = Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;
293 unmodified lines
364 expect(text).not.toContain(given);365 expect(JSON.parse(text)).toStrictEqual({366 command: "login",367 data: {361 gitConfig: [362 [363 "git",364 "config",365 "--global",366 "--replace-all",367 `credential.${url}.helper`,368 "",369 ],370 [371 "git",372 "config",373 "--global",374 "--add",375 `credential.${url}.helper`,376 Brand.slug,377 ],378 [379 "git",380 "config",381 "--global",382 `credential.${url}.useHttpPath`,383 "true",384 ],385 ],368 gitConfig: helperArgv(url),369 gitConfigSet: true,370 handle: "alice",371 profile: "default",372 url,373 },
4 unmodified lines
378 30_000379 );380381 it.live(382 "with --no-git-config, leaves git's config alone and hands back the lines to set, in --json too",383 () =>384 Effect.gen(function* () {385 const env = yield* home;386 const platform = yield* seams(signedInAs("alice"));387388 const exit = yield* cli(389 ["login", "--url", url, "--token-stdin", "--no-git-config", "--json"],390 { env, seams: platform.layer, stdin: `${given}\n` }391 );392393 expect(Exit.isSuccess(exit)).toBeTruthy();394 expect(395 (yield* gitConfig(env, "--get-all", `credential.${url}.helper`))396 .exitCode397 ).toBe(1);398399 expect(JSON.parse((yield* printed).stdout.join("\n"))).toMatchObject({400 data: { gitConfig: helperArgv(url), gitConfigSet: false },401 ok: true,402 });403 }).pipe(Effect.scoped, Effect.provide(testServices)),404 30_000405 );406407 it.live(408 "prints each git config line so a shell takes it as it was run, quotes and all",409 () =>410 Effect.gen(function* () {411 const env = yield* home;412 const platform = yield* seams(signedInAs("alice"));413 const odd = "https://o'brien.test";414415 yield* cli(["login", "--url", odd, "--token-stdin"], {416 env,417 seams: platform.layer,418 stdin: `${given}\n`,419 });420421 expect(422 (yield* printed).stdout.map((line) => line.trim())423 ).toStrictEqual(424 expect.arrayContaining([425 String.raw`git config --global --add 'credential.https://o'\''brien.test.helper' ${Brand.slug}`,426 ])427 );428 }).pipe(Effect.scoped, Effect.provide(testServices)),429 30_000430 );431432 it.live(433 "keeps nothing, and leaves git alone, when the platform refuses the token",434 () =>435 Effect.gen(function* () {436 const env = yield* home;
39 unmodified lines
476 30_000477 );478479 it.live(480 "without --url, logs the current profile in again on its platform, but asks for --url for another profile",481 () =>482 Effect.gen(function* () {483 const env = yield* home;484 const platform = yield* seams(signedInAs("alice"));485 const run = { env, seams: platform.layer, stdin: `${given}\n` };486487 yield* cli(["login", "--url", url, "--token-stdin"], run);488489 const again = yield* cli(["login", "--token-stdin"], run);490491 const other = yield* cli(492 ["login", "--token-stdin", "--profile", "bob"],493 run494 );495496 expect({497 again: Exit.isSuccess(again),498 bob: yield* stored(env, "bob"),499 checked: (yield* platform.connected).map(({ url: at }) => at),500 other: Exit.isSuccess(other),501 }).toStrictEqual({502 again: true,503 bob: Option.none(),504 checked: [url, url],505 other: false,506 });507 expect((yield* printed).stderr.join("\n")).toContain("--url");508 }).pipe(Effect.scoped, Effect.provide(testServices)),509 30_000510 );511512 it.live(513 "with no --url and no stored profile, asks for --url",514 () =>515 Effect.gen(function* () {516 const env = yield* home;
142 unmodified lines
659 );660661 const shown = yield* signInUrl(server.origin);662595 expect(yield* platform.opened).toStrictEqual([shown]);663 expect(yield* visit(shown)).toBe(200);664 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();665 expect(yield* platform.opened).toStrictEqual([shown]);666 }).pipe(Effect.scoped, Effect.provide(testServices)),667 30_000668 );669
90 unmodified lines
760 30_000761 );762763 it.live(764 "removes useHttpPath even when git's config holds it twice",765 () =>766 Effect.gen(function* () {767 const env = yield* home;768 const platform = yield* seams(signedInAs("alice"));769 const run = { env, seams: platform.layer, stdin: `${given}\n` };770771 yield* cli(["login", "--url", url, "--token-stdin"], run);772 yield* gitConfig(env, "--add", `credential.${url}.useHttpPath`, "true");773774 const exit = yield* cli(["logout"], run);775776 expect(Exit.isSuccess(exit)).toBeTruthy();777 expect(778 (yield* gitConfig(env, "--get-all", `credential.${url}.useHttpPath`))779 .exitCode780 ).toBe(1);781 }).pipe(Effect.scoped, Effect.provide(testServices)),782 30_000783 );784785 it.live(786 "keeps git asking the helper while another profile is on the same platform",787 () =>788 Effect.gen(function* () {789 const env = yield* home;
27 unmodified lines