-
Notifications
You must be signed in to change notification settings - Fork 302
Add selective retries for STS token exchange #532
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
blalor
wants to merge
1
commit into
google-github-actions:main
Choose a base branch
from
blalor:sts-token-exchange-retries
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,6 +16,72 @@ import { errorMessage, writeSecureFile } from '@google-github-actions/actions-ut | |
|
|
||
| import { AuthClient, Client, ClientParameters } from './client'; | ||
|
|
||
| const STS_MAX_ATTEMPTS = 4; | ||
| const STS_RETRY_BACKOFF_MILLISECONDS = 100; | ||
| const RETRYABLE_STS_STATUS_CODES = new Set([408, 429, 500, 502, 503, 504]); | ||
| const RETRYABLE_CONNECTION_ERROR_CODES = new Set(['EAI_AGAIN', 'ECONNRESET', 'ETIMEDOUT']); | ||
|
|
||
| interface STSFailure { | ||
| readonly status?: number; | ||
| readonly errorClass: string; | ||
| readonly retryable: boolean; | ||
| } | ||
|
|
||
| function errorCode(err: unknown): string | undefined { | ||
| if (!err || typeof err !== 'object') { | ||
| return undefined; | ||
| } | ||
|
|
||
| const candidate = err as { code?: unknown; cause?: { code?: unknown } }; | ||
| if (typeof candidate.code === 'string') { | ||
| return candidate.code; | ||
| } | ||
| if (typeof candidate.cause?.code === 'string') { | ||
| return candidate.cause.code; | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| function classifySTSFailure(err: unknown): STSFailure { | ||
| if (err && typeof err === 'object') { | ||
| const status = (err as { statusCode?: unknown }).statusCode; | ||
| if (typeof status === 'number') { | ||
| return { | ||
| status, | ||
| errorClass: RETRYABLE_STS_STATUS_CODES.has(status) | ||
| ? 'transient_http_response' | ||
| : 'non_retryable_http_response', | ||
| retryable: RETRYABLE_STS_STATUS_CODES.has(status), | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| const code = errorCode(err); | ||
| if (code && RETRYABLE_CONNECTION_ERROR_CODES.has(code)) { | ||
| return { | ||
| errorClass: code, | ||
| retryable: true, | ||
| }; | ||
| } | ||
|
|
||
| // @actions/http-client emits an uncoded error when its socket timeout fires. | ||
| if (err instanceof Error && err.message.startsWith('Request timeout:')) { | ||
| return { | ||
| errorClass: 'request_timeout', | ||
| retryable: true, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| errorClass: 'non_retryable_error', | ||
| retryable: false, | ||
| }; | ||
| } | ||
|
|
||
| function sleep(milliseconds: number): Promise<void> { | ||
| return new Promise((resolve) => setTimeout(resolve, milliseconds)); | ||
| } | ||
|
|
||
| /** | ||
| * WorkloadIdentityFederationClientParameters is used as input to the | ||
| * WorkloadIdentityFederationClient. | ||
|
|
@@ -58,7 +124,6 @@ export class WorkloadIdentityFederationClient extends Client implements AuthClie | |
|
|
||
| const iamHost = new URL(this._endpoints.iam).host; | ||
| this.#audience = `//${iamHost}/${this.#workloadIdentityProviderName}`; | ||
| this._logger.debug(`Computed audience`, this.#audience); | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -93,34 +158,47 @@ export class WorkloadIdentityFederationClient extends Client implements AuthClie | |
| subjectToken: this.#githubOIDCToken, | ||
| }; | ||
|
|
||
| logger.debug(`Built request`, { | ||
| method: `POST`, | ||
| path: pth, | ||
| headers: headers, | ||
| body: body, | ||
| }); | ||
|
|
||
| try { | ||
| const resp = await this._httpClient.postJson<{ access_token: string }>(pth, body, headers); | ||
| const statusCode = resp.statusCode || 500; | ||
| if (statusCode < 200 || statusCode > 299) { | ||
| throw new Error(`Failed to call ${pth}: HTTP ${statusCode}: ${resp.result || '[no body]'}`); | ||
| } | ||
|
|
||
| const result = resp.result; | ||
| if (!result) { | ||
| throw new Error(`Successfully called ${pth}, but the result was empty`); | ||
| const endpoint = new URL(pth).hostname; | ||
| for (let attempt = 1; attempt <= STS_MAX_ATTEMPTS; attempt++) { | ||
| try { | ||
| const resp = await this._httpClient.postJson<{ access_token: string }>(pth, body, headers); | ||
| const statusCode = resp.statusCode || 500; | ||
| if (statusCode < 200 || statusCode > 299) { | ||
| const err = new Error(`STS token exchange returned HTTP ${statusCode}`); | ||
| Object.assign(err, { statusCode }); | ||
| throw err; | ||
| } | ||
|
|
||
| const result = resp.result; | ||
| if (!result) { | ||
| throw new Error(`STS token exchange returned an empty result`); | ||
| } | ||
|
|
||
| this.#cachedToken = result.access_token; | ||
| this.#cachedAt = now; | ||
| return result.access_token; | ||
| } catch (err) { | ||
| const failure = classifySTSFailure(err); | ||
| const status = failure.status ?? 'none'; | ||
| logger.warning( | ||
| `STS request failed: operation=token_exchange, endpoint_class=${endpoint}, ` + | ||
| `status=${status}, error_class=${failure.errorClass}, ` + | ||
| `attempt=${attempt}/${STS_MAX_ATTEMPTS}`, | ||
| ); | ||
|
|
||
| if (!failure.retryable || attempt === STS_MAX_ATTEMPTS) { | ||
| throw new Error( | ||
| `Failed to generate Google Cloud federated token: operation=token_exchange, ` + | ||
| `endpoint_class=${endpoint}, status=${status}, ` + | ||
| `error_class=${failure.errorClass}, attempt=${attempt}/${STS_MAX_ATTEMPTS}`, | ||
|
Comment on lines
+191
to
+193
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hiding the entire Including |
||
| ); | ||
| } | ||
|
|
||
| await sleep(STS_RETRY_BACKOFF_MILLISECONDS * 2 ** (attempt - 1)); | ||
| } | ||
|
|
||
| this.#cachedToken = result.access_token; | ||
| this.#cachedAt = now; | ||
| return result.access_token; | ||
| } catch (err) { | ||
| const msg = errorMessage(err); | ||
| throw new Error( | ||
| `Failed to generate Google Cloud federated token for ${this.#audience}: ${msg}`, | ||
| ); | ||
| } | ||
|
|
||
| throw new Error(`STS token exchange failed unexpectedly`); | ||
| } | ||
|
|
||
| /** | ||
|
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A delay of <1 second across all 4 attempts might be too short to see the backend to recover.
Please, consider bumping the base backoff up. For example, using a 500ms base will provide delays of 500ms, 1s, 2s, which buys a more resilient 3.5 seconds for the backend to recover.