Skip to content

fix: keep sudo id when login(sudoId) also logs in the API user - #1777

Closed
Priyank-gouda678 wants to merge 1 commit into
looker-open-source:mainfrom
Priyank-gouda678:sudo-login-keep-sudo-id
Closed

Priyank-gouda678 wants to merge 1 commit into
looker-open-source:mainfrom
Priyank-gouda678:sudo-login-keep-sudo-id

Conversation

@Priyank-gouda678

Copy link
Copy Markdown

NodeSession._login() assigns the requested sudo id and then, when the API user's token is not active, calls reset() before logging the API user in. reset() clears sudoId, so the if (this.sudoId) check that follows is false, POST /login/{id} is never sent, and login(id) returns the API user's token. Every later call on that SDK then runs with the API3 credentials (normally an admin, since sudo needs that permission) while isSudo() reports false. It happens on the first login(id) of a fresh session and on any login(id) after the API user's token has expired, so a service that sudoes to scope calls to an end user's permissions gets admin-scoped results back. The Swift AuthSession._login() has the same ordering. The Kotlin, C# and Python sessions are not affected: Kotlin doesn't call reset() there, C# checks the sudoId argument, and Python keeps _sudo_id outside the API login.

The sudo id is now assigned after the API user login in both sessions. The new nodeSession.spec.ts covers a fresh login('5'): it fails before the change (only POST /api/4.0/login is sent) and passes after. The Swift change was checked with a mock transport: before, login("5") leaves isSudo() == false holding the API token; after, it sends POST /login/5 and holds the sudo token.

Developer Checklist ℹ️

  • Make sure to open an issue as a bug/issue before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
  • Ensure the tests and linter pass
  • Appropriate docs were updated (if necessary)

@Priyank-gouda678
Priyank-gouda678 requested a review from a team as a code owner October 29, 2026 17:49
@google-cla

google-cla Bot commented Oct 29, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request fixes an issue in both the Node and Swift SDKs where the requested sudo ID was being cleared immediately after assignment because the assignment occurred before the reset() call. To resolve this, the assignment of sudoId has been moved to execute after reset(). Additionally, a new unit test suite has been added for NodeSession to verify the sudo login behavior. The review feedback suggests normalizing newId in nodeSession.ts before comparison to prevent redundant assignments, and enhancing the new unit test to explicitly assert the exact sequence and number of API requests made during the login process.

