All files / packages/auth/src environ.ts

100% Statements 63/63
100% Branches 58/58
100% Functions 4/4
100% Lines 63/63

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                      1x                               26x 26x 26x   26x 26x 26x   26x 12x     14x 2x         12x 1x         11x 1x         10x   10x 3x 3x 7x 3x 3x     10x 2x 2x 8x 2x 2x     10x 2x 2x 8x 2x 2x     10x                                                                                   12x   12x 12x   12x               4x       12x 2x 2x     10x 2x 2x   2x           2x           8x 1x 1x         7x 4x 4x   4x 4x 2x 1x           1x     3x           3x             3x 3x      
import * as fs from 'node:fs'
import * as tls from 'node:tls'
 
import { loggers } from '@ydbjs/debug'
 
import { AccessTokenCredentialsProvider } from './access-token.js'
import { AnonymousCredentialsProvider } from './anonymous.js'
import { CredentialsProvider } from './index.js'
import { MetadataCredentialsProvider } from './metadata.js'
import { StaticCredentialsProvider } from './static.js'
 
let debug = loggers.auth.extend('environ')
 
/**
 * Reads TLS/SSL configuration from environment variables.
 *
 * Supported variables:
 * - CA: `YDB_SSL_ROOT_CERTIFICATES_FILE` (file path) or `NODE_EXTRA_CA_CERTS` (file path)
 *       or `YDB_SSL_ROOT_CERTIFICATES` (PEM string)
 * - Client cert: `YDB_SSL_CERTIFICATE_FILE` (file path) or `YDB_SSL_CERTIFICATE` (PEM string)
 * - Client key: `YDB_SSL_PRIVATE_KEY_FILE` (file path) or `YDB_SSL_PRIVATE_KEY` (PEM string)
 *
 * File variants take priority over string variants.
 *
 * @returns `tls.SecureContextOptions` if any TLS env vars are set, `undefined` otherwise.
 */
export function getSecureOptionsFromEnviron(): tls.SecureContextOptions | undefined {
	let caFile = process.env.YDB_SSL_ROOT_CERTIFICATES_FILE ?? process.env.NODE_EXTRA_CA_CERTS
	let crtFile = process.env.YDB_SSL_CERTIFICATE_FILE
	let keyFile = process.env.YDB_SSL_PRIVATE_KEY_FILE
 
	let caString = process.env.YDB_SSL_ROOT_CERTIFICATES
	let crtString = process.env.YDB_SSL_CERTIFICATE
	let keyString = process.env.YDB_SSL_PRIVATE_KEY
 
	if (!caFile && !crtFile && !keyFile && !caString && !crtString && !keyString) {
		return undefined
	}
 
	if (caFile && caString) {
		throw new Error(
			'Ambiguous CA configuration: both YDB_SSL_ROOT_CERTIFICATES_FILE (or NODE_EXTRA_CA_CERTS) and YDB_SSL_ROOT_CERTIFICATES are set. Use only one.'
		)
	}
 
	if (crtFile && crtString) {
		throw new Error(
			'Ambiguous client certificate configuration: both YDB_SSL_CERTIFICATE_FILE and YDB_SSL_CERTIFICATE are set. Use only one.'
		)
	}
 
	if (keyFile && keyString) {
		throw new Error(
			'Ambiguous private key configuration: both YDB_SSL_PRIVATE_KEY_FILE and YDB_SSL_PRIVATE_KEY are set. Use only one.'
		)
	}
 
	let options: tls.SecureContextOptions = {}
 
	if (caFile) {
		debug.log('reading CA certificate from %s', caFile)
		options.ca = fs.readFileSync(caFile)
	} else if (caString) {
		debug.log('using CA certificate from env string')
		options.ca = caString
	}
 
	if (crtFile) {
		debug.log('reading client certificate from %s', crtFile)
		options.cert = fs.readFileSync(crtFile)
	} else if (crtString) {
		debug.log('using client certificate from env string')
		options.cert = crtString
	}
 
	if (keyFile) {
		debug.log('reading client private key from %s', keyFile)
		options.key = fs.readFileSync(keyFile)
	} else if (keyString) {
		debug.log('using client private key from env string')
		options.key = keyString
	}
 
	return options
}
 
