-
Notifications
You must be signed in to change notification settings - Fork 21
feat: Agentic Identities in Cloudrun #854
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
vverman
wants to merge
5
commits into
googleapis:agentic-identities-cloudrun
Choose a base branch
from
vverman:agentic-identities-cloudrun
base: agentic-identities-cloudrun
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
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1e4e6ad
feat: Agentic Identities for CloudRun.
vverman a02e261
Changed the polling logic to make it deterministic for cert config an…
vverman 73a1443
Lint fixes.
vverman 317fe9e
Added logging for agentic identities.
vverman 4680434
Using setTimeout from node:timers/promises directly.
vverman 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
202 changes: 202 additions & 0 deletions
202
packages/google-auth-library-nodejs/src/auth/agentidentity.ts
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 |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import * as crypto from 'crypto'; | ||
| import * as fs from 'fs'; | ||
| import {setTimeout as sleep} from 'node:timers/promises'; | ||
| import {log as makeLog} from 'google-logging-utils'; | ||
|
|
||
| const log = makeLog('google-auth-library:agentidentity'); | ||
|
|
||
| const CERT_CONFIG_ENV_VAR = 'GOOGLE_API_CERTIFICATE_CONFIG'; | ||
| const PREVENT_SHARING_ENV_VAR = | ||
| 'GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES'; | ||
|
|
||
| const AGENT_IDENTITY_SPIFFE_PATTERNS = [ | ||
| /^agents\.global\.org-\d+\.system\.id\.goog$/, | ||
| /^agents\.global\.proj-\d+\.system\.id\.goog$/, | ||
| ]; | ||
|
|
||
| // Polling configuration | ||
| // Total timeout: 30 seconds | ||
| const TOTAL_TIMEOUT_MS = 30000; | ||
| // Phase 1: 5 seconds of fast polling (every 0.1s) = 50 cycles | ||
| const FAST_POLL_CYCLES = 50; | ||
| const FAST_POLL_INTERVAL_MS = 100; | ||
| // Phase 2: 25 seconds of slow polling (every 0.5s) = 50 cycles | ||
| const SLOW_POLL_INTERVAL_MS = 500; | ||
|
|
||
| // Precalculates the polling intervals. | ||
| const POLLING_INTERVALS: number[] = (() => { | ||
| const fast = Array(FAST_POLL_CYCLES).fill(FAST_POLL_INTERVAL_MS); | ||
|
|
||
| const remainingTime = | ||
| TOTAL_TIMEOUT_MS - FAST_POLL_CYCLES * FAST_POLL_INTERVAL_MS; | ||
| const slowCycles = Math.floor(remainingTime / SLOW_POLL_INTERVAL_MS); | ||
| const slow = Array(slowCycles).fill(SLOW_POLL_INTERVAL_MS); | ||
|
|
||
| return fast.concat(slow); | ||
| })(); | ||
|
|
||
| /** | ||
| * Interface for the certificate configuration file. | ||
| * Matches the structure expected by CertificateSubjectTokenSupplier but strictly for Workload. | ||
| */ | ||
| interface CertificateConfigFile { | ||
| cert_configs: { | ||
| workload?: { | ||
| cert_path: string; | ||
| }; | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Retrieves the path to the agent identity certificate by polling the configuration file. | ||
| * @returns The path to the certificate file, or null if not configured. | ||
| * @throws Error if the configuration or certificate file cannot be found after the timeout. | ||
| */ | ||
| async function getAgentIdentityCertificatePath(): Promise<string | null> { | ||
| const certConfigPath = process.env[CERT_CONFIG_ENV_VAR]; | ||
| if (!certConfigPath) { | ||
| return null; | ||
| } | ||
|
|
||
vverman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| log.debug( | ||
| `Agent identity certificate configuration detected: ${CERT_CONFIG_ENV_VAR}=${certConfigPath}`, | ||
| ); | ||
|
|
||
| let hasLoggedWarning = false; | ||
| for (const interval of POLLING_INTERVALS) { | ||
| try { | ||
| if (fs.existsSync(certConfigPath)) { | ||
| // If cert-config file exists, extract cert path from contents. | ||
| const configContent = await fs.promises.readFile( | ||
| certConfigPath, | ||
| 'utf-8', | ||
| ); | ||
| const config = JSON.parse(configContent) as CertificateConfigFile; | ||
| const certPath = config.cert_configs?.workload?.cert_path; | ||
|
|
||
| if (certPath && fs.existsSync(certPath)) { | ||
| return certPath; | ||
| } | ||
| } | ||
| } catch (error) { | ||
| // Ignore errors during polling, will retry. | ||
vverman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| log.debug( | ||
| `Error during polling for agent identity certificate: ${error}`, | ||
| ); | ||
| } | ||
|
|
||
| if (!hasLoggedWarning) { | ||
| // Log warning once about polling cycle. | ||
| log.warn( | ||
| `Certificate config file not found at ${certConfigPath} (from ${CERT_CONFIG_ENV_VAR} environment variable). ` + | ||
| 'Retrying for up to 30 seconds.', | ||
| ); | ||
| hasLoggedWarning = true; | ||
| } | ||
|
|
||
| await sleep(interval); | ||
| } | ||
|
|
||
| const errorMessage = | ||
| 'Certificate config or certificate file not found after multiple retries. ' + | ||
| 'Token binding protection is failing. You can turn off this protection by setting ' + | ||
| `${PREVENT_SHARING_ENV_VAR} to false to fall back to unbound tokens.`; | ||
| log.error(errorMessage); | ||
| throw new Error(errorMessage); | ||
| } | ||
|
|
||
| /** | ||
| * Parses a PEM-encoded certificate. | ||
| * @param certBuffer The certificate data. | ||
| * @returns The parsed X509Certificate object. | ||
| */ | ||
| function parseCertificate(certBuffer: Buffer): crypto.X509Certificate { | ||
| return new crypto.X509Certificate(certBuffer); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the certificate is an Agent Identity certificate by inspecting the SPIFFE ID in the SAN. | ||
| * @param cert The parsed certificate. | ||
| * @returns True if it matches an Agent Identity pattern. | ||
| */ | ||
| function isAgentIdentityCertificate(cert: crypto.X509Certificate): boolean { | ||
| const san = cert.subjectAltName; | ||
| if (!san) { | ||
| return false; | ||
| } | ||
|
|
||
| // Node's X509Certificate.subjectAltName returns a string like "URI:spiffe://..., DNS:..." | ||
| // We use a regex to find all SPIFFE URIs and check their trust domains. | ||
| const uriMatches = san.matchAll(/URI:spiffe:\/\/([^/]+)\/.*?(?:,|$)/g); | ||
| for (const match of uriMatches) { | ||
| const trustDomain = match[1]; | ||
| for (const pattern of AGENT_IDENTITY_SPIFFE_PATTERNS) { | ||
| if (pattern.test(trustDomain)) { | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * Calculates the unpadded base64url-encoded SHA256 fingerprint of the certificate. | ||
| * @param cert The parsed certificate. | ||
| * @returns The fingerprint string. | ||
| */ | ||
| function calculateCertificateFingerprint(cert: crypto.X509Certificate): string { | ||
| return crypto.createHash('sha256').update(cert.raw).digest('base64url'); | ||
| } | ||
|
|
||
| /** | ||
| * Main entry point to get the bind certificate fingerprint if appropriate. | ||
| * Checks opt-out env var, polls for cert, validates it's an Agent Identity cert, and returns the fingerprint. | ||
| * @returns The fingerprint if a bound token should be requested, otherwise undefined. | ||
| */ | ||
| export async function getBindCertificateFingerprint(): Promise< | ||
| string | undefined | ||
| > { | ||
| // Check opt-out. | ||
| if (process.env[PREVENT_SHARING_ENV_VAR]?.toLowerCase() === 'false') { | ||
| log.debug( | ||
| `Agent identity token sharing prevention is disabled via ${PREVENT_SHARING_ENV_VAR} environment variable.`, | ||
| ); | ||
| return undefined; | ||
vverman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // Get certificate path (polling if necessary). | ||
| const certPath = await getAgentIdentityCertificatePath(); | ||
| if (!certPath) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // Read and parse certificate | ||
| // We use fs.promises.readFile here. The existence was checked in polling, | ||
| // but it might have disappeared or be unreadable. | ||
| // We let standard IO errors propagate if it fails now after polling succeeded. | ||
| const certBuffer = await fs.promises.readFile(certPath); | ||
| const cert = parseCertificate(certBuffer); | ||
|
|
||
| // Check if it's an Agent Identity certificate | ||
| if (!isAgentIdentityCertificate(cert)) { | ||
| return undefined; | ||
| } | ||
|
|
||
| // Calculate and return fingerprint | ||
| return calculateCertificateFingerprint(cert); | ||
| } | ||
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
20 changes: 20 additions & 0 deletions
20
packages/google-auth-library-nodejs/test/fixtures/external-account-cert/agentic_cert.pem
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 |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| -----BEGIN CERTIFICATE----- | ||
vverman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| MIIDPjCCAiagAwIBAgIUCYeV4dwM29T5yucwWrSWlOC9wwYwDQYJKoZIhvcNAQEL | ||
| BQAwIjEgMB4GA1UEAwwXVGVzdCBTUElGRkUgQ2VydGlmaWNhdGUwHhcNMjUxMTA3 | ||
| MDEyMjQ4WhcNMzUxMTA1MDEyMjQ4WjAiMSAwHgYDVQQDDBdUZXN0IFNQSUZGRSBD | ||
| ZXJ0aWZpY2F0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANDr1Bzo | ||
| KtzIZB35acQ+mpk6yScf59AnwHjjgNCMbC7kq2DSUfQzTlu9Kd0uUB6O7DmJ73D8 | ||
| Pge4XLE/Q1B6dI6DzJx7lhPoC1BiQFUGJ4Cu+TbbdlK3RiXNAZYjIj9UKP7DejCY | ||
| WRgFB+PYyLczEkByvU9cy7Z9Uuufsn6LnYu7qOG+DcRSE41ThurZxQ14OWvLfjZm | ||
| lhZXam4VBBli8Qku8qFIALe78kpy+hp2YCRnK84amATwPpGprRACp9WVka2JDYKD | ||
| LY0OoYlyAQel6960aS11N3/2v0cvx03/LM5+Yj+DTvdyb2Mk/NVeRIKo8cM5YwPn | ||
| sTLCf1cdxJvseRMCAwEAAaNsMGowSQYDVR0RBEIwQIY+c3BpZmZlOi8vYWdlbnRz | ||
| Lmdsb2JhbC5wcm9qLTEyMzQ1LnN5c3RlbS5pZC5nb29nL3Rlc3Qtd29ya2xvYWQw | ||
| HQYDVR0OBBYEFPvn+KXBcrYCmAMopkghUczUx/IkMA0GCSqGSIb3DQEBCwUAA4IB | ||
| AQCbwd9RMFkr1C9AEgnLMWd1l9ciBbK0t1Sydu3eA0SNm2w6E58ih8O+huo6eGsM | ||
| 7z0E4i7YuaHnTdah/lPMqd75YRO57GSRbvi2g+yPyw6XdFl9HCHwF4WARdTF4Nkf | ||
| 1c1WstvBXb24PSSQQdy9un72ZG6f9fSVQrko6hchv8Rg6yyBTFE8APPkeMR/EJtV | ||
| cnXg4CgsQIPHxJGQrhNvQhF7VLZePlTass4bqTqTYXwAte2jX/KW3qlW/t/v4AJe | ||
| /q+pcXmNIvwRpT8zYA5tJHIDVJ+v9pWZA+nhoD9Qtr7FVHfB4mdNuFv7bMPoXN0+ | ||
| mCPzP08MnjgbX7zRETVlblrx | ||
| -----END CERTIFICATE----- | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.