Profiles·Public

google-auth-library

semver>=8.0.0 <11.0.0postconditions15functions15last verified2026-04-16

Postconditions — what we check

  • OAuth2Client.getToken · get-token-unprotected
    error
    WhenAsync call to getToken() is not wrapped in a try-catch block. A GaxiosError will be thrown if the authorization code is invalid, expired, already used, or if there is a network failure.
    ThrowsGaxiosError
    Required handlingCaller MUST wrap await client.getToken() in a try-catch block. GaxiosError is thrown on invalid_grant (expired/already used code), invalid_client (bad credentials), network failures, and 5xx errors. Uncaught errors will crash the OAuth callback route and leave the user unable to authenticate.
    costhighin prodimmediate exceptionusers seeauthentication failurevisibilityvisible
    Sources[1][2]
  • OAuth2Client.getTokenInfo · get-token-info-unprotected
    error
    WhenAsync call to getTokenInfo() is not wrapped in a try-catch block. Documentation states this method will throw if the token is invalid. Also throws GaxiosError on network failure.
    ThrowsError
    Required handlingCaller MUST wrap await client.getTokenInfo() in a try-catch block. The documentation explicitly states the method throws if the token is invalid. This is commonly called immediately after getToken() to validate scopes, and missing error handling means an invalid token crashes the auth flow.
    costhighin prodimmediate exceptionusers seeauthentication failurevisibilityvisible
    Sources[1]
  • GoogleAuth.getClient · get-client-unprotected
    warning
    WhenAsync call to auth.getClient() is not wrapped in a try-catch. Throws Error('Could not load the default credentials') when no ADC is available. Common in server-side code that assumes credentials are configured.
    ThrowsError
    Required handlingCaller MUST wrap await auth.getClient() in a try-catch block. Throws with message 'Could not load the default credentials' when GOOGLE_APPLICATION_CREDENTIALS is not set and the server is not running on GCP. Missing error handling causes unhandled exceptions at server startup or request time.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • OAuth2Client.verifyIdToken · verify-id-token-unprotected
    error
    WhenAsync call to client.verifyIdToken() is not wrapped in a try-catch. Throws on: (1) missing/empty idToken — Error('The verifyIdToken method requires an ID Token'); (2) cert fetch failure — GaxiosError on network error fetching Google certs; (3) signature mismatch — Error('Invalid token signature: ...'); (4) token expiry — Error('Token used too late, ...'); (5) audience mismatch — Error('Wrong recipient, payload audience != requiredAudience'); (6) invalid issuer — Error('Invalid issuer, expected one of [...]').
    ThrowsError | GaxiosError
    Required handlingCaller MUST wrap await client.verifyIdToken({ idToken, audience }) in a try-catch block. Common in Google Sign-In routes where the frontend sends an ID token for server-side validation. An uncaught exception means the user cannot log in and the route crashes. Distinguish token validation errors (user-facing: 'Invalid token') from network errors (retry-able).
    costhighin prodimmediate exceptionusers seeauthentication failurevisibilityvisible
    Sources[3]
  • OAuth2Client.refreshAccessToken · refresh-access-token-unprotected
    error
    WhenAsync call to client.refreshAccessToken() is not wrapped in a try-catch. Throws Error('No refresh token is set.') when client.credentials.refresh_token is absent — common when users authenticate with access_type:'online' (default) instead of 'offline'. Also throws GaxiosError when Google's token endpoint returns invalid_grant (refresh token expired/revoked), invalid_client (bad client credentials), or network failure.
    ThrowsError | GaxiosError
    Required handlingCaller MUST wrap await client.refreshAccessToken() in a try-catch block. Handle Error message 'No refresh token is set.' as a configuration error (offline access was not requested). Handle GaxiosError.response.data.error === 'invalid_grant' as a revoked/expired refresh token requiring user to re-authenticate. Unhandled exceptions in token refresh background tasks cause cascading API call failures without alerting.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[3]
  • OAuth2Client.getAccessToken · get-access-token-unprotected
    warning
    WhenAsync call to client.getAccessToken() is not wrapped in a try-catch. Throws Error('No refresh token or refresh handler callback is set.') when neither credentials.refresh_token nor refreshHandler callback is configured. Also throws Error('Could not refresh access token.') when the underlying refresh attempt fails. Commonly called in middleware and API proxy helpers where missing error handling causes every downstream API request to fail.
    ThrowsError | GaxiosError
    Required handlingCaller MUST wrap await client.getAccessToken() in a try-catch block. The Error message 'No refresh token or refresh handler callback is set.' indicates incomplete OAuth configuration — the user must re-authenticate with access_type:'offline'. The error 'Could not refresh access token.' wraps GaxiosError and should be retried or re-authenticated.
    costmediumin prodimmediate exceptionusers seedegraded performancevisibilitysilent
    Sources[3]
  • GoogleAuth.getApplicationDefault · get-application-default-unprotected
    warning
    WhenAsync call to auth.getApplicationDefault() is not wrapped in a try-catch. Throws Error with message 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.' when (1) GOOGLE_APPLICATION_CREDENTIALS env var is not set, (2) no well-known credentials file exists (~/.config/gcloud/), and (3) the server is not running on GCP. Also throws RangeError when API keys and credentials are combined (mutually exclusive).
    ThrowsError | RangeError
    Required handlingCaller MUST wrap await auth.getApplicationDefault() in a try-catch block. Distinguish Error('Could not load the default credentials') — configuration error requiring GOOGLE_APPLICATION_CREDENTIALS — from network errors during GCE metadata server checks. Commonly uncaught in server initialization code, causing crash-on-startup rather than a startup-time warning.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • GoogleAuth.getIdTokenClient · get-id-token-client-unprotected
    warning
    WhenAsync call to auth.getIdTokenClient(targetAudience) is not wrapped in a try-catch. Throws Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.') when the current credentials are user credentials (OAuth2) rather than service account or Compute Engine credentials. Common pattern: code works in production on GCP but crashes locally where developers use user credentials from gcloud auth login.
    ThrowsError
    Required handlingCaller MUST wrap await auth.getIdTokenClient(audience) in a try-catch. Error message 'Cannot fetch ID token in this environment' indicates the credential type is wrong — check that GOOGLE_APPLICATION_CREDENTIALS points to a service account key file or that the runtime is GCP Compute Engine. This error commonly surfaces in CI environments where gcloud user credentials are active but the app expects service account credentials.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • GoogleAuth.getProjectId · get-project-id-unprotected
    warning
    WhenAsync call to auth.getProjectId() is not wrapped in a try-catch. Throws Error with message 'Unable to detect a Project Id in the current environment. To fix this, include the project ID when creating the GoogleAuth constructor or set the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variables.' when project ID cannot be found from any source. Common in local development, Docker containers, and CI environments where GCLOUD_PROJECT env var is not set.
    ThrowsError
    Required handlingCaller MUST wrap await auth.getProjectId() in a try-catch block. Set GOOGLE_CLOUD_PROJECT environment variable or pass projectId to GoogleAuth constructor. The error message includes a URL to documentation. Missing handling causes unhandled exceptions in initialization flows that assume GCP context is available.
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • GoogleAuth.sign · sign-unprotected
    warning
    WhenAsync call to auth.sign(data) is not wrapped in a try-catch. Throws Error('Cannot sign data without `client_email`.') when the current credentials are user credentials (OAuth2) or missing client_email — common when using Application Default Credentials in environments where gcloud auth login (user credentials) is active instead of a service account key file. Also throws GaxiosError when the IAM signBlob API call fails (on GCE).
    ThrowsError | GaxiosError
    Required handlingCaller MUST wrap await auth.sign(data) in a try-catch block. Error('Cannot sign data without client_email') requires using service account credentials rather than user credentials. For GCE environments, ensure the service account has roles/iam.serviceAccountTokenCreator permission to use signBlob API. Unhandled errors in signed URL generation break file uploads and download flows silently.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • JWT.authorize · jwt-authorize-unprotected
    error
    WhenAsync call to jwtClient.authorize() is not wrapped in a try-catch. Throws GaxiosError when Google's token endpoint (https://oauth2.googleapis.com/token) returns an error — e.g. invalid_grant (wrong service account email), unauthorized_client (service account not authorized for domain-wide delegation), or access_denied (API not enabled in project). Error message is reformatted to include 'error: error_description' from the response body. Also throws Error('A key or a keyFile must be provided') from JWT.getCredentials() if key material is missing.
    ThrowsGaxiosError | Error
    Required handlingCaller MUST wrap await jwtClient.authorize() in a try-catch block. Parse error.message for token endpoint error codes — 'invalid_grant' indicates service account does not exist, 'unauthorized_client' indicates missing IAM permission, 'access_denied' indicates the API is not enabled. Unhandled errors in service account initialization silently fail all downstream Google API calls.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[4]
  • JWT.fetchIdToken · jwt-fetch-id-token-unprotected
    error
    WhenAsync call to jwtClient.fetchIdToken(targetAudience) is not wrapped in a try-catch block. Throws GaxiosError when Google's token endpoint (https://oauth2.googleapis.com/token) rejects the JWT assertion — e.g., invalid_grant (service account does not exist or key is revoked), access_denied (API not enabled in project), or network failure. Error message is reformatted to include 'error: error_description' from the OAuth response. Also throws Error('Unknown error: Failed to fetch ID token') when the token endpoint responds but does not return an idToken field.
    ThrowsGaxiosError | Error
    Required handlingCaller MUST wrap await jwtClient.fetchIdToken(audience) in a try-catch block. This is commonly used in service-to-service authentication middleware where unhandled token fetch failures silently break all downstream calls to Cloud Run or Cloud Functions. Parse error.message for OAuth error codes — 'invalid_grant' indicates the service account key is invalid or revoked, 'access_denied' indicates a missing IAM permission. Retry GaxiosError network failures; treat invalid_grant as a credential configuration error requiring key rotation.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[4][5]
  • GoogleAuth.fromStream · from-stream-unprotected
    error
    WhenAsync call to auth.fromStream(inputStream) is not wrapped in a try-catch block. Throws Error('Must pass in a stream containing the Google auth settings.') when null or undefined is passed as the stream argument. Also propagates any stream read errors (e.g., network stream dropped mid-read) via the .on('error') handler. JSON.parse() failures propagate as SyntaxError if keyFilename fallback is absent. Commonly used in initialization code that loads credentials from Google Secret Manager or AWS Secrets Manager, where stream errors are often silently swallowed.
    ThrowsError | SyntaxError
    Required handlingCaller MUST wrap await auth.fromStream(stream) in a try-catch block. Validate that the stream argument is non-null before calling. Handle SyntaxError for invalid JSON credentials (common when secrets are rotated to an unexpected format). Handle stream read errors separately — these are often transient network errors that warrant retry. Unhandled errors in credential loading cause all downstream Google API calls to fail with 'No credentials found'.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[2]
  • GoogleAuth.getCredentials · get-credentials-unprotected
    warning
    WhenAsync call to auth.getCredentials() is not wrapped in a try-catch block. Throws Error('Unable to find credentials in current environment. To learn more about authentication and Google APIs, visit: https://cloud.google.com/docs/authentication/getting-started') when (1) no JSON credentials are loaded, (2) not running on GCE, and (3) no external account client is configured. Also propagates GaxiosError from the GCE metadata server call if running in a restricted environment where metadata server access is blocked.
    ThrowsError | GaxiosError
    Required handlingCaller MUST wrap await auth.getCredentials() in a try-catch block. Error('Unable to find credentials in current environment') indicates the auth client has no credentials loaded — ensure GOOGLE_APPLICATION_CREDENTIALS is set or credentials were loaded via fromStream()/fromJSON(). The GaxiosError from metadata server access is typically a network error in locked-down environments. Commonly used in logging/monitoring code where missing credentials is silently ignored, causing NullPointerError-style failures downstream.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[2]
  • Impersonated.fetchIdToken · impersonated-fetch-id-token-unprotected
    error
    WhenAsync call to impersonatedClient.fetchIdToken(targetAudience) is not wrapped in a try-catch block. Makes two network calls: (1) sourceClient.getAccessToken() which throws GaxiosError on source credential failure; (2) IAM Credentials API POST to generateIdToken which throws GaxiosError with reformatted message 'PERMISSION_DENIED: unable to impersonate: ...' when the source SA lacks roles/iam.serviceAccountTokenCreator on the target SA, 'NOT_FOUND: unable to impersonate: ...' when targetPrincipal does not exist, or 'INVALID_ARGUMENT' for malformed audience URLs.
    ThrowsGaxiosError
    Required handlingCaller MUST wrap await impersonatedClient.fetchIdToken(audience) in a try-catch block. Check error.message for IAM status prefix ('PERMISSION_DENIED', 'NOT_FOUND', 'INVALID_ARGUMENT') to distinguish misconfigured IAM roles from nonexistent service accounts. PERMISSION_DENIED requires granting roles/iam.serviceAccountTokenCreator on the target service account. This is commonly used in cross-service auth middleware where a single uncaught error blocks all requests to impersonated services.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitysilent
    Sources[6][7]

Sources

Every postcondition cites at least one of these. Numbered to match the footnotes above.

  1. [1]raw.githubusercontent.com/googleapis/google-auth-library-nodejshttps://raw.githubusercontent.com/googleapis/google-auth-library-nodejs/main/README.md
  2. [2]googleapis.dev/nodejs/google-auth-libraryhttps://googleapis.dev/nodejs/google-auth-library/latest/classes/GoogleAuth.html
  3. [3]googleapis.dev/nodejs/google-auth-libraryhttps://googleapis.dev/nodejs/google-auth-library/latest/classes/OAuth2Client.html
  4. [4]googleapis.dev/nodejs/google-auth-libraryhttps://googleapis.dev/nodejs/google-auth-library/latest/classes/JWT.html
  5. [5]github.com/googleapis/google-auth-library-nodejshttps://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js
  6. [6]googleapis.dev/nodejs/google-auth-libraryhttps://googleapis.dev/nodejs/google-auth-library/latest/classes/Impersonated.html
  7. [7]cloud.google.com/iam/docshttps://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken
Need a different package?
Request a profile