Skip to content

feat(auth): support workspace env override#96

Open
AmanVarshney01 wants to merge 1 commit into
mainfrom
aman/auth-workspace-env-override
Open

feat(auth): support workspace env override#96
AmanVarshney01 wants to merge 1 commit into
mainfrom
aman/auth-workspace-env-override

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Jun 23, 2026

Copy link
Copy Markdown
Member

Summary

  • add PRISMA_CLI_WORKSPACE_ID as a process-local OAuth workspace selector, with PRISMA_SERVICE_TOKEN remaining highest priority
  • keep the stored active workspace pointer unchanged when the env override is used, including legacy auth files without a context file
  • avoid stale env overrides shadowing auth login, auto-login, full logout, or interactive auth workspace use recovery
  • make auth login, auth workspace use, and logout outputs include env-aware next steps for agents
  • surface structured errors for empty, missing, or ambiguous overrides and document the precedence rules

Examples

Use a locally authenticated workspace for one command without changing the stored active workspace:

PRISMA_CLI_WORKSPACE_ID=wksp_123 prisma-cli project list

Switch the stored active workspace for normal CLI usage:

prisma-cli auth workspace use wksp_123

Use the interactive picker when no workspace id/name is provided:

prisma-cli auth workspace use

List cached OAuth workspaces with ids for troubleshooting or agent use:

prisma-cli auth workspace list
prisma-cli auth workspace list --json

Remove one cached OAuth workspace session:

prisma-cli auth workspace logout wksp_123
prisma-cli auth logout --workspace wksp_123

Recover from a stale env override by choosing another stored workspace:

unset PRISMA_CLI_WORKSPACE_ID
prisma-cli auth workspace use

Behavior Notes

  • PRISMA_SERVICE_TOKEN wins over PRISMA_CLI_WORKSPACE_ID and stored OAuth sessions.
  • PRISMA_CLI_WORKSPACE_ID matches workspace ids/canonical ids, not workspace names.
  • PRISMA_CLI_WORKSPACE_ID does not mutate the stored active workspace pointer, so parallel agents can target different workspaces without fighting over shared local state.
  • If the override is empty, missing, or ambiguous, commands fail with structured auth errors instead of silently falling back to another workspace.
  • auth workspace use can still recover from a stale override when no workspace argument is provided.
  • Logging out the active workspace intentionally leaves no fallback active workspace; users must explicitly choose the next workspace.

Testing

  • pnpm --filter @prisma/cli test
  • pnpm --recursive exec tsc --noEmit
  • pnpm lint
  • git diff --check

Note: pnpm lint exits 0, but the repo still prints existing warning/info diagnostics outside this change.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated the authentication spec for runtime workspace selection, including new precedence rules and failure behaviors.
  • New Features

    • Added PRISMA_CLI_WORKSPACE_ID to select a workspace at runtime without changing stored workspace “active” preferences.
  • Bug Fixes

    • Improved handling of empty/whitespace workspace ids and tightened service-token behavior to prevent unintended fallbacks.
    • Enhanced workspace/auth error messaging and remediation steps, including proper CLI guidance.
  • Tests

    • Expanded coverage for workspace override selection, token retrieval, and logout/login flows.

Walkthrough

The pull request introduces PRISMA_CLI_WORKSPACE_ID as a process-local OAuth workspace selector in the Prisma CLI. The environment variable allows selecting a stored workspace by ID without mutating the stored active workspace pointer. getWorkspaceIdOverride() in client.ts reads and validates the variable, returning null when unset, trimming whitespace, and throwing when set but empty. FileTokenStorage.getTokens() gains an override branch that calls private helpers selectWorkspaceTokens and buildStoredAuthWorkspaces using a new exported workspaceMatchesIdRef matcher for ID-only selection. The auth controller's login, logout, and workspace listing are updated to strip or respect the override in environment variables passed to readAuthState, and workspace listing now resolves the override to determine the active workspace by credential ID comparison. WorkspaceSelectionError is mapped to structured CLI errors in toCliError, with authConfigInvalidError branching its remediation guidance for the workspace-override case. Error functions accept an optional workspaceIdOverride flag to tailor guidance toward env-var workflows. The spec documentation, auth controller nextSteps builders, presenter output, and comprehensive tests are updated accordingly.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(auth): support workspace env override' clearly and concisely summarizes the main change—introducing support for the PRISMA_CLI_WORKSPACE_ID environment variable for workspace selection.
Description check ✅ Passed The description is comprehensive, well-organized, and directly related to the changeset. It explains the feature's purpose, behavior, examples, and testing approach, all of which align with the actual changes across multiple files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch aman/auth-workspace-env-override
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch aman/auth-workspace-env-override

Comment @coderabbitai help to get the list of available commands.

