|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +'use strict'; |
| 15 | + |
| 16 | +const {IdentityPoolClient} = require('google-auth-library'); |
| 17 | +const {Gaxios} = require('gaxios'); |
| 18 | +require('dotenv').config(); |
| 19 | + |
| 20 | +// Workload Identity Pool Configuration |
| 21 | +const gcpWorkloadAudience = process.env.GCP_WORKLOAD_AUDIENCE; |
| 22 | +const serviceAccountImpersonationUrl = |
| 23 | + process.env.GCP_SERVICE_ACCOUNT_IMPERSONATION_URL; |
| 24 | +const gcsBucketName = process.env.GCS_BUCKET_NAME; |
| 25 | + |
| 26 | +// Okta Configuration |
| 27 | +const oktaDomain = process.env.OKTA_DOMAIN; // e.g., 'https://dev-12345.okta.com' |
| 28 | +const oktaClientId = process.env.OKTA_CLIENT_ID; // The Client ID of your Okta M2M application |
| 29 | +const oktaClientSecret = process.env.OKTA_CLIENT_SECRET; // The Client Secret of your Okta M2M application |
| 30 | + |
| 31 | +// Constants for the authentication flow |
| 32 | +const TOKEN_URL = 'https://sts.googleapis.com/v1/token'; |
| 33 | +const SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt'; |
| 34 | + |
| 35 | +/** |
| 36 | + * A custom SubjectTokenSupplier that authenticates with Okta using the |
| 37 | + * Client Credentials grant flow. |
| 38 | + * |
| 39 | + * This flow is designed for machine-to-machine (M2M) authentication and |
| 40 | + * exchanges the application'''s client_id and client_secret for an access token. |
| 41 | + */ |
| 42 | +class OktaClientCredentialsSupplier { |
| 43 | + constructor(domain, clientId, clientSecret) { |
| 44 | + this.oktaTokenUrl = `${domain}/oauth2/default/v1/token`; |
| 45 | + this.clientId = clientId; |
| 46 | + this.clientSecret = clientSecret; |
| 47 | + this.accessToken = null; |
| 48 | + this.expiryTime = 0; |
| 49 | + this.gaxios = new Gaxios(); |
| 50 | + console.log('OktaClientCredentialsSupplier initialized.'); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Main method called by the auth library. It will fetch a new token if one |
| 55 | + * is not already cached. |
| 56 | + * @returns {Promise<string>} A promise that resolves with the Okta Access token. |
| 57 | + */ |
| 58 | + async getSubjectToken() { |
| 59 | + // Check if the current token is still valid (with a 60-second buffer). |
| 60 | + const isTokenValid = |
| 61 | + this.accessToken && Date.now() < this.expiryTime - 60 * 1000; |
| 62 | + |
| 63 | + if (isTokenValid) { |
| 64 | + console.log('[Supplier] Returning cached Okta Access token.'); |
| 65 | + return this.accessToken; |
| 66 | + } |
| 67 | + |
| 68 | + console.log( |
| 69 | + '[Supplier] Token is missing or expired. Fetching new Okta Access token via Client Credentials grant...', |
| 70 | + ); |
| 71 | + const {accessToken, expiresIn} = await this.fetchOktaAccessToken(); |
| 72 | + this.accessToken = accessToken; |
| 73 | + // Calculate the absolute expiry time in milliseconds. |
| 74 | + this.expiryTime = Date.now() + expiresIn * 1000; |
| 75 | + return this.accessToken; |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Performs the Client Credentials grant flow by making a POST request to Okta'''s token endpoint. |
| 80 | + * @returns {Promise<{accessToken: string, expiresIn: number}>} A promise that resolves with the Access Token and expiry from Okta. |
| 81 | + */ |
| 82 | + async fetchOktaAccessToken() { |
| 83 | + const params = new URLSearchParams(); |
| 84 | + params.append('grant_type', 'client_credentials'); |
| 85 | + |
| 86 | + // For Client Credentials, scopes are optional and define the permissions |
| 87 | + // the token will have. If you have custom scopes, add them here. |
| 88 | + params.append('scope', 'gcp.test.read'); |
| 89 | + |
| 90 | + // The client_id and client_secret are sent in a Basic Auth header. |
| 91 | + const authHeader = |
| 92 | + 'Basic ' + |
| 93 | + Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64'); |
| 94 | + |
| 95 | + try { |
| 96 | + const response = await this.gaxios.request({ |
| 97 | + url: this.oktaTokenUrl, |
| 98 | + method: 'POST', |
| 99 | + headers: { |
| 100 | + Authorization: authHeader, |
| 101 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 102 | + }, |
| 103 | + data: params.toString(), |
| 104 | + }); |
| 105 | + |
| 106 | + const {access_token, expires_in} = response.data; |
| 107 | + |
| 108 | + if (access_token && expires_in) { |
| 109 | + console.log( |
| 110 | + `[Supplier] Successfully received Access Token from Okta. Expires in ${expires_in} seconds.`, |
| 111 | + ); |
| 112 | + return {accessToken: access_token, expiresIn: expires_in}; |
| 113 | + } else { |
| 114 | + throw new Error( |
| 115 | + 'Access token or expires_in not found in Okta response.', |
| 116 | + ); |
| 117 | + } |
| 118 | + } catch (error) { |
| 119 | + console.error( |
| 120 | + '[Supplier] Error fetching token from Okta:', |
| 121 | + error.response?.data || error.message, |
| 122 | + ); |
| 123 | + throw new Error( |
| 124 | + 'Failed to authenticate with Okta using Client Credentials grant.', |
| 125 | + ); |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +/** |
| 131 | + * Main function to demonstrate the custom supplier. |
| 132 | + */ |
| 133 | +async function main() { |
| 134 | + if ( |
| 135 | + !gcpWorkloadAudience || |
| 136 | + !gcsBucketName || |
| 137 | + !oktaDomain || |
| 138 | + !oktaClientId || |
| 139 | + !oktaClientSecret |
| 140 | + ) { |
| 141 | + throw new Error( |
| 142 | + 'Missing required environment variables. Please check your .env file.', |
| 143 | + ); |
| 144 | + } |
| 145 | + |
| 146 | + // 1. Instantiate our custom supplier with Okta credentials. |
| 147 | + const oktaSupplier = new OktaClientCredentialsSupplier( |
| 148 | + oktaDomain, |
| 149 | + oktaClientId, |
| 150 | + oktaClientSecret, |
| 151 | + ); |
| 152 | + |
| 153 | + // 2. Instantiate an IdentityPoolClient directly with the required configuration. |
| 154 | + // This client is specialized for workload identity federation flows. |
| 155 | + const client = new IdentityPoolClient({ |
| 156 | + audience: gcpWorkloadAudience, |
| 157 | + subject_token_type: SUBJECT_TOKEN_TYPE, |
| 158 | + token_url: TOKEN_URL, |
| 159 | + subject_token_supplier: oktaSupplier, |
| 160 | + service_account_impersonation_url: serviceAccountImpersonationUrl, |
| 161 | + }); |
| 162 | + |
| 163 | + // 3. Construct the URL for the Cloud Storage JSON API to get bucket metadata. |
| 164 | + const bucketUrl = `https://storage.googleapis.com/storage/v1/b/${gcsBucketName}`; |
| 165 | + console.log(`[Test] Getting metadata for bucket: ${gcsBucketName}...`); |
| 166 | + console.log(`[Test] Request URL: ${bucketUrl}`); |
| 167 | + |
| 168 | + // 4. Use the client to make an authenticated request. |
| 169 | + const res = await client.request({url: bucketUrl}); |
| 170 | + |
| 171 | + console.log('--- SUCCESS! ---'); |
| 172 | + console.log('Successfully authenticated and retrieved bucket data:'); |
| 173 | + console.log(JSON.stringify(res.data, null, 2)); |
| 174 | +} |
| 175 | + |
| 176 | +main().catch(error => { |
| 177 | + console.error('--- FAILED ---'); |
| 178 | + const fullError = error.response?.data || error; |
| 179 | + console.error(JSON.stringify(fullError, null, 2)); |
| 180 | + process.exitCode = 1; |
| 181 | +}); |
0 commit comments