diff --git a/.gitleaksignore b/.gitleaksignore new file mode 100644 index 0000000..4690e96 --- /dev/null +++ b/.gitleaksignore @@ -0,0 +1,4 @@ +# Known synthetic subprocess and connection fixtures in the existing draft history. +0158faa80366165ac20edcd692c71e5ed564652c:packages/cli/test/system.test.ts:generic-api-key:223 +e0e2e8b8714bb7f5dacdb99c828a191f54d4a0da:packages/cli/test/system.test.ts:generic-api-key:20 +c59bc451dbf1cfeea6e73591a02678e8dd050d0b:packages/cli/test/connect-id-track.test.ts:generic-api-key:31 diff --git a/AGENTS.md b/AGENTS.md index 4caf8ca..c293e29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,9 @@ Cloudflare account. to Cloudflare. A value a person must keep is shown once, with words that say so. 4. **A second run finishes the first and does nothing twice.** 5. **The tool holds no logic a product's own deploy lacks.** It runs each product's repository at - a release tag; it does not fork their configuration. + a release tag; it does not fork their configuration. The one exception is `connect`: it does + what both products' self-hosting guides describe by hand to connect them, and nothing more. The + one value it makes is ID's `OIDC_PAIRWISE_SECRET`, as ID's guide says to. 6. **Never run against a Cloudflare account that holds anything you care about** in tests or by hand. Rehearse only in a separate, empty account. diff --git a/README.md b/README.md index 9df78e6..5a26d2e 100644 --- a/README.md +++ b/README.md @@ -5,19 +5,23 @@ Cloudflare account and check the deployment. **Status: early.** `gateweave deploy`, `gateweave doctor` and `gateweave update` for Track and ID are tested against a fake Wrangler, git and pnpm. `deploy track` and `doctor track` were also -rehearsed in a real, empty Cloudflare account. Nothing else exists yet. Run it with -`npx gateweave` (see [Install](#install)). +rehearsed in a real, empty Cloudflare account. `gateweave connect id track` is tested against the +same fakes and its live rehearsal is pending. Run the CLI with `npx gateweave` +(see [Install](#install)). ## Commands -| Command | Purpose | -| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | -| `gateweave deploy track` | Create what Track needs in your Cloudflare account, set its secrets, apply migrations, deploy, and check the result from outside | -| `gateweave deploy id` | The same for ID: Worker, D1 database, logout Queue and RateLimiter Durable Object | -| `gateweave doctor track` | Say what is wrong with a Track deployment, in words | -| `gateweave doctor id` | Say what is wrong with an ID deployment; Track-only checks say they are not checked for ID | -| `gateweave update track` | Bring a Track deployment to a newer release, keeping the names of its Worker, database and bucket | -| `gateweave update id` | Bring an ID deployment to a newer release, keeping the names of its Worker, database and queue | +| Command | Purpose | +| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `gateweave deploy track` | Create what Track needs in your Cloudflare account, set its secrets, apply migrations, deploy, and check the result from outside | +| `gateweave deploy id` | The same for ID: Worker, D1 database, logout Queue and RateLimiter Durable Object | +| `gateweave doctor track` | Say what is wrong with a Track deployment, in words | +| `gateweave doctor id` | Say what is wrong with an ID deployment; Track-only checks say they are not checked for ID | +| `gateweave update track` | Bring a Track deployment to a newer release, keeping the names of its Worker, database and bucket | +| `gateweave update id` | Bring an ID deployment to a newer release, keeping the names of its Worker, database and queue | +| `gateweave connect id track` | Set up ID's provider, register Track and configure Track to sign people in through ID | + +`connect id track` is described in [the package's README](packages/cli/README.md#gateweave-connect-id-track). ## `gateweave deploy track` diff --git a/packages/cli/README.md b/packages/cli/README.md index 5203746..e5e8740 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -26,6 +26,153 @@ one. See the [repository](https://github.com/gateweavehq/cli) for what the commands do. +## `gateweave connect id track` + +``` +gateweave connect id track [--id-url
] [--track-url
] [--keep-secret-at ] + [--id-name ] [--track-name ] [--account ] + [--no-account-name] [--yes] [--json] +``` + +Connects a Track deployment to an ID deployment, so Track signs people in through ID. Both must be +on this tool's record (`gateweave deploy id`, `gateweave deploy track`). With several of one product +in the account, choose with `--id-name` or `--track-name`. A deployment that `gateweave update` +recorded without having made it is used only when named that way, never picked on its own. +`--id-url` and `--track-url` replace the recorded addresses, such as a Custom Domain you added since. +`--no-account-name` keeps the Cloudflare account's name out of the plan, the errors and `--json`, +which then name the account by its id. Addresses are still shown, so an account named after its +`workers.dev` subdomain still shows through a `workers.dev` address. + +1. **Looks, changing nothing.** For each Worker: its secrets (`secret list`), and every binding of + its deployed version (`deployments status`, `versions view`), so a setting kept as a text + variable in `vars` counts as set too, and its compatibility flags. Then ID's + `/.well-known/openid-configuration`, ID's D1 database by name, and whether Track is already + registered with ID, with one fixed `SELECT` on that database. A look that fails, listings that + disagree, or a deployment split across versions stop the run with exit 3: a setting this tool + could not see is never taken for one that is not there. +2. **Shows the plan and waits for a yes:** both deployments and their addresses, ID's database by + name and id, and every setting by name, each marked `set now`, `already set; left as it is` or + `already set as a text variable; left as it is`. `--yes` answers for you; without a terminal and + without `--yes` it stops at once. +3. **On ID:** sets `BETTER_AUTH_URL` to ID's address if it is unset, and `OIDC_PAIRWISE_SECRET` if it + is unset, to 48 random bytes in base64, made here. +4. **Registers Track with ID's own `apps:add`**, from ID's release in your cache folder, in ID's + database: app `track`, redirect URI `/api/auth/callback/oidc` and back-channel logout URI + `/api/auth/backchannel-logout/oidc`. Its output stays in memory. It is read only when it is + exactly the three lines `apps:add` prints, with a client id and a secret of the shapes ID makes; + anything else stops the run, and no part of the output is shown, whatever the exit code. + An existing registration must have the exact back-channel logout URI before connect can use it. +5. **On Track:** sets `OIDC_CLIENT_SECRET`, `OIDC_CLIENT_ID`, `OIDC_ISSUER` and `OIDC_PROVIDER_NAME` + (`Gateweave ID`), and `BETTER_AUTH_URL` if it is unset, which also turns MCP on. +6. **Checks:** ID's discovery answers with the issuer, Track's sign-in page shows the button with the + exact provider name, and the findings `doctor id` (`oidc-provider`) and `doctor track` + (`sign-in-provider`) report for the connection are all `ok`. + +Every value goes to `wrangler secret put` on stdin, never as an argument. A setting that is already +set, as a secret or as a text variable, is left alone and never replaced. A text variable's value +is used where it matters: ID's `BETTER_AUTH_URL` names the issuer, and Track's `OIDC_PROVIDER_NAME` +is the button the check looks for, read as the page shows it (`Acme & Co` is `Acme & Co`). +If Track holds `BETTER_AUTH_URL` as a secret, connect checks the selected Track address's public +`/.well-known/oauth-protected-resource` without signing in or following redirects. The response's +`resource` must be exactly the selected address followed by `/mcp`. If this check fails, connect +stops before making changes. Verify the address in Track's deployment configuration and make sure +its public metadata is reachable before running connect again. +Track's `OIDC_CLIENT_ID` and `OIDC_ISSUER` as text variables are kept when they are exactly ID's +client id and issuer, path and all. A secret cannot be read back, so the command stops where it +would have to guess one: Track's `OIDC_PROVIDER_NAME` set as a secret by someone else, a client id +on record that differs from the one ID has registered for Track, or Track's `OIDC_CLIENT_ID` or +`OIDC_ISSUER` as a secret this tool's record does not show it set. The record names a Track setting +as this tool's only once its put is confirmed, by Wrangler or by Track's list; one tried and never +confirmed makes no claim. Each stop says what to do, and changes nothing; the advice to restore a +known client secret also names the settings to remove so the rerun finishes. Every address in a +message, whether given or read from a Worker, is shown without a name and password, whatever +characters the password holds. + +Only one run at a time: a run takes the lock file `connect-id-track.lock` beside the record, and +removes it when it ends. A run that finds the file stops, whatever its age: it gives the file's +path, the process id and start time of the run that took it, and whether that process is running +on this machine now. This tool never removes a lock it did not take; delete the file yourself only +once you are sure no run is going. + +**The issuer cannot change.** ID's `BETTER_AUTH_URL` becomes the issuer that apps compare, and +passkeys are bound to it for good. Once any app has signed anyone in, it can never change. Choose +the address people will always use before you run this: give ID a Custom Domain first and pass it +with `--id-url`. + +**`workers.dev` has a limit.** A Worker reaches another Worker's `workers.dev` address only when +the calling Worker has `global_fetch_strictly_public` in its `compatibility_flags`. Track calls ID +to sign people in, and ID calls Track for back-channel logout. As released, Track has the flag and +ID does not, so signing out of ID does not end Track's sessions on `workers.dev`. The plan reads +each Worker's own flag and warns once for each direction that lacks it. A +[Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) on +Track, or on both, is the setup that works. + +**What to keep, and where.** `OIDC_PAIRWISE_SECRET` is the one value you must keep: it gives each app +its own id for each person, and losing or changing it gives everybody a new id in every app. +Cloudflare cannot show a secret back. When this run makes it: + +- with `--keep-secret-at `, it is written to that new file, readable by its owner alone where + the system has file modes, before it is set on ID. The path must be outside the folder you run the + command from, and the file must not exist yet. Both are checked for the plan and again when the + file is opened: it is made new, never through a link in its last part, and then looked for where + its folder really leads, so a folder changed in between cannot carry the value into the working + directory. Move the value into your password manager. +- without it, it is shown once on the terminal, with words to keep it, before it is set on ID. With + `--json`, or without a terminal, the command refuses instead and asks for `--keep-secret-at`, so + the value never lands in JSON or a log. + +When ID already has `OIDC_PAIRWISE_SECRET`, nothing is made: `--json` and a run without a terminal +need no `--keep-secret-at`. The keep path can stay on a rerun even if its file already exists. + +Nothing else needs keeping. The client secret goes from `apps:add` to Track and is never shown. No +secret, token or Wrangler sign-in is printed, logged, written to the record, to the working +directory or to the system's temporary folder; the generated and captured values join the output +filter, so even a child process that echoes one shows `[secret]`. Every program this tool starts +gets its environment without `NODE_DEBUG` and without `WRANGLER_LOG_SANITIZE`, so Wrangler keeps +its log sanitised; and since Node prints what it hands a child once `NODE_DEBUG` asks for it, every +command stops at once while `NODE_DEBUG` is set. The record keeps which Track is connected to which +ID, the address and issuer, the provider name and the client id, and no field for a secret. + +**A run cut short, and what the next run does.** Each run looks again before it changes anything, +so running the same command again is the way to finish: + +| Where it stopped | What the next run does | +| ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Before the yes | Starts over; nothing was changed. | +| Setting ID's `BETTER_AUTH_URL` | Sets it. | +| Writing the keep file | Nothing was set on ID; it makes a new value. | +| Setting the pairwise secret | The keep file is never removed once the put was tried. If ID's list shows the value, the put counted. If the list failed too, the value may be set: keep the file and run again, which makes no new value when ID has one. If the list shows it is not set, delete the file and run again with a new path. | +| ID's discovery not answering yet | Leaves ID's settings alone and registers Track once discovery answers. | +| `apps:add` failing before it registered | Registers Track. | +| After `apps:add` registered, before Track had the secret (output unreadable, or three failed tries to set it) | The registration needs cleaning up, as the client secret is gone with the run; the message gives the steps: remove the registration (and any Track OIDC settings), then the run after registers anew. | +| Setting Track's other settings | The client id is on record before Track is given anything, and ID has the registration: it sets what is missing and registers nothing again. | +| The checks | Changes nothing and checks again. | + +`gateweave doctor track` and `gateweave doctor id` report the connection at the addresses it was made +on. Doctor track says what it can see from outside: the button by its exact name, and the issuer +Track names in its sign-in page's Content-Security-Policy. The client id Track holds is a secret it +cannot read, and it says so; it says this tool gave Track its client id only when the record shows +this tool set `OIDC_CLIENT_ID`. Doctor id reads ID's database and says whether Track is still +registered with the client id on record. A message that says to run again gives the command with +the options you gave (`--id-name`, `--track-name`, `--id-url`, `--track-url`, `--keep-secret-at` +with its path, `--yes`, `--json`), each quoted where it needs it: single quotes off Windows, +double quotes on Windows, which PowerShell and cmd both read. Inside those double quotes +PowerShell still expands `$name` and cmd still expands `%name%`, so on Windows a path holding +`$` or `%` must be edited by hand before the command is pasted. + +With `--json`, stdout holds one object: the result, or `{ "ok": false, "code", "reason" }`. + +| Exit code | Meaning | +| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0 | Connected, or already connected, and every check passed | +| 1 | Something unexpected; the reason says what | +| 2 | Wrong usage: an unknown option, an address that is not `https://`, an external deployment not named, a `--keep-secret-at` inside the working directory, already there or moved, or none given where it is needed | +| 3 | A requirement is missing: a deployment not recorded, a Worker or database gone, a look that failed, another run going, `NODE_DEBUG` set, an issuer other than the one given, a setting it cannot read, Track registered without its secret or holding OIDC settings this tool did not set, or Track with another provider | +| 4 | The account: several to choose from, or the one named is not reachable | +| 7 | No yes: declined, or no terminal and no `--yes`; nothing was changed | +| 8 | Setting a secret (or not knowing whether it was set), installing ID's release or its `apps:add` failed; the reason says what to do | +| 9 | Connected, but a check failed, or ID's discovery did not answer before registering | + ## License [AGPL-3.0-only](LICENSE). diff --git a/packages/cli/src/checks.ts b/packages/cli/src/checks.ts index d3d0054..b3a9faf 100644 --- a/packages/cli/src/checks.ts +++ b/packages/cli/src/checks.ts @@ -146,6 +146,100 @@ export async function mcpIsOn(sys: System, address: string): Promise { + try { + const response = await sys.fetch(new URL("/.well-known/openid-configuration", address).href); + if (response.status !== 200) return null; + const issuer = (JSON.parse(response.text) as { issuer?: unknown } | null)?.issuer; + return typeof issuer === "string" && issuer !== "" ? issuer : null; + } catch { + return null; + } +} + +/** Track publishes the MCP resource from BETTER_AUTH_URL in its public OAuth metadata. */ +export async function confirmsTrackResource(sys: System, address: string): Promise { + try { + const response = await sys.fetch( + new URL("/.well-known/oauth-protected-resource", address).href, + { + method: "GET", + }, + ); + if (response.status !== 200) return false; + const resource = (JSON.parse(response.text) as { resource?: unknown } | null)?.resource; + return resource === `${address}/mcp`; + } catch { + return false; + } +} + +const ENTITIES: Record = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }; + +/** + * Text as the page shows it: HTML's character references decoded, by name for the five a page + * escapes text with, and by number. "Acme & Co" reads "Acme & Co". One pass, so "&lt;" + * is "<", as a browser shows it. + */ +export function decodeEntities(text: string): string { + return text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|([a-zA-Z]+));/g, (whole, dec, hex, name) => { + if (name !== undefined) return ENTITIES[name] ?? whole; + const code = Number.parseInt(dec ?? hex, dec !== undefined ? 10 : 16); + return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole; + }); +} + +/** + * The names on the provider buttons of Track's sign-in page, other than GitHub's. Track shows its + * OpenID Connect button only while OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are all set. + * Null when the page did not answer. + */ +export async function providerButtons(sys: System, address: string): Promise { + try { + const page = await sys.fetch(new URL("/login", address).href); + if (page.status !== 200) return null; + return [...page.text.matchAll(/>\s*Continue with ([^<]+?)\s* decodeEntities(match[1] ?? "")) + .filter((name) => name !== "" && name !== "GitHub"); + } catch { + return null; + } +} + +/** + * The issuer Track names, as its sign-in page's Content-Security-Policy shows it: Track allows + * pictures from GitHub and from the origin of its OIDC_ISSUER, and from nowhere else. The setting + * itself is a secret, which cannot be read back; this is how it shows from outside. An empty list + * when the policy names none, null when the page or its policy could not be had. + */ +export async function pagePolicyIssuers(sys: System, address: string): Promise { + try { + const page = await sys.fetch(new URL("/login", address).href); + const policy = Object.entries(page.headers).find( + ([name]) => name.toLowerCase() === "content-security-policy", + )?.[1]; + if (page.status !== 200 || !policy) return null; + const images = policy + .split(";") + .map((directive) => directive.trim().split(/\s+/)) + .find(([name]) => name === "img-src"); + if (!images) return null; + return images + .slice(1) + .filter((source) => /^https?:\/\//.test(source)) + .filter((source) => source !== "https://avatars.githubusercontent.com"); + } catch { + return null; + } +} + /** * Runs every check against the address, retrying each for up to `withinMs` while a new * `workers.dev` address comes up. diff --git a/packages/cli/src/connect.ts b/packages/cli/src/connect.ts new file mode 100644 index 0000000..8180004 --- /dev/null +++ b/packages/cli/src/connect.ts @@ -0,0 +1,1479 @@ +import { randomBytes } from "node:crypto"; +import { constants, type Stats } from "node:fs"; +import { access, type FileHandle, lstat, mkdir, open, realpath, rm } from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { + type CheckResult, + confirmsTrackResource, + discoveredIssuer, + ID_PROVIDER_NAME, + providerButtons, +} from "./checks.ts"; +import { + type Account, + chooseAccount, + confirm, + json, + outputGuard, + plain, + withoutCredentials, +} from "./deploy-track.ts"; +import { + databaseId, + ensureCheckout, + type Finding, + idProviderFindings, + readRegistrations, + trackSignInFindings, +} from "./doctor-track.ts"; +import { CliError } from "./errors.ts"; +import { takeLock } from "./lock.ts"; +import { cacheDir, npxCli } from "./paths.ts"; +import { PRODUCTS, type ProductKey } from "./products.ts"; +import { + type ConnectionStep, + type DeploymentRecord, + findConnections, + listRecords, + saveConnection, +} from "./record.ts"; +import { + backchannelLogoutUri, + callbackUri, + readTrackRegistrations, + sqlString, + TRACK_APP, + trackRegistrationSql, +} from "./registration.ts"; +import { type Pins, readPins, releaseTags } from "./release.ts"; +import { PROCESS_TIMEOUTS, type RunResult, type System } from "./system.ts"; + +export interface ConnectOptions { + /** ID's address, which becomes the issuer. Default: the record's. */ + idUrl?: string; + /** Track's address, which the redirect URIs are built on. Default: the record's. */ + trackUrl?: string; + /** Where to write OIDC_PAIRWISE_SECRET when this run makes it. Never inside the working directory. */ + keepSecretAt?: string; + /** The recorded ID Worker, when the account holds more than one, or the one recorded external. */ + idName?: string; + /** The recorded Track Worker, when the account holds more than one, or the one recorded external. */ + trackName?: string; + account?: string; + /** Whether the account's name may appear in the output. */ + accountName: boolean; + yes: boolean; + json: boolean; +} + +export interface ConnectSetting { + product: ProductKey; + worker: string; + name: string; + /** False when it was already set and this run left it alone. */ + setNow: boolean; + shown: false; +} + +export interface ConnectResult { + ok: true; + /** The name only when --no-account-name was not given. */ + account: { id: string; name?: string }; + id: { worker: string; address: string; issuer: string }; + track: { worker: string; address: string }; + /** What ID gave Track. Not a secret; the client secret is never part of the result. */ + clientId: string; + registeredNow: boolean; + /** False when an earlier run had connected them and this one only checked. */ + changedNow: boolean; + settings: ConnectSetting[]; + pairwiseSecret: { generatedNow: boolean; keptAt: string | null; shownOnTerminal: boolean }; + warnings: string[]; + checks: CheckResult[]; +} + +/** The name Track is registered under, as in ID's own example. */ +const APP_NAME = "Gateweave Track"; + +const PAIRWISE = "OIDC_PAIRWISE_SECRET"; +const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const; +const STRICTLY_PUBLIC = "global_fetch_strictly_public"; + +/** + * All that ID's `apps:add` prints when it registers an app (apps/web/scripts/add-app.ts): three + * lines and nothing else. Its client ids are 24 random bytes and its secrets 32, both base64url, + * the secret behind ID's prefix. Anything else, a line more or a value of another shape, is not + * read at all, so a secret can never be taken for the client id. + */ +const APPS_ADD_OUTPUT = new RegExp( + `^Registered ${APP_NAME}\\. The secret is shown this once, and only its hash is kept\\.\\nclient id: {5}([A-Za-z0-9_-]{32})\\nclient secret: (gwid_cs_[A-Za-z0-9_-]{43})\\n?$`, +); + +/** + * An address as the origin it names. Anything after the host would make a different issuer and + * different redirect URIs, so a path, a query or a name and password is refused, not dropped. A + * value that may hold a password is never repeated. + */ +export function originOf(value: string, what: string): string { + let url: URL | null = null; + try { + url = new URL(value); + } catch { + url = null; + } + if (url && (url.username !== "" || url.password !== "")) { + throw new CliError( + "usage", + "bad-url", + `${what} holds a name or a password. It is not repeated here; give the address alone: https://, with nothing after the host.`, + ); + } + if ( + url?.protocol !== "https:" || + url.search !== "" || + url.hash !== "" || + url.pathname !== "/" || + !/^[a-z0-9.-]+(?::\d+)?$/.test(url.host) + ) { + throw new CliError( + "usage", + "bad-url", + `${what}${value.includes("@") ? "" : ` "${value}"`} is not an address: use https://, with nothing after the host.`, + ); + } + return url.origin; +} + +/** + * One argument as the person's shell takes it back unchanged, quoted only when it needs it. Off + * Windows, POSIX single quotes, each "'" written '\''. On Windows, where the shell may be + * PowerShell or cmd, double quotes, which both read; a name there cannot hold '"'. + */ +export function shellArg(value: string, platform: string): string { + const windows = platform === "win32"; + if (value !== "" && (windows ? /^[A-Za-z0-9_+=:./\\-]+$/ : /^[A-Za-z0-9_+=:./-]+$/).test(value)) { + return value; + } + return windows ? `"${value.replaceAll('"', '""')}"` : `'${value.replaceAll("'", "'\\''")}'`; +} + +/** Whether this Node runs a `.ts` file as ID's `apps:add` does (`node scripts/add-app.ts`). */ +export function stripsTypes(version: string): boolean { + const [major = 0, minor = 0] = version.split(".").map(Number); + return major > 23 || (major === 23 && minor >= 6) || (major === 22 && minor >= 18); +} + +function inside(base: string, target: string): boolean { + const rel = relative(base, target); + return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); +} + +/** + * The file OIDC_PAIRWISE_SECRET is kept in. It must be outside the working directory, so it cannot + * be committed with a project, in a folder that exists, and new: a kept secret is never overwritten. + * Checked here for the plan, and again where it is opened. + */ +interface KeepPath { + path: string; + /** Where its folder really was when the plan was shown. The file is written there or nowhere. */ + folder: string; +} + +async function keepPath(sys: System, given: string): Promise { + const cwd = resolve(sys.cwd ?? process.cwd()); + const path = resolve(cwd, given); + let folder: string; + try { + folder = await realpath(dirname(path)); + } catch { + throw new CliError( + "usage", + "keep-path-folder-missing", + `The folder of --keep-secret-at, ${dirname(path)}, does not exist.`, + ); + } + const realCwd = await realpath(cwd).catch(() => cwd); + if (inside(cwd, path) || inside(realCwd, folder)) { + throw new CliError( + "usage", + "keep-path-inside", + `--keep-secret-at must be outside the folder you run this from (${cwd}), so the secret cannot end up in a project or a commit. Choose a path elsewhere, such as in your home folder.`, + ); + } + const taken = await lstat(path).then( + () => true, + () => false, + ); + if (taken) { + throw new CliError( + "usage", + "keep-path-exists", + `${path} already exists. This tool never overwrites a file that may hold a kept secret; choose a new path.`, + ); + } + return { path, folder }; +} + +const sameFile = (a: Stats, b: Stats) => a.ino === b.ino && a.dev === b.dev; + +/** + * Writes the value a person is to keep. The file is made new (never through a link in its last + * part, never over a file), readable by its owner alone; then, opened, it is looked for again + * where its folder really is now. That must be the folder the plan checked: a link in the path + * retargeted since, into the working directory or anywhere else, is refused, and nothing is + * written in the new place. + */ +async function writeKept(sys: System, keep: KeepPath, value: string): Promise { + const { path } = keep; + const cwd = resolve(sys.cwd ?? process.cwd()); + const realCwd = await realpath(cwd).catch(() => cwd); + const flags = + constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0); + let handle: FileHandle; + try { + handle = await (sys.openNew ?? open)(path, flags, 0o600); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + throw code === "EEXIST" + ? new CliError( + "usage", + "keep-path-exists", + `${path} appeared after the plan was shown. This tool never overwrites a file that may hold a kept secret. Nothing was set on ID for ${PAIRWISE}; run again with a new path.`, + ) + : new CliError( + "requirement", + "keep-path-unwritable", + `Could not write ${path} (${code ?? "error"}). Nothing was set on ID for ${PAIRWISE}.`, + ); + } + let opened: Stats | null = null; + let written = false; + try { + opened = await handle.stat(); + const folder = await realpath(dirname(path)); + const there = await lstat(join(folder, basename(path))); + const same = there.isFile() && sameFile(there, opened); + if (!same || folder !== keep.folder || inside(cwd, folder) || inside(realCwd, folder)) { + throw new CliError( + "usage", + "keep-path-moved", + `${path} no longer leads where it was checked to: its folder changed after the plan, and now leads ${inside(realCwd, folder) || inside(cwd, folder) ? "inside the folder you run this from" : `to ${folder}, not ${keep.folder}`}. Nothing was written to it, and nothing was set on ID for ${PAIRWISE}. Choose a path in a folder nobody else changes.`, + ); + } + await handle.writeFile(`${value}\n`); + if (sys.platform !== "win32") await handle.chmod(0o600); + await handle.sync(); + written = true; + } finally { + await handle.close(); + if (!written && opened) { + // The empty file this run made goes again, wherever its folder now leads. + const now = await lstat(path).catch(() => null); + if (now && sameFile(now, opened)) await rm(path, { force: true }); + } + } +} + +async function exists(path: string): Promise { + return access(path).then( + () => true, + () => false, + ); +} + +/** + * The recorded deployment of a product in the account: the one named, or the only one this tool + * deployed. A deployment `update` recorded without having made it is used only when named. + */ +async function pickRecord( + sys: System, + accountId: string, + accountLabel: string, + key: ProductKey, + name: string | undefined, +): Promise { + const records = (await listRecords(sys, accountId, key)).filter( + (record) => record.steps.includes("deployed") || record.external === true, + ); + const option = key === "id" ? "--id-name" : "--track-name"; + const label = PRODUCTS[key].label; + if (name !== undefined) { + const named = records.find(({ worker }) => worker === name); + if (named) return named; + throw new CliError( + "requirement", + "not-recorded", + `This tool has no record of a ${label} deployment named ${name} in ${accountLabel}. Deploy it with \`gateweave deploy ${key} --name ${name}\` first.`, + ); + } + const [only, ...more] = records; + if (!only) { + throw new CliError( + "requirement", + "not-recorded", + `This tool has no record of a ${label} deployment in ${accountLabel}. Deploy one with \`gateweave deploy ${key}\` first.`, + ); + } + if (more.length > 0) { + throw new CliError( + "usage", + "deployment-ambiguous", + `${accountLabel} holds several ${label} deployments: ${records.map(({ worker }) => worker).join(", ")}. Choose one with ${option} .`, + ); + } + if (only.external === true) { + throw new CliError( + "usage", + "deployment-not-named", + `The only ${label} deployment on record, ${only.worker}, is one this tool did not make (\`gateweave update\` recorded it). It is changed only when named: run again with ${option} ${only.worker}.`, + ); + } + return only; +} + +function lastLine(text: string): string { + return ( + plain(text) + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + .at(-1) ?? "" + ); +} + +async function waitFor( + sys: System, + withinMs: number, + attempt: () => Promise, + done: (value: T) => boolean, +): Promise { + const deadline = sys.now() + withinMs; + for (;;) { + const value = await attempt(); + if (done(value) || sys.now() >= deadline) return value; + await sys.sleep(5_000); + } +} + +/** A binding of the deployed Worker: a secret, a text variable, or anything else by its type. */ +interface Binding { + type: string; + /** A text variable's value. Secrets have none: Cloudflare never shows one back. */ + text?: string; +} + +/** What a deployed Worker has, as its deployed version says: every binding, and its flags. */ +interface Deployed { + bindings: Map; + flags: string[]; +} + +/** + * Connects a Track deployment to an ID deployment, so Track signs people in through ID: turns on + * ID's provider, registers Track with ID's own `apps:add`, and gives Track the result. + */ +export async function connectIdTrack(sys: System, options: ConnectOptions): Promise { + // What can be refused before anything is asked of Cloudflare. + const idGiven = options.idUrl !== undefined ? originOf(options.idUrl, "--id-url") : null; + const trackGiven = + options.trackUrl !== undefined ? originOf(options.trackUrl, "--track-url") : null; + const nodeMajor = Number(sys.nodeVersion.split(".")[0]); + if (nodeMajor < 22) { + throw new CliError( + "requirement", + "node-too-old", + `Node ${sys.nodeVersion} is too old: use Node 22 or newer.`, + ); + } + // One run at a time: two could both make the pairwise secret, or both register Track. + const release = await takeLock(sys, "connect-id-track"); + try { + return await connect(sys, options, idGiven, trackGiven); + } finally { + await release(); + } +} + +async function connect( + sys: System, + options: ConnectOptions, + idGiven: string | null, + trackGiven: string | null, +): Promise { + const say = (line = "") => sys.err(`${withoutCredentials(line)}\n`); + // The command to run again: with the names and addresses given, as a bare rerun would not + // pick an external deployment or the same addresses. + const rerun = `\`${[ + "gateweave connect id track", + ...(options.account ? ["--account", options.account] : []), + ...(options.idName ? ["--id-name", options.idName] : []), + ...(options.trackName ? ["--track-name", options.trackName] : []), + ...(idGiven ? ["--id-url", idGiven] : []), + ...(trackGiven ? ["--track-url", trackGiven] : []), + ...(options.accountName ? [] : ["--no-account-name"]), + // The path as given: it is where a value is kept, not a value. + ...(options.keepSecretAt !== undefined ? ["--keep-secret-at", options.keepSecretAt] : []), + ...(options.yes ? ["--yes"] : []), + ...(options.json ? ["--json"] : []), + ] + .map((arg, index) => (index === 0 ? arg : shellArg(arg, sys.platform))) + .join(" ")}\``; + const npx = npxCli(sys); + const cache = cacheDir(sys); + await mkdir(cache, { recursive: true }); + + const git = await sys.run("git", ["--version"], { + cwd: cache, + env: sys.env, + ...PROCESS_TIMEOUTS.version, + }); + if (git.status !== 0) { + throw new CliError("requirement", "git-missing", "git is not installed or not on the PATH."); + } + const npxVersion = await sys.run(sys.execPath, [npx, "--version"], { + cwd: cache, + env: sys.env, + ...PROCESS_TIMEOUTS.version, + }); + if (npxVersion.status !== 0) { + throw new CliError( + "requirement", + "npx-missing", + `npm's npx was not found next to this Node (${npx}). Install Node with npm.`, + ); + } + + // The shared output filter: the API token and Wrangler's sign-in from the start, and below, what + // this run generates and what ID's apps:add returns. Everything shown passes through it. The + // account's name is shown unless --no-account-name keeps it out, as in deploy. + const showName = options.accountName; + const reachable: { accounts: Account[] } = { accounts: [] }; + const hiddenNames = () => (showName ? [] : reachable.accounts.map(({ name }) => name)); + const guard = await outputGuard(sys, hiddenNames); + const { hide } = guard; + + const latest = (await releaseTags(sys, cache, PRODUCTS.id, hide))[0]; + if (!latest) { + throw new CliError("requirement", "release-not-found", "ID has no release tag yet."); + } + const latestPins = await readPins(sys, latest, PRODUCTS.id); + let env: Record = sys.env; + const wranglerAt = + (pins: Pins) => + (args: string[], cwd = cache, input?: string): Promise => + sys.run(sys.execPath, [npx, "--yes", `wrangler@${pins.wrangler}`, ...args], { + cwd, + env, + ...(input === undefined ? PROCESS_TIMEOUTS.listing : { ...PROCESS_TIMEOUTS.deploy, input }), + }); + const account = await chooseAccount( + sys, + (args) => wranglerAt(latestPins)(args), + latestPins, + options.account, + showName, + reachable, + ); + env = { ...sys.env, CLOUDFLARE_ACCOUNT_ID: account.id }; + const accountLabel = showName + ? `the Cloudflare account ${account.name} (${account.id})` + : `the Cloudflare account ${account.id}`; + + const idRecord = await pickRecord(sys, account.id, accountLabel, "id", options.idName); + const trackRecord = await pickRecord(sys, account.id, accountLabel, "track", options.trackName); + const idPins = await readPins(sys, idRecord.release, PRODUCTS.id); + const trackPins = await readPins(sys, trackRecord.release, PRODUCTS.track); + const idWrangler = wranglerAt(idPins); + const trackWrangler = wranglerAt(trackPins); + const recordedAddress = (record: DeploymentRecord, option: string): string => { + if (!record.address) { + throw new CliError( + "requirement", + "address-unknown", + `The record of ${record.worker} has no address. Give it with ${option} https://.`, + ); + } + return originOf(record.address, `The recorded address of ${record.worker}`); + }; + let idAddress = idGiven ?? recordedAddress(idRecord, "--id-url"); + const trackAddress = trackGiven ?? recordedAddress(trackRecord, "--track-url"); + + // Looks, changing nothing. A look that fails stops the run: a setting it could not see is never + // taken for one that is not there. + const unseen = (worker: string, why: string) => + new CliError( + "requirement", + "lookup-failed", + `Could not read the settings of ${worker}: ${why}. This tool sets only what it has seen is not set. Nothing was changed.`, + ); + const listSecrets = async ( + wrangler: ReturnType, + worker: string, + ): Promise> => { + const listed = await wrangler(["secret", "list", "--name", worker, "--format", "json"]); + if (listed.status !== 0) { + if (/Worker ".+" not found/.test(plain(listed.stderr + listed.stdout))) { + throw new CliError( + "requirement", + "worker-missing", + `The Worker ${worker} is not in ${accountLabel} any more. Nothing was changed.`, + ); + } + throw unseen(worker, `Wrangler's secret list failed (${hide(lastLine(listed.stderr))})`); + } + try { + return new Set(json<{ name: string }[]>(listed.stdout).map(({ name }) => name)); + } catch { + throw unseen(worker, "Wrangler's secret list was not JSON"); + } + }; + // The secrets, and from the deployed version every binding: text variables show only there. + const readDeployed = async ( + wrangler: ReturnType, + worker: string, + ): Promise => { + const secrets = await listSecrets(wrangler, worker); + const status = await wrangler(["deployments", "status", "--name", worker, "--json"]); + if (status.status !== 0) { + throw unseen( + worker, + `Wrangler's deployments status failed (${hide(lastLine(status.stderr))})`, + ); + } + let versions: string[]; + try { + const latestDeployment = json<{ versions?: { version_id?: unknown }[] }>(status.stdout); + versions = (latestDeployment.versions ?? []).map(({ version_id }) => String(version_id)); + } catch { + throw unseen(worker, "Wrangler's deployments status was not JSON"); + } + const [version, ...others] = versions; + if (!version || !/^[0-9a-f][0-9a-f-]{7,63}$/i.test(version)) { + throw unseen(worker, "its deployment names no version"); + } + if (others.length > 0) { + throw new CliError( + "requirement", + "gradual-deployment", + `${worker} is in a gradual deployment across ${versions.length} versions, so which settings it has depends on the request. Finish it with \`npx wrangler versions deploy\`, then run this again. Nothing was changed.`, + ); + } + const view = await wrangler(["versions", "view", version, "--name", worker, "--json"]); + if (view.status !== 0) { + throw unseen(worker, `Wrangler's versions view failed (${hide(lastLine(view.stderr))})`); + } + let deployed: Deployed; + try { + const read = json<{ + resources?: { + bindings?: { type?: unknown; name?: unknown; text?: unknown }[]; + script_runtime?: { compatibility_flags?: unknown }; + }; + }>(view.stdout); + const bindings = read.resources?.bindings; + if (!Array.isArray(bindings)) throw new Error("no bindings"); + const flags = read.resources?.script_runtime?.compatibility_flags ?? []; + if (!Array.isArray(flags)) throw new Error("no flags"); + deployed = { + bindings: new Map( + bindings.map(({ type, name, text }) => [ + String(name), + { type: String(type), ...(typeof text === "string" ? { text } : {}) }, + ]), + ), + flags: flags.map(String), + }; + } catch { + throw unseen(worker, "Wrangler's versions view could not be read"); + } + // Two listings that disagree are not proof of either. + for (const name of secrets) { + if (deployed.bindings.get(name)?.type !== "secret_text") { + throw unseen(worker, `its secret ${name} is not in the deployed version`); + } + } + return deployed; + }; + const idDeployed = await readDeployed(idWrangler, idRecord.worker); + const trackDeployed = await readDeployed(trackWrangler, trackRecord.worker); + /** How a setting is held: "secret", "text", another binding's type, or undefined when absent. */ + const held = (deployed: Deployed, name: string): string | undefined => { + const binding = deployed.bindings.get(name); + if (!binding) return undefined; + if (binding.type === "secret_text") return "secret"; + if (binding.type === "plain_text") return "text"; + return binding.type; + }; + const textOf = (deployed: Deployed, name: string) => deployed.bindings.get(name)?.text; + for (const [deployed, worker, names] of [ + [idDeployed, idRecord.worker, ["BETTER_AUTH_URL", PAIRWISE]], + [trackDeployed, trackRecord.worker, [...TRACK_OIDC, "OIDC_PROVIDER_NAME", "BETTER_AUTH_URL"]], + ] as const) { + for (const name of names) { + const how = held(deployed, name); + if (how !== undefined && how !== "secret" && how !== "text") { + throw new CliError( + "requirement", + "name-in-use", + `${worker} has a ${how} binding named ${name}, where its guide has a setting. This tool replaces nothing; rename or remove that binding, then run again. Nothing was changed.`, + ); + } + } + } + + // The issuer. ID's BETTER_AUTH_URL names it; while that and OIDC_PAIRWISE_SECRET are both set, + // the provider also answers with it. A text variable shows its value; a secret does not. + const idUrlSet = held(idDeployed, "BETTER_AUTH_URL") !== undefined; + const pairwiseSet = held(idDeployed, PAIRWISE) !== undefined; + let issuerBefore: string | null = null; + if (idUrlSet && pairwiseSet) { + issuerBefore = await discoveredIssuer(sys, idAddress); + if (issuerBefore === null) { + throw new CliError( + "requirement", + "provider-unreachable", + `ID's BETTER_AUTH_URL and ${PAIRWISE} are both set, but ${idAddress}/.well-known/openid-configuration did not answer, so ID's issuer could not be seen. If ID answers at another address, run again with --id-url. Nothing was changed.`, + ); + } + } else { + const text = textOf(idDeployed, "BETTER_AUTH_URL"); + if (text !== undefined) { + try { + issuerBefore = new URL(text).origin; + } catch { + throw new CliError( + "requirement", + "issuer-unreadable", + `ID's BETTER_AUTH_URL is a text variable that is not an address, so its issuer cannot be told. Nothing was changed.`, + ); + } + } + } + let adoptedIssuer = false; + if (issuerBefore !== null && issuerBefore !== idAddress) { + if (idGiven) { + throw new CliError( + "requirement", + "issuer-differs", + `ID's issuer is ${issuerBefore}, not ${idGiven}. An issuer cannot change once any app has signed anyone in, so Track has to name that one: run again with --id-url ${issuerBefore}, or without --id-url. Nothing was changed.`, + ); + } + idAddress = originOf(issuerBefore, "ID's issuer"); + adoptedIssuer = true; + } + const trackUrlHeld = held(trackDeployed, "BETTER_AUTH_URL"); + if (trackUrlHeld === "secret" && !(await confirmsTrackResource(sys, trackAddress))) { + throw new CliError( + "requirement", + "track-address-unverified", + `Track's BETTER_AUTH_URL on ${trackRecord.worker} is a secret, and its public OAuth resource metadata did not confirm ${trackAddress}/mcp. Verify the value through Track's deployment configuration and make sure its OAuth resource metadata is reachable at the address people use. Then run ${rerun} again with --track-url if that address differs. Nothing was changed.`, + ); + } + const trackUrlText = textOf(trackDeployed, "BETTER_AUTH_URL"); + if (trackUrlText !== undefined && originOrNull(trackUrlText) !== trackAddress) { + throw new CliError( + "requirement", + "track-address-differs", + `Track's BETTER_AUTH_URL is ${trackUrlText}, not ${trackAddress}. Track builds its sign-in addresses on it, so it has to be the address registered with ID: run again with --track-url set to it. Nothing was changed.`, + ); + } + + // ID's database, by name in the account, and the one the record names. + const idDatabaseId = await databaseId( + (pins, args) => wranglerAt(pins)(args), + idPins, + idRecord.database, + hide, + ); + if (idDatabaseId === null) { + throw new CliError( + "requirement", + "database-missing", + `ID's D1 database ${idRecord.database} is not in ${accountLabel}, so Track cannot be registered with ID. Nothing was changed.`, + ); + } + if (idRecord.databaseId && idRecord.databaseId !== idDatabaseId) { + throw new CliError( + "requirement", + "database-differs", + `ID's D1 database ${idRecord.database} is ${idDatabaseId} now, not ${idRecord.databaseId} as recorded: it was made again. Look at it before anything is registered in it. Nothing was changed.`, + ); + } + const idNames = { + worker: idRecord.worker, + database: idRecord.database, + databaseId: idDatabaseId, + bucket: null, + queue: idRecord.queue ?? `${idRecord.worker}${PRODUCTS.id.queue?.suffix ?? ""}`, + }; + const checkout = await ensureCheckout(sys, idRecord.release, idNames, PRODUCTS.id); + if (!checkout) { + throw new CliError( + "requirement", + "release-unreadable", + `Could not fetch ID ${idRecord.release} into the cache, where its apps:add runs.`, + ); + } + const redirectUri = callbackUri(trackAddress); + const logoutUri = backchannelLogoutUri(trackAddress); + + // One fixed query on ID's own database: the first-party apps registered as Track with Track's + // redirect URI. The address in it is an origin checked above, and quoted besides. + const lookup = await idWrangler( + ["d1", "execute", "DB", "--remote", "--json", "--command", trackRegistrationSql(redirectUri)], + checkout, + ); + if (lookup.status !== 0) { + throw new CliError( + "requirement", + "lookup-failed", + `Could not read the apps registered with ID ${idRecord.worker}: ${hide(lastLine(lookup.stderr))}. Nothing was changed.`, + ); + } + const registered = readTrackRegistrations(lookup.stdout); + if (registered === null) { + throw new CliError( + "requirement", + "lookup-failed", + `Could not read the apps registered with ID ${idRecord.worker}: Wrangler's answer could not be read. Nothing was changed.`, + ); + } + + const connections = await findConnections(sys, account.id, { + idWorker: idRecord.worker, + trackWorker: trackRecord.worker, + }); + const previous = connections[0]; + const trackHas = (name: string) => held(trackDeployed, name) !== undefined; + const deleteOnTrack = (name: string) => + held(trackDeployed, name) === "text" + ? `remove ${name} from the vars in Track's configuration and deploy it` + : `npx wrangler@${trackPins.wrangler} secret delete ${name} --name ${trackRecord.worker}`; + /** The steps that start the connection again from nothing, ending in a run that works. */ + const startAgain = (clientId: string, onTrack: readonly string[]) => + `remove the registration from ID, in ${checkout}: npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "DELETE FROM oauth_client WHERE client_id = ${sqlString(clientId)}"${onTrack.length ? `; remove ${onTrack.join(", ")} from Track: ${onTrack.map(deleteOnTrack).join("; ")}` : ""}; then run ${rerun} again, which registers Track anew.`; + const recovery = (clientId: string, onTrack: readonly string[], unproven: readonly string[]) => + `ID shows a client secret once and keeps only its hash, so it cannot be read back. If you still have it, set it on Track (npx wrangler@${trackPins.wrangler} secret put OIDC_CLIENT_SECRET --name ${trackRecord.worker}, which asks for the value)${unproven.length ? `, remove ${unproven.join(" and ")}, which cannot be shown to be this registration's (${unproven.map(deleteOnTrack).join("; ")}),` : ""} and run ${rerun} again, which sets what is missing. If not, ${startAgain(clientId, onTrack)}`; + + if (registered.length > 1) { + throw new CliError( + "requirement", + "registered-twice", + `Track's redirect URI ${redirectUri} is registered with ID ${idRecord.worker} more than once (client ids ${registered.map(({ clientId }) => clientId).join(", ")}). This tool cannot tell which one Track holds the secret of. Remove the ones Track does not use, then run it again. Nothing was changed.`, + ); + } + const [registration] = registered; + if (registration && registration.logoutUri !== logoutUri) { + throw new CliError( + "requirement", + "registration-logout-unverified", + `Track's registration with ID ${idRecord.worker} (client id ${registration.clientId}) does not have the expected back-channel logout URI ${logoutUri}. In ID's database ${idRecord.database}, correct backchannel_logout_uri on that registration to the expected URI, then run ${rerun} again. Nothing was changed.`, + ); + } + const existingClient = registration?.clientId ?? null; + const trackHeld = TRACK_OIDC.filter(trackHas); + const wantedIssuer = issuerBefore ?? idAddress; + /** What Track's setting must be to belong to the registration ID has. */ + const expected = (name: string) => + name === "OIDC_CLIENT_ID" ? existingClient : name === "OIDC_ISSUER" ? wantedIssuer : null; + /** + * Whether Track's setting is shown to belong to that registration: a text variable with the + * value it must have, or a secret this tool's record shows it set, confirmed, for this client. + * Anything else, a secret nobody can read or a value that differs, is not taken for it. + */ + const proven = (name: string) => + name === "OIDC_CLIENT_SECRET" || + (held(trackDeployed, name) === "text" + ? textOf(trackDeployed, name) === expected(name) + : previous?.clientId === existingClient && previous.trackSet?.includes(name) === true); + const unproven = existingClient === null ? [] : trackHeld.filter((name) => !proven(name)); + if (existingClient && !trackHas("OIDC_CLIENT_SECRET")) { + throw new CliError( + "requirement", + "registered-without-secret", + `Track ${trackRecord.worker} is already registered with ID ${idRecord.worker} (client id ${existingClient}), but Track's OIDC_CLIENT_SECRET is not set. This tool never registers Track a second time. ${recovery(existingClient, trackHeld, unproven)} Nothing was changed.`, + ); + } + if (existingClient) { + // What Track holds must be this registration: the record says which client it was given, and + // a text variable shows its value. A secret cannot be read, so a record that disagrees stops. + const idText = textOf(trackDeployed, "OIDC_CLIENT_ID"); + const issuerText = textOf(trackDeployed, "OIDC_ISSUER"); + const differs = + previous?.clientId && previous.clientId !== existingClient + ? `this tool gave Track the client id ${previous.clientId}, as its record says` + : idText !== undefined && idText !== existingClient + ? `Track's OIDC_CLIENT_ID is ${idText}` + : issuerText !== undefined && issuerText !== wantedIssuer + ? `Track's OIDC_ISSUER is ${issuerText}, not ${wantedIssuer}` + : null; + if (differs) { + throw new CliError( + "requirement", + "client-differs", + `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but ${differs}. Which client Track signs in with cannot be told, so nothing is changed. To start again, ${startAgain(existingClient, trackHeld)}`, + ); + } + // OIDC_CLIENT_ID or OIDC_ISSUER that this tool did not set, as its record shows, may name + // another client: a setting that cannot be read is not taken for this registration's. + const notOurs = unproven; + if (notOurs.length > 0) { + throw new CliError( + "requirement", + "track-settings-not-ours", + `ID has Track ${trackRecord.worker} registered as client id ${existingClient}, but Track holds ${notOurs.join(" and ")} as ${notOurs.length === 1 ? "a secret" : "secrets"} this tool's record does not show it set${notOurs.some((name) => previous?.trackPending?.includes(name)) ? " (it tried to, but the put was never confirmed)" : ""}, so which client Track signs in with cannot be told. Nothing was changed. To start again, ${startAgain(existingClient, trackHeld)}`, + ); + } + } + const register = existingClient === null; + if (register) { + if (trackHeld.length > 0) { + throw new CliError( + "requirement", + "track-has-provider", + `Track ${trackRecord.worker} already has ${trackHeld.join(", ")} set, but ID ${idRecord.worker} has no app registered as Track for ${redirectUri}: Track signs in through another provider, or its registration was removed. This tool replaces no setting. To connect it to ID instead, remove those first (${trackHeld.map(deleteOnTrack).join("; ")}), then run ${rerun} again. Nothing was changed.`, + ); + } + if (!stripsTypes(sys.nodeVersion)) { + throw new CliError( + "requirement", + "node-too-old", + `ID's apps:add is a TypeScript file that Node runs as it is from 22.18 (or 23.6); this is Node ${sys.nodeVersion}.`, + ); + } + if (!(await exists(join(checkout, "apps", "web", "scripts", "add-app.ts")))) { + throw new CliError( + "requirement", + "apps-add-missing", + `ID ${idRecord.release} has no apps:add to register Track with. Update ID first: gateweave update id --name ${idRecord.worker}`, + ); + } + } + + // The name on Track's button, which the checks look for exactly: the one this run sets, the text + // variable's, or the one this tool set before. A secret set by someone else cannot be read. + const nameHeld = held(trackDeployed, "OIDC_PROVIDER_NAME"); + const providerName = + nameHeld === undefined + ? ID_PROVIDER_NAME + : nameHeld === "text" + ? (textOf(trackDeployed, "OIDC_PROVIDER_NAME") ?? "") + : (previous?.providerName ?? null); + if (providerName === null || providerName === "") { + throw new CliError( + "requirement", + "provider-name-unknown", + `Track's OIDC_PROVIDER_NAME is set as a secret this tool did not set, and a secret cannot be read back, so the check that Track's sign-in page shows ID's button could not be made. Remove it (${deleteOnTrack("OIDC_PROVIDER_NAME")}) to have this tool set it to "${ID_PROVIDER_NAME}", or make it a text variable in Track's configuration; then run ${rerun} again. Nothing was changed.`, + ); + } + + interface Planned { + product: ProductKey; + worker: string; + name: string; + value: string; + /** How it is held already, or undefined when this run sets it. */ + held: string | undefined; + } + const generate = !pairwiseSet; + // The keep path counts only when this run makes the value. Decided first, so a run that makes + // nothing never refuses a path, such as the file an earlier run wrote. + const keepAt = + generate && options.keepSecretAt !== undefined + ? await keepPath(sys, options.keepSecretAt) + : null; + const idPlan: Planned[] = [ + { + product: "id", + worker: idRecord.worker, + name: "BETTER_AUTH_URL", + value: idAddress, + held: held(idDeployed, "BETTER_AUTH_URL"), + }, + { + product: "id", + worker: idRecord.worker, + name: PAIRWISE, + value: keepAt + ? `generated here, kept at ${keepAt.path}, never shown` + : "generated here and shown once on this terminal, before it is set, for you to keep", + held: held(idDeployed, PAIRWISE), + }, + ]; + const trackPlan: Planned[] = [ + { + product: "track", + worker: trackRecord.worker, + name: "OIDC_CLIENT_SECRET", + value: "from the registration, never shown", + held: held(trackDeployed, "OIDC_CLIENT_SECRET"), + }, + { + product: "track", + worker: trackRecord.worker, + name: "OIDC_CLIENT_ID", + value: existingClient ?? "from the registration", + held: held(trackDeployed, "OIDC_CLIENT_ID"), + }, + { + product: "track", + worker: trackRecord.worker, + name: "OIDC_ISSUER", + value: idAddress, + held: held(trackDeployed, "OIDC_ISSUER"), + }, + { + product: "track", + worker: trackRecord.worker, + name: "OIDC_PROVIDER_NAME", + value: ID_PROVIDER_NAME, + held: nameHeld, + }, + { + product: "track", + worker: trackRecord.worker, + name: "BETTER_AUTH_URL", + value: `${trackAddress} (this also turns MCP on)`, + held: trackUrlHeld, + }, + ]; + const plan = [...idPlan, ...trackPlan]; + const changing = register || plan.some((item) => item.held === undefined); + + // The value a person must keep goes to a file outside the working directory, or to a terminal + // they are looking at: never into --json, and never into a log that stderr may be. When it is + // set already, nothing is made, and --json needs no file. + if (generate && !keepAt && (options.json || !sys.interactive)) { + throw new CliError( + "usage", + "keep-path-needed", + `ID's ${PAIRWISE} is not set, and this run would make it: a value you must keep, as losing it gives everyone a new id in every app. ${options.json ? "With --json it is never printed" : "Without a terminal it would land in a log"}, so give a file to keep it in, outside this folder: --keep-secret-at . Nothing was changed.`, + ); + } + + const warnings: string[] = []; + if (!idUrlSet) { + warnings.push( + `The issuer, ID's BETTER_AUTH_URL (${idAddress}), can never change once any app has signed anyone in: apps compare it, and passkeys are bound to it for good. Choose the address people will always use.`, + ); + } + const onWorkersDev = (address: string) => new URL(address).hostname.endsWith(".workers.dev"); + if (onWorkersDev(idAddress)) { + warnings.push( + `The issuer ${idAddress} is a workers.dev address, and it can never change once any app has signed anyone in. To give ID a domain of its own later, every app would have to be connected again. If you mean to have one, add a Custom Domain to ${idRecord.worker} first and run this with --id-url.`, + ); + } + // A Worker reaches another on workers.dev only with this flag, and it is the calling Worker's + // that counts: Track calls ID to sign people in, and ID calls Track to sign them out. + // Each direction is told from its own Worker's flag alone, so one warning never speaks for the + // other direction. + const customDomains = + "https://developers.cloudflare.com/workers/configuration/routing/custom-domains/"; + if (onWorkersDev(idAddress) && !trackDeployed.flags.includes(STRICTLY_PUBLIC)) { + warnings.push( + `Track (${trackRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so it cannot reach ID on workers.dev: sign-in through ID fails with Cloudflare's error 1042. A Custom Domain on ID is the setup that works: ${customDomains}`, + ); + } + if (onWorkersDev(trackAddress) && !idDeployed.flags.includes(STRICTLY_PUBLIC)) { + warnings.push( + `ID (${idRecord.worker}) does not have ${STRICTLY_PUBLIC} in its compatibility_flags, so its back-channel logout cannot reach Track on workers.dev: signing out of ID does not end Track's sessions. A Custom Domain on Track is the setup that works: ${customDomains}`, + ); + } + + // The plan. + const state = (item: Planned) => + item.held === undefined + ? "set now" + : `already set${item.held === "text" ? " as a text variable" : ""}; left as it is`; + const line = (item: Planned) => + ` ${item.name.padEnd(22)} ${item.held === undefined ? `${item.value} ` : ""}(${state(item)})`; + say(`Connect Track to ID in ${accountLabel}, so Track signs people in through ID:`); + say( + ` ID ${idRecord.worker} at ${idAddress} (ID ${idRecord.release}${adoptedIssuer ? "; the address is ID's issuer" : ""})`, + ); + say( + ` Track ${trackRecord.worker} at ${trackAddress} (Track ${trackRecord.release})`, + ); + say(); + say(` On ID (${idRecord.worker}):`); + for (const item of idPlan) say(line(item)); + say(); + if (register) { + say( + ` Register Track with ID, with ID's own apps:add, in ID's D1 database ${idRecord.database} (${idDatabaseId}):`, + ); + say(` app ${TRACK_APP} ("${APP_NAME}")`); + say(` redirect URI ${redirectUri}`); + say(` back-channel logout ${logoutUri}`); + } else { + say( + ` Track is already registered with ID (client id ${existingClient}, in ID's D1 database ${idRecord.database}); nothing is registered.`, + ); + } + say(); + say(` On Track (${trackRecord.worker}):`); + for (const item of trackPlan) say(line(item)); + say(); + for (const warning of warnings) say(` Warning: ${warning}`); + if (warnings.length > 0) say(); + if (!generate && options.keepSecretAt !== undefined) + say(` ${PAIRWISE} is already set, so --keep-secret-at is not used and nothing is written.`); + + // "checked" is earned again by this run's own checks. + let steps: ConnectionStep[] = (previous?.steps ?? []).filter((step) => step !== "checked"); + // The Track settings this tool set, for this client: what doctor may say this tool gave Track. + const sameClient = existingClient !== null && previous?.clientId === existingClient; + let trackSet: string[] = sameClient ? (previous.trackSet ?? []) : []; + // The ones tried and not confirmed: a put whose answer was lost. They make no claim. + let trackPending: string[] = sameClient ? (previous.trackPending ?? []) : []; + let clientId = existingClient; + const save = async () => { + try { + await saveConnection(sys, { + kind: "id-track", + accountId: account.id, + idWorker: idRecord.worker, + trackWorker: trackRecord.worker, + issuer: idAddress, + trackAddress, + providerName, + clientId, + trackSet, + trackPending, + steps, + updatedAt: new Date(sys.now()).toISOString(), + }); + } catch (error) { + if (error instanceof CliError) throw error; + throw new CliError( + "requirement", + "record-unwritable", + `The record of connections could not be written (${(error as NodeJS.ErrnoException).code ?? "error"}). What was set stays; run the command again once the record can be written.`, + ); + } + }; + const addStep = (step: ConnectionStep) => { + if (!steps.includes(step)) steps = [...steps, step]; + }; + + const settings: ConnectSetting[] = plan.map(({ product, worker, name, held: was }) => ({ + product, + worker, + name, + setNow: was === undefined, + shown: false, + })); + let generatedNow = false; + let shownOnTerminal = false; + let keptAt: string | null = null; + /** A record save that failed after ID registered Track; it is tried again at the end. */ + let recordFailure: CliError | null = null; + let issuer = idAddress; + + const put = async ( + wrangler: ReturnType, + worker: string, + name: string, + value: string, + ): Promise<{ done: boolean; detail: string }> => { + const result = await wrangler(["secret", "put", name, "--name", worker], cache, value); + const done = + result.status === 0 && plain(result.stdout).includes(`Success! Uploaded secret ${name}`); + return { + done, + detail: hide(lastLine(result.stderr) || lastLine(result.stdout) || `exit ${result.status}`), + }; + }; + /** + * Whether a setting is on the Worker now: true, false, or null when the listing failed. A put + * whose answer was lost may still have been taken, so a failed listing proves nothing either way. + */ + const listedNow = ( + wrangler: ReturnType, + worker: string, + name: string, + ): Promise => + listSecrets(wrangler, worker).then( + (names) => names.has(name), + () => null, + ); + /** Saves the record, best effort: a failure is told, and tried again, at the end. */ + const saveQuietly = async () => { + recordFailure = await save().then( + () => null, + (error: CliError) => error, + ); + }; + // A Track setting is pending while its put is tried, and this tool's only once confirmed: + // the put succeeded, or Track's list shows it. A failed put leaves no claim. + const trying = async (name: string) => { + trackPending = [...new Set([...trackPending, name])]; + await saveQuietly(); + }; + const confirmed = async (name: string) => { + trackPending = trackPending.filter((other) => other !== name); + trackSet = [...new Set([...trackSet, name])]; + await saveQuietly(); + }; + const putOrStop = async ( + item: Planned, + wrangler: ReturnType, + value: string, + ) => { + if (item.product === "track") await trying(item.name); + const { done, detail } = await put(wrangler, item.worker, item.name, value); + if (!done && (await listedNow(wrangler, item.worker, item.name)) !== true) { + throw new CliError( + "deploy-failed", + "secret-put-failed", + `Could not set ${item.name} on ${item.worker}: ${detail}. Run ${rerun} to finish; what is set stays, and nothing is registered twice.`, + ); + } + if (item.product === "track") await confirmed(item.name); + say(` set ${item.name} on ${item.worker}`); + }; + + if (!changing) { + say("An earlier run connected these already; nothing will be changed. Checking them."); + } else { + await confirm(sys, options.yes, "connect"); + + // ID's provider first: nothing can be registered against an issuer that does not answer. + const idUrl = idPlan[0]; + if (idUrl && idUrl.held === undefined) await putOrStop(idUrl, idWrangler, idAddress); + if (generate) { + const value = Buffer.from((sys.random ?? randomBytes)(48)).toString("base64"); + guard.remember(value); + generatedNow = true; + // Kept before it is set, so a value that reached ID is never one nobody kept. + if (keepAt) { + await writeKept(sys, keepAt, value); + } else { + shownOnTerminal = true; + say(); + say( + ` Keep this value now, in your password manager. It is ${PAIRWISE}, shown this once and never again: Cloudflare cannot show it back, and losing or changing it gives everyone a new id in every app. It is set on ID next.`, + ); + say(); + say(` ${value}`); + say(); + } + // From here the file is never removed: once a put was tried, the value may be on ID. + const kept = keepAt ? keepAt.path : "the value shown above"; + const { done, detail } = await put(idWrangler, idRecord.worker, PAIRWISE, value); + const listed = done ? true : await listedNow(idWrangler, idRecord.worker, PAIRWISE); + if (listed === null) { + throw new CliError( + "deploy-failed", + "secret-put-unknown", + `Setting ${PAIRWISE} on ${idRecord.worker} failed (${detail}), and listing its secrets afterwards failed too, so whether ID has the value is unknown: it may be set. Keep ${kept}, and run ${rerun}: it looks again, and makes no new value if ID has this one.`, + ); + } + if (!listed) { + throw new CliError( + "deploy-failed", + "secret-put-failed", + `Could not set ${PAIRWISE} on ${idRecord.worker}: ${detail}. ID's list of secrets shows it is not set, so ${kept} holds a value ID does not have. ${keepAt ? `This tool does not remove it; delete it yourself, and run ${rerun} with a new --keep-secret-at path.` : `Do not keep it, and run ${rerun}.`} The next run makes a new one.`, + ); + } + say(` set ${PAIRWISE} on ${idRecord.worker}`); + if (keepAt) { + keptAt = keepAt.path; + say( + ` Keep ${keepAt.path}: it holds ${PAIRWISE}, the one value of this connection you must keep. Move it into your password manager. Losing or changing it gives everyone a new id in every app, and Cloudflare cannot show it again.`, + ); + } else { + say(` The value shown above is set on ID now; it is the one to keep.`); + } + } + + const discovered = await waitFor( + sys, + 60_000, + () => discoveredIssuer(sys, idAddress), + (found) => found !== null, + ); + if (discovered === null) { + throw new CliError( + "checks-failed", + "provider-off", + `ID's settings are set, but ${idAddress}/.well-known/openid-configuration does not answer, so Track was not registered. Wait a minute and run ${rerun} again.`, + ); + } + if (discovered !== idAddress) { + throw new CliError( + "requirement", + "issuer-differs", + `ID's issuer is ${discovered}, not ${idAddress}: its BETTER_AUTH_URL was set before. Track has to name that issuer, so run again with --id-url ${discovered}. Nothing was registered.`, + ); + } + issuer = discovered; + + let clientSecret: string | null = null; + if (register) { + const install = await sys.run( + sys.execPath, + [npx, "--yes", `pnpm@${idPins.pnpm}`, "install", "--frozen-lockfile"], + { + cwd: checkout, + env: sys.env, + stream: true, + streamFilter: guard.stream(hiddenNames()), + ...PROCESS_TIMEOUTS.install, + }, + ); + if (install.status !== 0) { + throw new CliError( + "deploy-failed", + "install-failed", + `Installing ID ${idRecord.release}'s dependencies failed; pnpm's output is above. Nothing was registered; run the command again.`, + ); + } + say("Registering Track with ID (ID's apps:add)"); + // Its output is kept in memory only, never streamed or repeated: it holds the client secret. + // It is the package's own script (`apps:add` is `node scripts/add-app.ts`), started with + // this Node and no shell, so no value here is parsed as a command. + const added = await sys.run( + sys.execPath, + [ + join("scripts", "add-app.ts"), + "--app", + TRACK_APP, + "--name", + APP_NAME, + "--redirect-uri", + redirectUri, + "--backchannel-logout-uri", + logoutUri, + ], + { cwd: join(checkout, "apps", "web"), env, ...PROCESS_TIMEOUTS.deploy }, + ); + // Whatever looks like a secret is hidden from everything shown after, read or not. + for (const match of plain(`${added.stdout}\n${added.stderr}`).matchAll( + /client secret:\s*(\S+)|(gwid_cs_[A-Za-z0-9_-]+)/gi, + )) { + const found = match[1] ?? match[2]; + if (found) guard.remember(found); + } + const where = `To see why, check that Wrangler reaches ID's database: in ${join(checkout, "apps", "web")}, run npx wrangler@${idPins.wrangler} d1 execute DB --remote --command "SELECT 1".`; + if (added.status !== 0) { + const failure = added.timeout + ? `timed out (${added.timeout})` + : `stopped (exit ${added.status})`; + const cleanup = + added.cleanup === "unconfirmed" + ? " A child process may still be running. Confirm the process tree has stopped before retrying." + : ""; + throw new CliError( + "deploy-failed", + "register-failed", + `ID's apps:add ${failure}, and Track was given nothing.${cleanup} What it printed is not shown, as it may hold the client secret. ${where} Then run ${rerun} again: it first looks whether Track was registered.`, + ); + } + const output = APPS_ADD_OUTPUT.exec(added.stdout.replace(/\r\n/g, "\n")); + const [, givenId, givenSecret] = output ?? []; + if (!givenId || !givenSecret || givenId.startsWith("gwid_cs_")) { + throw new CliError( + "deploy-failed", + "register-output-unreadable", + `ID's apps:add finished, but what it printed was not the three lines this tool reads, so Track was given nothing. None of it is shown, as it may hold the client secret. If Track was registered, the next run says so and how to recover.`, + ); + } + clientId = givenId; + clientSecret = givenSecret; + // On record before Track is given anything: a rerun then knows the client, never its secret. + addStep("registered"); + recordFailure = await save().then( + () => null, + (error: CliError) => error, + ); + say( + ` registered Track with ID: client id ${clientId}; its secret goes to Track and is never shown`, + ); + } + + if (clientId === null) throw new Error("no client id"); + const values: Record = { + OIDC_CLIENT_ID: clientId, + OIDC_ISSUER: issuer, + OIDC_PROVIDER_NAME: ID_PROVIDER_NAME, + BETTER_AUTH_URL: trackAddress, + }; + for (const item of trackPlan) { + if (item.held !== undefined) continue; + if (item.name === "OIDC_CLIENT_SECRET") { + if (clientSecret === null) throw new Error("no client secret"); + // First, and tried again: it lives only in this run's memory until Track has it. + await trying(item.name); + let listed: boolean | null = false; + let detail = ""; + for (let attempt = 0; attempt < 3 && listed !== true; attempt++) { + if (attempt > 0) await sys.sleep(5_000); + const tried = await put(trackWrangler, item.worker, item.name, clientSecret); + detail = tried.detail; + listed = tried.done ? true : await listedNow(trackWrangler, item.worker, item.name); + } + if (listed !== true) { + // The secret lived only in this run's memory, so the registration it belongs to has to go. + throw new CliError( + "deploy-failed", + "client-secret-not-set", + `Track was registered with ID (client id ${clientId}), but OIDC_CLIENT_SECRET could not be set on ${item.worker} in three tries: ${detail}.${listed === null ? ` Listing Track's secrets failed too, so it may be set after all: run ${rerun} first, which finishes if Track has it.` : ""} The client secret is gone with this run, so the registration needs cleaning up: ${startAgain(clientId, [])}`, + ); + } + await confirmed(item.name); + say(` set ${item.name} on ${item.worker}`); + continue; + } + const value = values[item.name]; + if (value === undefined) throw new Error(`no value for ${item.name}`); + await putOrStop(item, trackWrangler, value); + } + addStep("connected"); + await save(); + if (recordFailure) say(` The record could be written only now: ${recordFailure.message}`); + } + if (clientId === null) throw new Error("no client id"); + if (!changing) { + issuer = issuerBefore ?? idAddress; + addStep("connected"); + } + + // The checks: ID's provider from outside, Track's button by its exact name, and what doctor says + // of both, ID's database included. + say(`Checking the connection from outside (up to two minutes while the new settings come up)`); + const checks: CheckResult[] = []; + const finalIssuer = await waitFor( + sys, + 60_000, + () => discoveredIssuer(sys, idAddress), + (found) => found === issuer, + ); + checks.push({ + name: `ID's /.well-known/openid-configuration answers with the issuer ${issuer}`, + ok: finalIssuer === issuer, + detail: + finalIssuer === issuer ? "passed" : finalIssuer ? `answered ${finalIssuer}` : "no answer", + }); + const buttons = await waitFor( + sys, + 120_000, + () => providerButtons(sys, trackAddress), + (found) => found?.includes(providerName) === true, + ); + const buttonOk = buttons?.includes(providerName) === true; + checks.push({ + name: `Track's sign-in page shows "Continue with ${providerName}"`, + ok: buttonOk, + detail: buttonOk ? "passed" : buttons ? "the button is not there" : "the page did not answer", + }); + await save(); + const connectedNow = await findConnections(sys, account.id, { + idWorker: idRecord.worker, + trackWorker: trackRecord.worker, + }); + const doctorSays = (product: ProductKey, findings: Finding[]) => + findings.map( + (finding): CheckResult => ({ + name: `doctor ${product}: ${finding.message.replace(/\.$/, "")}`, + ok: finding.status === "ok", + detail: finding.status === "ok" ? "passed" : (finding.fix ?? finding.status), + }), + ); + // Set is set, as a secret or as a text variable: the variables do not change here. + const setOn = async ( + wrangler: ReturnType, + worker: string, + deployed: Deployed, + ) => + new Set([ + ...(await listSecrets(wrangler, worker)), + ...[...deployed.bindings] + .filter(([, { type }]) => type === "plain_text") + .map(([name]) => name), + ]); + checks.push( + ...doctorSays( + "id", + await idProviderFindings( + sys, + await setOn(idWrangler, idRecord.worker, idDeployed), + idAddress, + connectedNow, + await readRegistrations((args, cwd) => idWrangler(args, cwd), checkout, connectedNow), + ), + ), + ...doctorSays( + "track", + await trackSignInFindings( + sys, + await setOn(trackWrangler, trackRecord.worker, trackDeployed), + trackAddress, + connectedNow, + ), + ), + ); + for (const check of checks) + say(` ${check.ok ? "ok " : "FAIL"} ${check.name}: ${check.detail}`); + const failed = checks.filter(({ ok }) => !ok); + if (failed.length > 0) { + throw new CliError( + "checks-failed", + "checks-failed", + `Track and ID are set up, but ${failed.map(({ name, detail }) => `${name} (${detail})`).join("; ")}. Run \`gateweave doctor track\` and \`gateweave doctor id\` for more.`, + ); + } + addStep("checked"); + await save(); + + return { + ok: true, + account: showName ? { id: account.id, name: account.name } : { id: account.id }, + id: { worker: idRecord.worker, address: idAddress, issuer }, + track: { worker: trackRecord.worker, address: trackAddress }, + clientId, + registeredNow: register, + changedNow: changing, + settings, + pairwiseSecret: { generatedNow, keptAt, shownOnTerminal }, + warnings, + checks, + }; +} + +function originOrNull(value: string): string | null { + try { + return new URL(value).origin; + } catch { + return null; + } +} + +/** The result in words. It names settings and never holds a secret's value. */ +export function describeConnect(result: ConnectResult): string { + const now = result.settings.filter(({ setNow }) => setNow); + const kept = result.settings.filter(({ setNow }) => !setNow); + const list = (items: ConnectSetting[]) => + items.length + ? items.map(({ product, name }) => `${PRODUCTS[product].label} ${name}`).join(", ") + : "none"; + const secret = result.pairwiseSecret; + const lines = [ + result.changedNow + ? `Track (${result.track.worker}) signs people in through ID (${result.id.worker}) now.` + : `Track (${result.track.worker}) was already connected to ID (${result.id.worker}); nothing was changed.`, + "", + ` Issuer ${result.id.issuer}`, + ` Track ${result.track.address}`, + ` Client id ${result.clientId}${result.registeredNow ? " (registered now)" : ""}`, + ` Set now ${list(now)}`, + ` Left as they were ${list(kept)}`, + ` ${PAIRWISE.padEnd(20)} ${secret.generatedNow ? (secret.keptAt ? `generated; kept at ${secret.keptAt}, the only value to keep` : "generated; shown once above, the only value to keep") : "already set; left as it is"}`, + "", + ...result.checks.map((check) => ` ok ${check.name}`), + ...(result.warnings.length + ? ["", ...result.warnings.map((warning) => `Warning: ${warning}`)] + : []), + ]; + return `${lines.join("\n")}\n`; +} diff --git a/packages/cli/src/deploy-track.ts b/packages/cli/src/deploy-track.ts index 8baa075..0288974 100644 --- a/packages/cli/src/deploy-track.ts +++ b/packages/cli/src/deploy-track.ts @@ -609,28 +609,57 @@ export function hideAccountNames(text: string, names: readonly string[]): string const REDACTED = "[secret]"; +/** + * Takes the name and password out of every address in a text, so `https://user:pass@host` reads + * `https://host`. Every message passes through it: an address read from a Worker's settings or + * from a child's output can hold them as well as one a person typed. + */ +export function withoutCredentials(text: string): string { + // Every "://" on its own, whatever comes before it: its span runs to the next "/", "?", + // "#", white space or the end, and everything up to the span's last "@" is userinfo, + // whatever a password holds. The "//" of an address right after ends the span before it. + let clean = ""; + let from = 0; + for (let at = text.indexOf("://"); at >= 0; at = text.indexOf("://", at + 3)) { + const start = at + 3; + let stop = start; + while (stop < text.length && !/[\s/?#]/.test(text[stop] ?? "")) stop++; + const cut = text.lastIndexOf("@", stop - 1); + if (cut >= start) { + clean += text.slice(from, start); + from = cut + 1; + } + } + return clean + text.slice(from); +} + /** Hides exact secret values and secret assignments in child output or an error message. */ export function hideSecrets(text: string, values: readonly string[]): string { - let clean = text; + let clean = withoutCredentials(text); for (const value of new Set(values.filter((secret) => secret.length >= 8))) { clean = clean.replaceAll(value, REDACTED); } // Formatted JSON can place a quoted value on the next line. An unquoted value must start // on the assignment's line so a separate message below an empty assignment stays visible. - const key = "(?:BETTER_AUTH_SECRET|(?:oauth|api|refresh)_token)"; + const key = + "(?:BETTER_AUTH_SECRET|OIDC_PAIRWISE_SECRET|OIDC_CLIENT_SECRET|(?:oauth|api|refresh)_token|client[ _]secret)"; const quoted = new RegExp( `(${key}["']?\\s*[:=]\\s*)(["'])(?:\\\\.|(?!\\2)[^\\\\\\r\\n])*(\\2)?`, "gi", ); const unquoted = new RegExp(`(${key}["']?[ \\t]*[:=][ \\t]*)[^"'\\s,}]+`, "gi"); - return clean - .replace( - quoted, - (_match, before: string, quote: string, end?: string) => - `${before}${quote}${REDACTED}${end ?? ""}`, - ) - .replace(unquoted, `$1${REDACTED}`) - .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`); + return ( + clean + .replace( + quoted, + (_match, before: string, quote: string, end?: string) => + `${before}${quote}${REDACTED}${end ?? ""}`, + ) + .replace(unquoted, `$1${REDACTED}`) + .replace(/(Authorization:\s*Bearer\s+)\S+/gi, `$1${REDACTED}`) + // The prefix ID gives every client secret, so one this run has not learned yet is caught. + .replace(/gwid_cs_[A-Za-z0-9_-]+/g, REDACTED) + ); } export function hideSensitive( @@ -650,6 +679,13 @@ export async function outputGuard(sys: System, names: () => readonly string[] = return { hide: (text: string): string => hideSensitive(text, names(), secrets), stream: (hidden: readonly string[] = []) => sensitiveStreamFilter(hidden, secrets), + /** + * Adds a value this run made or was handed, such as a generated secret or one a child printed, + * so everything shown after, a child's echo included, hides it too. + */ + remember: (value: string): void => { + if (value.length >= 8 && !secrets.includes(value)) secrets.push(value); + }, }; } @@ -658,7 +694,9 @@ export async function outputGuard(sys: System, names: () => readonly string[] = * is: the legacy `~/.wrangler` when that folder exists, otherwise `.wrangler` in its XDG config * folder (`%APPDATA%\xdg.config` on Windows, `~/Library/Preferences` on macOS, `~/.config` on * Linux, each replaced by `XDG_CONFIG_HOME` when that is set). Both are read, so whichever one the - * installed Wrangler chose is covered. + * installed Wrangler chose is covered. That is a superset of Wrangler's rule on purpose: these + * folders are read only to learn values to hide, and hiding a value from a sign-in Wrangler no + * longer uses costs nothing, while missing the one it uses would print a token. */ function wranglerConfigFolders(sys: System): string[] { const set = (name: string) => sys.env[name] || undefined; @@ -874,6 +912,7 @@ export async function lookUp( const CONFIRMATION = { create: { question: "Create these? [y/N] ", nothing: "Nothing was created" }, update: { question: "Update it? [y/N] ", nothing: "Nothing was changed" }, + connect: { question: "Make these changes? [y/N] ", nothing: "Nothing was changed" }, } as const; /** Asks for the yes the plan above waits for; `operation` words the question and the refusal. */ diff --git a/packages/cli/src/doctor-track.ts b/packages/cli/src/doctor-track.ts index 65d6647..0fffc0e 100644 --- a/packages/cli/src/doctor-track.ts +++ b/packages/cli/src/doctor-track.ts @@ -1,6 +1,13 @@ import { access, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { checkFromOutside, checkIdsFor, mcpIsOn } from "./checks.ts"; +import { + checkFromOutside, + checkIdsFor, + discoveredIssuer, + mcpIsOn, + pagePolicyIssuers, + providerButtons, +} from "./checks.ts"; import { type Account, chooseAccount, @@ -12,10 +19,16 @@ import { import { CliError } from "./errors.ts"; import { cacheDir, npxCli } from "./paths.ts"; import { PRODUCTS, type ProductDescription } from "./products.ts"; -import { type DeploymentRecord, findRecord } from "./record.ts"; +import { + type ConnectionRecord, + type DeploymentRecord, + findConnections, + findRecord, +} from "./record.ts"; +import { callbackUri, readClientIds, trackRegistrationSql } from "./registration.ts"; import { compareTags, type Pins, readPins, releaseTags } from "./release.ts"; import { PROCESS_TIMEOUTS, type RunResult, type System } from "./system.ts"; -import { nameProduct } from "./wrangler-config.ts"; +import { nameProduct, type ProductNames } from "./wrangler-config.ts"; export type Status = "ok" | "warn" | "fail"; @@ -212,6 +225,12 @@ export async function doctorProduct( queue: record?.queue ?? (product.queue ? `${worker}${product.queue.suffix}` : null), }; const address = options.url ?? record?.address ?? null; + const connections = await findConnections( + sys, + account.id, + product.key === "track" ? { trackWorker: worker } : { idWorker: worker }, + ); + let registrations: Registrations = new Map(); const database = await databaseId(wrangler, latestPins, names.database, hide); if (database === null) { @@ -239,6 +258,13 @@ export async function doctorProduct( ), ); findings.push(...(await signUpFindings(sys, read, address, product))); + if (product.key === "id" && checkout) { + registrations = await readRegistrations( + (args, cwd) => wrangler(pins, args, cwd), + checkout, + connections, + ); + } } findings.push( @@ -246,10 +272,230 @@ export async function doctorProduct( ? await mcpFinding(sys, pins, worker, secrets, address) : { id: "mcp", status: "ok", message: "MCP is not checked for id.", fix: null }, ); + findings.push( + ...(product.key === "track" + ? await trackSignInFindings(sys, secrets, address, connections) + : await idProviderFindings(sys, secrets, address, connections, registrations)), + ); findings.push(...(await outsideFindings(sys, address, product))); return finish(); } +const TRACK_OIDC = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"] as const; + +/** What ID's database says of each Track a recorded connection names: its client ids, or null. */ +export type Registrations = Map; + +/** Runs the one registration query for each recorded connection, in ID's checkout. */ +export async function readRegistrations( + run: (args: string[], cwd: string) => Promise, + checkout: string, + connections: readonly ConnectionRecord[], +): Promise { + const found: Registrations = new Map(); + for (const connection of connections) { + const sql = trackRegistrationSql(callbackUri(connection.trackAddress)); + const answer = await run( + ["d1", "execute", "DB", "--remote", "--json", "--command", sql], + checkout, + ); + found.set(connection.trackWorker, answer.status === 0 ? readClientIds(answer.stdout) : null); + } + return found; +} + +const worst = (statuses: Status[]): Status => + statuses.includes("fail") ? "fail" : statuses.includes("warn") ? "warn" : "ok"; + +/** + * Whether Track signs people in through an OpenID Connect provider. Said only when Track has one of + * its settings or `gateweave connect id track` connected it, so a Track without one is not told off. + * For a recorded connection it looks at the address the connection was made on, and says what it + * can see from outside (the button by its exact name, the issuer in the page's policy) and what it + * cannot: the client id Track holds is a secret. + */ +export async function trackSignInFindings( + sys: System, + secrets: Set, + address: string | null, + connections: readonly ConnectionRecord[], +): Promise { + const connection = connections.find(({ steps }) => steps.includes("connected")); + const set = TRACK_OIDC.filter((name) => secrets.has(name)); + if (set.length === 0 && !connection) return []; + const at = connection?.trackAddress ?? address; + const fix = `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.track)}`; + const finding = (status: Status, message: string, fixWith: string | null = fix): Finding[] => [ + { id: "sign-in-provider", status, message, fix: status === "ok" ? null : fixWith }, + ]; + const signIn = connection + ? `Sign-in through ID ${connection.idWorker} (${connection.issuer})` + : "Sign-in through an OpenID Connect provider"; + // A setting may be a text variable, which the list of secrets does not show; the page does. + const buttons = at ? await providerButtons(sys, at) : null; + const wanted = connection ? connection.providerName : null; + const shown = + buttons !== null && + (connection ? wanted !== null && buttons.includes(wanted) : buttons.length > 0); + const missing = TRACK_OIDC.filter((name) => !secrets.has(name)); + if (missing.length > 0 && !shown) { + return finding( + "fail", + `${signIn} is set up only in part: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set, so the sign-in page has no button for it.`, + ); + } + if (!at) { + return connection + ? finding( + "warn", + `${signIn}: its settings are set, but the address is unknown, so nothing was seen from outside.`, + "Run again with --url https://", + ) + : finding( + "ok", + `${signIn} is set up (OIDC_ISSUER, OIDC_CLIENT_ID and OIDC_CLIENT_SECRET are set).`, + ); + } + if (buttons === null) { + return finding( + "warn", + `${signIn}: its settings are set, but the sign-in page did not answer, so its button was not seen.`, + `Open ${at}/login; if the Worker was just changed, wait a minute and run again.`, + ); + } + if (connection && wanted === null) { + return finding( + "warn", + `${signIn}: which button on the sign-in page is ID's cannot be told, as the provider's name is not on record.`, + "Run gateweave connect id track, which says how to give Track a name it can check.", + ); + } + if (!shown) { + return finding( + "fail", + `${signIn}: the settings are set, but the sign-in page shows no "Continue with ${wanted ?? "…"}" button.`, + ); + } + if (!connection) { + return finding("ok", `${signIn} is set up, and the sign-in page shows its button.`); + } + // Track names the issuer in its page's policy, the one place OIDC_ISSUER shows from outside. + const issuers = await pagePolicyIssuers(sys, at); + // Only a value this tool's record shows it set is said to come from it. + const unread = + connection.clientId && connection.trackSet?.includes("OIDC_CLIENT_ID") + ? `The client id Track holds is a secret, which cannot be read back; this tool gave it ${connection.clientId}, and \`gateweave doctor id\` checks that ID still has that one.` + : "The client id Track holds is a secret this tool's record does not show it set, so which client Track signs in as cannot be told here."; + if (issuers === null) { + return finding( + "warn", + `${signIn}: the sign-in page shows "Continue with ${wanted}", but which issuer Track names could not be seen, as the page sent no policy naming one. ${unread}`, + `Open ${at}/login; Track names its issuer in the page's Content-Security-Policy from v0.29.5.`, + ); + } + if (!issuers.includes(connection.issuer)) { + return finding( + "fail", + `${signIn}: the sign-in page shows "Continue with ${wanted}", but Track names ${issuers.length ? `the issuer ${issuers.join(", ")}` : "no issuer"}, not ${connection.issuer}, so its button does not lead to this ID.`, + ); + } + return finding( + "ok", + `${signIn} is set up: the sign-in page shows "Continue with ${wanted}", and Track names the issuer ${connection.issuer}. ${unread}`, + ); +} + +/** + * Whether ID's OpenID Connect provider is on, and whether ID still has each Track this tool + * connected, as its database shows. Said only when OIDC_PAIRWISE_SECRET is set or a connection is + * recorded. It asks the provider at the address a connection was made with: the issuer. + */ +export async function idProviderFindings( + sys: System, + secrets: Set, + address: string | null, + connections: readonly ConnectionRecord[], + registrations: Registrations = new Map(), +): Promise { + const connected = connections.filter(({ steps }) => steps.includes("connected")); + if (!secrets.has("OIDC_PAIRWISE_SECRET") && connected.length === 0) return []; + const at = connected[0]?.issuer ?? address; + const fix = `Run gateweave connect id track, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`; + if (!at) { + return [ + { + id: "oidc-provider", + status: "warn", + message: + "Whether the OpenID Connect provider is on could not be told: the address is unknown.", + fix: "Run again with --url https://..workers.dev", + }, + ]; + } + const issuer = await discoveredIssuer(sys, at); + if (issuer === null) { + const missing = ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"].filter( + (name) => !secrets.has(name), + ); + return [ + { + id: "oidc-provider", + status: "fail", + message: `The OpenID Connect provider is off: ${at}/.well-known/openid-configuration does not answer${missing.length ? `, and ${missing.join(" and ")} ${missing.length === 1 ? "is" : "are"} not set` : ""}. No app can sign anyone in.`, + fix, + }, + ]; + } + const stale = connected.filter((connection) => connection.issuer !== issuer); + if (stale.length > 0) { + return [ + { + id: "oidc-provider", + status: "fail", + message: `The OpenID Connect provider answers with the issuer ${issuer}, but ${stale.map(({ trackWorker, issuer: was }) => `Track ${trackWorker} was connected to ${was}`).join(", ")}. Sign-in from there fails.`, + fix: `An issuer cannot change once an app has signed anyone in; set ID's BETTER_AUTH_URL back, or see ${selfHosting(PRODUCTS.id)}#turning-on-the-provider`, + }, + ]; + } + // What ID's own database says of each Track: proof, where the record alone is only a claim. + const seen = connected.map(({ trackWorker, clientId }): { status: Status; text: string } => { + const ids = registrations.get(trackWorker); + if (!ids) { + return { + status: "warn", + text: `whether Track ${trackWorker} is still registered could not be read from ID's database`, + }; + } + if (ids.length === 0) { + return { + status: "fail", + text: `Track ${trackWorker} is not registered any more (this tool registered it as client id ${clientId})`, + }; + } + if (ids.length > 1) { + return { + status: "fail", + text: `Track ${trackWorker} is registered ${ids.length} times (client ids ${ids.join(", ")})`, + }; + } + return ids[0] === clientId + ? { status: "ok", text: `Track ${trackWorker} is registered, as client id ${clientId}` } + : { + status: "fail", + text: `Track ${trackWorker} is registered as client id ${ids[0]}, not ${clientId}, the one this tool gave Track`, + }; + }); + const status = worst(seen.map((item) => item.status)); + return [ + { + id: "oidc-provider", + status, + message: `The OpenID Connect provider is on, with the issuer ${issuer}.${seen.length ? ` In ID's database: ${seen.map(({ text }) => text).join("; ")}.` : ""}`, + fix: status === "ok" ? null : fix, + }, + ]; +} + function releaseFinding( record: DeploymentRecord | undefined, latest: string, @@ -279,7 +525,7 @@ function releaseFinding( }; } -async function databaseId( +export async function databaseId( wrangler: (pins: Pins, args: string[]) => Promise, pins: Pins, name: string, @@ -309,10 +555,10 @@ async function databaseId( * Wrangler needs to find the migrations and the database. A checkout the deploy made is reused, * and its names are written again. Null when it cannot be had. */ -async function ensureCheckout( +export async function ensureCheckout( sys: System, release: string, - names: { worker: string; database: string; bucket: string | null; queue?: string | null }, + names: ProductNames, product: ProductDescription, ): Promise { const parent = join(cacheDir(sys), product.key); @@ -359,7 +605,7 @@ async function cloneRelease( product.repository, checkout, ], - { cwd: parent, env: sys.env }, + { cwd: parent, env: sys.env, ...PROCESS_TIMEOUTS.clone }, ); return clone.status === 0; } diff --git a/packages/cli/src/lock.ts b/packages/cli/src/lock.ts new file mode 100644 index 0000000..e942eb0 --- /dev/null +++ b/packages/cli/src/lock.ts @@ -0,0 +1,89 @@ +import { mkdir, open, readFile, rm } from "node:fs/promises"; +import { hostname } from "node:os"; +import { join } from "node:path"; +import { CliError } from "./errors.ts"; +import { configDir } from "./paths.ts"; +import type { System } from "./system.ts"; + +interface Holder { + pid: number; + host: string; + startedAt: string; +} + +/** Whether a process of this machine is running. EPERM: it is, only someone else's. */ +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "EPERM"; + } +} + +function holderOf(text: string): Holder | null { + try { + const held = JSON.parse(text) as Partial; + return typeof held.pid === "number" && + typeof held.host === "string" && + typeof held.startedAt === "string" + ? (held as Holder) + : null; + } catch { + return null; + } +} + +/** + * One run of a command at a time: an exclusive lock file beside the record. A lock that is there + * is never cleared by this tool, however old, and whether or not its process still runs: a run + * stops, says who holds it, and leaves the file to the person, who alone can tell that no run is + * going. Returns the release, which removes only this run's own lock. + */ +export async function takeLock(sys: System, command: string): Promise<() => Promise> { + const dir = configDir(sys); + await mkdir(dir, { recursive: true }); + const path = join(dir, `${command}.lock`); + const mine = JSON.stringify({ + pid: process.pid, + host: hostname(), + startedAt: new Date(Date.now()).toISOString(), + } satisfies Holder); + try { + const handle = await open(path, "wx", 0o600); + try { + await handle.writeFile(mine); + } finally { + await handle.close(); + } + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== "EEXIST") { + throw new CliError( + "requirement", + "lock-unwritable", + `Could not take the lock ${path} (${code ?? "error"}).`, + ); + } + const held = holderOf((await readFile(path, "utf8").catch(() => null)) ?? ""); + const who = held + ? `It was taken by process ${held.pid} on ${held.host}, at ${held.startedAt}; ${ + held.host !== hostname() + ? "that is another machine, so whether it still runs cannot be told here" + : isAlive(held.pid) + ? "a process with that id is running on this machine now" + : "no process with that id is running on this machine now" + }.` + : "Who took it cannot be read from it."; + throw new CliError( + "requirement", + "run-in-progress", + `Another \`gateweave ${command.replaceAll("-", " ")}\` may be running: its lock ${path} is there. ${who} Two at once could both make ID's pairwise secret or both register Track, so this one stops; nothing was changed. This tool never removes a lock it did not take. Delete ${path} yourself only once you are sure no such run is going, then run this again.`, + ); + } + return async () => { + // Only its own lock: a file someone replaced meanwhile stays. + const now = await readFile(path, "utf8").catch(() => null); + if (now === mine) await rm(path, { force: true }); + }; +} diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index f55d854..d229d6a 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,5 +1,11 @@ import { parseArgs } from "node:util"; -import { type DeployTrackResult, deployId, deployTrack } from "./deploy-track.ts"; +import { connectIdTrack, describeConnect } from "./connect.ts"; +import { + type DeployTrackResult, + deployId, + deployTrack, + withoutCredentials, +} from "./deploy-track.ts"; import { type DoctorTrackResult, doctorId, doctorTrack } from "./doctor-track.ts"; import { CliError } from "./errors.ts"; import { PRODUCTS } from "./products.ts"; @@ -65,6 +71,33 @@ Options: Each finding is ok, warn or fail. The exit code is 1 when there is a fail, else 0. `; +const CONNECT_USAGE = `Usage: gateweave connect id track [options] + +Connects a Track deployment to an ID deployment, so Track signs people in through ID. It turns on +ID's OpenID Connect provider, registers Track with ID's own apps:add and gives Track the client. +It shows both deployments and every setting it will set, by name, and waits for a yes. + +Options: + --id-url
ID's address, which becomes the issuer for good. Default: the record's. + --track-url
Track's address, for its redirect URIs. Default: the record's. + --keep-secret-at Writes OIDC_PAIRWISE_SECRET, the one value you must keep, to this new + file outside the working directory. Without it the value is shown once + on the terminal. Needed with --json, and without a terminal. + --id-name The recorded ID Worker, when the account has several. + --track-name The recorded Track Worker, when the account has several. + --account The Cloudflare account, when the sign-in reaches several. + Default: CLOUDFLARE_ACCOUNT_ID. + --no-account-name Print only the Cloudflare account id, never its name. Addresses + are still shown, so an account named after its workers.dev + subdomain shows through a workers.dev address. + --yes Make the changes without asking. Needed when there is no terminal. + --json Print the result, or the failure, as one JSON object on stdout. + --help Show this. +`; + +/** The options only `connect id track` takes. */ +const CONNECT_ONLY = ["id-url", "track-url", "keep-secret-at", "id-name", "track-name"]; + function deployUsage(product: (typeof PRODUCTS)[keyof typeof PRODUCTS]): string { if (product.key === "track") return USAGE; return `Usage: gateweave deploy id [options] @@ -204,9 +237,10 @@ function describeDoctor(result: DoctorTrackResult, label = "Track"): string { export async function main(argv: string[], sys: System): Promise { let json = argv.includes("--json"); const fail = (error: CliError): number => { - if (json) - sys.out(`${JSON.stringify({ ok: false, code: error.code, reason: error.message })}\n`); - else sys.err(`gateweave: ${error.message}\n`); + // Whatever address a reason holds, read or given, goes without a name and password. + const reason = withoutCredentials(error.message); + if (json) sys.out(`${JSON.stringify({ ok: false, code: error.code, reason })}\n`); + else sys.err(`gateweave: ${reason}\n`); return error.exitCode; }; @@ -220,6 +254,7 @@ export async function main(argv: string[], sys: System): Promise { const { values, positionals } = parsed; json = values.json === true; const command = positionals.join(" "); + const connect = command === "connect id track"; const doctor = command === "doctor track" || command === "doctor id"; const update = command === "update track" || command === "update id"; const deployProduct = @@ -233,39 +268,60 @@ export async function main(argv: string[], sys: System): Promise { sys.out(`${version()}\n`); return 0; } + const usageOf = () => { + if (connect) return CONNECT_USAGE; + if (doctor) return doctorUsage(product); + return update ? updateUsage(product) : deployUsage(product); + }; if (values.help) { - sys.err(doctor ? doctorUsage(product) : update ? updateUsage(product) : deployUsage(product)); + sys.err(usageOf()); return 0; } - if (!deployProduct && !doctor && !update) { + if (!deployProduct && !doctor && !update && !connect) { throw new CliError( "usage", "usage", - `This version knows these commands: \`gateweave deploy track\`, \`gateweave deploy id\`, \`gateweave doctor track\`, \`gateweave doctor id\`, \`gateweave update track\` and \`gateweave update id\`.\n\n${USAGE}`, + `This version knows these commands: \`gateweave deploy track\`, \`gateweave deploy id\`, \`gateweave doctor track\`, \`gateweave doctor id\`, \`gateweave update track\`, \`gateweave update id\` and \`gateweave connect id track\`.\n\n${USAGE}`, ); } // Another command's options are refused, not ignored, so a typo cannot pass for a choice. - const foreignOptions = doctor - ? [ - "release", - "no-attachments", - "no-account-name", - "yes", - "to", - "from", - "worker", - "database", - "bucket", - "queue", - ] - : update + const connectForeign = [ + "name", + "url", + "release", + "to", + "from", + "worker", + "database", + "bucket", + "queue", + "no-attachments", + ]; + const foreignOptions = connect + ? connectForeign + : doctor ? [ - "url", + ...CONNECT_ONLY, "release", + "no-attachments", "no-account-name", - ...(product.key === "track" ? ["queue"] : ["bucket", "no-attachments"]), + "yes", + "to", + "from", + "worker", + "database", + "bucket", + "queue", ] - : ["url", "to", "from", "worker", "database", "bucket", "queue"]; + : update + ? [ + ...CONNECT_ONLY, + "url", + "release", + "no-account-name", + ...(product.key === "track" ? ["queue"] : ["bucket", "no-attachments"]), + ] + : [...CONNECT_ONLY, "url", "to", "from", "worker", "database", "bucket", "queue"]; const foreign = foreignOptions.filter( (option) => values[option as keyof typeof values] !== undefined, ); @@ -273,9 +329,46 @@ export async function main(argv: string[], sys: System): Promise { throw new CliError( "usage", "usage", - `\`gateweave ${command}\` has no option --${foreign[0]}.\n\n${doctor ? doctorUsage(product) : update ? updateUsage(product) : deployUsage(product)}`, + `\`gateweave ${command}\` has no option --${foreign[0]}.\n\n${usageOf()}`, + ); + } + // Node prints what it hands a child, the environment with the Cloudflare API token included, + // once NODE_DEBUG names child_process. It reads NODE_DEBUG as it starts, so it cannot be + // unset from here: the run stops instead. + if ( + Object.entries(sys.env).some(([key, value]) => key.toUpperCase() === "NODE_DEBUG" && value) + ) { + throw new CliError( + "requirement", + "node-debug-set", + "NODE_DEBUG is set, which makes Node print what this tool hands the programs it starts, the Cloudflare API token included. Run it again without NODE_DEBUG.", ); } + for (const option of ["id-name", "track-name"] as const) { + const given = values[option]; + if (given !== undefined && !NAME.test(given)) { + throw new CliError( + "usage", + "bad-name", + `"${given}" given with --${option} cannot name a Worker: use lowercase letters, digits and dashes.`, + ); + } + } + if (connect) { + const result = await connectIdTrack(sys, { + idUrl: values["id-url"], + trackUrl: values["track-url"], + keepSecretAt: values["keep-secret-at"], + idName: values["id-name"], + trackName: values["track-name"], + account: values.account, + accountName: values["no-account-name"] !== true, + yes: values.yes === true, + json, + }); + sys.out(json ? `${JSON.stringify(result)}\n` : describeConnect(result)); + return 0; + } const name = values.name ?? product.defaultName; if (!NAME.test(name)) { throw new CliError( @@ -286,10 +379,11 @@ export async function main(argv: string[], sys: System): Promise { } if (doctor) { if (values.url !== undefined && !/^https?:\/\/[^\s/]+/.test(values.url)) { + // A value with an @ may hold a name and password, so it is not repeated. throw new CliError( "usage", "bad-url", - `"${values.url}" is not an address: use https://.`, + `${values.url.includes("@") ? "--url" : `"${values.url}"`} is not an address: use https://.`, ); } const found = await (command === "doctor id" ? doctorId : doctorTrack)(sys, { @@ -348,6 +442,11 @@ function parse(argv: string[]) { bucket: { type: "string" }, queue: { type: "string" }, account: { type: "string" }, + "id-url": { type: "string" }, + "track-url": { type: "string" }, + "keep-secret-at": { type: "string" }, + "id-name": { type: "string" }, + "track-name": { type: "string" }, "no-attachments": { type: "boolean" }, "no-account-name": { type: "boolean" }, yes: { type: "boolean", short: "y" }, diff --git a/packages/cli/src/record.ts b/packages/cli/src/record.ts index 52770ea..8847b88 100644 --- a/packages/cli/src/record.ts +++ b/packages/cli/src/record.ts @@ -53,9 +53,55 @@ export const RECORD_FIELDS: readonly (keyof DeploymentRecord)[] = [ "updatedAt", ]; +export const CONNECTION_STEPS = ["registered", "connected", "checked"] as const; +export type ConnectionStep = (typeof CONNECTION_STEPS)[number]; + +/** + * What `gateweave connect id track` connected: which Track signs in through which ID, and the + * client id ID gave it. The client id is not a secret. There is no field for the client secret or + * the pairwise secret, and none may be added. + */ +export interface ConnectionRecord { + kind: "id-track"; + accountId: string; + idWorker: string; + trackWorker: string; + /** ID's issuer, the origin of its BETTER_AUTH_URL, which Track's OIDC_ISSUER names. */ + issuer: string; + trackAddress: string; + /** The OIDC_PROVIDER_NAME this tool set, or null when Track already had one and kept it. */ + providerName: string | null; + clientId: string | null; + /** + * The Track settings this tool set for that client, by name. Only what is named here may be said + * to come from this tool: a secret cannot be read back to tell. + */ + trackSet?: string[]; + /** Track settings whose put was tried and never confirmed. They are not this tool's. */ + trackPending?: string[]; + steps: ConnectionStep[]; + updatedAt: string; +} + +export const CONNECTION_FIELDS: readonly (keyof ConnectionRecord)[] = [ + "kind", + "accountId", + "idWorker", + "trackWorker", + "issuer", + "trackAddress", + "providerName", + "clientId", + "trackSet", + "trackPending", + "steps", + "updatedAt", +]; + interface RecordFile { version: 1; deployments: DeploymentRecord[]; + connections: ConnectionRecord[]; } export function recordPath(sys: System): string { @@ -65,9 +111,15 @@ export function recordPath(sys: System): string { async function readAll(sys: System): Promise { try { const file = JSON.parse(await readFile(recordPath(sys), "utf8")) as RecordFile; - return { version: 1, deployments: Array.isArray(file.deployments) ? file.deployments : [] }; + return { + version: 1, + deployments: Array.isArray(file.deployments) ? file.deployments : [], + connections: Array.isArray(file.connections) ? file.connections : [], + }; } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, deployments: [] }; + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return { version: 1, deployments: [], connections: [] }; + } // Whatever else stops the read (a folder in its place, no permission) is the same stop. The // error's own text quotes JSON or a path, so it is not passed on. throw new CliError( @@ -78,6 +130,14 @@ async function readAll(sys: System): Promise { } } +async function writeAll(sys: System, file: RecordFile): Promise { + const path = recordPath(sys); + await mkdir(configDir(sys), { recursive: true }); + // Written beside and moved into place, so an interrupted write never leaves half a record. + await writeFile(`${path}.tmp`, `${JSON.stringify(file, null, "\t")}\n`); + await rename(`${path}.tmp`, path); +} + export async function findRecord( sys: System, accountId: string, @@ -91,6 +151,18 @@ export async function findRecord( ); } +/** Every recorded deployment of a product in an account. */ +export async function listRecords( + sys: System, + accountId: string, + product: DeploymentRecord["product"], +): Promise { + const { deployments } = await readAll(sys); + return deployments.filter( + (record) => record.product === product && record.accountId === accountId, + ); +} + /** Saves a record, keeping only the known fields, so nothing else can slip into the file. */ export async function saveRecord(sys: System, record: DeploymentRecord): Promise { const file = await readAll(sys); @@ -108,12 +180,37 @@ export async function saveRecord(sys: System, record: DeploymentRecord): Promise other.worker === clean.worker ), ); - const path = recordPath(sys); - await mkdir(configDir(sys), { recursive: true }); - // Written beside and moved into place, so an interrupted write never leaves half a record. - await writeFile( - `${path}.tmp`, - `${JSON.stringify({ version: 1, deployments: [...others, clean] }, null, "\t")}\n`, + await writeAll(sys, { ...file, deployments: [...others, clean] }); +} + +/** The recorded connections in an account that name this ID Worker or this Track Worker. */ +export async function findConnections( + sys: System, + accountId: string, + match: { idWorker?: string; trackWorker?: string }, +): Promise { + const { connections } = await readAll(sys); + return connections.filter( + (connection) => + connection.accountId === accountId && + (match.idWorker === undefined || connection.idWorker === match.idWorker) && + (match.trackWorker === undefined || connection.trackWorker === match.trackWorker), ); - await rename(`${path}.tmp`, path); +} + +/** Saves a connection, keeping only the known fields, so no secret can slip into the file. */ +export async function saveConnection(sys: System, connection: ConnectionRecord): Promise { + const file = await readAll(sys); + const clean = Object.fromEntries( + CONNECTION_FIELDS.map((field) => [field, connection[field]]), + ) as unknown as ConnectionRecord; + const others = file.connections.filter( + (other) => + !( + other.accountId === clean.accountId && + other.idWorker === clean.idWorker && + other.trackWorker === clean.trackWorker + ), + ); + await writeAll(sys, { ...file, connections: [...others, clean] }); } diff --git a/packages/cli/src/registration.ts b/packages/cli/src/registration.ts new file mode 100644 index 0000000..6ae1e9f --- /dev/null +++ b/packages/cli/src/registration.ts @@ -0,0 +1,60 @@ +import { json } from "./deploy-track.ts"; + +/** The app id Track is registered under with ID's `apps:add`, as in ID's own example. */ +export const TRACK_APP = "track"; + +/** Where ID sends someone back to Track after sign-in, as Track's self-hosting guide names it. */ +export function callbackUri(trackAddress: string): string { + return `${trackAddress}/api/auth/callback/oidc`; +} + +/** Where ID tells Track that someone signed out of ID. */ +export function backchannelLogoutUri(trackAddress: string): string { + return `${trackAddress}/api/auth/backchannel-logout/oidc`; +} + +/** A text as an SQL string literal, its quotes doubled, as ID's own apps:add writes its values. */ +export function sqlString(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +} + +/** + * The one query this tool runs on ID's database: the first-party apps registered as Track with + * Track's redirect URI. apps:add stores the URIs as a JSON list and the app id in `metadata`. + * json_quote makes the whole URI the thing matched, so a longer URI on the same host does not + * count; the app id keeps another app with the same callback from being taken for Track; and a + * `metadata` that is not JSON is passed over instead of failing the whole query. + */ +export function trackRegistrationSql(redirectUri: string): string { + return [ + "SELECT client_id, backchannel_logout_uri FROM oauth_client", + "WHERE reference_id IS NULL", + `AND (CASE WHEN json_valid(metadata) THEN json_extract(metadata, '$.app') END) = ${sqlString(TRACK_APP)}`, + `AND instr(redirect_uris, json_quote(${sqlString(redirectUri)})) > 0`, + ].join(" "); +} + +/** Keep rows with an unproven logout URI so connect cannot mistake them for an empty result. */ +export function readTrackRegistrations( + stdout: string, +): { clientId: string; logoutUri: unknown }[] | null { + try { + const answer = + json<{ results?: { client_id?: unknown; backchannel_logout_uri?: unknown }[] }[]>(stdout); + const rows = answer[0]?.results; + if (!Array.isArray(rows)) return null; + const registrations = []; + for (const { client_id, backchannel_logout_uri } of rows) { + if (typeof client_id !== "string") return null; + registrations.push({ clientId: client_id, logoutUri: backchannel_logout_uri }); + } + return registrations; + } catch { + return null; + } +} + +/** The client ids in Wrangler's `d1 execute --json` answer, or null when it cannot be read. */ +export function readClientIds(stdout: string): string[] | null { + return readTrackRegistrations(stdout)?.map(({ clientId }) => clientId) ?? null; +} diff --git a/packages/cli/src/release.ts b/packages/cli/src/release.ts index 0235bc4..a4bb577 100644 --- a/packages/cli/src/release.ts +++ b/packages/cli/src/release.ts @@ -22,6 +22,7 @@ export async function releaseTags( sys: System, cwd: string, product: ProductDescription = PRODUCTS.track, + hide: (text: string) => string = (text) => text, ): Promise { const result = await sys.run("git", ["ls-remote", "--tags", "--refs", product.repository], { cwd, @@ -32,7 +33,7 @@ export async function releaseTags( throw new CliError( "requirement", "release-unreachable", - `Could not list ${product.label}'s releases from ${product.repository}: ${result.stderr.trim()}`, + `Could not list ${product.label}'s releases from ${product.repository}: ${hide(result.stderr.trim())}`, ); } return result.stdout diff --git a/packages/cli/src/system.ts b/packages/cli/src/system.ts index c6843bb..2afe00d 100644 --- a/packages/cli/src/system.ts +++ b/packages/cli/src/system.ts @@ -1,4 +1,5 @@ import { type ChildProcess, spawn } from "node:child_process"; +import type { FileHandle } from "node:fs/promises"; import { homedir } from "node:os"; import { createInterface } from "node:readline"; import { setTimeout as delay } from "node:timers/promises"; @@ -12,6 +13,11 @@ export interface RunOptions { stream?: boolean; /** Filters streamed output before it reaches this process's stderr. */ streamFilter?: StreamFilter; + /** + * Written to the child's stdin, which is then closed. A secret travels this way only: never in + * an argument, which other users of the machine can read from the process list. + */ + input?: string; /** Kill the child when it writes nothing for this long. */ idleTimeoutMs?: number; /** Kill the child after this long altogether. */ @@ -75,6 +81,32 @@ export interface System { nodeVersion: string; sleep(ms: number): Promise; now(): number; + /** The folder the command was started in. A value a person must keep is never written there. */ + cwd?: string; + /** Random bytes for a secret this tool makes itself; node:crypto's when unset. Tests set it. */ + random?: (bytes: number) => Uint8Array; + /** + * Opens a new file a person is to keep; node:fs's `open` when unset. Tests wrap it to see the + * flags and the mode asked for, which Windows does not keep. + */ + openNew?: (path: string, flags: number, mode: number) => Promise; +} + +/** + * What a child is started with: the given environment without the two settings that make a child + * write what it is handed where this tool cannot filter it. NODE_DEBUG has Node print a process's + * internals, the environment of what it starts included; WRANGLER_LOG_SANITIZE=false has Wrangler + * keep request bodies, such as a secret's value, in its log file. Without it, Wrangler sanitises. + */ +export function childEnv( + env: Record, +): Record { + // Windows matches names in any case, so they are compared in one. + return Object.fromEntries( + Object.entries(env).filter( + ([name]) => !["NODE_DEBUG", "WRANGLER_LOG_SANITIZE"].includes(name.toUpperCase()), + ), + ); } const DEFAULT_CLEANUP_TIMEOUT_MS = 2_000; @@ -93,16 +125,19 @@ export function runProcess( platform: NodeJS.Platform = process.platform, ): Promise { return new Promise((resolve) => { - const child = spawnProcess(command, args, { + const common = { cwd: options.cwd, - env: options.env ?? process.env, + env: childEnv(options.env ?? process.env), shell: false, - // Nothing a child asks can be answered: this tool asks its one question itself. - stdio: ["ignore", "pipe", "pipe"], windowsHide: true, // A group of its own lets a Unix timeout kill npx's grandchildren too. detached: platform !== "win32", - }); + } as const; + // A child receives only the explicitly supplied input. Interactive prompts can read no input. + const child = + options.input === undefined + ? spawnProcess(command, args, { ...common, stdio: ["ignore", "pipe", "pipe"] }) + : spawnProcess(command, args, { ...common, stdio: ["pipe", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; let timeout: RunTimeout | undefined; @@ -129,6 +164,7 @@ export function runProcess( child.stdout.removeAllListeners(); child.stderr.removeAllListeners(); child.removeAllListeners(); + child.stdin?.destroy(); child.stdout.destroy(); child.stderr.destroy(); child.unref(); @@ -301,6 +337,11 @@ export function runProcess( } finishClose(code); }); + if (options.input !== undefined && child.stdin) { + // A child may exit or time out before it reads stdin. + child.stdin.on("error", () => undefined); + child.stdin.end(options.input); + } }); } @@ -342,5 +383,6 @@ export function realSystem(): System { nodeVersion: process.versions.node, sleep: (ms) => delay(ms), now: () => Date.now(), + cwd: process.cwd(), }; } diff --git a/packages/cli/test/connect-id-track.test.ts b/packages/cli/test/connect-id-track.test.ts new file mode 100644 index 0000000..49ac641 --- /dev/null +++ b/packages/cli/test/connect-id-track.test.ts @@ -0,0 +1,1984 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { + constants, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmdirSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + utimesSync, + writeFileSync, +} from "node:fs"; +import { open } from "node:fs/promises"; +import { hostname, tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { after, describe, test } from "node:test"; +import { parse } from "jsonc-parser"; +import { decodeEntities } from "../src/checks.ts"; +import { shellArg } from "../src/connect.ts"; +import { hideSecrets, withoutCredentials } from "../src/deploy-track.ts"; +import { main } from "../src/main.ts"; +import { cacheDir, configDir } from "../src/paths.ts"; +import { type ConnectionRecord, recordPath, saveConnection, saveRecord } from "../src/record.ts"; +import { backchannelLogoutUri } from "../src/registration.ts"; +import { + type HttpRequest, + type HttpResponse, + PROCESS_TIMEOUTS, + type RunOptions, + runProcess, +} from "../src/system.ts"; +import { type FakeOptions, fakeSystem, readsOnly, WRANGLER } from "./fake.ts"; + +// Known fake secrets, in the shapes ID makes them. Each must reach only what the test allows. +const PAIRWISE_BYTES = Buffer.from("pairwise-bytes-known-to-this-test-only-0123456789").subarray( + 0, + 48, +); +const PAIRWISE = PAIRWISE_BYTES.toString("base64"); +const CLIENT_ID = Buffer.from("test-client-id-012345678").toString("base64url"); +const OTHER_CLIENT_ID = Buffer.from("another-client-id-987654").toString("base64url"); +const CLIENT_SECRET = `gwid_cs_${Buffer.from("secret-of-the-test-client-012345").toString("base64url")}`; +const API_TOKEN = "api-token-known-to-this-test-0123456789"; +const OAUTH_TOKEN = "oauth-token-known-to-this-test-abcdefghij"; +const SECRETS = { PAIRWISE, CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN }; +/** In Wrangler's deployment JSON, which is read and never shown. */ +const AUTHOR_EMAIL = "deployment-author@example.com"; + +const ID = "https://gateweave-id.rehearsal.workers.dev"; +const TRACK = "https://gateweave-track.rehearsal.workers.dev"; +const RESOURCE_PATH = "/.well-known/oauth-protected-resource"; +const ADD_APP = join("scripts", "add-app.ts"); +const STRICT = "global_fetch_strictly_public"; +const LOCK = "connect-id-track.lock"; + +const cleanup: string[] = []; +after(() => { + for (const dir of cleanup) rmSync(dir, { recursive: true, force: true }); +}); + +interface ConnectFakeOptions extends FakeOptions { + /** Secrets each Worker has besides BETTER_AUTH_SECRET. */ + idSecrets?: string[]; + trackSecrets?: string[]; + /** Text variables of each Worker, by name. */ + idVars?: Record; + trackVars?: Record; + /** Other bindings of Track, by name and type. */ + trackBindings?: Record; + /** Each Worker's compatibility flags. Default: Track has global_fetch_strictly_public, ID not. */ + idFlags?: string[]; + trackFlags?: string[]; + /** Client ids already registered in ID for Track's redirect URI. */ + registered?: string[]; + /** Overrides the registration lookup with a failed or unreadable response. */ + registrationFailure?: "command" | "json"; + /** Replaces what the fake apps:add prints, and its status and stderr. */ + appsAdd?: { stdout: string; status?: number; stderr?: string }; + /** The client id ID keeps for the app apps:add registers. Default: CLIENT_ID. */ + registerAs?: string; + /** A `secret put` of this name fails, echoing its value and the tokens on stderr. */ + failPut?: string; + /** Makes this look fail. */ + failLook?: "deployments" | "versions"; + /** A secret the secret list shows and the deployed version does not. */ + missingFromVersion?: string; + /** How many versions the deployment spreads over. */ + versions?: number; + /** ID's discovery never answers. */ + discoveryDown?: boolean; + /** A button Track's sign-in page shows whatever is set. */ + extraButton?: string; + /** The name on Track's provider button, instead of the one set. */ + buttonName?: string; +} + +/** + * Two deployments made by this tool in the fake account, ID and Track, and a fake that also knows + * `wrangler secret put`, the deployed version's bindings, ID's apps:add, the registration query and + * the two pages the checks read. + */ +async function connectFake(options: ConnectFakeOptions = {}) { + const fake = fakeSystem({ ...options, env: { CLOUDFLARE_API_TOKEN: API_TOKEN, ...options.env } }); + cleanup.push(fake.home); + const work = mkdtempSync(join(tmpdir(), "gateweave-connect-work-")); + const keepDir = mkdtempSync(join(tmpdir(), "gateweave-connect-keep-")); + cleanup.push(work, keepDir); + const wranglerConfig = join(fake.home, ".wrangler", "config"); + mkdirSync(wranglerConfig, { recursive: true }); + const oauthFile = join(wranglerConfig, "default.toml"); + writeFileSync( + oauthFile, + `oauth_token = "${OAUTH_TOKEN}"\nrefresh_token = "refresh-0123456789"\n`, + ); + + const state = { + failPut: options.failPut, + beforeOpen: undefined as (() => void) | undefined, + /** A put of this name is taken by Cloudflare, but its answer is lost: Wrangler fails. */ + lostPut: undefined as string | undefined, + /** Every `secret list` after a put of this name fails. */ + failListAfter: undefined as string | undefined, + listFails: false, + resourceProof: undefined as HttpResponse | undefined, + }; + const puts: { + worker: string; + name: string; + input: string | undefined; + errBefore: string; + /** The record file as it was when this put ran, or null. */ + recordBefore: string | null; + }[] = []; + const appsAdd: { args: string[]; cwd: string }[] = []; + const registrations = [...(options.registered ?? [])]; + const logoutUris = new Map( + registrations.map((id) => [id, backchannelLogoutUri(TRACK)]), + ); + /** What each put set, so the pages show what Track was given. */ + const values = new Map(); + const vars: Record> = { + "gateweave-id": { ...options.idVars }, + "gateweave-track": { ...options.trackVars }, + }; + let randomCalls = 0; + /** Each file opened for a person to keep, with the flags and mode asked for. */ + const kept: { path: string; flags: number; mode: number }[] = []; + const secretsOf = (worker: string) => { + let set = fake.cloud.secrets.get(worker); + if (!set) { + set = new Set(["BETTER_AUTH_SECRET"]); + fake.cloud.secrets.set(worker, set); + } + return set; + }; + const setting = (worker: string, name: string) => + vars[worker]?.[name] ?? (secretsOf(worker).has(name) ? values.get(`${worker} ${name}`) : null); + const isSet = (worker: string, name: string) => + vars[worker]?.[name] !== undefined || secretsOf(worker).has(name); + + const inner = fake.sys.run; + fake.sys.run = async (command: string, args: string[], runOptions: RunOptions) => { + const record = () => + fake.calls.push({ + argv: [command, ...args], + cwd: runOptions.cwd, + accountId: runOptions.env?.CLOUDFLARE_ACCOUNT_ID, + }); + const at = args.indexOf(`wrangler@${WRANGLER}`); + const rest = at >= 0 ? args.slice(at + 1) : []; + const worker = rest[rest.indexOf("--name") + 1] ?? ""; + if ( + command === fake.sys.execPath && + rest[0] === "secret" && + rest[1] === "list" && + state.listFails + ) { + record(); + return { + status: 1, + stdout: "", + stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n", + }; + } + if (command === fake.sys.execPath && rest[0] === "secret" && rest[1] === "put") { + record(); + const name = rest[2] ?? ""; + puts.push({ + worker, + name, + input: runOptions.input, + errBefore: fake.output.err, + recordBefore: existsSync(recordPath(fake.sys)) + ? readFileSync(recordPath(fake.sys), "utf8") + : null, + }); + if (state.failListAfter === name) state.listFails = true; + if (state.lostPut === name) { + secretsOf(worker).add(name); + values.set(`${worker} ${name}`, runOptions.input ?? ""); + return { status: 1, stdout: "", stderr: "✘ [ERROR] The connection was reset.\n" }; + } + if (state.failPut === name) { + return { + status: 1, + stdout: "", + stderr: `✘ [ERROR] A request to the Cloudflare API failed: the body ${runOptions.input} was sent with ${API_TOKEN} and ${OAUTH_TOKEN}\n`, + }; + } + secretsOf(worker).add(name); + values.set(`${worker} ${name}`, runOptions.input ?? ""); + return { + status: 0, + stdout: `🌀 Creating the secret for the Worker "${worker}"\n✨ Success! Uploaded secret ${name}\n`, + stderr: "", + }; + } + if (command === fake.sys.execPath && rest[0] === "deployments" && rest[1] === "status") { + record(); + if (options.failLook === "deployments") { + return { + status: 1, + stdout: "", + stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n", + }; + } + const versions = Array.from({ length: options.versions ?? 1 }, (_, index) => ({ + version_id: `0000000${index}-aaaa-bbbb-cccc-${worker.length.toString().padStart(12, "0")}`, + percentage: 100 / (options.versions ?? 1), + })); + return { + status: 0, + stdout: JSON.stringify({ id: "d1", author_email: AUTHOR_EMAIL, versions }), + stderr: "", + }; + } + if (command === fake.sys.execPath && rest[0] === "versions" && rest[1] === "view") { + record(); + if (options.failLook === "versions") { + return { + status: 1, + stdout: "", + stderr: "✘ [ERROR] A request to the Cloudflare API failed.\n", + }; + } + const flags = + worker === "gateweave-track" ? (options.trackFlags ?? [STRICT]) : (options.idFlags ?? []); + const bindings = [ + { type: "d1", name: "DB", id: `uuid-${worker}` }, + ...[...secretsOf(worker)] + .filter((name) => name !== options.missingFromVersion) + .map((name) => ({ type: "secret_text", name })), + ...Object.entries(vars[worker] ?? {}).map(([name, text]) => ({ + type: "plain_text", + name, + text, + })), + ...Object.entries(worker === "gateweave-track" ? (options.trackBindings ?? {}) : {}).map( + ([name, type]) => ({ type, name }), + ), + ]; + return { + status: 0, + stdout: JSON.stringify({ + id: rest[2], + metadata: { author_email: AUTHOR_EMAIL }, + resources: { + bindings, + script_runtime: { compatibility_date: "2026-01-01", compatibility_flags: flags }, + }, + }), + stderr: "", + }; + } + if ( + command === fake.sys.execPath && + rest[0] === "d1" && + rest[1] === "execute" && + rest.join(" ").includes("oauth_client") + ) { + record(); + // It runs in ID's checkout, whose wrangler.jsonc must name ID's database. + const config = parse(readFileSync(join(runOptions.cwd, "wrangler.jsonc"), "utf8")) as { + d1_databases: { database_name: string; database_id?: string }[]; + }; + assert.equal(config.d1_databases[0]?.database_name, "gateweave-id"); + assert.equal(config.d1_databases[0]?.database_id, "uuid-gateweave-id"); + if (options.registrationFailure === "command") { + return { status: 1, stdout: "", stderr: `D1 lookup failed with ${API_TOKEN}` }; + } + if (options.registrationFailure === "json") { + return { status: 0, stdout: "unreadable", stderr: "" }; + } + return { + status: 0, + stdout: JSON.stringify([ + { + results: registrations.map((id) => ({ + client_id: id, + backchannel_logout_uri: logoutUris.get(id), + })), + success: true, + meta: {}, + }, + ]), + stderr: "", + }; + } + if (command === fake.sys.execPath && args[0] === ADD_APP) { + record(); + appsAdd.push({ args, cwd: runOptions.cwd }); + // ID's script runs in apps/web and reaches the database through the checkout's config. + const config = readFileSync(join(runOptions.cwd, "..", "..", "wrangler.jsonc"), "utf8"); + assert.match(config, /"database_name": "gateweave-id"/); + assert.equal(runOptions.stream, undefined); + const id = options.registerAs ?? CLIENT_ID; + registrations.push(id); + logoutUris.set(id, args[args.indexOf("--backchannel-logout-uri") + 1]); + if (options.appsAdd !== undefined) { + return { + status: options.appsAdd.status ?? 0, + stdout: options.appsAdd.stdout, + stderr: options.appsAdd.stderr ?? "", + }; + } + return { + status: 0, + stdout: `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\n`, + stderr: "(node) ExperimentalWarning: Type Stripping is an experimental feature\n", + }; + } + const result = await inner(command, args, runOptions); + if ( + command === "git" && + args.includes("clone") && + args.includes("https://github.com/gateweavehq/id.git") + ) { + const scripts = join(args.at(-1) ?? "", "apps", "web", "scripts"); + mkdirSync(scripts, { recursive: true }); + writeFileSync(join(scripts, "add-app.ts"), "// ID's apps:add\n"); + } + return result; + }; + + const innerFetch = fake.sys.fetch; + fake.sys.fetch = async (url: string, request: HttpRequest = {}) => { + const { pathname, origin } = new URL(url); + if (pathname === "/.well-known/openid-configuration") { + fake.events.push(`fetch GET ${url}`); + return !options.discoveryDown && + isSet("gateweave-id", "BETTER_AUTH_URL") && + isSet("gateweave-id", "OIDC_PAIRWISE_SECRET") + ? { status: 200, headers: {}, text: JSON.stringify({ issuer: origin }) } + : { status: 404, headers: {}, text: "" }; + } + if (pathname === RESOURCE_PATH) { + assert.deepEqual(request, { method: "GET" }); + fake.events.push(`fetch GET ${url}`); + if (state.resourceProof) return state.resourceProof; + const pinned = setting("gateweave-track", "BETTER_AUTH_URL"); + return pinned + ? { + status: 200, + headers: {}, + text: JSON.stringify({ resource: new URL("/mcp", pinned).href }), + } + : { status: 404, headers: {}, text: "" }; + } + if (pathname === "/login" && !url.startsWith(ID) && !url.startsWith("https://id.")) { + fake.events.push(`fetch GET ${url}`); + const track = "gateweave-track"; + const on = ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"].every((name) => + isSet(track, name), + ); + const name = options.buttonName ?? setting(track, "OIDC_PROVIDER_NAME") ?? "single sign-on"; + const issuer = setting(track, "OIDC_ISSUER"); + const buttons = [ + ...(on ? [``] : []), + ...(options.extraButton ? [``] : []), + ].join(""); + return { + status: 200, + headers: { + "content-security-policy": `default-src 'none'; img-src 'self' data: blob: https://avatars.githubusercontent.com${issuer ? ` ${new URL(issuer).origin}` : ""}; font-src 'self'`, + }, + text: `Gateweave Track${buttons}`, + }; + } + return innerFetch(url, request); + }; + + fake.sys.cwd = work; + fake.sys.openNew = async (path, flags, mode) => { + kept.push({ path, flags, mode }); + state.beforeOpen?.(); + return open(path, flags, mode); + }; + fake.sys.random = (bytes: number) => { + randomCalls++; + assert.equal(bytes, 48); + return new Uint8Array(PAIRWISE_BYTES); + }; + + assert.equal(await main(["deploy", "id", "--yes"], fake.sys), 0); + assert.equal(await main(["deploy", "track", "--yes"], fake.sys), 0); + for (const name of options.idSecrets ?? []) secretsOf("gateweave-id").add(name); + for (const name of options.trackSecrets ?? []) secretsOf("gateweave-track").add(name); + fake.output.out = ""; + fake.output.err = ""; + const callsBefore = fake.calls.length; + const tmpBefore = new Set(readdirSync(tmpdir())); + + async function connect(args: string[]) { + fake.output.out = ""; + fake.output.err = ""; + const code = await main(["connect", "id", "track", ...args], fake.sys); + const result = + args.includes("--json") && fake.output.out ? JSON.parse(fake.output.out) : undefined; + return { code, result, out: fake.output.out, err: fake.output.err }; + } + + /** Every file this run could have written to, outside the ones the test allows. */ + function writtenFiles(allowed: readonly string[] = []): string[] { + const files: string[] = []; + const visit = (path: string) => { + let stat: ReturnType; + try { + stat = lstatSync(path); + } catch { + return; // Another test file removed it meanwhile. + } + if (stat.isFile()) { + files.push(path); + return; + } + if (!stat.isDirectory()) return; + let entries: string[] = []; + try { + entries = readdirSync(path); + } catch { + return; + } + for (const entry of entries) visit(join(path, entry)); + }; + visit(work); + visit(fake.home); + // The OS temp folder: new folders, and new files at its top level too. + for (const entry of readdirSync(tmpdir())) { + if (!tmpBefore.has(entry)) visit(join(tmpdir(), entry)); + } + const skip = new Set([oauthFile, ...allowed].map((path) => resolve(path))); + return files.filter((path) => !skip.has(resolve(path))); + } + + return { + fake, + work, + keepDir, + puts, + appsAdd, + registrations, + logoutUris, + values, + vars, + state, + connect, + writtenFiles, + randomCalls: () => randomCalls, + kept, + newCalls: () => fake.calls.slice(callsBefore), + changes: () => + fake.calls + .slice(callsBefore) + .filter((call) => !readsOnly(call) && !call.argv.includes("clone")), + }; +} + +function leaked(text: string, which: Record = SECRETS): string[] { + return Object.entries(which) + .filter(([, value]) => text.includes(value)) + .map(([name]) => name); +} + +function leakedInFiles(files: string[], which: Record = SECRETS): string[] { + const found: string[] = []; + for (const file of files) { + let text: string; + try { + text = readFileSync(file, "latin1"); + } catch { + continue; + } + for (const name of leaked(text, which)) found.push(`${name} in ${file}`); + } + return found; +} + +/** A folder link that needs no rights on Windows: a junction there, a symlink elsewhere. */ +function linkFolder(target: string, path: string) { + symlinkSync(target, path, "junction"); +} + +function unlinkFolder(path: string) { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +const keepArgs = (run: { keepDir: string }, name = "pairwise.txt") => [ + "--keep-secret-at", + join(run.keepDir, name), +]; + +describe("gateweave connect id track", () => { + test("the shared filter hides ID's client secret line, its prefix and OIDC secret assignments", () => { + assert.equal(hideSecrets("client secret: abcdefghijkl", []), "client secret: [secret]"); + assert.equal(hideSecrets(`{"client_secret": "zz zz"}`, []), `{"client_secret": "[secret]"}`); + assert.equal(hideSecrets("OIDC_CLIENT_SECRET=xyz123", []), "OIDC_CLIENT_SECRET=[secret]"); + assert.equal( + hideSecrets('OIDC_PAIRWISE_SECRET: "a b c"', []), + 'OIDC_PAIRWISE_SECRET: "[secret]"', + ); + assert.equal(hideSecrets("see gwid_cs_abcDEF-_1 here", []), "see [secret] here"); + }); + + test("the secrets reach only the stdin of secret put and the --keep-secret-at file", async () => { + const run = await connectFake(); + const keep = join(run.keepDir, "pairwise.txt"); + const { code, result, out, err } = await run.connect([ + "--keep-secret-at", + keep, + "--yes", + "--json", + ]); + assert.equal(code, 0, err); + assert.equal(result.ok, true); + assert.equal(result.clientId, CLIENT_ID); + assert.equal(result.registeredNow, true); + assert.deepEqual(result.account, { id: "a1b2c3", name: "Rehearsal" }); + assert.deepEqual(result.id, { worker: "gateweave-id", address: ID, issuer: ID }); + assert.deepEqual(result.track, { worker: "gateweave-track", address: TRACK }); + assert.deepEqual(result.pairwiseSecret, { + generatedNow: true, + keptAt: keep, + shownOnTerminal: false, + }); + assert.ok(result.checks.length >= 4); + assert.ok(result.checks.every((check: { ok: boolean }) => check.ok)); + + // Where each value went: the generated one to ID, the registration's to Track, on stdin. + assert.deepEqual( + run.puts.map(({ worker, name }) => `${worker} ${name}`), + [ + "gateweave-id BETTER_AUTH_URL", + "gateweave-id OIDC_PAIRWISE_SECRET", + "gateweave-track OIDC_CLIENT_SECRET", + "gateweave-track OIDC_CLIENT_ID", + "gateweave-track OIDC_ISSUER", + "gateweave-track OIDC_PROVIDER_NAME", + "gateweave-track BETTER_AUTH_URL", + ], + ); + const input = (name: string) => run.puts.find((put) => put.name === name)?.input; + assert.equal(input("OIDC_PAIRWISE_SECRET"), PAIRWISE); + assert.equal(input("OIDC_CLIENT_SECRET"), CLIENT_SECRET); + assert.equal(input("OIDC_CLIENT_ID"), CLIENT_ID); + assert.equal(input("OIDC_ISSUER"), ID); + assert.equal(input("OIDC_PROVIDER_NAME"), "Gateweave ID"); + assert.deepEqual( + run.puts.filter((put) => leaked(put.input ?? "").length > 0).map(({ name }) => name), + ["OIDC_PAIRWISE_SECRET", "OIDC_CLIENT_SECRET"], + ); + assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`); + // Asked for on every platform: made new, never through a link in its last part, readable by + // its owner alone. Where the system keeps modes, the file has it. + assert.equal(run.kept.length, 1); + const [opened] = run.kept; + assert.equal(opened?.path, keep); + assert.equal(opened?.mode, 0o600); + for (const flag of [constants.O_CREAT, constants.O_EXCL, constants.O_WRONLY]) { + assert.equal((opened?.flags ?? 0) & flag, flag); + } + if (constants.O_NOFOLLOW !== undefined) { + assert.equal((opened?.flags ?? 0) & constants.O_NOFOLLOW, constants.O_NOFOLLOW); + } + if (process.platform !== "win32") assert.equal(statSync(keep).mode & 0o777, 0o600); + + // Nowhere else: not the screen, not --json, not the record, not a file, not an argument. + assert.deepEqual(leaked(out), []); + assert.deepEqual(leaked(err), []); + assert.ok(!`${out}${err}`.includes(AUTHOR_EMAIL)); + assert.deepEqual(leaked(readFileSync(recordPath(run.fake.sys), "utf8")), []); + assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []); + assert.deepEqual( + run.fake.calls.filter(({ argv }) => leaked(argv.join(" ")).length > 0), + [], + ); + + // Registered with ID's own apps:add, the redirect and back-channel logout URIs on Track. + assert.equal(run.appsAdd.length, 1); + assert.deepEqual(run.appsAdd[0]?.args, [ + ADD_APP, + "--app", + "track", + "--name", + "Gateweave Track", + "--redirect-uri", + `${TRACK}/api/auth/callback/oidc`, + "--backchannel-logout-uri", + `${TRACK}/api/auth/backchannel-logout/oidc`, + ]); + assert.match(run.appsAdd[0]?.cwd ?? "", /[\\/]id[\\/]v0\.50\.0-gateweave-id[\\/]apps[\\/]web$/); + + // The record keeps the client id, never a secret, and the lock is gone again. + const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")); + assert.equal(file.deployments.length, 2); + assert.deepEqual( + file.connections.map(({ clientId, steps }: { clientId: string; steps: string[] }) => ({ + clientId, + steps, + })), + [{ clientId: CLIENT_ID, steps: ["registered", "connected", "checked"] }], + ); + assert.ok(!existsSync(join(configDir(run.fake.sys), LOCK))); + }); + + test("--no-account-name keeps the account's name out of the plan, the errors and --json", async () => { + const name = "owner@example.com's Account"; + const run = await connectFake({ accounts: [{ id: "a1b2c3", name }] }); + const { code, result, out, err } = await run.connect([ + ...keepArgs(run), + "--no-account-name", + "--yes", + "--json", + ]); + assert.equal(code, 0, err); + assert.deepEqual(result.account, { id: "a1b2c3" }); + assert.match(err, /Connect Track to ID in the Cloudflare account a1b2c3, so/); + for (const text of [out, err]) { + assert.ok(!text.includes("owner@example.com"), text); + assert.ok(!text.includes(name)); + } + // An error that names the account names it by id alone. + const again = await connectFake({ accounts: [{ id: "a1b2c3", name }] }); + const failed = await again.connect(["--no-account-name", "--id-name", "nope", "--json"]); + assert.equal(failed.code, 3); + assert.match(failed.result.reason, /in the Cloudflare account a1b2c3\./); + assert.ok(!`${failed.out}${failed.err}`.includes("owner@example.com")); + }); + + test("without --keep-secret-at, a terminal shows the pairwise secret once, before it is set", async () => { + const run = await connectFake({ interactive: true, answer: true }); + const { code, out, err } = await run.connect([]); + assert.equal(code, 0, err); + assert.equal(err.split(PAIRWISE).length - 1, 1); + assert.match(err, /Keep this value now, in your password manager/); + assert.match(err, /gives everyone a new id in every app/); + // On the screen before ID has it, so a run cut short after the put leaves a copy. + const pairwisePut = run.puts.find(({ name }) => name === "OIDC_PAIRWISE_SECRET"); + assert.ok(pairwisePut?.errBefore.includes(PAIRWISE)); + assert.deepEqual(leaked(out), []); + assert.deepEqual(leaked(err, { CLIENT_SECRET, API_TOKEN, OAUTH_TOKEN }), []); + assert.deepEqual(leakedInFiles(run.writtenFiles()), []); + assert.deepEqual(run.fake.questions, ["Make these changes? [y/N] "]); + assert.match(out, /signs people in through ID \(gateweave-id\) now/); + }); + + test("an exact rerun checks the Track URL it first put as a secret and changes nothing", async () => { + const run = await connectFake(); + const keep = join(run.keepDir, "pairwise.txt"); + const args = ["--keep-secret-at", keep, "--yes", "--json"]; + const first = await run.connect(args); + assert.equal(first.code, 0, first.err); + assert.equal(first.result.registeredNow, true); + assert.equal(run.values.get("gateweave-track BETTER_AUTH_URL"), TRACK); + assert.equal(run.fake.cloud.secrets.get("gateweave-track")?.has("BETTER_AUTH_URL"), true); + assert.equal(run.fake.events.includes(`fetch GET ${TRACK}${RESOURCE_PATH}`), false); + const puts = run.puts.length; + // The same command again: the file it wrote exists, and nothing is made to go in it. + const second = await run.connect(args); + assert.equal(second.code, 0, second.err); + assert.equal(second.result.changedNow, false); + assert.equal(second.result.registeredNow, false); + assert.equal(second.result.clientId, CLIENT_ID); + assert.equal(second.result.pairwiseSecret.keptAt, null); + assert.equal(run.appsAdd.length, 1); + assert.equal(run.puts.length, puts); + assert.equal(run.randomCalls(), 1); + assert.equal(run.registrations.length, 1); + assert.equal( + run.fake.events.filter((event) => event === `fetch GET ${TRACK}${RESOURCE_PATH}`).length, + 1, + ); + assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`); + assert.match(second.err, /An earlier run connected these already; nothing will be changed/); + assert.match( + second.err, + /OIDC_PAIRWISE_SECRET is already set, so --keep-secret-at is not used/, + ); + }); + + test("apps:add output in any other form stops, and nothing it printed is shown", async () => { + const tooLong = `${CLIENT_ID}xy`; + const secretAsId = `gwid_cs_${"a".repeat(24)}`; + for (const output of [ + `Registered Gateweave Track.\nclient id ${CLIENT_ID}\nclient secret ${CLIENT_SECRET}\n`, + `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: plain-secret-without-its-prefix-0123456789\n`, + `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nclient secret: ${CLIENT_SECRET}\n`, + `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\nextra: something else\n`, + `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${tooLong}\nclient secret: ${CLIENT_SECRET}\n`, + `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${secretAsId}\nclient secret: ${CLIENT_SECRET}\n`, + ]) { + const run = await connectFake({ appsAdd: { stdout: output } }); + const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 8, output); + assert.equal(result.code, "register-output-unreadable"); + for (const text of [out, err]) { + assert.doesNotMatch(text, /Registered Gateweave Track/); + for (const value of [CLIENT_ID, tooLong, secretAsId, "plain-secret-without-its-prefix"]) { + assert.ok(!text.includes(value), "nothing captured is shown"); + } + assert.deepEqual(leaked(text), []); + } + assert.deepEqual( + run.puts.filter(({ worker }) => worker === "gateweave-track"), + [], + "Track is given nothing", + ); + assert.ok(!readFileSync(recordPath(run.fake.sys), "utf8").includes(secretAsId)); + assert.deepEqual(leakedInFiles(run.writtenFiles([join(run.keepDir, "pairwise.txt")])), []); + } + }); + + test("apps:add stopping says where to look and repeats none of its output", async () => { + const run = await connectFake({ + appsAdd: { + status: 1, + stdout: "", + stderr: "✘ [ERROR] D1 said no: detail-from-the-child-0123 and plain-secret-zz-0123456789\n", + }, + }); + const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 8); + assert.equal(result.code, "register-failed"); + assert.match(result.reason, /exit 1/); + assert.match(result.reason, /d1 execute DB --remote --command "SELECT 1"/); + for (const text of [out, err]) { + assert.ok(!text.includes("detail-from-the-child")); + assert.ok(!text.includes("plain-secret-zz")); + } + assert.deepEqual( + run.puts.filter(({ worker }) => worker === "gateweave-track"), + [], + ); + }); + + test("every connect child uses its category's process timeouts", async () => { + const run = await connectFake(); + rmSync(join(cacheDir(run.fake.sys), "id"), { recursive: true }); + const inner = run.fake.sys.run; + const seen = new Set(); + run.fake.sys.run = (command, args, options) => { + let category: keyof typeof PROCESS_TIMEOUTS = "listing"; + if (args.includes("--version")) category = "version"; + else if (args.includes("clone")) category = "clone"; + else if (args.includes("install")) category = "install"; + else if (args[0] === ADD_APP || options.input !== undefined) category = "deploy"; + seen.add(category); + assert.equal(options.timeoutMs, PROCESS_TIMEOUTS[category].timeoutMs, args.join(" ")); + assert.equal(options.idleTimeoutMs, PROCESS_TIMEOUTS[category].idleTimeoutMs, args.join(" ")); + return inner(command, args, options); + }; + const { code, err } = await run.connect([...keepArgs(run), "--yes"]); + assert.equal(code, 0, err); + assert.deepEqual(seen, new Set(Object.keys(PROCESS_TIMEOUTS))); + }); + + test("a hung apps:add is stopped without exposing its output or registering twice on retry", async () => { + const run = await connectFake(); + const inner = run.fake.sys.run; + run.fake.sys.run = async (command, args, options) => { + if (args[0] !== ADD_APP) return inner(command, args, options); + assert.equal(options.timeoutMs, PROCESS_TIMEOUTS.deploy.timeoutMs); + assert.equal(options.idleTimeoutMs, PROCESS_TIMEOUTS.deploy.idleTimeoutMs); + assert.equal(options.stream, undefined); + // The registration may have landed before the subprocess stopped responding. + await inner(command, args, options); + const stopped = await runProcess( + process.execPath, + [ + "-e", + "console.log(process.env.FAKE_SECRET); console.error(process.env.FAKE_TOKEN); setInterval(() => {}, 1000)", + ], + { + ...options, + env: { FAKE_SECRET: CLIENT_SECRET, FAKE_TOKEN: API_TOKEN }, + idleTimeoutMs: 0, + timeoutMs: 1_000, + }, + ); + assert.equal(stopped.timeout, "overall"); + assert.equal(stopped.cleanup, "confirmed"); + assert.match(stopped.stdout, /gwid_cs_/); + assert.ok(stopped.stderr.includes(API_TOKEN)); + return stopped; + }; + const first = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(first.code, 8, first.err); + assert.equal(first.result.code, "register-failed"); + assert.match(first.result.reason, /timed out \(overall\)/); + assert.deepEqual(leaked(first.out + first.err), []); + assert.ok(!run.puts.some(({ worker }) => worker === "gateweave-track")); + assert.ok(!existsSync(join(configDir(run.fake.sys), LOCK))); + const second = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(second.result.code, "registered-without-secret"); + assert.equal(run.appsAdd.length, 1); + assert.equal(run.registrations.length, 1); + }); + + test("settings already set are left alone, text variables included, and their values used", async () => { + const run = await connectFake({ + idSecrets: ["OIDC_PAIRWISE_SECRET"], + idVars: { BETTER_AUTH_URL: ID }, + trackVars: { BETTER_AUTH_URL: TRACK, OIDC_PROVIDER_NAME: "Acme Sign-in" }, + }); + // No pairwise secret is made, so --json needs no file to keep one in. + const { code, result, err } = await run.connect(["--yes", "--json"]); + assert.equal(code, 0, err); + assert.deepEqual( + run.puts.map(({ worker, name }) => `${worker} ${name}`), + [ + "gateweave-track OIDC_CLIENT_SECRET", + "gateweave-track OIDC_CLIENT_ID", + "gateweave-track OIDC_ISSUER", + ], + ); + assert.equal(run.randomCalls(), 0); + assert.equal(result.pairwiseSecret.generatedNow, false); + assert.deepEqual( + result.settings + .filter(({ setNow }: { setNow: boolean }) => !setNow) + .map(({ product, name }: { product: string; name: string }) => `${product} ${name}`), + [ + "id BETTER_AUTH_URL", + "id OIDC_PAIRWISE_SECRET", + "track OIDC_PROVIDER_NAME", + "track BETTER_AUTH_URL", + ], + ); + assert.match(err, /BETTER_AUTH_URL\s+\(already set as a text variable; left as it is\)/); + assert.match(err, /OIDC_PAIRWISE_SECRET\s+\(already set; left as it is\)/); + assert.match(err, /OIDC_PROVIDER_NAME\s+\(already set as a text variable; left as it is\)/); + assert.doesNotMatch(err, /issuer, ID's BETTER_AUTH_URL .* can never change/); + // The button is looked for by the text variable's name. + assert.ok( + result.checks.some(({ name }: { name: string }) => + name.includes('"Continue with Acme Sign-in"'), + ), + ); + }); + + test("ID's BETTER_AUTH_URL as a text variable names the issuer, before anything changes", async () => { + const run = await connectFake({ idVars: { BETTER_AUTH_URL: "https://id.example.com" } }); + const given = await run.connect(["--id-url", ID, ...keepArgs(run), "--yes", "--json"]); + assert.equal(given.code, 3); + assert.equal(given.result.code, "issuer-differs"); + assert.deepEqual(run.changes(), []); + }); + + test("a setting held by another kind of binding stops the run, and replaces nothing", async () => { + const run = await connectFake({ trackBindings: { OIDC_ISSUER: "kv_namespace" } }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "name-in-use"); + assert.deepEqual(run.changes(), []); + }); + + test("Track's BETTER_AUTH_URL as a text variable for another address stops the run", async () => { + const run = await connectFake({ + trackVars: { BETTER_AUTH_URL: "https://elsewhere.example.com" }, + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "track-address-differs"); + assert.deepEqual(run.changes(), []); + }); + + test("first connect verifies an existing secret Track URL without replacing it", async () => { + const run = await connectFake({ trackSecrets: ["BETTER_AUTH_URL"] }); + run.values.set("gateweave-track BETTER_AUTH_URL", TRACK); + const { code, result, err } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 0, err); + assert.equal(result.registeredNow, true); + assert.equal(run.appsAdd.length, 1); + assert.ok(run.fake.events.includes(`fetch GET ${TRACK}${RESOURCE_PATH}`)); + assert.ok( + !run.puts.some( + ({ worker, name }) => worker === "gateweave-track" && name === "BETTER_AUTH_URL", + ), + ); + }); + + test("unproven secret Track URLs stop before writes on first connect and reruns", async () => { + const hiddenUrl = "https://private-track-address.example.com"; + const failures: [string, HttpResponse | undefined][] = [ + ["other origin", undefined], + [ + "other path", + { status: 200, headers: {}, text: JSON.stringify({ resource: `${TRACK}/mcp/` }) }, + ], + ["missing endpoint", { status: 404, headers: {}, text: "" }], + ["missing resource", { status: 200, headers: {}, text: "{}" }], + ["malformed", { status: 200, headers: {}, text: `not JSON: ${hiddenUrl}` }], + [ + "redirected", + { + status: 302, + headers: { location: hiddenUrl }, + text: JSON.stringify({ resource: `${TRACK}/mcp` }), + }, + ], + ]; + for (const rerun of [false, true]) { + for (const [kind, response] of failures) { + const run = await connectFake({ trackSecrets: rerun ? [] : ["BETTER_AUTH_URL"] }); + const args = [...keepArgs(run), "--yes", "--json"]; + if (rerun) { + const first = await run.connect(args); + assert.equal(first.code, 0, first.err); + } + run.values.set("gateweave-track BETTER_AUTH_URL", hiddenUrl); + run.state.resourceProof = response; + const changes = run.changes().length; + const random = run.randomCalls(); + const record = readFileSync(recordPath(run.fake.sys), "utf8"); + const before = run.fake.events.length; + const { code, result, out, err } = await run.connect(args); + assert.equal(code, 3, `${kind} on ${rerun ? "rerun" : "first run"}: ${err}`); + assert.equal(result.code, "track-address-unverified"); + assert.match(result.reason, /verify the value through Track's deployment configuration/i); + assert.match(result.reason, /public OAuth resource metadata did not confirm/); + assert.match(result.reason, /Nothing was changed/); + assert.equal(run.changes().length, changes); + assert.equal(run.randomCalls(), random); + assert.equal(readFileSync(recordPath(run.fake.sys), "utf8"), record); + const events = run.fake.events.slice(before); + assert.equal( + events.filter((event) => event === `fetch GET ${TRACK}${RESOURCE_PATH}`).length, + 1, + ); + assert.ok(!events.some((event) => event.includes(hiddenUrl))); + assert.deepEqual(leaked(out + err, { ...SECRETS, hiddenUrl }), []); + } + } + }); + + test("a look that fails, or listings that disagree, stop the run: nothing unseen counts as absent", async () => { + const looks: [ConnectFakeOptions, string][] = [ + [{ failLook: "deployments" }, "lookup-failed"], + [{ failLook: "versions" }, "lookup-failed"], + [{ missingFromVersion: "BETTER_AUTH_SECRET" }, "lookup-failed"], + [{ versions: 2 }, "gradual-deployment"], + [ + { idSecrets: ["BETTER_AUTH_URL", "OIDC_PAIRWISE_SECRET"], discoveryDown: true }, + "provider-unreachable", + ], + ]; + for (const [fakeOptions, code] of looks) { + const run = await connectFake(fakeOptions); + const { + code: exit, + result, + out, + err, + } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(exit, 3, JSON.stringify(fakeOptions)); + assert.equal(result.code, code); + assert.match(result.reason, /Nothing was changed/); + assert.deepEqual(run.changes(), []); + assert.ok(!`${out}${err}`.includes(AUTHOR_EMAIL)); + } + }); + + test("the plan names both deployments, ID's database and every setting, and waits", async () => { + const run = await connectFake(); + const { code, err } = await run.connect(keepArgs(run, "k")); + assert.equal(code, 7); + for (const text of [ + /Connect Track to ID in the Cloudflare account Rehearsal \(a1b2c3\)/, + /ID\s+gateweave-id\s+at https:\/\/gateweave-id\.rehearsal\.workers\.dev/, + /Track\s+gateweave-track\s+at https:\/\/gateweave-track\.rehearsal\.workers\.dev/, + /On ID \(gateweave-id\):\n\s+BETTER_AUTH_URL\s+https:\/\/gateweave-id\.rehearsal\.workers\.dev\s+\(set now\)/, + /OIDC_PAIRWISE_SECRET\s+generated here, kept at .*k, never shown\s+\(set now\)/, + /Register Track with ID, with ID's own apps:add, in ID's D1 database gateweave-id \(uuid-gateweave-id\):/, + /redirect URI\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/callback\/oidc/, + /back-channel logout\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev\/api\/auth\/backchannel-logout\/oidc/, + /OIDC_CLIENT_SECRET\s+from the registration, never shown\s+\(set now\)/, + /OIDC_CLIENT_ID\s+from the registration\s+\(set now\)/, + /OIDC_ISSUER\s+https:\/\/gateweave-id\.rehearsal\.workers\.dev\s+\(set now\)/, + /OIDC_PROVIDER_NAME\s+Gateweave ID\s+\(set now\)/, + /On Track \(gateweave-track\):[\s\S]*BETTER_AUTH_URL\s+https:\/\/gateweave-track\.rehearsal\.workers\.dev \(this also turns MCP on\)\s+\(set now\)/, + /Nothing was changed: there is no terminal/, + ]) { + assert.match(err, text); + } + // Before the yes it only read: listings, the one SELECT, outside pages, and the release cache. + assert.deepEqual(run.changes(), []); + assert.deepEqual(run.puts, []); + assert.equal(run.appsAdd.length, 0); + assert.ok(!existsSync(join(run.keepDir, "k"))); + }); + + test("a deployment recorded as not made by this tool is used only when named", async () => { + const run = await connectFake(); + const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")); + for (const deployment of file.deployments) { + if (deployment.product === "id") deployment.external = true; + } + writeFileSync(recordPath(run.fake.sys), JSON.stringify(file)); + const silent = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(silent.code, 2); + assert.equal(silent.result.code, "deployment-not-named"); + assert.match(silent.result.reason, /--id-name gateweave-id/); + assert.deepEqual(run.changes(), []); + const named = await run.connect([ + ...keepArgs(run), + "--id-name", + "gateweave-id", + "--yes", + "--json", + ]); + assert.equal(named.code, 0, named.err); + }); + + test("ID's database is checked against the record before anything is registered in it", async () => { + const run = await connectFake(); + const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")); + for (const deployment of file.deployments) { + if (deployment.product === "id") deployment.databaseId = "uuid-from-before"; + } + writeFileSync(recordPath(run.fake.sys), JSON.stringify(file)); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "database-differs"); + assert.deepEqual(run.changes(), []); + }); + + test("the workers.dev warning names the Worker that calls the other and lacks the flag", async () => { + // As released: Track has global_fetch_strictly_public, ID does not. + const run = await connectFake(); + const { code, err } = await run.connect(keepArgs(run, "k")); + assert.equal(code, 7); + assert.match( + err, + /Warning: The issuer, ID's BETTER_AUTH_URL \(https:\/\/gateweave-id\.rehearsal\.workers\.dev\), can never change once any app has signed anyone in/, + ); + assert.match( + err, + /Warning: The issuer https:\/\/gateweave-id\.rehearsal\.workers\.dev is a workers\.dev address/, + ); + assert.match( + err, + /ID \(gateweave-id\) does not have global_fetch_strictly_public in its compatibility_flags, so its back-channel logout cannot reach Track on workers\.dev/, + ); + assert.doesNotMatch(err, /sign-in through ID fails/); + assert.doesNotMatch(err, /Sign-in works/); + + // Neither Worker has the flag: each direction is told once, and nothing says the other works. + const bare = await connectFake({ trackFlags: [] }); + const without = await bare.connect(keepArgs(bare, "k")); + assert.match( + without.err, + /Track \(gateweave-track\) does not have global_fetch_strictly_public in its compatibility_flags, so it cannot reach ID on workers\.dev: sign-in through ID fails/, + ); + assert.match( + without.err, + /ID \(gateweave-id\) does not have global_fetch_strictly_public in its compatibility_flags, so its back-channel logout cannot reach Track/, + ); + assert.doesNotMatch(without.err, /Sign-in works|sign-in works/); + + // Only ID has it: sign-in fails, and back-channel logout is not warned about. + const idOnly = await connectFake({ trackFlags: [], idFlags: [STRICT] }); + const fromId = await idOnly.connect(keepArgs(idOnly, "k")); + assert.match(fromId.err, /sign-in through ID fails/); + assert.doesNotMatch(fromId.err, /back-channel logout cannot reach/); + + const custom = await connectFake(); + const own = await custom.connect([ + "--id-url", + "https://id.example.com", + "--track-url", + "https://track.example.com", + ...keepArgs(custom, "k"), + ]); + assert.equal(own.code, 7); + assert.match(own.err, /can never change once any app has signed anyone in/); + assert.doesNotMatch(own.err, /workers\.dev/); + assert.match( + own.err, + /redirect URI\s+https:\/\/track\.example\.com\/api\/auth\/callback\/oidc/, + ); + }); + + test("--json without --keep-secret-at refuses while the secret is to be made, as does no terminal", async () => { + const run = await connectFake(); + const { code, result, err } = await run.connect(["--yes", "--json"]); + assert.equal(code, 2); + assert.equal(result.ok, false); + assert.equal(result.code, "keep-path-needed"); + assert.match(result.reason, /With --json it is never printed/); + assert.deepEqual(leaked(err), []); + const plain = await run.connect(["--yes"]); + assert.equal(plain.code, 2); + assert.match(plain.err, /Without a terminal it would land in a log/); + assert.deepEqual(run.puts, []); + assert.equal(run.randomCalls(), 0); + }); + + test("a --keep-secret-at path inside the working directory is refused before anything changes", async () => { + const run = await connectFake(); + // Into the working directory through a folder link: only the real path shows it. + const linked = join(run.keepDir, "looks-outside"); + linkFolder(run.work, linked); + for (const path of [ + join(run.work, "pairwise.txt"), + "pairwise.txt", + join("..", "x", "..", run.work.split(/[\\/]/).at(-1) ?? "", "k"), + join(linked, "pairwise.txt"), + ]) { + const { code, result } = await run.connect(["--keep-secret-at", path, "--yes", "--json"]); + assert.equal(code, 2, path); + assert.equal(result.code, "keep-path-inside", path); + } + assert.deepEqual(run.changes(), []); + assert.deepEqual(readdirSync(run.work), []); + }); + + test("a folder changed after the plan cannot carry the kept secret into the working directory", async () => { + const run = await connectFake(); + const outside = join(run.keepDir, "real"); + mkdirSync(outside); + const folder = join(run.keepDir, "folder"); + linkFolder(outside, folder); + // Between the plan and the write, the folder is pointed into the working directory. + run.state.beforeOpen = () => { + unlinkFolder(folder); + linkFolder(run.work, folder); + }; + const { code, result, out, err } = await run.connect([ + "--keep-secret-at", + join(folder, "pairwise.txt"), + "--yes", + "--json", + ]); + assert.equal(code, 2); + assert.equal(result.code, "keep-path-moved"); + assert.deepEqual(readdirSync(run.work), [], "nothing is left in the working directory"); + assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET")); + assert.deepEqual(leaked(out), []); + assert.deepEqual(leaked(err), []); + assert.deepEqual(leakedInFiles(run.writtenFiles()), []); + }); + + test("a --keep-secret-at file that exists, or a link in its place, is never overwritten", async () => { + const run = await connectFake(); + const keep = join(run.keepDir, "kept.txt"); + writeFileSync(keep, "a value someone kept\n"); + const { code, result } = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]); + assert.equal(code, 2); + assert.equal(result.code, "keep-path-exists"); + assert.equal(readFileSync(keep, "utf8"), "a value someone kept\n"); + const link = join(run.keepDir, "a-link"); + linkFolder(join(run.keepDir, "nowhere"), link); + const linked = await run.connect(["--keep-secret-at", link, "--yes", "--json"]); + assert.equal(linked.code, 2); + assert.equal(linked.result.code, "keep-path-exists"); + // A file that appears after the plan is refused where it is opened. + const late = join(run.keepDir, "late.txt"); + run.state.beforeOpen = () => writeFileSync(late, "someone else's\n"); + const raced = await run.connect(["--keep-secret-at", late, "--yes", "--json"]); + assert.equal(raced.code, 2); + assert.equal(raced.result.code, "keep-path-exists"); + assert.equal(readFileSync(late, "utf8"), "someone else's\n"); + assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET")); + }); + + test("Track registered in ID without Track's secret stops, with steps that end in a run that works", async () => { + const run = await connectFake({ + registered: [CLIENT_ID], + trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID"], + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "registered-without-secret"); + assert.match(result.reason, /never registers Track a second time/); + assert.match(result.reason, /secret put OIDC_CLIENT_SECRET --name gateweave-track/); + assert.match( + result.reason, + new RegExp(`DELETE FROM oauth_client WHERE client_id = '${CLIENT_ID}'`), + ); + assert.match(result.reason, /secret delete OIDC_ISSUER --name gateweave-track/); + assert.match(result.reason, /secret delete OIDC_CLIENT_ID --name gateweave-track/); + assert.equal(run.appsAdd.length, 0); + assert.deepEqual(run.puts, []); + + // Doing what it says, then running again, connects them. + run.registrations.splice(0); + const track = run.fake.cloud.secrets.get("gateweave-track"); + track?.delete("OIDC_ISSUER"); + track?.delete("OIDC_CLIENT_ID"); + const again = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(again.code, 0, again.err); + assert.equal(again.result.registeredNow, true); + }); + + test("an existing registration must prove the exact back-channel logout URI before any writes", async () => { + const logoutUri = backchannelLogoutUri(TRACK); + for (const uri of [undefined, null, 7, "invalid", `${logoutUri}/`]) { + const run = await connectFake({ + registered: [CLIENT_ID], + trackSecrets: ["OIDC_CLIENT_SECRET"], + }); + run.logoutUris.set(CLIENT_ID, uri); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3, String(uri)); + assert.equal(result.code, "registration-logout-unverified"); + assert.ok(result.reason.includes(CLIENT_ID)); + assert.ok(result.reason.includes(logoutUri)); + assert.match(result.reason, /correct backchannel_logout_uri.*then run/); + assert.deepEqual(run.changes(), []); + assert.equal(run.randomCalls(), 0); + + run.logoutUris.set(CLIENT_ID, logoutUri); + const fixed = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(fixed.code, 0, fixed.err); + assert.equal(fixed.result.registeredNow, false); + assert.deepEqual(run.registrations, [CLIENT_ID]); + } + }); + + test("a failed registration lookup never counts as an absent registration", async () => { + for (const registrationFailure of ["command", "json"] as const) { + const run = await connectFake({ registrationFailure }); + const { code, result, out, err } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "lookup-failed"); + assert.deepEqual(run.changes(), []); + assert.deepEqual(leaked(out + err), []); + } + }); + + test("a visible button is not taken for Track's settings", async () => { + const run = await connectFake({ registered: [CLIENT_ID], extraButton: "single sign-on" }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "registered-without-secret"); + }); + + test("an OIDC_PROVIDER_NAME secret this tool did not set stops before anything changes", async () => { + const run = await connectFake({ trackSecrets: ["OIDC_PROVIDER_NAME"] }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "provider-name-unknown"); + assert.match(result.reason, /secret delete OIDC_PROVIDER_NAME --name gateweave-track/); + assert.deepEqual(run.changes(), []); + }); + + test("the button check needs the exact provider name", async () => { + const run = await connectFake({ buttonName: "Someone Else" }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 9); + assert.equal(result.code, "checks-failed"); + assert.match(result.reason, /shows "Continue with Gateweave ID" \(the button is not there\)/); + }); + + test("a registration that differs from the one Track was given stops, with steps to start again", async () => { + const run = await connectFake({ trackVars: { BETTER_AUTH_URL: TRACK } }); + assert.equal((await run.connect([...keepArgs(run), "--yes"])).code, 0); + run.registrations.splice(0, 1, OTHER_CLIENT_ID); + run.logoutUris.set(OTHER_CLIENT_ID, backchannelLogoutUri(TRACK)); + const { code, result } = await run.connect(["--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "client-differs"); + assert.match(result.reason, new RegExp(`registered as client id ${OTHER_CLIENT_ID}`)); + assert.match(result.reason, new RegExp(`gave Track the client id ${CLIENT_ID}`)); + assert.match(result.reason, new RegExp(`client_id = '${OTHER_CLIENT_ID}'`)); + assert.match(result.reason, /secret delete OIDC_CLIENT_SECRET --name gateweave-track/); + assert.equal(run.appsAdd.length, 1); + }); + + test("a Track that already has another provider's client is not changed", async () => { + const run = await connectFake({ + trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET"], + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "track-has-provider"); + assert.match(result.reason, /replaces no setting/); + assert.equal(run.appsAdd.length, 0); + assert.deepEqual(run.puts, []); + }); + + test("a child process that echoes a secret or a token is filtered, and the client secret is tried again", async () => { + const run = await connectFake({ failPut: "OIDC_CLIENT_SECRET" }); + const keep = join(run.keepDir, "pairwise.txt"); + const { code, result, out, err } = await run.connect([ + "--keep-secret-at", + keep, + "--yes", + "--json", + ]); + assert.equal(code, 8); + assert.equal(result.code, "client-secret-not-set"); + assert.match(result.reason, /the body \[secret\] was sent with \[secret\] and \[secret\]/); + assert.match(result.reason, /DELETE FROM oauth_client/); + assert.match(result.reason, /in three tries/); + assert.match( + result.reason, + /The client secret is gone with this run, so the registration needs cleaning up: remove the registration from ID/, + ); + assert.ok( + result.reason.includes( + `then run \`gateweave connect id track --keep-secret-at ${shellArg(keep, process.platform)} --yes --json\` again, which registers`, + ), + result.reason, + ); + assert.equal(run.puts.filter(({ name }) => name === "OIDC_CLIENT_SECRET").length, 3); + assert.deepEqual(leaked(out), []); + assert.deepEqual(leaked(err), []); + const [connection] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections; + assert.equal(connection.clientId, CLIENT_ID); + assert.deepEqual(connection.steps, ["registered"]); + assert.deepEqual(leakedInFiles(run.writtenFiles([keep])), []); + + // The generated value, echoed by a failed put, is filtered too. ID's list shows it is not set; + // even so its file stays, as only the person removes a file that held a secret. + const pairwise = await connectFake({ failPut: "OIDC_PAIRWISE_SECRET" }); + const kept = join(pairwise.keepDir, "pairwise.txt"); + const failed = await pairwise.connect(["--keep-secret-at", kept, "--yes", "--json"]); + assert.equal(failed.code, 8); + assert.equal(failed.result.code, "secret-put-failed"); + assert.match(failed.result.reason, /the body \[secret\] was sent/); + assert.match(failed.result.reason, /ID's list of secrets shows it is not set/); + assert.match(failed.result.reason, /This tool does not remove it; delete it yourself/); + assert.deepEqual(leaked(failed.out), []); + assert.deepEqual(leaked(failed.err), []); + assert.ok(existsSync(kept), "the file is never removed once the put was tried"); + assert.equal(pairwise.appsAdd.length, 0); + // The rerun, with a new path, makes a new value and finishes. + pairwise.state.failPut = undefined; + const again = join(pairwise.keepDir, "pairwise-2.txt"); + const rerun = await pairwise.connect(["--keep-secret-at", again, "--yes", "--json"]); + assert.equal(rerun.code, 0, rerun.err); + assert.equal(pairwise.randomCalls(), 2); + }); + + test("a run cut short after the registration is finished by the next, without registering again", async () => { + const run = await connectFake({ failPut: "OIDC_ISSUER" }); + const first = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(first.code, 8); + assert.equal(first.result.code, "secret-put-failed"); + // The client id was on record before Track was given anything; no secret ever is. + const recorded = readFileSync(recordPath(run.fake.sys), "utf8"); + const [connection] = JSON.parse(recorded).connections; + assert.equal(connection.clientId, CLIENT_ID); + assert.deepEqual(connection.steps, ["registered"]); + assert.deepEqual(leaked(recorded), []); + + run.state.failPut = undefined; + const before = run.puts.length; + const second = await run.connect(["--yes", "--json"]); + assert.equal(second.code, 0, second.err); + assert.equal(second.result.registeredNow, false); + assert.equal(run.appsAdd.length, 1); + assert.equal(run.randomCalls(), 1); + assert.deepEqual( + run.puts.slice(before).map(({ name }) => name), + ["OIDC_ISSUER", "OIDC_PROVIDER_NAME", "BETTER_AUTH_URL"], + ); + }); + + test("a put whose answer is lost, with no listing after it, keeps the file and says the value may be set", async () => { + const run = await connectFake(); + run.state.lostPut = "OIDC_PAIRWISE_SECRET"; + run.state.failListAfter = "OIDC_PAIRWISE_SECRET"; + const keep = join(run.keepDir, "pairwise.txt"); + const first = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]); + assert.equal(first.code, 8); + assert.equal(first.result.code, "secret-put-unknown"); + assert.match(first.result.reason, /whether ID has the value is unknown: it may be set/); + assert.ok(first.result.reason.includes(`Keep ${keep}`)); + assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`, "the only copy stays"); + assert.deepEqual(leaked(first.out), []); + assert.deepEqual(leaked(first.err), []); + assert.equal(run.appsAdd.length, 0); + + // The rerun sees ID has it, makes nothing new, and finishes with the kept value. + run.state.lostPut = undefined; + run.state.failListAfter = undefined; + run.state.listFails = false; + const second = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]); + assert.equal(second.code, 0, second.err); + assert.equal(run.randomCalls(), 1); + assert.equal(run.values.get("gateweave-id OIDC_PAIRWISE_SECRET"), PAIRWISE); + assert.equal(readFileSync(keep, "utf8"), `${PAIRWISE}\n`); + + // A lost answer whose listing shows the value is a put that worked. + const listed = await connectFake(); + listed.state.lostPut = "OIDC_PAIRWISE_SECRET"; + const kept = await listed.connect([...keepArgs(listed), "--yes", "--json"]); + assert.equal(kept.code, 0, kept.err); + }); + + test("a lock that is there is never cleared: the run says who holds it and stops", async () => { + const run = await connectFake(); + const lock = join(configDir(run.fake.sys), LOCK); + mkdirSync(configDir(run.fake.sys), { recursive: true }); + const ended = spawnSync(process.execPath, ["-e", ""]).pid; + const cases: [Record, RegExp][] = [ + [ + { pid: process.pid, host: hostname(), startedAt: "2026-01-02T03:04:05.000Z" }, + /a process with that id is running on this machine now/, + ], + [ + { pid: ended, host: hostname(), startedAt: "2026-01-02T03:04:05.000Z" }, + /no process with that id is running on this machine now/, + ], + [ + { pid: ended, host: `not-${hostname()}`, startedAt: "2026-01-02T03:04:05.000Z" }, + /that is another machine, so whether it still runs cannot be told here/, + ], + ]; + for (const [holder, alive] of cases) { + const text = JSON.stringify(holder); + writeFileSync(lock, text); + // Days old: age clears nothing. + const old = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000); + utimesSync(lock, old, old); + const busy = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(busy.code, 3); + assert.equal(busy.result.code, "run-in-progress"); + assert.ok(busy.result.reason.includes(lock), "the lock's path"); + assert.match(busy.result.reason, new RegExp(`process ${holder.pid}`)); + assert.match(busy.result.reason, /at 2026-01-02T03:04:05\.000Z/); + assert.match(busy.result.reason, alive); + assert.match(busy.result.reason, /only once you are sure no such run is going/); + assert.equal(readFileSync(lock, "utf8"), text, "the lock stays as it was"); + assert.deepEqual(run.newCalls(), []); + } + assert.deepEqual( + readdirSync(configDir(run.fake.sys)).filter((name) => name.includes(".lock")), + [LOCK], + ); + // Removed by the person, the next run goes, and removes its own lock. + rmSync(lock); + const after = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(after.code, 0, after.err); + assert.ok(!existsSync(lock)); + }); + + test("Track's OIDC_CLIENT_ID or OIDC_ISSUER that this tool did not set stops before any change", async () => { + for (const held of [["OIDC_CLIENT_ID"], ["OIDC_ISSUER"], ["OIDC_ISSUER", "OIDC_CLIENT_ID"]]) { + const run = await connectFake({ + registered: [CLIENT_ID], + trackSecrets: ["OIDC_CLIENT_SECRET", ...held], + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3, held.join()); + assert.equal(result.code, "track-settings-not-ours"); + assert.match( + result.reason, + new RegExp( + `Track holds ${held.join(" and ")} as (a secret|secrets) this tool's record does not show it set`, + ), + ); + assert.match(result.reason, /Nothing was changed/); + // The same steps as for a registration without its secret. + assert.match( + result.reason, + new RegExp(`DELETE FROM oauth_client WHERE client_id = '${CLIENT_ID}'`), + ); + for (const name of ["OIDC_CLIENT_SECRET", ...held]) { + assert.match(result.reason, new RegExp(`secret delete ${name} --name gateweave-track`)); + } + assert.deepEqual(run.changes(), []); + } + // One the record shows this tool set is its own: a rerun goes on. + const ours = await connectFake({ trackVars: { BETTER_AUTH_URL: TRACK } }); + assert.equal((await ours.connect([...keepArgs(ours), "--yes"])).code, 0); + const again = await ours.connect(["--yes", "--json"]); + assert.equal(again.code, 0, again.err); + // A record of this client that does not name the setting is not enough. + const file = JSON.parse(readFileSync(recordPath(ours.fake.sys), "utf8")); + assert.equal(file.connections[0].clientId, CLIENT_ID); + file.connections[0].trackSet = file.connections[0].trackSet.filter( + (name: string) => name !== "OIDC_ISSUER", + ); + writeFileSync(recordPath(ours.fake.sys), JSON.stringify(file)); + const unnamed = await ours.connect(["--yes", "--json"]); + assert.equal(unnamed.code, 3); + assert.equal(unnamed.result.code, "track-settings-not-ours"); + assert.match(unnamed.result.reason, /Track holds OIDC_ISSUER as a secret this tool's record/); + }); + + test("a text OIDC_ISSUER is compared whole with the issuer, its path included", async () => { + for (const issuer of [`${ID}/wrong`, `${ID}/`, "https://elsewhere.example.com"]) { + const run = await connectFake({ + registered: [CLIENT_ID], + trackSecrets: ["OIDC_CLIENT_SECRET"], + trackVars: { OIDC_ISSUER: issuer }, + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3, issuer); + assert.equal(result.code, "client-differs"); + assert.ok(result.reason.includes(`Track's OIDC_ISSUER is ${issuer}, not ${ID}`)); + assert.deepEqual(run.changes(), []); + } + }); + + test("an address read from a Worker is repeated without its name and password", async () => { + const run = await connectFake({ + trackVars: { BETTER_AUTH_URL: "https://admin:pa55word-zz@elsewhere.example.com" }, + }); + const json = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(json.code, 3); + assert.equal(json.result.code, "track-address-differs"); + assert.ok( + json.result.reason.includes("Track's BETTER_AUTH_URL is https://elsewhere.example.com,"), + ); + const plainRun = await run.connect([...keepArgs(run), "--yes"]); + for (const text of [json.out, json.err, plainRun.out, plainRun.err]) { + assert.ok(!text.includes("pa55word"), "no password"); + assert.ok(!text.includes("admin"), "no name"); + } + assert.equal( + withoutCredentials( + "at https://u:p@a.example.com/x and http://u@b.example.com, not mailto:u@c.example.com", + ), + "at https://a.example.com/x and http://b.example.com, not mailto:u@c.example.com", + ); + }); + + test("Track's button is read as the page shows it, character references decoded", async () => { + const run = await connectFake({ + trackVars: { OIDC_PROVIDER_NAME: "Acme & Co" }, + buttonName: "Acme & Co", + }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 0, JSON.stringify(result)); + assert.equal( + decodeEntities("<b> "A" 'B' & & &lt;   �"), + ` "A" 'B' & & <   �`, + ); + }); + + test("apps:add output is read as captured: control characters are not stripped first", async () => { + const lines = `Registered Gateweave Track. The secret is shown this once, and only its hash is kept.\nclient id: ${CLIENT_ID}\nclient secret: ${CLIENT_SECRET}\n`; + for (const output of [ + `\u001b[32m${lines}`, + lines.replace("client id:", "client\u001b[0m id:"), + ]) { + const run = await connectFake({ appsAdd: { stdout: output } }); + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 8); + assert.equal(result.code, "register-output-unreadable"); + assert.deepEqual( + run.puts.filter(({ worker }) => worker === "gateweave-track"), + [], + ); + } + // Windows line endings are the same output. + const crlf = await connectFake({ appsAdd: { stdout: lines.replaceAll("\n", "\r\n") } }); + assert.equal((await crlf.connect([...keepArgs(crlf), "--yes", "--json"])).code, 0); + // ID's random ids can start with "gwid_"; only the secret's own prefix is refused as an id. + const gwid = `gwid_${CLIENT_ID.slice(5)}`; + const lucky = await connectFake({ + appsAdd: { stdout: lines.replace(CLIENT_ID, gwid) }, + registerAs: gwid, + }); + const taken = await lucky.connect([...keepArgs(lucky), "--yes", "--json"]); + assert.equal(taken.code, 0, taken.err); + assert.equal(taken.result.clientId, gwid); + }); + + test("a folder link retargeted after the plan, to another folder outside, is refused", async () => { + const run = await connectFake(); + const first = join(run.keepDir, "first"); + const second = join(run.keepDir, "second"); + mkdirSync(first); + mkdirSync(second); + const folder = join(run.keepDir, "folder"); + linkFolder(first, folder); + run.state.beforeOpen = () => { + unlinkFolder(folder); + linkFolder(second, folder); + }; + const { code, result, out, err } = await run.connect([ + "--keep-secret-at", + join(folder, "pairwise.txt"), + "--yes", + "--json", + ]); + assert.equal(code, 2); + assert.equal(result.code, "keep-path-moved"); + assert.deepEqual(readdirSync(second), [], "nothing is written in the new place"); + assert.deepEqual(readdirSync(first), []); + assert.ok(!run.puts.some(({ name }) => name === "OIDC_PAIRWISE_SECRET")); + assert.deepEqual(leaked(out), []); + assert.deepEqual(leaked(err), []); + }); + + test("the rerun a message gives repeats the names and addresses given", async () => { + const run = await connectFake({ registered: [CLIENT_ID] }); + const { code, result } = await run.connect([ + "--id-name", + "gateweave-id", + "--track-name", + "gateweave-track", + "--id-url", + ID, + "--track-url", + TRACK, + "--no-account-name", + ...keepArgs(run), + "--yes", + "--json", + ]); + assert.equal(code, 3); + assert.equal(result.code, "registered-without-secret"); + const rerun = `\`gateweave connect id track --id-name gateweave-id --track-name gateweave-track --id-url ${ID} --track-url ${TRACK} --no-account-name --keep-secret-at ${shellArg(keepArgs(run)[1] ?? "", process.platform)} --yes --json\``; + assert.ok( + result.reason.includes(`and run ${rerun} again, which sets what is missing. If not,`), + result.reason, + ); + assert.ok(result.reason.includes(`then run ${rerun} again, which registers Track anew`)); + }); + + test("the record holds the client id before Track's first secret is put", async () => { + const run = await connectFake(); + const { code, err } = await run.connect([...keepArgs(run), "--yes"]); + assert.equal(code, 0, err); + const onTrack = run.puts.filter(({ worker }) => worker === "gateweave-track"); + assert.equal(onTrack[0]?.name, "OIDC_CLIENT_SECRET"); + const before = JSON.parse(onTrack[0]?.recordBefore ?? "{}") as { + connections?: { clientId: string; steps: string[] }[]; + }; + assert.equal(before.connections?.[0]?.clientId, CLIENT_ID); + assert.deepEqual(before.connections?.[0]?.steps, ["registered"]); + // Each setting is on record as tried before its put, and as this tool's only once confirmed. + for (const put of onTrack) { + const record = JSON.parse(put.recordBefore ?? "{}") as { + connections?: { trackSet?: string[]; trackPending?: string[] }[]; + }; + assert.ok(record.connections?.[0]?.trackPending?.includes(put.name), put.name); + assert.ok(!record.connections?.[0]?.trackSet?.includes(put.name), put.name); + } + const [after] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections; + assert.deepEqual(after.trackPending, []); + assert.deepEqual([...after.trackSet].sort(), onTrack.map(({ name }) => name).sort()); + }); + + test("a Track setting whose put failed is not this tool's, and makes no claim", async () => { + const run = await connectFake({ failPut: "OIDC_CLIENT_ID" }); + const first = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(first.code, 8); + assert.equal(first.result.code, "secret-put-failed"); + const [connection] = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")).connections; + assert.ok(!connection.trackSet.includes("OIDC_CLIENT_ID")); + assert.deepEqual(connection.trackPending, ["OIDC_CLIENT_ID"]); + assert.ok(connection.trackSet.includes("OIDC_CLIENT_SECRET"), "the confirmed one is"); + + // Someone sets a client id of their own meanwhile: it is not taken for this tool's. + run.fake.cloud.secrets.get("gateweave-track")?.add("OIDC_CLIENT_ID"); + run.values.set("gateweave-track OIDC_CLIENT_ID", OTHER_CLIENT_ID); + run.state.failPut = undefined; + const second = await run.connect(["--yes", "--json"]); + assert.equal(second.code, 3); + assert.equal(second.result.code, "track-settings-not-ours"); + assert.match(second.result.reason, /it tried to, but the put was never confirmed/); + run.fake.output.out = ""; + await main(["doctor", "track", "--json"], run.fake.sys); + assert.doesNotMatch(run.fake.output.out, /this tool gave it/); + + // OIDC_CLIENT_SECRET follows the same rule. + const secret = await connectFake({ failPut: "OIDC_CLIENT_SECRET" }); + const failed = await secret.connect([...keepArgs(secret), "--yes", "--json"]); + assert.equal(failed.result.code, "client-secret-not-set"); + const [record] = JSON.parse(readFileSync(recordPath(secret.fake.sys), "utf8")).connections; + assert.deepEqual(record.trackSet, []); + assert.deepEqual(record.trackPending, ["OIDC_CLIENT_SECRET"]); + }); + + test("a password with an apostrophe, a colon or an at sign is still taken out of an address", async () => { + assert.equal( + withoutCredentials("is https://ad'min:pa'ss:w@rd@track.example.com/x?y#z, not that"), + "is https://track.example.com/x?y#z, not that", + ); + assert.equal( + withoutCredentials("'https://u:p@a.example.com' and https://b.example.com/@c"), + "'https://a.example.com' and https://b.example.com/@c", + ); + const run = await connectFake({ + trackVars: { BETTER_AUTH_URL: "https://ad'min:pa'ss:w@rd-zz@elsewhere.example.com" }, + }); + const json = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(json.result.code, "track-address-differs"); + assert.ok( + json.result.reason.includes("Track's BETTER_AUTH_URL is https://elsewhere.example.com,"), + ); + const plainRun = await run.connect([...keepArgs(run), "--yes"]); + for (const text of [json.out, json.err, plainRun.out, plainRun.err]) { + assert.ok(!text.includes("pa'ss"), "no password"); + assert.ok(!text.includes("ad'min"), "no name"); + assert.ok(!text.includes("rd-zz"), "no part of the password"); + } + }); + + test("two addresses with no space between them each lose their name and password", () => { + for (const between of [",", ";", ""]) { + assert.equal( + withoutCredentials(`https://a:p1@x.example${between}https://b:p2@y.example/z`), + `https://x.example${between}https://y.example/z`, + ); + } + // Digits right before the next address: a port, with no scheme boundary to find. + assert.equal( + withoutCredentials("https://a:p1@x.example:8443https://b:p2@y.example"), + "https://x.example:8443https://y.example", + ); + assert.equal(withoutCredentials("x://u:p@h 9://v:q@k"), "x://h 9://k"); + const both = withoutCredentials("was https://a:p1@x.example,http://b:p'2@y.example, then"); + assert.ok(!both.includes("p1") && !both.includes("p'2"), both); + assert.equal( + withoutCredentials("no address here, a@b and c://d"), + "no address here, a@b and c://d", + ); + }); + + test("the printed command quotes each argument for the shell, and only where needed", async () => { + // POSIX: single quotes, each "'" written '\''. + assert.equal(shellArg("/home/me/pairwise.txt", "linux"), "/home/me/pairwise.txt"); + assert.equal(shellArg("/home/me/O'Brien.txt", "linux"), "'/home/me/O'\\''Brien.txt'"); + assert.equal(shellArg("/home/me/my keep.txt", "darwin"), "'/home/me/my keep.txt'"); + assert.equal(shellArg("C:\\keep\\a.txt", "linux"), "'C:\\keep\\a.txt'"); + assert.equal(shellArg("$HOME/a`b`", "linux"), "'$HOME/a`b`'"); + // Windows: double quotes, which PowerShell and cmd both read. + assert.equal(shellArg("C:\\keep\\pairwise.txt", "win32"), "C:\\keep\\pairwise.txt"); + assert.equal(shellArg("C:\\keep\\O'Brien.txt", "win32"), '"C:\\keep\\O\'Brien.txt"'); + assert.equal(shellArg("C:\\my keep\\a.txt", "win32"), '"C:\\my keep\\a.txt"'); + assert.equal(shellArg("a,b", "win32"), '"a,b"'); + // A POSIX shell, where there is one, gives each quoted argument back unchanged. + for (const value of ["/tmp/O'Brien.txt", "it's 'quoted'", "a b\tc", '$x `y` \\z "w" ;&|']) { + const echoed = spawnSync("sh", ["-c", `printf %s ${shellArg(value, "linux")}`], { + encoding: "utf8", + }); + if (echoed.error) break; + assert.equal(echoed.stdout, value); + } + + // The rerun a stop prints quotes the keep path for this system. + const run = await connectFake({ registered: [CLIENT_ID] }); + const keep = join(run.keepDir, "O'Brien.txt"); + const { result } = await run.connect(["--keep-secret-at", keep, "--yes", "--json"]); + assert.equal(result.code, "registered-without-secret"); + const quoted = + process.platform === "win32" ? `"${keep}"` : `'${keep.replaceAll("'", "'\\''")}'`; + assert.ok( + result.reason.includes( + `\`gateweave connect id track --keep-secret-at ${quoted} --yes --json\``, + ), + result.reason, + ); + }); + + test("restoring a known client secret, as the stop advises, lets the rerun finish", async () => { + // Track's client id and issuer as secrets nobody can read: the advice names them to remove. + const secrets = await connectFake({ + registered: [CLIENT_ID], + trackSecrets: ["OIDC_ISSUER", "OIDC_CLIENT_ID"], + }); + const stopped = await secrets.connect([...keepArgs(secrets), "--yes", "--json"]); + assert.equal(stopped.result.code, "registered-without-secret"); + assert.match( + stopped.result.reason, + /secret put OIDC_CLIENT_SECRET --name gateweave-track, which asks for the value\), remove OIDC_ISSUER and OIDC_CLIENT_ID, which cannot be shown to be this registration's \(.*secret delete OIDC_ISSUER --name gateweave-track; .*secret delete OIDC_CLIENT_ID --name gateweave-track\), and run/, + ); + const track = secrets.fake.cloud.secrets.get("gateweave-track"); + track?.add("OIDC_CLIENT_SECRET"); + secrets.values.set("gateweave-track OIDC_CLIENT_SECRET", CLIENT_SECRET); + track?.delete("OIDC_ISSUER"); + track?.delete("OIDC_CLIENT_ID"); + const restored = await secrets.connect([...keepArgs(secrets), "--yes", "--json"]); + assert.equal(restored.code, 0, restored.err); + assert.equal(restored.result.registeredNow, false); + assert.equal(secrets.appsAdd.length, 0); + + // As text variables that match ID's registration, they are consistent and stay. + const texts = await connectFake({ + registered: [CLIENT_ID], + trackVars: { OIDC_CLIENT_ID: CLIENT_ID, OIDC_ISSUER: ID }, + }); + const told = await texts.connect([...keepArgs(texts), "--yes", "--json"]); + assert.equal(told.result.code, "registered-without-secret"); + assert.doesNotMatch(told.result.reason, /cannot be shown to be this registration's/); + texts.fake.cloud.secrets.get("gateweave-track")?.add("OIDC_CLIENT_SECRET"); + texts.values.set("gateweave-track OIDC_CLIENT_SECRET", CLIENT_SECRET); + const finished = await texts.connect([...keepArgs(texts), "--yes", "--json"]); + assert.equal(finished.code, 0, finished.err); + assert.equal(texts.appsAdd.length, 0); + assert.ok( + !texts.puts.some(({ name }) => name === "OIDC_CLIENT_ID" || name === "OIDC_ISSUER"), + "the matching text variables are left as they are", + ); + + // A text variable that differs is named too, and stops the run while it is there. + const wrong = await connectFake({ + registered: [CLIENT_ID], + trackVars: { OIDC_ISSUER: `${ID}/wrong` }, + }); + const named = await wrong.connect([...keepArgs(wrong), "--yes", "--json"]); + assert.match(named.result.reason, /remove OIDC_ISSUER, which cannot be shown/); + }); + + test("an address with a name and password in it is refused without repeating it", async () => { + const run = await connectFake(); + for (const args of [ + ["--id-url", "https://admin:pa55word-zz@id.example.com"], + ["--track-url", "https://admin:pa55word-zz@bad host"], + ["--track-url", "https://track'example.com"], + ]) { + const { code, out, err } = await run.connect([...args, "--json"]); + assert.equal(code, 2, args.join(" ")); + assert.ok(!`${out}${err}`.includes("pa55word-zz")); + } + run.fake.output.out = ""; + assert.equal( + await main(["doctor", "track", "--url", "admin:pa55word-zz@x", "--json"], run.fake.sys), + 2, + ); + assert.ok(!`${run.fake.output.out}${run.fake.output.err}`.includes("pa55word-zz")); + assert.deepEqual(run.newCalls(), []); + }); + + test("NODE_DEBUG stops every command before it starts anything", async () => { + const run = await connectFake(); + run.fake.sys.env.NODE_DEBUG = "child_process"; + const { code, result } = await run.connect([...keepArgs(run), "--yes", "--json"]); + assert.equal(code, 3); + assert.equal(result.code, "node-debug-set"); + assert.equal(await main(["doctor", "track"], run.fake.sys), 3); + assert.deepEqual(run.newCalls(), []); + }); + + test("the record keeps only its known fields, whatever is handed to it", async () => { + const run = await connectFake(); + await saveConnection(run.fake.sys, { + kind: "id-track", + accountId: "a1b2c3", + idWorker: "x-id", + trackWorker: "x-track", + issuer: ID, + trackAddress: TRACK, + providerName: "Gateweave ID", + clientId: CLIENT_ID, + steps: ["registered"], + updatedAt: "now", + clientSecret: CLIENT_SECRET, + pairwiseSecret: PAIRWISE, + } as ConnectionRecord); + const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")); + const [deployment] = file.deployments; + await saveRecord(run.fake.sys, { ...deployment, worker: "y", secret: API_TOKEN }); + const text = readFileSync(recordPath(run.fake.sys), "utf8"); + assert.deepEqual(leaked(text), []); + assert.doesNotMatch(text, /clientSecret|pairwiseSecret|"secret"/); + }); + + test("doctor reports what it can see of the connection on both sides, and what it cannot", async () => { + const run = await connectFake(); + assert.equal( + ( + await run.connect([ + "--id-url", + "https://id.example.com", + "--track-url", + "https://track.example.com", + ...keepArgs(run, "k"), + "--yes", + ]) + ).code, + 0, + ); + const findings = async (product: string) => { + run.fake.output.out = ""; + run.fake.events.length = 0; + await main(["doctor", product, "--json"], run.fake.sys); + return JSON.parse(run.fake.output.out) as { id: string; status: string; message: string }[]; + }; + const track = (await findings("track")).find(({ id }) => id === "sign-in-provider"); + // At the address the connection was made on, not only the deployment's. + assert.ok(run.fake.events.includes("fetch GET https://track.example.com/login")); + assert.equal(track?.status, "ok"); + assert.match(track?.message ?? "", /shows "Continue with Gateweave ID"/); + assert.match(track?.message ?? "", /Track names the issuer https:\/\/id\.example\.com/); + assert.match(track?.message ?? "", /a secret, which cannot be read back/); + assert.doesNotMatch(track?.message ?? "", /connected/); + assert.ok((track?.message ?? "").includes(`this tool gave it ${CLIENT_ID}`)); + // A record that does not show this tool set OIDC_CLIENT_ID makes no such claim. + const file = JSON.parse(readFileSync(recordPath(run.fake.sys), "utf8")); + const saved = file.connections[0].trackSet; + file.connections[0].trackSet = saved.filter((name: string) => name !== "OIDC_CLIENT_ID"); + writeFileSync(recordPath(run.fake.sys), JSON.stringify(file)); + const unclaimed = (await findings("track")).find(({ id }) => id === "sign-in-provider"); + assert.doesNotMatch(unclaimed?.message ?? "", /this tool gave it/); + assert.match(unclaimed?.message ?? "", /this tool's record does not show it set/); + file.connections[0].trackSet = saved; + writeFileSync(recordPath(run.fake.sys), JSON.stringify(file)); + const id = (await findings("id")).find(({ id: found }) => found === "oidc-provider"); + assert.ok( + run.fake.events.includes("fetch GET https://id.example.com/.well-known/openid-configuration"), + ); + assert.equal(id?.status, "ok"); + assert.match(id?.message ?? "", /with the issuer https:\/\/id\.example\.com/); + assert.match( + id?.message ?? "", + new RegExp(`Track gateweave-track is registered, as client id ${CLIENT_ID}`), + ); + + // ID's database has another client for Track: doctor id says so. + run.registrations.splice(0, 1, OTHER_CLIENT_ID); + const other = (await findings("id")).find(({ id: found }) => found === "oidc-provider"); + assert.equal(other?.status, "fail"); + assert.match( + other?.message ?? "", + new RegExp(`registered as client id ${OTHER_CLIENT_ID}, not ${CLIENT_ID}`), + ); + run.registrations.splice(0, 1, CLIENT_ID); + + // Track names another issuer: doctor track says so. + run.values.set("gateweave-track OIDC_ISSUER", "https://other.example.com"); + const moved = (await findings("track")).find(({ id: found }) => found === "sign-in-provider"); + assert.equal(moved?.status, "fail"); + assert.match( + moved?.message ?? "", + /names the issuer https:\/\/other\.example\.com, not https:\/\/id\.example\.com/, + ); + run.values.set("gateweave-track OIDC_ISSUER", "https://id.example.com"); + + // A button with another name is not ID's. + run.values.set("gateweave-track OIDC_PROVIDER_NAME", "Someone Else"); + const renamed = (await findings("track")).find(({ id: found }) => found === "sign-in-provider"); + assert.equal(renamed?.status, "fail"); + assert.match(renamed?.message ?? "", /shows no "Continue with Gateweave ID" button/); + run.values.set("gateweave-track OIDC_PROVIDER_NAME", "Gateweave ID"); + + // Half a setup is a fail, with the command that finishes it. + run.fake.cloud.secrets.get("gateweave-track")?.delete("OIDC_CLIENT_SECRET"); + const half = (await findings("track")).find(({ id: found }) => found === "sign-in-provider"); + assert.equal(half?.status, "fail"); + assert.match(half?.message ?? "", /OIDC_CLIENT_SECRET is not set/); + }); + + test("options of other commands are refused, and the new options only belong to connect", async () => { + const run = await connectFake(); + assert.equal((await run.connect(["--name", "x"])).code, 2); + assert.equal((await run.connect(["--id-url", "http://id.example.com"])).code, 2); + assert.equal((await run.connect(["--id-url", "https://id.example.com/path"])).code, 2); + assert.equal( + await main(["deploy", "track", "--id-url", "https://id.example.com"], run.fake.sys), + 2, + ); + assert.equal(await main(["doctor", "id", "--keep-secret-at", "x"], run.fake.sys), 2); + assert.equal(await main(["doctor", "id", "--no-account-name"], run.fake.sys), 2); + assert.deepEqual(run.newCalls(), []); + }); +}); diff --git a/packages/cli/test/fake.ts b/packages/cli/test/fake.ts index 04cb2a6..ec51265 100644 --- a/packages/cli/test/fake.ts +++ b/packages/cli/test/fake.ts @@ -390,6 +390,8 @@ const READ_ONLY = [ /npx-cli\.js --version$/, / wrangler@[\d.]+ whoami --json$/, / wrangler@[\d.]+ secret list --name \S+ --format json$/, + / wrangler@[\d.]+ deployments status --name \S+ --json$/, + / wrangler@[\d.]+ versions view \S+ --name \S+ --json$/, / wrangler@[\d.]+ d1 list --json$/, / wrangler@[\d.]+ d1 migrations list DB --remote$/, / wrangler@[\d.]+ d1 execute DB --remote --json --command SELECT [^;]*$/, diff --git a/packages/cli/test/registration.test.ts b/packages/cli/test/registration.test.ts new file mode 100644 index 0000000..4395e13 --- /dev/null +++ b/packages/cli/test/registration.test.ts @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + backchannelLogoutUri, + callbackUri, + readClientIds, + sqlString, + trackRegistrationSql, +} from "../src/registration.ts"; + +// The query runs on D1, which is SQLite. node:sqlite (Node 22.5 and later) runs the very text this +// tool sends, against the columns of ID's oauth_client that it reads. +type Database = { + exec(sql: string): void; + prepare(sql: string): { all(): unknown[] }; +}; +let open: (() => Database) | null = null; +let missing = ""; +try { + const { DatabaseSync } = await import("node:sqlite"); + open = () => new DatabaseSync(":memory:") as unknown as Database; +} catch (error) { + missing = `node:sqlite is not in Node ${process.versions.node}: ${(error as Error).message}`; +} + +/** The columns of ID's `oauth_client` (migrations/0001) the query reads, as ID declares them. */ +const SCHEMA = `CREATE TABLE oauth_client ( + id text PRIMARY KEY NOT NULL, + client_id text NOT NULL, + redirect_uris text NOT NULL, + backchannel_logout_uri text, + reference_id text, + metadata text +)`; + +/** A row as ID's apps:add writes it: the URIs as a JSON list, the app id in the metadata. */ +function insert( + db: Database, + row: { + clientId: string; + uris: string[]; + logoutUri?: string; + app?: string; + workspace?: string; + metadata?: string; + }, +) { + const metadata = + row.metadata ?? + JSON.stringify( + row.workspace ? { app: row.clientId, workspace: row.workspace } : { app: row.app }, + ); + db.exec( + `INSERT INTO "oauth_client" ("id", "client_id", "redirect_uris", "backchannel_logout_uri", "reference_id", "metadata") VALUES (${[ + sqlString(`row-${row.clientId}`), + sqlString(row.clientId), + sqlString(JSON.stringify(row.uris)), + row.logoutUri ? sqlString(row.logoutUri) : "NULL", + row.workspace ? sqlString(row.workspace) : "NULL", + sqlString(metadata), + ].join(", ")});`, + ); +} + +function lookup(db: Database, trackAddress: string): string[] { + return db + .prepare(trackRegistrationSql(callbackUri(trackAddress))) + .all() + .map((row) => (row as { client_id: string }).client_id); +} + +const TRACK = "https://track.example.com"; + +test("the registration query finds Track's own row and nothing else", { + skip: open ? false : missing, +}, () => { + const db = (open as () => Database)(); + db.exec(SCHEMA); + // Nothing registered: nothing found. + assert.deepEqual(lookup(db, TRACK), []); + insert(db, { clientId: "track-client", app: "track", uris: [callbackUri(TRACK)] }); + // Another first-party app with the same callback is not Track. + insert(db, { clientId: "other-app", app: "wiki", uris: [callbackUri(TRACK)] }); + // A workspace's own app with the same callback is not Track either. + insert(db, { clientId: "workspace-app", workspace: "org-1", uris: [callbackUri(TRACK)] }); + // A longer URI on the same host is another URI. + insert(db, { + clientId: "longer-uri", + app: "track", + uris: [`${callbackUri(TRACK)}/more`, `${TRACK}/api/auth/callback/oidcx`], + }); + // A row whose metadata is not JSON is passed over, and does not fail the query. + insert(db, { clientId: "broken", uris: [callbackUri(TRACK)], metadata: "{not json" }); + assert.deepEqual(lookup(db, TRACK), ["track-client"]); + // Another Track elsewhere is not this one. + assert.deepEqual(lookup(db, "https://track.other.example.com"), []); +}); + +test("the registration query returns matching rows even without a logout URI", { + skip: open ? false : missing, +}, () => { + const db = (open as () => Database)(); + db.exec(SCHEMA); + const logoutUri = backchannelLogoutUri(TRACK); + insert(db, { clientId: "first", app: "track", uris: [callbackUri(TRACK)], logoutUri }); + insert(db, { clientId: "second", app: "track", uris: [callbackUri(TRACK)] }); + const rows = db.prepare(`${trackRegistrationSql(callbackUri(TRACK))} ORDER BY client_id`).all(); + assert.deepEqual( + rows.map((row) => ({ ...(row as object) })), + [ + { client_id: "first", backchannel_logout_uri: logoutUri }, + { client_id: "second", backchannel_logout_uri: null }, + ], + ); +}); + +test("the registration query takes an address with quotes as text", { + skip: open ? false : missing, +}, () => { + const db = (open as () => Database)(); + db.exec(SCHEMA); + const quoted = "https://it's.example.com"; + insert(db, { clientId: "quoted", app: "track", uris: [callbackUri(quoted)] }); + insert(db, { clientId: "plain", app: "track", uris: [callbackUri(TRACK)] }); + assert.deepEqual(lookup(db, quoted), ["quoted"]); + // What would end the string and widen the query finds nothing, and changes nothing. + assert.deepEqual(lookup(db, "https://x') OR 1=1 OR ('"), []); + assert.deepEqual(lookup(db, `https://x'; DELETE FROM oauth_client; --`), []); + assert.deepEqual(lookup(db, TRACK), ["plain"]); +}); + +test("Wrangler's answer is read as client ids, or not at all", () => { + assert.deepEqual(readClientIds(JSON.stringify([{ results: [{ client_id: "a" }] }])), ["a"]); + assert.deepEqual(readClientIds(JSON.stringify([{ results: [] }])), []); + assert.equal(readClientIds("not json"), null); + assert.equal(readClientIds(JSON.stringify([{ success: true }])), null); + assert.equal(readClientIds(JSON.stringify([{ results: [{ client_id: 7 }] }])), null); +}); diff --git a/packages/cli/test/source.test.ts b/packages/cli/test/source.test.ts index 59502cf..e3af115 100644 --- a/packages/cli/test/source.test.ts +++ b/packages/cli/test/source.test.ts @@ -6,6 +6,16 @@ import { fileURLToPath } from "node:url"; const src = fileURLToPath(new URL("../src", import.meta.url)); +const RANDOM = /randomBytes|randomUUID|getRandomValues/; +const SECRET_PUT = /"secret",\s*"put"/; + +/** + * The exception in invariant 5 of AGENTS.md: `connect` does what both products' self-hosting guides + * describe by hand, and makes one value, ID's OIDC_PAIRWISE_SECRET. So connect.ts, and no other + * file, may make a random value and give a value to `wrangler secret put`. + */ +const CONNECTING = new Map([["connect.ts", [RANDOM, SECRET_PUT]]]); + // The product's own deploy does these; the tool holds no copy of that logic. test("the source never deploys, migrates or makes a secret itself", () => { for (const file of readdirSync(src)) { @@ -16,10 +26,19 @@ test("the source never deploys, migrates or makes a secret itself", () => { // Any `d1 migrations ` other than `list`: apply, or a subcommand held in a variable. /["'`]d1["'`]\s*,\s*["'`]migrations["'`](?!\s*,\s*["'`]list["'`])/, /--secrets-file/, - /randomBytes|randomUUID|getRandomValues/, - /"secret",\s*"put"/, + RANDOM, + SECRET_PUT, ]) { + if (CONNECTING.get(file)?.includes(pattern)) continue; assert.doesNotMatch(text, pattern, `${file} matches ${pattern}`); } } }); + +test("only connect.ts makes a secret, and it hands each one to Wrangler on stdin", () => { + const text = readFileSync(join(src, "connect.ts"), "utf8"); + assert.match(text, RANDOM); + // Every `secret put` goes through one helper, whose value is the run's input, never an argument. + assert.equal(text.match(/"secret", "put"/g)?.length, 1); + assert.match(text, /\["secret", "put", name, "--name", worker\], cache, value\)/); +}); diff --git a/packages/cli/test/system.test.ts b/packages/cli/test/system.test.ts index 4ca377b..5777f88 100644 --- a/packages/cli/test/system.test.ts +++ b/packages/cli/test/system.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { PassThrough } from "node:stream"; import { test } from "node:test"; -import { realSystem, runProcess } from "../src/system.ts"; +import { childEnv, realSystem, runProcess } from "../src/system.ts"; test("a child that never answers is stopped instead of waiting forever", async () => { const sys = realSystem(); @@ -205,3 +205,61 @@ test("the Windows termination helper is released when the result settles", async assert.match(parent.stdout, /"cleanup":"unconfirmed"/); assert.ok(Date.now() - started < 2_000, `parent stayed open for ${Date.now() - started} ms`); }); + +/** A tiny child that says what it was given: its arguments, its stdin and three settings. */ +const ECHO = `let input = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { input += chunk; }); +process.stdin.on("end", () => { + process.stdout.write(JSON.stringify({ + argv: process.argv.slice(1), + input, + debug: process.env.NODE_DEBUG ?? null, + sanitize: process.env.WRANGLER_LOG_SANITIZE ?? null, + kept: process.env.GATEWEAVE_TEST_KEPT ?? null, + })); +});`; + +const SECRET = ["synthetic", "stdin", "fixture", "value"].join("-"); + +test("realSystem().run hands a value to the child on stdin, never as an argument", async () => { + const sys = realSystem(); + const result = await sys.run(process.execPath, ["-e", ECHO, "--", "one"], { + cwd: tmpdir(), + env: { ...process.env, GATEWEAVE_TEST_KEPT: "yes" }, + input: SECRET, + timeoutMs: 5_000, + }); + assert.equal(result.status, 0, result.stderr); + const seen = JSON.parse(result.stdout); + assert.equal(seen.input, SECRET); + assert.ok(!seen.argv.some((arg: string) => arg.includes(SECRET)), "not in the process list"); + assert.deepEqual(seen.argv.slice(-1), ["one"]); + // Without a value, the child's stdin is closed: nothing it asks can be answered. + const none = JSON.parse( + (await sys.run(process.execPath, ["-e", ECHO], { cwd: tmpdir(), env: process.env })).stdout, + ); + assert.equal(none.input, ""); +}); + +test("a child starts without NODE_DEBUG and without WRANGLER_LOG_SANITIZE turned off", async () => { + const sys = realSystem(); + const result = await sys.run(process.execPath, ["-e", ECHO], { + cwd: tmpdir(), + env: { + ...process.env, + NODE_DEBUG: "gateweave-test-nothing", + WRANGLER_LOG_SANITIZE: "false", + GATEWEAVE_TEST_KEPT: "yes", + }, + input: "", + }); + const seen = JSON.parse(result.stdout); + assert.equal(seen.debug, null); + assert.equal(seen.sanitize, null); + assert.equal(seen.kept, "yes"); + // In any case: Windows does not tell names apart by case. + assert.deepEqual(childEnv({ node_debug: "x", Wrangler_Log_Sanitize: "false", PATH: "p" }), { + PATH: "p", + }); +});