Repository navigation
Conversation
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
tianhr
force-pushed
the
feat/golang-sdk-token-rotation
branch
from
September 28, 2026 08:23
9b21d62 to
c828cf8
Compare
# Conflicts: # runtime/README.md # runtime/README_zh-CH.md
tianhr
marked this pull request as draft
November 11, 2026 05:09
tianhr
marked this pull request as ready for review
November 11, 2026 05:09
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this PR does
Ports the Python SDK's Traffic JWT auto-refresh capability (
e2b/python/kruise_agents) to the Go SDK as a native implementation (no monkey-patching). Sandboxes created with metadata"security.agents.kruise.io/enable-jwt-auth": "true"get a short-lived Traffic JWT from sandbox-manager; every data-plane request must carry it in thee2b-traffic-access-tokenheader or the gateway rejects it with 403. The Go SDK now attaches and rotates this token transparently — no caller-side code change required.Key changes
Token manager (
e2b/traffic_token.go)trafficTokenManager: refreshes ahead of expiry (min(300s, max(60s, validity/5))minus up to 10% random jitter), coalesces concurrent refreshes into one call (single-flight with pre-lock generation/attempts/busy snapshots), retries failures with exponential backoff (1s → 30s, serverRetry-Afterhonored), degrades to the still-valid current token on refresh failure, and fails closed with*TrafficAccessTokenExpiredonce the token has expired instead of sending a request the gateway would reject.context.WithoutCancel): cancelling a data-plane call does not abort an in-flight refresh that other callers depend on.expclaim within 5s tolerance, already-expired tokens are rejected.Data-plane injection (
runtime/traffic_token.go,runtime/client.go,runtime/config.go)runtime.TrafficTokenProvider+WithTrafficTokenProvideroption;NewWithConfigwraps the non-streaming and streaming HTTP clients'RoundTripperso every data-plane request (Commands / Files / CodeInterpreter, unary and streaming alike) obtains a valid token right before it is sent — the Go counterpart of the Python patch's envd interceptors, httpx event hooks and Jupyter client hooks.Sandbox integration (
e2b/sandbox.go,e2b/sandbox_api.go,e2b/config.go)Create/Connectseed the manager from the management-API response token;Connectwithout a token probes sandbox metadata viaGetInfoand bootstraps lazily whenenable-jwt-auth=true(best-effort: non-JWT deployments are unaffected), mirroring the Python patch's lazy-Connect behavior.WithTrafficAccessToken(token)sandbox option seeds an externally issued JWT (external identity-provider deployments), the counterpart of the PythonSandbox(traffic_access_token=...)constructor parameter; non-JWT values keep the legacy no-header behavior.Sandbox.TrafficAccessToken()(cached token, no refresh) andSandbox.RefreshTrafficAccessToken(ctx)(forced refresh, concurrent forces coalesce).SandboxApi.RefreshTrafficAccessTokenendpoint (POST /sandboxes/{id}/traffic-access-token, not emitted by the OpenAPI generator): sendsConnectionConfig.HeaderswithX-API-Keyapplied last so the API key wins on collision (matching Python_refresh_headers), never surfaces the response body on failure, preserves status code andRetry-Afterin*TrafficAccessTokenRefreshError.WithHeader(key, value)connection option; custom headers now ride on every management request viaDefaultHeader.ConnectionConfig.TrafficAPIBase(): upstream registers the refresh endpoint only under its/kruise/apiprefix (web.RegisterRoute, asserted by upstream'sTestTrafficAccessTokenRouteIsKruiseOnly), so the SDK always targets{scheme}://{domain}/kruise/api/sandboxes/{id}/traffic-access-tokenregardless of routing protocol — the defaultProtocolNativeincluded, whosehttps://api.<domain>base would 404. An explicitWithAPIURLoverride still wins as-is (proxy / port-forwarding escape hatch). This mirrors the Python patch, whose derivedapi_urlalways carries the prefix.WithDebug(true)keep the existing behavior: no traffic header, no refresh.Key compatibility encoding (
e2b/keys.go)EncodeForE2BSDKwraps a raw OpenKruise Agents API key into thee2b_-prefixed format enforced by official E2B SDK tooling (e2b_+ magic6f6b6167+ version01+ 8-hex length + hex body + salted SHA-256 checksum), byte-for-byte identical to Pythonkeys.py:encode_for_e2b_sdk(golden-value tests).Testing
e2b/traffic_token_test.go+e2b/keys_test.go: full manager matrix (refresh window, jitter, bootstrap, coalescing incl. concurrent failed forced refreshes, backoff, Retry-After, fail-closed, response validation incl. not-a-JWT branches), HTTP integration against mock management/data-plane servers (header injection, custom headers, seed override, legacy degradation), andTestSandboxApiRefreshTrafficAccessTokenURLpinning the refresh path for native / private /WithAPIURL-override configurations.go build ./...,go vet,go test ./e2b/... ./runtime/...all green.demo_jwt_gateway.py): data-plane calls without a valid JWT are rejected with 403, externally seeded tokens authenticate successfully, and two automatic rotations were observed under a 65s token validity with zero data-plane interruption.Docs & examples
e2b/README.md+README_zh-CH.md: new "Traffic JWT Refresh" section (mechanism, manual-control APIs, refresh-endpoint routing note, rollout guidance — deploy refreshing clients before shortening--traffic-access-token-validity, deploy lazy-Connect before upgrading to a manager that no longer issues tokens from Connect);runtimeREADMEs documentWithTrafficTokenProvider.examples/jwt-gateway-example: Go counterpart ofdemo_jwt_gateway.py— full flow against a real gateway with an external OIDC issuer, using a local translating proxy for the refresh endpoint so the entire SDK refresh path (headers, Retry-After, response validation) is exercised.examples/e2b-example: adds a pause → connect (resume) → data-plane re-verification segment;examples/runtime-example: adds aTRAFFIC_ACCESS_TOKEN-based provider demo.Notes