All files / third-parties/auth-yandex-cloud/src service-account.ts

91.96% Statements 103/112
80.3% Branches 53/66
95% Functions 19/20
92.72% Lines 102/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437                  2x   2x                     7x 7x     7x 7x 7x             75x 75x                                                                 21x 21x 21x       21x                 21x   21x 1x             20x             20x 20x 1x     20x                                   5x 5x     5x 5x   1x           4x 4x   2x         2x                         2x 2x 1x         1x                             23x   23x   4x 3x     4x     19x       19x 1x 1x           19x   19x 19x     19x                   3x       3x 3x         1x 1x       3x 3x       3x               22x 22x   22x 17x         17x 17x       17x         5x       5x                   13x         13x       13x 10x     10x 4x       6x 2x       4x 4x         3x       2x       1x                 26x         26x   26x           26x             26x 26x 26x                 26x           26x   26x                         22x 9x       4x   4x     2x                 22x 26x   26x             24x 7x 7x             17x         17x       17x       17x              
import * as fs from 'node:fs'
import * as path from 'node:path'
import { constants, createPrivateKey, sign } from 'node:crypto'
import { channel as dc, tracingChannel } from 'node:diagnostics_channel'
import { CredentialsProvider } from '@ydbjs/auth'
import { loggers } from '@ydbjs/debug'
import { type RetryConfig, retry } from '@ydbjs/retry'
import { type RetryStrategy, exponential, fixed } from '@ydbjs/retry/strategy'
 
let dbg = loggers.auth.extend('yc-sa')
 
let authTokenFetchCh = tracingChannel<
	{ provider: 'yc-service-account' },
	{ provider: 'yc-service-account' }
>('tracing:ydb:auth.token.fetch')
 
/**
 * HTTP error with status code for IAM API requests.
 */
class IamApiError extends Error {
	constructor(
		message: string,
		public readonly status: number,
		public readonly statusText: string,
		cause?: unknown
	) {
		super(message)
		this.name = 'IamApiError'
		this.cause = cause
	}
}
 
// Base64URL encode helper (JWT uses Base64URL, not regular Base64)
// Node.js 18+ supports base64url directly
function base64UrlEncode(data: string | Buffer): string {
	let buffer = typeof data === 'string' ? Buffer.from(data, 'utf8') : data
	return buffer.toString('base64url')
}
 
export type ServiceAccountKey = {
	id: string
	service_account_id: string
	private_key: string
	created_at?: string
	key_algorithm?: string
	public_key?: string
}
 
export type IamToken = {
	value: string
	expires_at: number // timestamp in ms
}
 
export type ServiceAccountCredentialsOptions = {
	iamEndpoint?: string
}
 
/**
 * A credentials provider that authenticates using Yandex Cloud Service Account authorized key.
 *
 * This provider reads a Service Account authorized key JSON file, creates a JWT signed with PS256,
 * exchanges it for an IAM token via Yandex Cloud IAM API, and uses that token for YDB authentication.
 *
 * Tokens are automatically cached and refreshed before expiration.
 *
 * @extends CredentialsProvider
 */
export class ServiceAccountCredentialsProvider extends CredentialsProvider {
	#key: ServiceAccountKey
	#token: IamToken | null = null
	#promise: Promise<string> | null = null
	#iamEndpoint: string = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'
 
	// Fire `token.expired` at most once per incident; reset on every successful
	// refresh. Mirrors the per-incident semantics of @ydbjs/auth providers.
	#expiredReported = false
 
	/**
	 * Creates an instance of ServiceAccountCredentialsProvider.
	 *
	 * @param key - Service Account authorized key JSON object
	 * @param options - Optional configuration (IAM endpoint override)
	 */
	constructor(key: ServiceAccountKey, options?: ServiceAccountCredentialsOptions) {
		super()
 
		if (!key.id || !key.service_account_id || !key.private_key) {
			throw new Error(
				'Invalid Service Account key: missing required fields (id, service_account_id, private_key)'
			)
		}
 
		// Yandex Cloud authorized keys may contain a warning line before the PEM key
		// Remove it if present to get clean PEM format
		Iif (key.private_key.includes('PLEASE DO NOT REMOVE')) {
			key.private_key = key.private_key.replace(
				/^.*?-----BEGIN PRIVATE KEY-----/s,
				'-----BEGIN PRIVATE KEY-----'
			)
		}
 
		this.#key = key
		if (options?.iamEndpoint) {
			this.#iamEndpoint = options.iamEndpoint
		}
 
		dbg.log(
			'creating service account credentials provider for SA: %s (key ID: %s)',
			key.service_account_id,
			key.id
		)
	}
 
