Repository navigation
fix: keep sudo id when login(sudoId) also logs in the API user - #1777
Priyank-gouda678 wants to merge 1 commit into
Conversation
|
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. |
There was a problem hiding this comment.
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.
| if (newId !== this.sudoId) { | ||
| // Assign new requested sudo id after reset() above, which clears it | ||
| this.sudoId = newId || ''; | ||
| } |
There was a problem hiding this comment.
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.
| 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; | |
| } |
| expect(request).toHaveBeenCalledWith( | ||
| 'POST', | ||
| '/api/4.0/login/5', | ||
| null, | ||
| null, | ||
| expect.any(Function), | ||
| settings | ||
| ); |
There was a problem hiding this comment.
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.
| 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 | |
| ); |
28c1e8d to
98e4b86
Compare
drstrangelooker
left a comment
There was a problem hiding this comment.
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:
- Regression on failed non-sudo login after expiry: Suppose a session previously ran
login('5'), and later both_sudoTokenand_authTokenexpire (isSudo()is nowfalse, whilethis.sudoIdis still'5'). When a caller callsawait session.login()with nosudoIdto revert to the API3 user, currentmainclearsthis.sudoId = ''beforePOST /api/4.0/login. Moving that assignment below the API login means a transient failure onPOST /api/4.0/loginthrows before clearingthis.sudoId. The session stays stuck on'5', so the nextgetToken()call silently sudoes again. - Stale comments: Both files would retain
// Assign new requested sudo id after reset() above, which clears itbelow blocks that no longer callreset().
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:
- Verify both login calls and the
Authorizationheader: Update thetransport.requestmock to invoke theauthenticatorcallback (5th argument), assertexpect(request).toHaveBeenCalledTimes(2), checkPOST /api/4.0/loginon call 1, and verify that call 2 (POST /api/4.0/login/5) setsAuthorization: Bearer apion the request headers. - Update the license header: Use the
Copyright 2026 Google LLCMIT header frompackages/sdk-node/src/nodeTransport.spec.ts(updated onmainin#1783). - 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.swiftorauthSessionTests.swiftalongside theMockSettings/ITransportpattern onmain.
(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.)
98e4b86 to
051a425
Compare
|
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(). |
|
any update? |
…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
|
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 |
NodeSession._login()assigns the requested sudo id and then, when the API user's token is not active, callsreset()before logging the API user in.reset()clearssudoId, so theif (this.sudoId)check that follows is false,POST /login/{id}is never sent, andlogin(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) whileisSudo()reports false. It happens on the firstlogin(id)of a fresh session and on anylogin(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 SwiftAuthSession._login()has the same ordering. The Kotlin, C# and Python sessions are not affected: Kotlin doesn't callreset()there, C# checks thesudoIdargument, and Python keeps_sudo_idoutside the API login.The sudo id is now assigned after the API user login in both sessions. The new
nodeSession.spec.tscovers a freshlogin('5'): it fails before the change (onlyPOST /api/4.0/loginis sent) and passes after. The Swift change was checked with a mock transport: before,login("5")leavesisSudo() == falseholding the API token; after, it sendsPOST /login/5and holds the sudo token.Developer Checklist ℹ️