@AmanVarshney01 AmanVarshney01 marked this pull request as draft June 23, 2026 10:08
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 23, 2026
@AmanVarshney01 AmanVarshney01 marked this pull request as ready for review June 23, 2026 10:14
@AmanVarshney01 AmanVarshney01 force-pushed the aman/auth-workspace-env-override branch from 9812132 to 937ac76 Compare June 23, 2026 10:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/controllers/auth.ts`:
- Around line 290-304: In the return object's workspaces array mapping, the
active flag is being set by comparing credentialWorkspaceId values, which
incorrectly marks all workspaces with null credentialWorkspaceId as active.
Since the active variable is always a reference from the localWorkspaces array
(from either resolveLocalWorkspaceIdOverride or the find call), replace the
property equality check `active?.credentialWorkspaceId ===
workspace.credentialWorkspaceId` with direct reference equality `active ===
workspace` to correctly identify the single active workspace.

In `@packages/cli/src/shell/command-runner.ts`:
- Around line 69-73: The error message for the "missing" reason case in the
authConfigInvalidError call is incorrectly describing it as "is set but empty",
which conflates two different failure modes. When error.reason === "missing",
the issue is that the provided workspace ID was not found or did not match any
available workspace, not that the environment variable itself is empty. Update
the error message returned in this branch to accurately describe the "missing"
case as a workspace ID lookup failure or mismatch, rather than an empty value
issue, so users receive correct remediation guidance.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1a06369a-e8ef-49bf-9162-962bd8501eab

📥 Commits

Reviewing files that changed from the base of the PR and between 9812132 and 937ac76.

📒 Files selected for processing (11)
  • docs/product/command-spec.md
  • packages/cli/src/adapters/token-storage.ts
  • packages/cli/src/controllers/auth.ts
  • packages/cli/src/lib/auth/client.ts
  • packages/cli/src/lib/auth/guard.ts
  • packages/cli/src/presenters/auth.ts
  • packages/cli/src/shell/command-runner.ts
  • packages/cli/src/shell/errors.ts
  • packages/cli/tests/auth-real-mode.test.ts
  • packages/cli/tests/auth.test.ts
  • packages/cli/tests/token-storage.test.ts

Comment thread packages/cli/src/controllers/auth.ts
Comment thread packages/cli/src/shell/command-runner.ts
@AmanVarshney01 AmanVarshney01 force-pushed the aman/auth-workspace-env-override branch from 937ac76 to 42062a8 Compare June 23, 2026 10:38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
packages/cli/src/shell/command-runner.ts (1)

73-77: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

WorkspaceSelectionError("missing") is translated to the wrong user-facing error.

This branch always reports PRISMA_CLI_WORKSPACE_ID is set but empty, which conflates a generic missing workspace reference with a specific env-var-empty case.

Suggested fix
     if (error.reason === "missing") {
-      return authConfigInvalidError(
-        `${WORKSPACE_ID_ENV_VAR} is set but empty. Provide a workspace id from prisma-cli auth workspace list, or unset the variable.`,
-      );
+      return workspaceNotAuthenticatedError(workspaceRef, {
+        workspaceIdOverride: fromWorkspaceIdOverride,
+      });
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/shell/command-runner.ts` around lines 73 - 77, The error
message in the branch checking `error.reason === "missing"` incorrectly assumes
the cause is specifically that WORKSPACE_ID_ENV_VAR is set but empty, when this
reason code represents a generic missing workspace reference. Update the message
returned by the authConfigInvalidError call to accurately reflect the generic
nature of the missing workspace error, or add additional logic to differentiate
between the specific env-var-empty case and other missing workspace scenarios
before reporting to the user.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@packages/cli/src/shell/command-runner.ts`:
- Around line 73-77: The error message in the branch checking `error.reason ===
"missing"` incorrectly assumes the cause is specifically that
WORKSPACE_ID_ENV_VAR is set but empty, when this reason code represents a
generic missing workspace reference. Update the message returned by the
authConfigInvalidError call to accurately reflect the generic nature of the
missing workspace error, or add additional logic to differentiate between the
specific env-var-empty case and other missing workspace scenarios before
reporting to the user.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c85c82d4-0c0d-45e4-a134-b54c06ebb967

📥 Commits

Reviewing files that changed from the base of the PR and between 937ac76 and 42062a8.

📒 Files selected for processing (11)
  • docs/product/command-spec.md
  • packages/cli/src/adapters/token-storage.ts
  • packages/cli/src/controllers/auth.ts
  • packages/cli/src/lib/auth/client.ts
  • packages/cli/src/lib/auth/guard.ts
  • packages/cli/src/presenters/auth.ts
  • packages/cli/src/shell/command-runner.ts
  • packages/cli/src/shell/errors.ts
  • packages/cli/tests/auth-real-mode.test.ts
  • packages/cli/tests/auth.test.ts
  • packages/cli/tests/token-storage.test.ts

@AmanVarshney01 AmanVarshney01 force-pushed the aman/auth-workspace-env-override branch from 42062a8 to f00852b Compare June 23, 2026 10:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/controllers/auth.ts`:
- Around line 345-409: The `hasWorkspaceIdOverride()` function currently only
checks if the workspace ID environment variable is set, but does not account for
the service token which takes precedence when both are present. Modify the
`hasWorkspaceIdOverride()` function to return true only when the workspace ID
environment variable is defined AND the service token environment variable
(SERVICE_TOKEN_ENV_VAR) is not defined. This ensures that the next steps
generated by `buildAuthLoginNextSteps()`, `buildAuthLogoutNextSteps()`,
`buildWorkspaceUseNextSteps()`, and `buildWorkspaceLogoutNextSteps()` correctly
handle the case where both variables are set by not treating the workspace ID as
an override when a service token is present.

