Repository navigation
test(oauth2lib): add golden vectors and run them against oauth2lib - #216
Merged
agrawalradhika-cell merged 4 commits intoDec 1, 2026
Merged
agrawalradhika-cell merged 4 commits into
agrawalradhika-cell merged 4 commits into
Conversation
Add package oauth2lib/goldenvectors: test vectors embedded with //go:embed *.json, so other modules' tests (such as Go gcloud's) can read them without Blaze runfiles. Each vector gives an input to BuildCredentials or Impersonate, the requests one Token call must send, the responses to give, and the token or RefreshError it must return. The package imports only the standard library; README.md documents the format. The 27 vectors cover authorized_user refresh (scopes, RAPT, rotated and echoed refresh tokens, token URL precedence, expires_in forms, universe domain), user errors (revoked token, invalid_rapt, rapt_required, CAA and plain access_denied, 503, network error), service account 2LO and self-signed JWT, and impersonation (JSON with user and service account sources, delegates and lifetime, custom endpoint, IAM 403, source reauth). TestGoldenVectors runs every vector with a transport that checks each request (method, URL, headers, exact form or JSON body, JWT assertion signature and claims) and answers without any network.
… and stable kinds in golden vectors
andyrzhao
previously approved these changes
Nov 29, 2026
burkedavison
approved these changes
Dec 1, 2026
- Add transport error type client_cert_alert (server TLS bad_certificate alert) and vector user_client_cert_alert. - Check errors.As on transport errors, and that creds.JSON() is Config.JSON for BuildCredentials and nil for Impersonate. - Validate rejects empty impersonation scopes and a negative lifetime; explicit JSON null counts as absent. - impersonated_json_source_universe_domain: use a different host in service_account_impersonation_url. - New vectors: user_rate_limited_invalid_grant, user_server_error_invalid_grant, service_account_2lo_config_token_url, impersonated_json_delegates_universe_domain.
…dCredentials parseAndImpersonate checked the raw Config.Scopes, while BuildCredentials trims them and drops blank ones before falling back to the JSON's scopes. Clean them the same way, and add vector impersonated_json_blank_config_scopes (Config.Scopes all blank) so a split-path adapter that skips the cleaning fails.
andyrzhao
approved these changes
Dec 1, 2026
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.
Adds golden vectors for oauth2lib: an exported package
oauth2lib/goldenvectorswith test vectors embedded via//go:embed *.json, and a test that runs every vector against oauth2lib. Tests and test data only; no production changes.Why
Go gcloud's tests need to check its oauth2lib adapter against the same cases oauth2lib is tested with. Embedding the files in a Go package lets another module read them with
goldenvectors.All(), with no Blaze runfiles or file paths (runfiles are banned in Go gcloud's tests, and GoB runs plaingo test ./...). The package imports only the standard library.Format
Each file is one vector (documented in
oauth2lib/goldenvectors/README.md):input: aconfigforBuildCredentialsor animpersonationforImpersonate(with its source config).exchanges: every request oneTokencall must send, in order (method, URL, required headers, exact form or JSON body, and for a JWTassertionits header, claims andexp - iat), with the response to give: status plus JSON body, text body, or atransport_error.transport_erroris{"message": "...", "type": "..."}, allowed only on the last exchange.typeis empty for a plain network error, or one ofclient_cert_refused(an error wrappingoauth2lib.ErrAccessDenied, as from a certificate callback or ECP signer),client_timeout(a realhttp.Client.Timeout),server_cert_untrusted(a*tls.CertificateVerificationError) orclient_cert_alert(the server's TLS bad_certificate alert, a*net.OpErrorwith Opremote error).expected: the token (value or self-signed JWT claims, type,expires_in_secondsor exactexpiry, exact metadata) or theRefreshError(kind, code, subtype, description, status, and exactly which sentinels it matches), plus the universe domain.kindis a stable id (unknown,reauth_required,access_denied,invalid_grant,transient), notErrorKind.String().All()rejects unknown fields and data after the vector, and runsVector.Validate()on each file (exactly one input and one outcome, known kinds, sentinels and transport error types, RFC 3339 expiry, and so on), so a consumer gets only well-formed vectors.No private key is checked in:
"private_key": "TEST_PRIVATE_KEY_PEM"is replaced with a key the test generates (Config.JSON(pem)). All tokens are obviously fake strings.Vectors (41)
token_urifrom the JSON vsConfig.TokenURL;expires_inas a string or missing; universe domain; scope not granted; revoked refresh token;invalid_rapt;rapt_required; CAA denial vs plainaccess_denied; 503; network error; noaccess_token; client certificate refused (access denied, not transient);http.Client.Timeout(transient, not a context error); server certificate untrusted (unknown); the server's TLS bad_certificate alert (access denied); 429 and 500 with aninvalid_grantbody (transient: status is checked before the body).invalid_grant; 2LO withConfig.TokenURLoverridingtoken_uri; self-signed JWT (no request); a key file in a non-default universe, with and withoutuse_self_signed_jwt(both self-sign, as go/auth and google-auth do outside googleapis.com).impersonated_service_accountJSON with anauthorized_usersource, with aservice_accountsource (which gets the IAM scope), with a source in a non-default universe (IAM host from the source's universe, not fromservice_account_impersonation_url), with two delegates and a top-leveluniverse_domainthat the source inherits, and with all-blankConfig.Scopes(cleaned away, so the JSON's scopes are used);Impersonatewith a delegate (two hops) and a 600s lifetime; custom IAM endpoint; a source in a non-default universe; IAM 403PERMISSION_DENIED; IAM client certificate refused; a source that needs reauth.TestGoldenVectors(oauth2lib/goldenvectors_test.go) runs each one with a transport that checks every request and answers it without any network. Everyimpersonated_service_accountvector also runs as<name>/parse_and_impersonate, throughParseImpersonatedServiceAccountJSON,SourceConfig,BuildCredentialsandImpersonate, and must give the same requests and result. Each run also checkscreds.JSON()(Config.JSONforBuildCredentials,nilforImpersonate) and, for transport errors, that the cause is still reachable witherrors.As.goldenvectors.TestAllWellFormed,TestValidateandTestDecodecheck the format.Comparison with Python
I sent the same inputs and responses through google3's google-auth 2.62.2 (
google.oauth2.credentials,service_account,impersonated_credentials) and compared the requests for the original 27 vectors. 24 were identical. The other three:impersonated_json_user_sourceandimpersonated_json_sa_source: for a file with"delegates": [](gcloud always writes the field), Python sends"delegates": []and oauth2lib sends"delegates": null. This is intended; the vectors recordnull, and the README lists it under "Known differences from Python".user_scope_not_granted: google-auth only warns, but Python gcloud's own refresh (google_auth_credentials._Refresh) raises the same "Not all requested scopes were granted…" error, which oauth2lib matches.google-auth also retries a 503 twice; oauth2lib doesn't retry by design (the caller does).
Testing
go test -race ./...inoauth2lib/on Go 1.27.3 and 1.26.0,go vet,go mod tidy -diff, the compat script and its unit tests. oauth2lib coverage unchanged at 97.5%.raptfrom the refresh form makes the two RAPT vectors fail; treatingErrAccessDeniedas transient makes the two client-certificate vectors fail; letting aClient.Timeouterror matchcontext.DeadlineExceededmakesuser_client_timeoutfail.596346c): removing the remote-alert case fromclassifyTransportError, checking the body before the status, dropping the JSON's delegates, ignoring the top-leveluniverse_domainfor the source, ignoringConfig.TokenURLfor SA keys, losingTimeout()on client timeouts, flattening the server-cert error, or returning non-nil JSON fromImpersonateeach make the matching new vector or check fail.47e5644:parseAndImpersonatenow cleansConfig.ScopeslikeBuildCredentials.impersonated_json_blank_config_scopesfails on the split path without that cleaning, and onBuildCredentialsifvalidateConfigstops cleaning scopes.