/**
 * A credentials provider that auto-detects the authentication method
 * from environment variables, following the official YDB SDK conventions.
 *
 * Detection priority (first match wins):
 * 1. `YDB_ANONYMOUS_CREDENTIALS=1` → Anonymous
 * 2. `YDB_METADATA_CREDENTIALS=1` → Metadata
 *    - `YDB_METADATA_CREDENTIALS_ENDPOINT` — custom metadata endpoint
 *    - `YDB_METADATA_CREDENTIALS_FLAVOR` — custom metadata flavor (e.g. `Google`)
 * 3. `YDB_ACCESS_TOKEN_CREDENTIALS` → Access Token
 * 4. `YDB_STATIC_CREDENTIALS_USER` → Static (username/password)
 * 5. None → Anonymous
 *
 * TLS/SSL is auto-detected from environment variables and exposed via `secureOptions`:
 * - `YDB_SSL_ROOT_CERTIFICATES_FILE` / `NODE_EXTRA_CA_CERTS` (file) or `YDB_SSL_ROOT_CERTIFICATES` (PEM string)
 * - `YDB_SSL_CERTIFICATE_FILE` (file) or `YDB_SSL_CERTIFICATE` (PEM string)
 * - `YDB_SSL_PRIVATE_KEY_FILE` (file) or `YDB_SSL_PRIVATE_KEY` (PEM string)
 *
 * @example
 * ```ts
 * import { EnvironCredentialsProvider } from '@ydbjs/auth/environ'
 *
 * let creds = new EnvironCredentialsProvider(connectionString)
 * let driver = new Driver(connectionString, {
 *   credentialsProvider: creds,
 *   secureOptions: creds.secureOptions,
 * })
 * ```
 */
export class EnvironCredentialsProvider extends CredentialsProvider {
	#inner: CredentialsProvider
 
	/**
	 * TLS/SSL options detected from environment variables.
	 * Pass this to `Driver` as `secureOptions`.
	 */
	readonly secureOptions: tls.SecureContextOptions | undefined
 
	constructor(connectionString?: string) {
		super()
 
		this.secureOptions = getSecureOptionsFromEnviron()
		this.#inner = this.#detect(connectionString)
 
		debug.log(
			'detected credentials provider: %s, secureOptions: %s',
			this.#inner.constructor.name,
			this.secureOptions ? 'yes' : 'no'
		)
	}
 
	async getToken(force?: boolean, signal?: AbortSignal): Promise<string> {
		return this.#inner.getToken(force, signal)
	}
 
	#detect(connectionString?: string): CredentialsProvider {
		if (process.env.YDB_ANONYMOUS_CREDENTIALS === '1') {
			debug.log('YDB_ANONYMOUS_CREDENTIALS=1, using anonymous auth')
			return new AnonymousCredentialsProvider()
		}
 
		if (process.env.YDB_METADATA_CREDENTIALS === '1') {
			let endpoint = process.env.YDB_METADATA_CREDENTIALS_ENDPOINT
			let flavor = process.env.YDB_METADATA_CREDENTIALS_FLAVOR
 
			debug.log(
				'YDB_METADATA_CREDENTIALS=1, using metadata auth (endpoint: %s, flavor: %s)',
				endpoint ?? 'default',
				flavor ?? 'default'
			)
 
			return new MetadataCredentialsProvider({
				...(endpoint && { endpoint }),
				...(flavor && { flavor }),
			})
		}
 
		if (process.env.YDB_ACCESS_TOKEN_CREDENTIALS) {
			debug.log('YDB_ACCESS_TOKEN_CREDENTIALS is set, using access token auth')
			return new AccessTokenCredentialsProvider({
				token: process.env.YDB_ACCESS_TOKEN_CREDENTIALS,
			})
		}
 
		if (process.env.YDB_STATIC_CREDENTIALS_USER) {
			let username = process.env.YDB_STATIC_CREDENTIALS_USER
			let password = process.env.YDB_STATIC_CREDENTIALS_PASSWORD ?? ''
 
			let endpoint = process.env.YDB_STATIC_CREDENTIALS_ENDPOINT
			if (!endpoint) {
				if (!connectionString) {
					throw new Error(
						'YDB_STATIC_CREDENTIALS_ENDPOINT is not set and no connection string was provided. ' +
							'Either set YDB_STATIC_CREDENTIALS_ENDPOINT or pass the connection string to EnvironCredentialsProvider.'
					)
				}
 
				endpoint = new URL('/', connectionString).href
			}
 
			debug.log(
				'YDB_STATIC_CREDENTIALS_USER is set, using static credentials for user: %s, endpoint: %s',
				username,
				endpoint
			)
 
			return new StaticCredentialsProvider(
				{ username, password },
				endpoint,
				this.secureOptions
			)
		}
 
		debug.log('no credentials env vars detected, using anonymous auth')
		return new AnonymousCredentialsProvider()
	}
}