Comment thread packages/sdk-node/src/nodeSession.ts Outdated
Comment on lines +184 to +187
if (newId !== this.sudoId) {
// Assign new requested sudo id after reset() above, which clears it
this.sudoId = newId || '';
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Comparing newId (which can be undefined) directly with this.sudoId (which is initialized to '') results in a redundant assignment of '' to this.sudoId when no sudo ID is requested. We can avoid this by normalizing newId first and then performing the comparison.

Suggested change
if (newId !== this.sudoId) {
// Assign new requested sudo id after reset() above, which clears it
this.sudoId = newId || '';
}
const targetSudoId = newId || '';
if (targetSudoId !== this.sudoId) {
// Assign new requested sudo id after reset() above, which clears it
this.sudoId = targetSudoId;
}

Comment on lines +66 to +73
expect(request).toHaveBeenCalledWith(
'POST',
'/api/4.0/login/5',
null,
null,
expect.any(Function),
settings
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To make the test more robust and explicitly verify the login sequence (first logging in the API user, then performing the sudo login), we should assert that request was called exactly twice and verify the second call specifically using toHaveBeenNthCalledWith.

Suggested change
expect(request).toHaveBeenCalledWith(
'POST',
'/api/4.0/login/5',
null,
null,
expect.any(Function),
settings
);
expect(request).toHaveBeenCalledTimes(2);
expect(request).toHaveBeenNthCalledWith(
2,
'POST',
'/api/4.0/login/5',
null,
null,
expect.any(Function),
settings
);

@drstrangelooker drstrangelooker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good catch on reset() clearing this.sudoId during initial login. #1787 (bd5fc9c4) landed on main after you opened this PR and already replaced reset() inside _login() with token-only invalidation in both SDKs (this._authToken.reset() + this._sudoToken.reset() in NodeSession, and self.invalidateTokens() in Swift AuthSession).

Please rebase onto main and drop the _login() ordering changes in packages/sdk-node/src/nodeSession.ts and swift/looker/rtl/authSession.swift, while keeping the unit test coverage. Merging those two hunks onto current main causes two issues even though Git reports no conflict:

  1. Regression on failed non-sudo login after expiry: Suppose a session previously ran login('5'), and later both _sudoToken and _authToken expire (isSudo() is now false, while this.sudoId is still '5'). When a caller calls await session.login() with no sudoId to revert to the API3 user, current main clears this.sudoId = '' before POST /api/4.0/login. Moving that assignment below the API login means a transient failure on POST /api/4.0/login throws before clearing this.sudoId. The session stays stuck on '5', so the next getToken() call silently sudoes again.
  2. Stale comments: Both files would retain // Assign new requested sudo id after reset() above, which clears it below blocks that no longer call reset().

main still has no direct Jest unit test file for NodeSession, so packages/sdk-node/src/nodeSession.spec.ts is useful regression coverage to land. Before we merge it, please make three small updates:

  1. Verify both login calls and the Authorization header: Update the transport.request mock to invoke the authenticator callback (5th argument), assert expect(request).toHaveBeenCalledTimes(2), check POST /api/4.0/login on call 1, and verify that call 2 (POST /api/4.0/login/5) sets Authorization: Bearer api on the request headers.
  2. Update the license header: Use the Copyright 2026 Google LLC MIT header from packages/sdk-node/src/nodeTransport.spec.ts (updated on main in #1783).
  3. Optional Swift test: If you still have the mock-transport Swift reproduction from your PR description, feel free to include it in swift/looker/Tests/lookerTests/authTokenTests.swift or authSessionTests.swift alongside the MockSettings / ITransport pattern on main.

(Separately, I'll file a follow-up for a distinct bug where an expired _sudoToken is sent instead of _authToken when _authToken is still active - no need to fold that into this PR.)

@Priyank-gouda678

Copy link
Copy Markdown
Author

Rebased onto main and dropped the _login() hunks in both SDKs, so this is just tests now.

The spec's request mock now runs the authenticator, and it checks for exactly two calls: POST /api/4.0/login, then POST /api/4.0/login/5 with Authorization: Bearer api. Header is the Google LLC one from nodeTransport.spec.ts.

Also added testLoginSudoLogsInApiUserFirst to authSessionTests.swift using the MockSettings/ITransport pattern. The Swift package doesn't seem to build on main at the moment (Agent is declared both as a typealias in rtl/transport.swift and as a model in sdk/models.swift), so I checked it against a copy with the typealias removed. Both tests pass on main and fail if _login() goes back to calling reset().

@Priyank-gouda678

Copy link
Copy Markdown
Author

any update?

drstrangelooker added a commit that referenced this pull request Dec 2, 2026
…across SDKs (#1806)

### Summary

Fixes sudo token renewal, revert, and failed-sudo privilege scoping
across the Node, Swift, Kotlin, C#, and Python SDKs (follow-up from
reviewing #1777):

1. **Scope `activeToken` by `sudoId` instead of
`_sudoToken.access_token`**
- **TypeScript / Node** (`packages/sdk-node/src/nodeSession.ts`),
**Swift** (`swift/looker/rtl/authSession.swift`), **Kotlin**
(`kotlin/src/main/com/looker/rtl/AuthSession.kt`), and **C#**
(`csharp/rtl/AuthSession.cs`): Return `_sudoToken` whenever `sudoId` is
set, rather than checking whether `_sudoToken.access_token` is
non-empty.
- Prevents a failed `POST /login/{id}` (or token reset while `sudoId` is
set) from silently falling back to an active admin `_authToken` and
reporting `isAuthenticated() === true`.

2. **Reset expired `_sudoToken` state and authenticate `POST
/login/{id}` with `_authToken`**
- **TypeScript / Node**, **Swift**, **Kotlin**, and **C#**: Reset
`_sudoToken` in `sudoLogout()` even when `isSudo()` is `false` (for
example after a 15-minute sudo token expires while the 60-minute API3
token is still active), and read `_authToken` directly when
authenticating `POST /login/{id}`.
- Clear `sudoId` and reset `_sudoToken` in `logout()` when a sudo token
has already expired so the session reverts cleanly to the API3 user
without sending an unnecessary `DELETE /logout`.
- **Python** (`python/looker_sdk/rtl/auth_session.py`): Reset an expired
`sudo_token` during `logout()` and still log out an active API3 token
when `logout(full=True)` is called after `sudo_token` expiry.

3. **Swift error propagation & C# repeated `Login(sudoId)` fix**
- **Swift** (`swift/looker/rtl/authSession.swift`): Replace `try?
self.ok(response)` + force-unwrap (`token!` / `sudoToken!`) in
`_login()` with `try self.ok(response)` and propagate errors from
`getToken()`, avoiding process crashes on auth errors.
- **C#** (`csharp/rtl/AuthSession.cs`): Fix `Login(string sudoId =
null)` so calling `Login("5")` while `"5"` is already active refreshes
sudo `"5"` instead of hitting the `else` branch (`_login(null)`) and
dropping back to the admin API3 user.

### Testing

- **TypeScript / Node**: `yarn jest
packages/sdk-node/src/nodeSession.spec.ts packages/sdk-rtl/src`, `tsc
--noEmit`, and `eslint`
- **Kotlin**: `./gradlew test` & `spotlessApply`
- **C#**: `dotnet test` (RTL unit tests)
- **Swift**: `swiftc` RTL unit test verification
- **Python**: `pytest python/tests/rtl/test_auth_session.py` & `black
--check`

## Developer Checklist

- [x] Make sure to open an issue as a
[bug/issue](https://github.com/looker-open-source/sdk-codegen/issues/new/choose)
before writing your code so we can discuss the change, evaluate designs,
and agree on the general idea
- [x] Ensure the tests and linter pass
- [x] Appropriate docs were updated (if necessary)

Fixes #1805
@drstrangelooker

Copy link
Copy Markdown
Collaborator

Thanks for catching this issue and following up with the tests, @Priyank-gouda678! Both the underlying fix (#1787) and the Node/Swift sudo session test coverage (#1806) have now landed on main, so I'm closing this PR as superseded.

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