diff --git a/cli/src/commands/workspace/workspace.ts b/cli/src/commands/workspace/workspace.ts index 49462155e1..8c8b90cc24 100644 --- a/cli/src/commands/workspace/workspace.ts +++ b/cli/src/commands/workspace/workspace.ts @@ -551,6 +551,106 @@ async function remove(_opts: GlobalOptions, name: string) { await removeWorkspace(name, false, _opts); } +const CLI_LOGIN_TOKEN_LABEL_PREFIX = "cli-login:"; + +// Only a token the CLI's own browser login minted is revoked: a token pasted into the profile may +// also be used elsewhere (CI, another machine), so deleting it could break more than this profile. +async function revokeCliLoginToken(token: string): Promise { + const prefix = token.substring(0, 10); + const perPage = 100; + for (let page = 1; page <= 50; page++) { + const tokens = await wmill.listTokens({ excludeEphemeral: true, page, perPage }); + const match = tokens.find((t) => t.token_prefix === prefix); + if (match) { + if (!match.label?.startsWith(CLI_LOGIN_TOKEN_LABEL_PREFIX)) { + return false; + } + await wmill.deleteToken({ tokenPrefix: prefix }); + return true; + } + if (tokens.length < perPage) { + return false; + } + } + return false; +} + +async function login(opts: GlobalOptions, workspaceName?: string) { + const workspace = workspaceName + ? await getWorkspaceByName(workspaceName, opts.configDir) + : await getActiveWorkspace(opts); + if (!workspace) { + log.info( + colors.red.bold( + workspaceName + ? `! Workspace profile ${workspaceName} does not exist locally` + : "! No active workspace profile. Add one with 'wmill workspace add'." + ) + ); + return process.exit(1); + } + if ( + opts.baseUrl && + new URL(opts.baseUrl).toString() !== new URL(workspace.remote).toString() + ) { + log.info( + colors.red.bold( + `! --base-url ${opts.baseUrl} does not match profile ${workspace.name} (${workspace.remote}). Use 'wmill workspace add' for another instance.` + ) + ); + return process.exit(1); + } + + let token = await tryGetLoginInfo(opts); + if (!token) { + if (!(process.stdin.isTTY ?? false)) { + log.info("Not a TTY, can't login interactively. Pass the token in --token"); + return process.exit(1); + } + log.info( + `Signing in again to ${workspace.workspaceId} on ${workspace.remote} for profile ${workspace.name}` + ); + token = await loginInteractive(workspace.remote); + } + if (!token) { + log.info(colors.red.bold("! Login failed, the profile was left unchanged.")); + return process.exit(1); + } + + const remote = workspace.remote.substring(0, workspace.remote.length - 1); + setClient(token, remote); + try { + await wmill.whoami({ workspace: workspace.workspaceId }); + } catch (e) { + log.info( + colors.red.bold( + `! The new token cannot access workspace ${workspace.workspaceId}, the profile was left unchanged.` + ) + ); + throw e; + } + + const oldToken = workspace.token; + await addWorkspace({ ...workspace, token }, opts); + + // `wmill instance pull --include-workspaces` copies one token into the instance profile and + // every workspace profile it creates: revoking it would sign all the others out. + const { allInstances } = await import("../instance/instance.ts"); + const stillReferenced = + (await allWorkspaces(opts.configDir)).some((w) => w.token === oldToken) || + (await allInstances()).some((i) => i.token === oldToken); + if (oldToken && oldToken !== token && !stillReferenced) { + try { + if (await revokeCliLoginToken(oldToken)) { + log.info("Revoked the profile's previous token."); + } + } catch { + // Already expired or deleted, or owned by another user: nothing left to revoke. + } + } + log.info(colors.green.underline(`Successfully signed in again for profile ${workspace.name}`)); +} + async function whoami(_opts: GlobalOptions) { const whoamiInfo = await requireLogin(_opts); log.info(JSON.stringify(whoamiInfo, null, 2)); @@ -937,6 +1037,13 @@ const command = new Command() .description("Remove a workspace") .arguments("") .action(remove as any) + .command("login") + .complete("workspace", async () => (await allWorkspaces()).map((x) => x.name)) + .description( + "Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it." + ) + .arguments("[workspace_name:string:workspace]") + .action(login as any) .command("whoami") .description("Show the currently active user") .action(whoami as any) diff --git a/cli/src/core/auth.ts b/cli/src/core/auth.ts index bee70aef28..4ce903e875 100644 --- a/cli/src/core/auth.ts +++ b/cli/src/core/auth.ts @@ -122,19 +122,27 @@ export async function requireLogin( return process.exit(1); } - log.infoStderr( - "! Could not reach API given existing credentials. Attempting to reauth..." - ); + const isUnauthorized = error && typeof error === "object" && + "name" in error && (error as { name: unknown }).name === "ApiError" && + (error as { status?: number }).status === 401; + log.infoStderr(colors.yellow( + isUnauthorized + ? `! The token of workspace profile '${workspace.name}' has expired or was revoked. Sign in again to continue.` + : "! Could not reach API given existing credentials. Attempting to reauth..." + )); const newToken = await loginInteractive(workspace.remote); if (!newToken) { - throw new Error("Unauthorized: Could not authenticate with the provided credentials"); + throw new Error( + `Unauthorized: Could not authenticate with the provided credentials. Run 'wmill workspace login ${workspace.name}' in a terminal to sign in again.` + ); } - // Update workspace token + // Removed silently first: `addWorkspace` logs the update to stdout, which would land in the + // output of the command being run (e.g. `wmill variable get … > file`). const { removeWorkspace, addWorkspace } = await import("../commands/workspace/workspace.ts"); - removeWorkspace(workspace.name, false, opts); + await removeWorkspace(workspace.name, true, opts); workspace.token = newToken; - addWorkspace(workspace, opts); + await addWorkspace(workspace, opts); setClient( newToken, diff --git a/cli/src/core/login.ts b/cli/src/core/login.ts index e6a06e8383..94a9ce11b8 100644 --- a/cli/src/core/login.ts +++ b/cli/src/core/login.ts @@ -97,7 +97,7 @@ export async function browserLogin( // Start the server server.listen(port, () => { - console.log(`Listening on port ${port}`); + log.infoStderr(`Listening on port ${port}`); }); }); } diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index d3e1672353..6a377e4f43 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -9703,6 +9703,7 @@ workspace related commands - \`--create-workspace-name \` - Specify the workspace name. Ignored if --create is not specified or the workspace already exists. Will default to the workspace id. - \`--create-username \` - Specify your own username in the newly created workspace. Ignored if --create is not specified, the workspace already exists or automatic username creation is enabled on the instance. - \`workspace remove \` - Remove a workspace +- \`workspace login [workspace_name:string:workspace]\` - Sign in again for a workspace profile (default: the active one) and replace its token, e.g. to extend one about to expire. The previous token is revoked when the CLI's browser login created it. - \`workspace whoami\` - Show the currently active user - \`workspace list\` - List local workspace profiles - \`workspace list-remote\` - List workspaces on the remote server that you have access to diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 0b7b7e9827..90157c4a31 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -37,11 +37,14 @@ Symbols, not line numbers, are cited: they drift less. so until `whoami` answers that browser still renders as its own last user. - **`tokens/impersonate`** (superadmin) returns a multi-use token and sets no cookie. - **`max_token_expiration_days`** caps `POST /users/tokens/create` and `tokens/impersonate`, by - shortening the stored expiration (`cap_token_expiration`), never by refusing: the CLI - authorization page, `wmill user create-token` and the editor's language-server token all pick a - lifetime without reading the setting, and CLIs already installed never will. The CLI signs in - again on its own when its token expires, which is why the authorization page labels it - `cli-login:`, reserved in `is_user_token` so its expiry does not email the user. A token + shortening the stored expiration (`cap_token_expiration`), never by refusing: `wmill user + create-token` and the editor's language-server token pick a lifetime without reading the + setting, and CLIs already installed never will. The CLI authorization page (`/user/cli`) reads + it only to offer the lifetimes that would be kept (30 days by default). The CLI signs in again + on its own when its token expires, which is why the authorization page labels it + `cli-login:`, reserved in `is_user_token` so its expiry does not email the user. + `wmill workspace login` replaces a profile's token before it expires, and revokes the previous + one only when that label shows the browser login minted it. A token owned by a service account is exempt: one in the workspace the token names, or in any workspace for a workspace-less token (for `tokens/impersonate`, the impersonated account). Any workspace admin can therefore create and impersonate a service account to hold an uncapped token, so the diff --git a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte index 9e9226d133..d0b576c329 100644 --- a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte @@ -1,25 +1,72 @@