All files / languages/sparql/services sparql-auth.ts

100% Statements 22/22
100% Branches 12/12
100% Functions 6/6
100% Lines 18/18

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                            40x 3x 3x     37x 6x 6x 6x     31x 6x   6x 3x     3x     25x 4x 4x 4x     21x                 15x    
import { AuthCredential, EntraClientAuthCredential } from '@src/services/core/credential';
import { EntraClientCredentialService } from '@src/services/core/entra-client-credential-service';
 
/**
 * Builds a provider that resolves the `Authorization` header value for the given credential.
 * Returns `undefined` when no usable credential is available (no credential, unknown type, or
 * a Microsoft credential without an access token), in which case no header should be sent.
 *
 * Prefer the provider over a one-shot value when the header is needed per request: for
 * Entra client credentials it acquires a fresh token on every invocation.
 * @param credential The authentication credential, if any.
 * @returns A function resolving the header value, or `undefined` if there is no usable credential.
 */
export function getAuthorizationHeaderProvider(credential?: AuthCredential): (() => Promise<string | undefined>) | undefined {
	if (credential?.type === 'basic') {
		const encoded = btoa(`${credential.username}:${credential.password}`);
		return async () => `Basic ${encoded}`;
	}
 
	if (credential?.type === 'bearer') {
		const prefix = credential.prefix || 'Bearer';
		const token = credential.token;
		return async () => `${prefix} ${token}`;
	}
 
	if (credential?.type === 'microsoft') {
		const accessToken = credential.accessToken;
 
		if (!accessToken) {
			return undefined;
		}
 
		return async () => `Bearer ${accessToken}`;
	}
 
	if (credential?.type === 'entra-client-credentials') {
		const entraCredential = credential as EntraClientAuthCredential;
		const tokenService = new EntraClientCredentialService();
		return async () => `Bearer ${await tokenService.acquireToken(entraCredential)}`;
	}
 
	return undefined;
}
 
/**
 * Resolves the `Authorization` header value for the given credential once.
 * @param credential The authentication credential, if any.
 * @returns The header value, or `undefined` when no usable credential is available.
 */
export async function getAuthorizationHeader(credential?: AuthCredential): Promise<string | undefined> {
	return getAuthorizationHeaderProvider(credential)?.();
}