In `@packages/cli/tests/auth-real-mode.test.ts`:
- Around line 132-137: The assertion using expect.not.objectContaining only
verifies that the specific key-value pair PRISMA_CLI_WORKSPACE_ID with value
"wksp_old" is not present, but it allows the env var to be forwarded with a
different value. Change the assertion to explicitly verify that the
PRISMA_CLI_WORKSPACE_ID property is completely absent from the object passed to
readAuthState, rather than just checking that it doesn't match the old value.
This fix needs to be applied in both the readAuthState expectation and the
similar assertion at line 205.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9bbc1585-3c82-45e1-893b-46d328dc2360

📥 Commits

Reviewing files that changed from the base of the PR and between 42062a8 and f00852b.

📒 Files selected for processing (11)
  • docs/product/command-spec.md
  • packages/cli/src/adapters/token-storage.ts
  • packages/cli/src/controllers/auth.ts
  • packages/cli/src/lib/auth/client.ts
  • packages/cli/src/lib/auth/guard.ts
  • packages/cli/src/presenters/auth.ts
  • packages/cli/src/shell/command-runner.ts
  • packages/cli/src/shell/errors.ts
  • packages/cli/tests/auth-real-mode.test.ts
  • packages/cli/tests/auth.test.ts
  • packages/cli/tests/token-storage.test.ts

Comment thread packages/cli/src/controllers/auth.ts Outdated
Comment thread packages/cli/tests/auth-real-mode.test.ts
@AmanVarshney01 AmanVarshney01 force-pushed the aman/auth-workspace-env-override branch from f00852b to dee25a5 Compare June 23, 2026 11:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/shell/errors.ts`:
- Around line 189-192: The summary for the WORKSPACE_AMBIGUOUS error code is too
specific and inaccurate when ambiguity originates from PRISMA_CLI_WORKSPACE_ID
(ID-based selection). Replace the summary field value from "Workspace name is
ambiguous" with a reference-neutral message that appropriately covers both
name-based and ID-based ambiguity scenarios without misleadingly suggesting the
ambiguity is specifically about the workspace name.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 07be49ba-6270-4930-8d06-b2574a41ccd7

📥 Commits

Reviewing files that changed from the base of the PR and between f00852b and dee25a5.

📒 Files selected for processing (11)
  • docs/product/command-spec.md
  • packages/cli/src/adapters/token-storage.ts
  • packages/cli/src/controllers/auth.ts
  • packages/cli/src/lib/auth/client.ts
  • packages/cli/src/lib/auth/guard.ts
  • packages/cli/src/presenters/auth.ts
  • packages/cli/src/shell/command-runner.ts
  • packages/cli/src/shell/errors.ts
  • packages/cli/tests/auth-real-mode.test.ts
  • packages/cli/tests/auth.test.ts
  • packages/cli/tests/token-storage.test.ts

Comment on lines 189 to 192
code: "WORKSPACE_AMBIGUOUS",
domain: "auth",
summary: "Workspace name is ambiguous",
why: `Multiple authenticated workspaces matched "${workspaceRef}".`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use a neutral ambiguity summary for ID-override paths.

At Line 191, "Workspace name is ambiguous" is inaccurate when ambiguity comes from PRISMA_CLI_WORKSPACE_ID (ID-based selection). Prefer a reference-neutral summary to avoid misleading remediation context.

Suggested fix
-    summary: "Workspace name is ambiguous",
+    summary: "Workspace reference is ambiguous",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
code: "WORKSPACE_AMBIGUOUS",
domain: "auth",
summary: "Workspace name is ambiguous",
why: `Multiple authenticated workspaces matched "${workspaceRef}".`,
code: "WORKSPACE_AMBIGUOUS",
domain: "auth",
summary: "Workspace reference is ambiguous",
why: `Multiple authenticated workspaces matched "${workspaceRef}".`,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/shell/errors.ts` around lines 189 - 192, The summary for the
WORKSPACE_AMBIGUOUS error code is too specific and inaccurate when ambiguity
originates from PRISMA_CLI_WORKSPACE_ID (ID-based selection). Replace the
summary field value from "Workspace name is ambiguous" with a reference-neutral
message that appropriately covers both name-based and ID-based ambiguity
scenarios without misleadingly suggesting the ambiguity is specifically about
the workspace name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants