Skip to content

fix(cli): use project client for Users service in JwtManager#1396

Merged
ChiragAgg5k merged 2 commits intomasterfrom
fix/cli-user-impersonation-jwt
Mar 27, 2026
Merged

fix(cli): use project client for Users service in JwtManager#1396
ChiragAgg5k merged 2 commits intomasterfrom
fix/cli-user-impersonation-jwt

Conversation

@ChiragAgg5k
Copy link
Copy Markdown
Member

@ChiragAgg5k ChiragAgg5k commented Mar 26, 2026

Summary

  • Fixes CLI local function execution with user impersonation (--user-id) failing on self-hosted instances
  • The CLI refactor (943c73277) changed JwtManager.setup() to use sdkForConsole() for both Users and Projects services, but the Users API (/users/{userId}, /users/{userId}/jwts) needs to target the actual project via sdkForProject() — not the "console" project
  • This caused usersClient.get() to fail before either JWT could be generated, resulting in empty x-appwrite-key and x-appwrite-user-jwt headers
Users client Projects client
v12.0.0 (working) sdkForProject() sdkForConsole()
v14.0.1 (broken) sdkForConsole() sdkForConsole()
This fix sdkForProject() sdkForConsole()

Test plan

  • Run appwrite run functions --function-id <ID> --user-id <USER_ID> on a self-hosted instance
  • Verify no "missing scopes" warning appears
  • Verify function logs show hasUserJwt: true and hasApiKey: true
  • Verify running without --user-id still works correctly

Summary by CodeRabbit

  • Bug Fixes
    • User-related requests now use project-scoped credentials and instantiate user handling only when needed, improving authentication accuracy and reducing unnecessary initialization.

The CLI refactor (943c732) changed JwtManager.setup() to use
sdkForConsole() for both Users and Projects services. However, the
Users API needs to target the actual project (via sdkForProject()),
not the console project. This caused user impersonation (--user-id)
to fail on self-hosted instances, as the user lookup and JWT creation
were sent to the wrong project context.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Walkthrough

Updated JwtManager.setup so the Users client is created with sdkForProject() only when a userId is provided; usersClient.get and usersClient.createJWT now run against the project-scoped SDK. Projects initialization continues to use the console-scoped client.

Changes

Cohort / File(s) Summary
Client Scope Refactoring
templates/cli/lib/emulation/utils.ts
Changed JwtManager.setup to defer Users client instantiation until userId is present and create it via sdkForProject() instead of using the console-scoped SDK; Projects remains initialized with the console client.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A scope-hop in code so spry,
Users leap to project sky,
Created when the ID is there,
Projects steady, console-aware. 🥕✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: switching the Users service client from console-scoped to project-scoped in JwtManager, which aligns with the core fix for user impersonation JWT generation on self-hosted instances.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cli-user-impersonation-jwt

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Mar 26, 2026

Greptile Summary

This PR fixes a regression introduced in the CLI refactor (943c73277) where JwtManager.setup() mistakenly used sdkForConsole() (targeting the "console" project) for the Users service. The Users API endpoints (/users/{userId}, /users/{userId}/jwts) are project-scoped and must use sdkForProject(), which targets the actual Appwrite project — exactly the behaviour present in v12.0.0. The one-line fix is correct, minimal, and well-described in the PR.\n\n- Imports sdkForProject and uses it to construct usersClient, while projectsClient continues to use consoleClient — matching the pre-regression behaviour.\n- The only non-critical observation is that sdkForProject() is now eagerly awaited even when userId is null and usersClient is never accessed; moving it inside the if (userId) block would be a small cleanup but has no impact on correctness.

Confidence Score: 5/5

Safe to merge — the change is a minimal, targeted fix that restores pre-regression behavior with no side-effects

The fix is one logical line change that correctly reverts the client used for the Users service back to sdkForProject(), matching the documented v12.0.0 behavior. No new logic is introduced, error handling is unchanged, and the only remaining note is a non-blocking style suggestion about lazy initialization.

No files require special attention

Important Files Changed

Filename Overview
templates/cli/lib/emulation/utils.ts Fixes JwtManager.setup() to use sdkForProject() for the Users client instead of sdkForConsole(), restoring correct project-scoped API targeting for user impersonation

Reviews (1): Last reviewed commit: "fix(cli): use project client for Users s..." | Re-trigger Greptile

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
templates/cli/lib/emulation/utils.ts (1)

140-151: Reset userJwt when no userId is provided to avoid stale state.

If setup() is called multiple times in one process, a prior JWT can persist when userId is omitted. Clearing first is safer.

Suggested patch
+    this.userJwt = null;
     if (userId) {
       const projectClient = await sdkForProject();
       const usersClient = new Users(projectClient);
       await usersClient.get({
         userId,
       });
       const userResponse = await usersClient.createJWT({
         userId,
         duration: 60 * 60,
       });
       this.userJwt = userResponse.jwt;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@templates/cli/lib/emulation/utils.ts` around lines 140 - 151, The setup
method can leave a stale JWT when called without a userId; modify setup (around
the sdkForProject()/Users logic) to explicitly clear this.userJwt when no userId
is provided—either set this.userJwt = undefined (or null) before the if (userId)
block or add an else branch that sets this.userJwt = undefined so prior JWTs are
not reused; reference symbols: setup, this.userJwt, sdkForProject, Users,
usersClient.createJWT.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@templates/cli/lib/emulation/utils.ts`:
- Around line 140-151: The setup method can leave a stale JWT when called
without a userId; modify setup (around the sdkForProject()/Users logic) to
explicitly clear this.userJwt when no userId is provided—either set this.userJwt
= undefined (or null) before the if (userId) block or add an else branch that
sets this.userJwt = undefined so prior JWTs are not reused; reference symbols:
setup, this.userJwt, sdkForProject, Users, usersClient.createJWT.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d78a4403-6b97-4f89-8059-7aaeffa67b08

📥 Commits

Reviewing files that changed from the base of the PR and between d2de304 and 3d20ce2.

📒 Files selected for processing (1)
  • templates/cli/lib/emulation/utils.ts

@ChiragAgg5k ChiragAgg5k merged commit 5899a28 into master Mar 27, 2026
56 checks passed
@ChiragAgg5k ChiragAgg5k deleted the fix/cli-user-impersonation-jwt branch March 27, 2026 07:52
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