All files / packages/auth/src static.ts

92.1% Statements 70/76
88.09% Branches 37/42
83.33% Functions 10/12
92.1% Lines 70/76

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                              3x   3x         3x 3x 3x 3x                                                   17x 17x 17x         17x               17x 17x 17x   17x           17x 17x 1x         16x   16x       16x       17x                               24x     24x         4x 4x     4x         2x   2x   2x         4x     20x 5x 5x           15x         1x       1x       1x     15x         24x               2x         2x 2x   2x                 17x                 17x 17x 17x       3x 3x     17x     17x       17x   17x       15x               15x 1x     14x 14x               14x         14x 14x 12x 12x 12x         2x 2x             2x             14x   14x       14x      
import * as tls from 'node:tls'
import { channel as dc, tracingChannel } from 'node:diagnostics_channel'
 
import { anyUnpack } from '@bufbuild/protobuf/wkt'
import { type ChannelOptions, credentials } from '@grpc/grpc-js'
import { AuthServiceDefinition, LoginResultSchema } from '@ydbjs/api/auth'
import { StatusIds_StatusCode } from '@ydbjs/api/operation'
import { loggers } from '@ydbjs/debug'
import { YDBError } from '@ydbjs/error'
import { type RetryContext, defaultRetryConfig, retry } from '@ydbjs/retry'
import { linkSignals } from '@ydbjs/abortable'
import { type Client, ClientError, Status, createChannel, createClient } from 'nice-grpc'
 
import { CredentialsProvider } from './index.js'
 
let debug = loggers.auth.extend('static')
 
let authTokenFetchCh = tracingChannel<{ provider: 'static' }, { provider: 'static' }>(
	'tracing:ydb:auth.token.fetch'
)
 
// Token refresh strategy configuration
const ACQUIRE_TOKEN_TIMEOUT_MS = 5_000 // 5 seconds timeout for token acquisition
const HARD_EXPIRY_BUFFER_SECONDS = 30 // Hard limit - must refresh
const SOFT_EXPIRY_BUFFER_SECONDS = 120 // Soft limit - start background refresh
const BACKGROUND_REFRESH_TIMEOUT_MS = 30_000 // 30 seconds timeout for background refresh
 
export type StaticCredentialsToken = {
	value: string
	aud: string[]
	exp: number
	iat: number
	sub: string
}
 
export type StaticCredentials = {
	username: string
	password: string
}
 
/**
 * A credentials provider that uses static username and password to authenticate.
 * It fetches and caches a token from the specified authentication service.
 *
 * @extends CredentialsProvider
 */
export class StaticCredentialsProvider extends CredentialsProvider {
	#client: Client<typeof AuthServiceDefinition>
	#username: string
	#password: string
 
	#token: StaticCredentialsToken | undefined = undefined
	#promise: Promise<string> | undefined = undefined
	#backgroundRefreshPromise: Promise<void> | undefined = undefined
 
	// Tracks whether the current token has already triggered a `token.expired`
	// event so concurrent getToken() calls don't fan out into N events for the
	// same incident. Reset on every successful refresh.
	#expiredReported = false
 