	/**
	 * Creates a provider instance from a JSON file path.
	 *
	 * @param filePath - Path to the authorized key JSON file
	 * @param options - Optional configuration
	 * @returns ServiceAccountCredentialsProvider instance
	 */
	static fromFile(
		filePath: string,
		options?: ServiceAccountCredentialsOptions
	): ServiceAccountCredentialsProvider {
		let resolvedPath = path.resolve(filePath)
		dbg.log('reading service account key from file: %s', resolvedPath)
 
		let content: string
		try {
			content = fs.readFileSync(resolvedPath, 'utf8')
		} catch (error) {
			throw new Error(`Failed to read Service Account key file: ${filePath}`, {
				cause: error,
			})
		}
 
		let key: ServiceAccountKey
		try {
			key = JSON.parse(content)
		} catch (error) {
			throw new Error(`Failed to parse Service Account key JSON`, {
				cause: error,
			})
		}
 
		return new ServiceAccountCredentialsProvider(key, options)
	}
 
	/**
	 * Creates a provider instance from environment variable.
	 *
	 * Reads path from YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS environment variable.
	 *
	 * @param options - Optional configuration
	 * @returns ServiceAccountCredentialsProvider instance
	 * @throws Error if environment variable is not set
	 */
	static fromEnv(options?: ServiceAccountCredentialsOptions): ServiceAccountCredentialsProvider {
		let filePath = process.env.YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS
		if (!filePath) {
			throw new Error(
				'YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS environment variable is not set'
			)
		}
 
		return ServiceAccountCredentialsProvider.fromFile(filePath, options)
	}
 
	/**
	 * Retrieves an IAM token for authentication.
	 *
	 * Always returns a valid token immediately if available.
	 * If token is expiring soon (< 5 minutes), returns it immediately and refreshes in background.
	 * Only blocks when token is expired or force=true.
	 *
	 * @param force - If true, forces fetching a new token regardless of cache
	 * @param signal - AbortSignal to cancel the operation
	 * @returns Promise resolving to IAM token string
	 */
	async getToken(force?: boolean, signal?: AbortSignal): Promise<string> {
		let now = Date.now()
 
		if (!force && this.#token && this.#token.expires_at > now) {
			// Refresh in background when token expires in < 5 minutes to avoid blocking on expiration
			if (this.#token.expires_at <= now + 5 * 60 * 1000) {
				this.#refreshTokenInBackground(signal)
			}
 
			return this.#token.value
		}
 
		Iif (this.#promise) {
			return this.#promise
		}
 
		if (this.#token && this.#token.expires_at <= now && !this.#expiredReported) {
			this.#expiredReported = true
			dc('ydb:auth.token.expired').publish({
				provider: 'yc-service-account',
				stalenessMs: now - this.#token.expires_at,
			})
		}
 
		dbg.log('fetching new IAM token (token expired or force=true, key ID: %s)', this.#key.id)
 
		this.#promise = this.#refreshOnce(signal).finally(() => {
			this.#promise = null
		})
 
