Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Redacted from "effect/Redacted";
3
4import { GitHubCredentials, isGitHubDotCom } from "../sourceControl/GitHubCredentials.ts";
5
6/**
7 * Subcommands that can send a request to a remote repository. Local reads (`status`, `rev-parse`,
8 * `diff`, …) never consult a credential helper, so resolving an account for them would only add
9 * work to the hottest commands in the server. Submodule commands are absent on purpose: each
10 * submodule is a repository with its own owner.
11 */
12const REMOTE_SUBCOMMANDS: ReadonlySet<string> = new Set(["clone", "fetch", "pull", "push"]);
13
14/**
15 * Global options that take the argument after them. Skipping them keeps a value such as
16 * `--git-dir /repo` from being read as the subcommand.
17 */
18const GLOBAL_OPTIONS_WITH_VALUE: ReadonlySet<string> = new Set([
19 "-C",
20 "-c",
21 "--git-dir",
22 "--work-tree",
23 "--namespace",
24 "--exec-path",
25 "--config-env",
26 "--super-prefix",
27 "--attr-source",
28]);
29
30export interface GitRemoteCommand {
31 readonly subcommand: string;
32 /**
33 * Arguments after the subcommand that are not options. Option values stay in this list, which is
34 * safe because a value is only read as a remote when it is a URL or a configured remote name:
35 * `--depth 1` can be mistaken for neither.
36 */
37 readonly operands: ReadonlyArray<string>;
38}
39
40/** The subcommand and operands of a git command that can reach a remote, or null when it cannot. */
41export function gitRemoteCommand(args: ReadonlyArray<string>): GitRemoteCommand | null {
42 let index = 0;
43 while (index < args.length) {
44 const arg = args[index]!;
45 if (arg === "--") {
46 index += 1;
47 break;
48 }
49 if (GLOBAL_OPTIONS_WITH_VALUE.has(arg)) {
50 index += 2;
51 continue;
52 }
53 // Any other option is global and valueless here, including `--git-dir=/repo` and `-c key=value`.
54 if (arg.startsWith("-")) {
55 index += 1;
56 continue;
57 }
58 break;
59 }
60 const subcommand = args[index];
61 if (subcommand === undefined || !REMOTE_SUBCOMMANDS.has(subcommand)) return null;
62 return {
63 subcommand,
64 operands: args.slice(index + 1).filter((arg) => !arg.startsWith("-")),
65 };
66}
67
68/** True for a token git reads as a repository location: a scheme URL or the `user@host:path` form. */
69export function isRepositoryUrl(token: string): boolean {
70 return /^[a-z][a-z0-9+.-]*:\/\//i.test(token) || /^[^\s/@]+@[^\s/:]+:/.test(token);
71}
72
73/**
74 * Host and owner of a repository URL a token can authenticate to, or null for any other location.
75 * Only `https` is answered: that is the scheme a credential helper is registered for, so ssh and
76 * local paths authenticate some other way and a token would change nothing.
77 */
78export function httpsRepositoryOwner(
79 url: string,
80): { readonly host: string; readonly owner: string } | null {
81 if (!/^https:\/\//i.test(url)) return null;
82 let host: string;
83 try {
84 host = new URL(url).host.toLowerCase();
85 } catch {
86 return null;
87 }
88 const segments = new URL(url).pathname.split("/").filter(Boolean);
89 return host.length === 0 || segments.length < 2 ? null : { host, owner: segments[0]! };
90}
91
92/** The remote the command names, or the one its repository only has one owner for. */
93function remoteUrlFor(
94 operands: ReadonlyArray<string>,
95 remoteUrls: ReadonlyMap<string, string>,
96): string | null {
97 const named = operands.find((operand) => remoteUrls.has(operand));
98 if (named !== undefined) return remoteUrls.get(named) ?? null;
99 // No operand names a remote, so git picks one from the branch. That is only unambiguous when
100 // every remote this repository has is an https repository owned by the same account on the same
101 // host; anything else keeps the account git would have used anyway.
102 const urls = [...new Set(remoteUrls.values())];
103 const coordinates = urls.map(httpsRepositoryOwner);
104 if (coordinates.length === 0 || coordinates.includes(null)) return null;
105 const resolved = coordinates.map((value) => value!);
106 const hosts = new Set(resolved.map((value) => value.host));
107 const owners = new Set(resolved.map((value) => value.owner.toLowerCase()));
108 return hosts.size === 1 && owners.size === 1 ? urls[0]! : null;
109}
110
111/**
112 * The token variables a credential helper reads for `host`, following the same rule as
113 * `environmentToken`: only a GitHub.com-like host is handed `GH_TOKEN`, and an enterprise token is
114 * never given to a host the URL chose for itself. `GH_DEBUG` is cleared because `gh` prints request
115 * headers, and with them the token, under debug output.
116 */
117export function credentialEnvironment(host: string, token: string): NodeJS.ProcessEnv {
118 if (isGitHubDotCom(host)) return { GH_DEBUG: "", GH_TOKEN: token, GITHUB_TOKEN: token };
119 return {
120 GH_DEBUG: "",
121 GH_HOST: host,
122 GH_ENTERPRISE_TOKEN: token,
123 GITHUB_ENTERPRISE_TOKEN: token,
124 };
125}
126
127/**
128 * The environment a git process needs to reach the repository it was asked for through the account
129 * that owns it.
130 *
131 * Git authenticates through a credential helper, and the helper `gh auth setup-git` installs always
132 * answers as the account active in `gh`. A repository owned by a second signed-in account therefore
133 * looks missing. `GH_TOKEN` makes the helper use that account for this process only: it switches no
134 * account — a global mutation that would corrupt a command running for the other owner — and writes
135 * no credential into a git config file.
136 *
137 * Everything unresolved yields an empty environment: the command then runs with the account the
138 * machine is already using, exactly as it did before.
139 */
140export const gitRemoteAccountEnv = Effect.fn("gitRemoteAccountEnv")(function* (input: {
141 readonly args: ReadonlyArray<string>;
142 /** Reads the repository's configured remotes; the caller owns spawning git, so it supplies this. */
143 readonly readRemoteUrls: () => Effect.Effect<ReadonlyMap<string, string>>;
144}) {
145 const command = gitRemoteCommand(input.args);
146 if (command === null) return {};
147 let url = command.operands.find(isRepositoryUrl) ?? null;
148 if (url === null) {
149 url = remoteUrlFor(command.operands, yield* input.readRemoteUrls());
150 }
151 if (url === null) return {};
152 const coordinates = httpsRepositoryOwner(url);
153 if (coordinates === null) return {};
154 const credentials = yield* GitHubCredentials;
155 const token = yield* credentials
156 // Owner only: the active login is what the helper answers as anyway, so naming it would replace
157 // whatever else this machine configured rather than add an account.
158 .get(coordinates.host, { account: coordinates.owner, ownerOnly: true })
159 .pipe(
160 Effect.map((credential) => Redacted.value(credential.token)),
161 // Every failure is reported as no account: the command then authenticates as it did before
162 // this resolution existed, and reports its own outcome, which is the error worth reading.
163 Effect.orElseSucceed(() => null),
164 );
165 return token === null ? {} : credentialEnvironment(coordinates.host, token);
166});