	constructor(
		{ username, password }: StaticCredentials,
		endpoint: string,
		secureOptions?: tls.SecureContextOptions | undefined,
		channelOptions?: ChannelOptions
	) {
		super()
		this.#username = username
		this.#password = password
 
		debug.log(
			'creating static credentials provider for user: %s, endpoint: %s',
			username,
			endpoint
		)
 
		let cs = new URL(endpoint)
		if (['unix:', 'http:', 'https:', 'grpc:', 'grpcs:'].includes(cs.protocol) === false) {
			throw new Error(
				'Invalid connection string protocol. Must be one of unix, grpc, grpcs, http, https'
			)
		}
 
		let address = cs.host
		// For unix sockets, keep the full URL
		Iif (cs.protocol === 'unix:') {
			address = `${cs.protocol}//${cs.host}${cs.pathname}`
		}
 
		let channelCredentials = secureOptions
			? credentials.createFromSecureContext(tls.createSecureContext(secureOptions))
			: credentials.createInsecure()
 
		this.#client = createClient(
			AuthServiceDefinition,
			createChannel(address, channelCredentials, channelOptions)
		)
	}
 
	/**
	 * Returns the token from the credentials.
	 * @param force - if true, forces a new token to be fetched
	 * @param signal - an optional AbortSignal to cancel the request. Defaults to a timeout of 5 seconds.
	 * @returns the token
	 */
	async getToken(
		force = false,
		signal: AbortSignal = AbortSignal.timeout(ACQUIRE_TOKEN_TIMEOUT_MS)
	): Promise<string> {
		let currentTimeSeconds = Date.now() / 1000
 
		// If token is still valid (hard buffer), return it
		if (
			!force &&
			this.#token &&
			this.#token.exp > currentTimeSeconds + HARD_EXPIRY_BUFFER_SECONDS
		) {
			let expiresInSeconds = this.#token.exp - currentTimeSeconds
			debug.log('returning cached token, expires in %d seconds', Math.floor(expiresInSeconds))
 
			// Start background refresh if approaching soft expiry
			if (
				this.#token.exp <= currentTimeSeconds + SOFT_EXPIRY_BUFFER_SECONDS &&
				!this.#promise &&
				!this.#backgroundRefreshPromise
			) {
				debug.log('token approaching soft expiry, starting background refresh')
				// Fire and forget background refresh with timeout
				this.#backgroundRefreshPromise = this.#refreshTokenInBackground(signal).finally(
					() => {
						this.#backgroundRefreshPromise = undefined
					}
				)
			}
 
			return this.#token.value
		}
 
		if (this.#promise) {
			debug.log('token refresh already in progress, waiting for result')
			return this.#promise
		}
 
		// Fire `token.expired` at most once per incident: only the first caller
		// who observes the cached token past its hard buffer publishes; the next
		// successful refresh resets the flag for the new token.
		if (
			this.#token &&
			this.#token.exp <= currentTimeSeconds + HARD_EXPIRY_BUFFER_SECONDS &&
			!this.#expiredReported
		) {
			this.#expiredReported = true
			// `stalenessMs` measures how long we've been past the hard buffer
			// (== exp + buffer). Negative values mean we're still inside the
			// buffer but planning a forced refresh — normalize to 0.
			let stalenessMs = Math.max(
				0,
				Date.now() - (this.#token.exp - HARD_EXPIRY_BUFFER_SECONDS) * 1000
			)
			dc('ydb:auth.token.expired').publish({ provider: 'static', stalenessMs })
		}
 
		debug.log(
			'fetching new token (force=%s, expired=%s)',
			force,
			this.#token ? 'true' : 'false'
		)
		return this.#refreshToken(signal)
	}
 
	/**
	 * Refreshes the token in the background without blocking current requests
	 * @param signal - an optional AbortSignal to cancel the request
	 */
	async #refreshTokenInBackground(signal: AbortSignal): Promise<void> {
		Iif (this.#promise || this.#backgroundRefreshPromise) {
			debug.log('background refresh skipped, already refreshing')
			return // Already refreshing (either sync or background)
		}
 
		debug.log('starting background token refresh')
		using linkedSignal = linkSignals(signal, AbortSignal.timeout(BACKGROUND_REFRESH_TIMEOUT_MS))
 
		await this.#refreshToken(linkedSignal.signal).catch(() => {})
	}
 
	/**
	 * Refreshes the authentication token from the service
	 * @param signal - an optional AbortSignal to cancel the request
	 * @returns the new token value
	 */
	async #refreshToken(signal: AbortSignal): Promise<string> {
		let retryConfig = {
			...defaultRetryConfig,
			signal,
			idempotent: true,
			onRetry: (ctx: RetryContext) => {
				debug.log('retry attempt #%d after error: %s', ctx.attempt, ctx.error)
			},
		}
 
		this.#promise = authTokenFetchCh
			.tracePromise(
				() => retry(retryConfig, (attemptSignal) => this.#loginAttempt(attemptSignal)),
				{ provider: 'static' }
			)
			.catch((error) => {
				dc('ydb:auth.provider.failed').publish({ provider: 'static', error })
				throw error
			})
			.finally(() => {
				this.#promise = undefined
			})
 
		return this.#promise
	}
 
	async #loginAttempt(signal: AbortSignal): Promise<string> {
		debug.log('attempting login with user: %s', this.#username)
 
		let response = await this.#client.login(
			{ user: this.#username, password: this.#password },
			{ signal }
		)
		Iif (!response.operation) {
			throw new ClientError(
				AuthServiceDefinition.login.path,
				Status.UNKNOWN,
				'No operation in response'
			)
		}
 
		if (response.operation.status !== StatusIds_StatusCode.SUCCESS) {
			throw new YDBError(response.operation.status, response.operation.issues)
		}
 
		let result = anyUnpack(response.operation.result!, LoginResultSchema)
		Iif (!result) {
			throw new ClientError(
				AuthServiceDefinition.login.path,
				Status.UNKNOWN,
				'No result in operation'
			)
		}
 
		debug.log('login successful, parsing JWT token')
 
		// The result.token is a JWT in the format header.payload.signature.
		// We attempt to decode the payload to extract token metadata (aud, exp, iat, sub).
		// If the token is not in the expected format, we fallback to default values.
		let [header, payload, signature] = result.token.split('.')
		if (header && payload && signature) {
			let decodedPayload = JSON.parse(Buffer.from(payload, 'base64').toString())
			this.#token = { value: result.token, ...decodedPayload }
			debug.log(
				'token parsed successfully, expires at %s',
				new Date(decodedPayload.exp * 1000).toISOString()
			)
		} else {
			debug.log('token not in JWT format, using fallback metadata')
			this.#token = {
				value: result.token,
				aud: [],
				exp: Math.floor(Date.now() / 1000) + 5 * 60, // fallback: 5 minutes from now
				iat: Math.floor(Date.now() / 1000),
				sub: '',
			}
			debug.log(
				'token created with fallback expiry: %s',
				new Date(this.#token.exp * 1000).toISOString()
			)
		}
 
		// Allow the next expiration incident to be reported.
		this.#expiredReported = false
 
		dc('ydb:auth.token.refreshed').publish({
			provider: 'static',
			expiresAt: this.#token!.exp * 1000,
		})
		return this.#token!.value!
	}
}