Repository navigation
Conversation
The gateway package needs the refresh_token grant to renew the token behind NewClient, but oidc imports gateway, so gateway cannot import oidc. Move discovery, the refresh grant with its per-directory lock, and reading and writing oidc_token.json to internal/oidcclient. oidc keeps thin wrappers, and ErrDiscovery and ErrTokenPersist are now the same variables as the internal ones, so errors.Is matches from either package. oidcclient.Refresh reports why a refresh did not happen instead of returning nil, nil. loginRefreshError maps those errors to what Login did before: run the interactive flow, or stop with ErrTimeout, the discovery error or the write error. Login behaves as before. Part of ai-openshell/openshell#4514. Signed-off-by: shvma <ich.shvml@gmail.com>
Login, and in a later commit the gateway client, renew the token through oidcclient.Refresh. The gateway runs it without a user watching, so: - Before writing, read the file again. If it was removed, as `openshell gateway logout` does, or now holds another refresh token or a token for another client, do not write it back; a fresh token found there is returned. A file that cannot be read at that point, for example while the CLI rewrites it in place, is written over, as before. - Check that the token directory is writable before the token request. A provider that rotates refresh tokens revokes the stored one when it answers, so a response that cannot be stored would cost the session. The check catches a missing write permission, not a full disk; if the write still fails, return the new token with the error, together with the file that could not be written and the one it was to replace. - Report the HTTP status when an error response is not JSON, such as a proxy's error page. Cut the provider's error code to 64 bytes and replace the refresh token in it, raw or form-encoded, if the provider echoes it; withhold a code that holds it encoded any other way. Treat a null expires_in as no expiry, as the CLI's oauth2 crate does, and cap expires_in at 2^31-1 seconds as golang.org/x/oauth2 does. - Key the lock by the directory itself (os.SameFile), not its path, so every spelling of one directory shares a lock: a relative path, a symlink and its target, another case or Unicode normalization where the file system ignores them, or a macOS firmlink. When the wait for the lock ends, say in the error that it was waiting for another refresh. - Add Request.FinishGrant, which lets the token requests and the write run to the end when ctx ends after discovery, and ScopesWithOpenID, which Login now uses. - Document in Login and ErrTimeout that a context ending after the token request reached a provider that rotates refresh tokens can leave the stored refresh token revoked. For Login, four outcomes change: an unwritable directory still fails with ErrTokenPersist but no longer spends the refresh token; a file that changed during the refresh is not overwritten, and Login uses its token if it is fresh and otherwise runs the interactive flow; a null expires_in gives a token without an expiry instead of the interactive flow; and expires_in is capped at 2^31-1 seconds (above about 9.2e9 seconds it overflowed time.Duration). Part of ai-openshell/openshell#4514. Signed-off-by: shvma <ich.shvml@gmail.com>
Once its cached token is inside the leeway, RefreshableToken waits for a refresh. If the call's context ended first, it returned the context's error, which gRPC reports as Unauthenticated, although the cached token had not expired. - A call with a deadline now waits for the refresh for at most half the time it has left while the cached token has not expired, and then sends the cached token. The refresh keeps running. - The refresh records its own outcome, so a new token is kept and a failure starts the backoff even when every caller stopped waiting. Before, only a caller that received the result recorded it. A source that returns neither a token nor an error now also starts the backoff. - A call whose context ends while it waits sends the cached token if it has not expired, as after a failed refresh. - Otherwise the error wraps the context's error and carries its gRPC status, so the call fails with DeadlineExceeded or Canceled rather than Unauthenticated, which suggests logging in again. Any token source that makes a network call can hit this. The gateway's OIDC token source in the next commit can take up to 2 seconds to answer inside the window, so gateway.NewClient clients would hit it routinely. Part of ai-openshell/openshell#4514. Signed-off-by: shvma <ich.shvml@gmail.com>
The OIDC auth that NewClient builds only read oidc_token.json, so once the access token expired every RPC failed as Unauthenticated (ErrTokenLoad) until the CLI refreshed the file. diskTokenSource now renews a token within 30 seconds of expiry, as the CLI and the Python SDK do, when the file has a refresh token and was issued for the issuer and client ID in metadata.json. Once it has renewed a token valid for less than a minute, it renews at half that lifetime. While the token has not expired, RPCs wait for the renewal until 2 seconds after it started, then send the current token and let the renewal finish in the background, so a slow or failing provider delays RPCs by at most 2 seconds per renewal. Concurrent calls share one renewal. Every failed renewal goes to the client's logger; while the token is still valid, the next one starts no sooner than 5 seconds later. An RPC that finds the token expired, or sees it expire while waiting, waits for the renewal until its own deadline. The renewal waits at most 30 seconds for the lock and discovery, then sends up to two token requests, each bounded by the HTTP client's 30-second timeout, and runs them to the end even after every RPC stopped waiting. If it fails, the RPC uses a token another process wrote meanwhile; otherwise the error names the cause. A renewed token that cannot be written, for example on a full disk, is kept in memory and used, since the provider may have revoked the stored refresh token, and the next renewal writes it first. While that write fails and the refresh token was rotated, no token request is sent: the provider may end the session when it sees the revoked refresh token in the file. A renewal is not tied to the client: closing the client does not stop it, and one still running when the process exits is cut off. NewClient gives RefreshableToken the same 30 second leeway and its logger. Part of ai-openshell/openshell#4514. Signed-off-by: shvma <ich.shvml@gmail.com>
rhuss
left a comment
There was a problem hiding this comment.
cc-review Summary
What Went Well
openshell/v1/auth_refresh.goGetRequestMetadata/record (lines 137-146, 196-225): the refresh outcome is recorded inside the singleflight function, so the backoff,lastErrand the new token survive even when every caller stopped waiting at half its deadline.refreshWaitErrorimplementsUnwrapandGRPCStatus, so a context that ends during a refresh reports DeadlineExceeded or Canceled instead of Unauthenticated.openshell/v1/internal/oidcclient/refresh.goRefresh (lines 215-263):checkWritableruns before the refresh token is spent, and the file is re-read under the per-directory lock before the request and again before the write. A read-only directory therefore does not burn a rotating refresh token, and a concurrent logout or newer login is not overwritten.openshell/v1/gateway/token.gosaveUnsaved/refresh (lines 301-305, 376-405): when a rotated refresh token cannot be written, the granted token stays in memory and renewals stop sending the revoked refresh token from the file, so provider reuse detection does not end the session.openshell/v1/internal/oidcclient/discovery.goHTTPClient and ValidateSecureURL (lines 22-27, 148-159): redirects are refused, a 30s timeout is set, and discovered endpoints must be HTTPS (or loopback HTTP) with a matching issuer, so the refresh token cannot be steered to another host.openshell/v1/internal/oidcclient/refresh.gorefreshToken (lines 400-452): provider error codes are scrubbed of the refresh token (including percent-decoded forms), truncated and quoted,error_descriptionand decoder input are never echoed, the response body is read through a 1 MiB limit, andexpires_inis capped before multiplying to avoid a duration overflow.openshell/v1/internal/oidcclient/errors.goandoidc/errors.go: moving discovery, the refresh grant and token I/O into an internal package breaks the oidc to gateway import cycle, andErrDiscoveryandErrTokenPersiststay the same sentinel values, so callers'errors.Ischecks keep working.- Tests:
TestDiskTokenSource_UnsavedTokenOutlivesWaitersingateway/refresh_test.gochecks which refresh token the provider actually received,newAuthRecorderingateway/refresh_rpc_test.gochecks the authorization headers on the wire against a real TLS gRPC server, andTestRetryReplaceininternal/oidcclient/token_test.goasserts the exact backoff schedule with an injected sleep.
Findings
| Severity | File | Description | Source |
|---|---|---|---|
| Notable | openshell/v1/auth_refresh.go:138 | RefreshableToken now treats a token source that returns (nil, nil) as a failed refresh: it s... |
goal-alignment |
| Minor | openshell/v1/gateway/gateway.go:177 | The gateway sets the RefreshableToken cache leeway to a fixed refreshWindow (30s), while di... |
production |
| Notable | openshell/v1/gateway/token.go:203 | Wait and retry policy for a refresh is now split across two layers with separate rules: refresh... |
architecture |
| Notable | openshell/v1/gateway/token.go:249 | When a renewal fails while the stored token is still usable, diskTokenSource.Token() returns t... |
gator |
| Minor | openshell/v1/gateway/token.go:376 | In the gateway package, saveUnsaved (token.go:376-405) repeats the lock, re-read, compare and... |
architecture |
| Minor | openshell/v1/internal/oidcclient/refresh.go:28 | The shared package exports RefreshWindow = 10 * time.Second, documented as the window Login... |
architecture |
| Minor | openshell/v1/internal/oidcclient/refresh_errors_test.go:322 | No test checks Result.Unwritten or Result.Replaced after a failed write. The "after the toke... |
test-quality |
| Minor | openshell/v1/oidc/oidcclient.go:21 | var oidcHTTPClient = oidcclient.HTTPClient keeps a second package-level handle to the HTTP cli... |
architecture |
Review Details
These findings were produced by cc-review's reviewer agents and posted without a per-finding review.
- Findings posted: 8
- Findings reviewed and not posted: 0
- Gate outcome: PASS
- Participating reviewers: goal-alignment, production, architecture, gator, test-quality
| // | ||
| // A renewal is not tied to the client: closing the client does not stop | ||
| // it, and a renewal still running when the process exits is cut off. | ||
| func (d *diskTokenSource) Token() (*oauth2.Token, error) { |
There was a problem hiding this comment.
Notable: Wait and retry policy for a refresh is now split across two layers with separate rules: refreshableAuth (singleflight, 1s to 30s exponential backoff, waits at most half the RPC deadline) and diskTokenSource (its own shared renewal, 2s refreshWait, 5s retry delay, forced renewal on expiry, background goroutine).
Why this matters: What an RPC actually sees can only be worked out by reading both layers together (auth_refresh.go:124-178 and 196-225, token.go:65-89 and 203-293), which is why docs/src/api/gateway.md needs a long section to explain it. This is a maintainability observation, not a defect.
Suggested fix: In a later change, consider letting diskTokenSource expose a non-blocking refresh to refreshableAuth, or letting one of the two own the whole policy, so a single component decides wait and retry timing.
Source: architecture agent
There was a problem hiding this comment.
Thanks for checking the fixes. I'd leave the wait and retry refactor for a follow-up.
The SDK tests passed with -race on d351a1e. I also checked the retry behavior with a local token endpoint returning HTTP 503. The client used the valid token during the source's cooldown and tried to refresh on the first RPC after expiry. When that failed, the next RPC returned Unauthenticated without another token request. A later RPC renewed the token after the endpoint recovered and the client's backoff elapsed.
Could you approve the Actions runs for this commit? If the checks pass, would you approve the PR as it stands?
Use the disk source window for cached tokens. Share the token file replacement logic and verify which token a failed write would have replaced. Part of ai-openshell/openshell#4514. Signed-off-by: shvma <ich.shvml@gmail.com>
gateway.NewClientnow uses the refresh token inoidc_token.jsonto renew an expiring access token. Previously it read the file without renewing it, so calls could fail withUnauthenticateduntil another process updated the file.Part of ai-openshell/openshell#4514. This follows #48, which added renewal to
Login. As discussed there, the gateway returns the reason when renewal fails and no usable token is available. TheLoginandErrTimeoutdocs explain how the stored token can become unusable if the context ends after a rotating provider receives the request. The CLI atomic-write patch follows separately.Changes
refactor(oidc)moves discovery, the refresh grant and token file I/O intointernal/oidcclientsogatewayandoidccan share them.Loginstill maps ordinary refresh errors to an interactive login. Git reportsoidc/refresh.goas deleted.git diff -M --color-movedon this commit shows the moved code.fix(oidc)checks directory write access before spending a refresh token. Before saving the new token, it rereads the file and skips the write if the file disappeared or now holds a different issuer, client ID, or refresh token. If the token rotated and writing fails, the gateway can use the new token in memory and retry the write before spending it again. Provider error codes are capped and scrubbed of the refresh token. A non-200 response without an error code reports the HTTP status. Malformed JSON in the token response or file gets a fixed diagnostic. The commit also handles null or very largeexpires_inand keys the in-process lock by directory identity.fix(auth)applies to allv1.RefreshableTokencallers. A call waiting for a slow refresh can use a still-valid cached token. Without one, cancellation or a deadline is reported with its gRPC status. The refresh records its result even if every caller has stopped waiting. A source that returns neither a token nor an error now triggers backoff and falls back to a cached token if it is still valid.fix(gateway)starts renewal up to 30 seconds before expiry, or at half the token lifetime once it observes a shorter-lived renewal. The cache uses the same window, so a token with a 20-second lifetime can stay in memory until it is due. Renewal needs the issuer and client ID frommetadata.jsonand a matching token file. Concurrent calls on one client share a renewal. With a usable token, callers wait up to two seconds from the start of renewal before using that token. A renewal failure in this window is logged, and the source waits at least five seconds before trying again. Once the token expires, callers wait for renewal or their own context to end, and a renewal error triggers the client's exponential backoff. The token request and write can finish in the background.Limits
oidc_scopeswithopenidfirst, likeLogin.invalid_grantand a replacement token on disk.Testing
mise run ciwith Go 1.26.7 and golangci-lint 2.12.2, plus the CI license-header check. Regression tests cover the cache window for short-lived tokens, which file contents a failed write would have replaced, and redaction in JSON decoding errors.go test -race -cpu 1,4 -count=25passed in the four affected packages.