		return this.#promise
	}
 
	/**
	 * Refresh the token in the background without blocking the caller.
	 * Reuses the same refresh path as `getToken(force)` so blocking and
	 * opportunistic refreshes behave identically from the caller's point
	 * of view.
	 */
	#refreshTokenInBackground(signal?: AbortSignal): void {
		Iif (this.#promise) {
			return
		}
 
		let refreshPromise: Promise<string> | null = null
		refreshPromise = this.#refreshOnce(signal)
			.catch((error) => {
				// Don't throw — failed background refresh will retry on next
				// getToken call. Return the existing token to avoid breaking
				// ongoing requests; if there's nothing cached, propagate.
				dbg.log('background IAM token refresh failed: %O (key ID: %s)', error, this.#key.id)
				Eif (this.#token) return this.#token.value
				throw error
			})
			.finally(() => {
				Eif (this.#promise === refreshPromise) {
					this.#promise = null
				}
			})
 
		this.#promise = refreshPromise
	}
 
	/**
	 * Performs one IAM-token exchange against Yandex Cloud and updates the
	 * cached token. Used by both blocking and background refresh.
	 */
	async #refreshOnce(signal?: AbortSignal): Promise<string> {
		try {
			return await authTokenFetchCh.tracePromise(
				async (): Promise<string> => {
					this.#token = await this.#fetchIamToken(signal)
					dbg.log(
						'IAM token fetched successfully, expires at %s (key ID: %s)',
						new Date(this.#token.expires_at).toISOString(),
						this.#key.id
					)
					this.#expiredReported = false
					dc('ydb:auth.token.refreshed').publish({
						provider: 'yc-service-account',
						expiresAt: this.#token.expires_at,
					})
					return this.#token.value
				},
				{ provider: 'yc-service-account' }
			)
		} catch (error) {
			dc('ydb:auth.provider.failed').publish({
				provider: 'yc-service-account',
				error,
			})
			throw error
		}
	}
 
	/**
	 * Determines retry strategy for error.
	 *
	 * @returns RetryStrategy for retryable errors, null for non-retryable
	 */
	#getRetryStrategy(error: unknown): RetryStrategy | null {
		Iif (!(error instanceof Error)) {
			return null
		}
 
		// AbortError is not retryable - user explicitly cancelled the operation
		Iif (error.name === 'AbortError') {
			return null
		}
 
		if (error instanceof IamApiError) {
			let status = error.status
 
			// 429/503 indicate server overload - exponential backoff prevents overwhelming the server
			if (status === 429 || status === 503) {
				return exponential(100)
			}
 
			// Other 5xx are transient server errors - fast retry to catch quick recovery
			if (status >= 500 && status < 600) {
				return fixed(0)
			}
 
			// 4xx are client errors (wrong credentials, bad request) - retry won't help
			Eif (status >= 400 && status < 500) {
				return null
			}
		}
 
		// Network errors are transient - fast retry to catch when connection restored
		if (
			error.name === 'TypeError' &&
			(error.message.includes('fetch') || error.message.includes('network'))
		) {
			return fixed(0)
		}
 
		// Unknown errors: assume not retryable (be conservative)
		return null
	}
 
	/**
	 * Creates a JWT signed with PS256 algorithm for IAM token exchange.
	 *
	 * @returns JWT string
	 */
	#createJWT(): string {
		let privateKey = createPrivateKey({
			key: this.#key.private_key,
			format: 'pem',
		})
 
		let now = Math.floor(Date.now() / 1000)
 
		let header = {
			typ: 'JWT',
			alg: 'PS256',
			kid: this.#key.id,
		}
 
		let payload = {
			iss: this.#key.service_account_id,
			aud: this.#iamEndpoint,
			iat: now,
			exp: now + 3600,
		}
 
		let encodedHeader = base64UrlEncode(JSON.stringify(header))
		let encodedPayload = base64UrlEncode(JSON.stringify(payload))
		let unsignedToken = `${encodedHeader}.${encodedPayload}`
 
		// PS256 (RSA-PSS with SHA-256) is required by Yandex Cloud IAM API
		// JWT RFC 7518 specifies PS256 as RSA-PSS using SHA-256 and MGF1 with SHA-256
		// Node.js sign() requires digest algorithm first, then RSA-PSS padding in options
		// saltLength 32 bytes matches SHA-256 digest size (required by JWT spec)
		// See:
		// - https://nodejs.org/api/crypto.html#cryptosignalgorithm-data-key-callback (Node.js crypto.sign documentation)
		// - https://datatracker.ietf.org/doc/html/rfc7518#section-3.5 (JWT PS256 algorithm specification)
		let signature = sign('sha256', Buffer.from(unsignedToken), {
			key: privateKey,
			padding: constants.RSA_PKCS1_PSS_PADDING,
			saltLength: 32,
		})
 
		let encodedSignature = base64UrlEncode(signature)
 
		return `${unsignedToken}.${encodedSignature}`
	}
 
	/**
	 * Fetches IAM token from Yandex Cloud IAM API using JWT.
	 * Includes built-in retry logic with smart strategy selection:
	 * - Fast retry for network errors and transient server errors
	 * - Exponential backoff for server overload (429, 503)
	 *
	 * @param signal - AbortSignal to cancel the request
	 * @returns Promise resolving to IamToken with value and expiration
	 */
	async #fetchIamToken(signal?: AbortSignal): Promise<IamToken> {
		let retryConfig: RetryConfig = {
			retry: (err) => this.#getRetryStrategy(err) !== null,
			signal,
			budget: 5,
			strategy: (ctx, cfg) => {
				let strategy = this.#getRetryStrategy(ctx.error)
 
				return strategy ? strategy(ctx, cfg) : 0
			},
			onRetry: (ctx) => {
				dbg.log(
					'retrying IAM token fetch, attempt %d, error: %O (key ID: %s)',
					ctx.attempt,
					ctx.error,
					this.#key.id
				)
			},
		}
 
		return await retry(retryConfig, async (signal) => {
			let jwt = this.#createJWT()
 
			let response = await fetch(this.#iamEndpoint, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ jwt }),
				signal: signal ?? null,
			})
 
			if (!response.ok) {
				let errorText = await response.text().catch(() => 'Unknown error')
				throw new IamApiError(
					`IAM API error: ${response.status} ${response.statusText} - ${errorText}`,
					response.status,
					response.statusText
				)
			}
 
			let data = (await response.json()) as {
				iamToken?: string
				expiresAt?: string
			}
 
			Iif (!data.iamToken) {
				throw new Error('IAM API response missing iamToken field')
			}
 
			Iif (!data.expiresAt) {
				throw new Error('IAM API response missing expiresAt field')
			}
 
			return {
				value: data.iamToken,
				expires_at: new Date(data.expiresAt).getTime(),
			}
		})
	}
}