You've already forked node-redis
mirror of
https://github.com/redis/node-redis.git
synced 2025-08-07 13:22:56 +03:00
feat(auth): add Entra ID identity provider integration for Redis client authentication (#2877)
* feat(auth): refactor authentication mechanism to use CredentialsProvider - Introduce new credential providers: AsyncCredentialsProvider, StreamingCredentialsProvider - Update client handshake process to use the new CredentialsProviders and to support async credentials fetch / credentials refresh - Internal conversion of username/password to a CredentialsProvider - Modify URL parsing to accommodate the new authentication structure - Tests * feat(auth): auth extensions Introduces TokenManager and supporting classes to handle token acquisition, automatic refresh, and updates via identity providers. This foundation enables consistent authentication token management across different identity provider implementations. Key additions: - Add TokenManager to obtain and maintain auth tokens from identity providers with automated refresh scheduling based on TTL and configurable thresholds - Add IdentityProvider interface for token acquisition from auth providers - Implement Token class for managing token state and TTL tracking - Include configurable retry mechanism with exponential backoff and jitter - Add comprehensive test suite covering refresh cycles and error handling This change establishes the core infrastructure needed for reliable token lifecycle management across different authentication providers. * feat(auth): add Entra ID identity provider integration Introduces Entra ID (former Azure AD) authentication support with multiple authentication flows and automated token lifecycle management. Key additions: - Add EntraIdCredentialsProvider for handling Entra ID authentication flows - Implement MSALIdentityProvider to integrate with MSAL/EntraID authentication library - Add support for multiple authentication methods: - Managed identities (system and user-assigned) - Client credentials with certificate - Client credentials with secret - Authorization Code flow with PKCE - Add factory class with builder methods for each authentication flow - Include sample Express server implementation for Authorization Code flow - Add comprehensive configuration options for authority and token management * feat(test-utils): improve cluster testing - Add support for configuring replica authentication with 'masterauth' - Allow default client configuration during test cluster creation This improves the testing framework's flexibility by automatically configuring replica authentication when '--requirepass' is used and enabling custom client configurations across cluster nodes. * feat(auth): add EntraId integration tests - Add integration tests for token renewal and re-authentication flows - Update credentials provider to use uniqueId as username instead of account username - Add test utilities for loading Redis endpoint configurations - Split TypeScript configs into separate files for samples and integration tests - Remove `@redis/authx` package and nest it under `@`
This commit is contained in:
140
packages/entraid/lib/entraid-credentials-provider.ts
Normal file
140
packages/entraid/lib/entraid-credentials-provider.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { AuthenticationResult } from '@azure/msal-common/node';
|
||||
import {
|
||||
BasicAuth, StreamingCredentialsProvider, IdentityProvider, TokenManager,
|
||||
ReAuthenticationError, StreamingCredentialsListener, IDPError, Token, Disposable
|
||||
} from '@redis/client/dist/lib/authx';
|
||||
|
||||
/**
|
||||
* A streaming credentials provider that uses the Entraid identity provider to provide credentials.
|
||||
* Please use one of the factory functions in `entraid-credetfactories.ts` to create an instance of this class for the different
|
||||
* type of authentication flows.
|
||||
*/
|
||||
export class EntraidCredentialsProvider implements StreamingCredentialsProvider {
|
||||
readonly type = 'streaming-credentials-provider';
|
||||
|
||||
readonly #listeners: Set<StreamingCredentialsListener<BasicAuth>> = new Set();
|
||||
|
||||
#tokenManagerDisposable: Disposable | null = null;
|
||||
#isStarting: boolean = false;
|
||||
|
||||
#pendingSubscribers: Array<{
|
||||
resolve: (value: [BasicAuth, Disposable]) => void;
|
||||
reject: (error: Error) => void;
|
||||
pendingListener: StreamingCredentialsListener<BasicAuth>;
|
||||
}> = [];
|
||||
|
||||
constructor(
|
||||
public readonly tokenManager: TokenManager<AuthenticationResult>,
|
||||
public readonly idp: IdentityProvider<AuthenticationResult>,
|
||||
private readonly options: {
|
||||
onReAuthenticationError?: (error: ReAuthenticationError) => void;
|
||||
credentialsMapper?: (token: AuthenticationResult) => BasicAuth;
|
||||
onRetryableError?: (error: string) => void;
|
||||
} = {}
|
||||
) {
|
||||
this.onReAuthenticationError = options.onReAuthenticationError ?? DEFAULT_ERROR_HANDLER;
|
||||
this.#credentialsMapper = options.credentialsMapper ?? DEFAULT_CREDENTIALS_MAPPER;
|
||||
}
|
||||
|
||||
async subscribe(
|
||||
listener: StreamingCredentialsListener<BasicAuth>
|
||||
): Promise<[BasicAuth, Disposable]> {
|
||||
|
||||
const currentToken = this.tokenManager.getCurrentToken();
|
||||
|
||||
if (currentToken) {
|
||||
return [this.#credentialsMapper(currentToken.value), this.#createDisposable(listener)];
|
||||
}
|
||||
|
||||
if (this.#isStarting) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.#pendingSubscribers.push({ resolve, reject, pendingListener: listener });
|
||||
});
|
||||
}
|
||||
|
||||
this.#isStarting = true;
|
||||
try {
|
||||
const initialToken = await this.#startTokenManagerAndObtainInitialToken();
|
||||
|
||||
this.#pendingSubscribers.forEach(({ resolve, pendingListener }) => {
|
||||
resolve([this.#credentialsMapper(initialToken.value), this.#createDisposable(pendingListener)]);
|
||||
});
|
||||
this.#pendingSubscribers = [];
|
||||
|
||||
return [this.#credentialsMapper(initialToken.value), this.#createDisposable(listener)];
|
||||
} finally {
|
||||
this.#isStarting = false;
|
||||
}
|
||||
}
|
||||
|
||||
onReAuthenticationError: (error: ReAuthenticationError) => void;
|
||||
|
||||
#credentialsMapper: (token: AuthenticationResult) => BasicAuth;
|
||||
|
||||
#createTokenManagerListener(subscribers: Set<StreamingCredentialsListener<BasicAuth>>) {
|
||||
return {
|
||||
onError: (error: IDPError): void => {
|
||||
if (!error.isRetryable) {
|
||||
subscribers.forEach(listener => listener.onError(error));
|
||||
} else {
|
||||
this.options.onRetryableError?.(error.message);
|
||||
}
|
||||
},
|
||||
onNext: (token: { value: AuthenticationResult }): void => {
|
||||
const credentials = this.#credentialsMapper(token.value);
|
||||
subscribers.forEach(listener => listener.onNext(credentials));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#createDisposable(listener: StreamingCredentialsListener<BasicAuth>): Disposable {
|
||||
this.#listeners.add(listener);
|
||||
|
||||
return {
|
||||
dispose: () => {
|
||||
this.#listeners.delete(listener);
|
||||
if (this.#listeners.size === 0 && this.#tokenManagerDisposable) {
|
||||
this.#tokenManagerDisposable.dispose();
|
||||
this.#tokenManagerDisposable = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async #startTokenManagerAndObtainInitialToken(): Promise<Token<AuthenticationResult>> {
|
||||
const initialResponse = await this.idp.requestToken();
|
||||
const token = this.tokenManager.wrapAndSetCurrentToken(initialResponse.token, initialResponse.ttlMs);
|
||||
|
||||
this.#tokenManagerDisposable = this.tokenManager.start(
|
||||
this.#createTokenManagerListener(this.#listeners),
|
||||
this.tokenManager.calculateRefreshTime(token)
|
||||
);
|
||||
return token;
|
||||
}
|
||||
|
||||
public hasActiveSubscriptions(): boolean {
|
||||
return this.#tokenManagerDisposable !== null && this.#listeners.size > 0;
|
||||
}
|
||||
|
||||
public getSubscriptionsCount(): number {
|
||||
return this.#listeners.size;
|
||||
}
|
||||
|
||||
public getTokenManager() {
|
||||
return this.tokenManager;
|
||||
}
|
||||
|
||||
public getCurrentCredentials(): BasicAuth | null {
|
||||
const currentToken = this.tokenManager.getCurrentToken();
|
||||
return currentToken ? this.#credentialsMapper(currentToken.value) : null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const DEFAULT_CREDENTIALS_MAPPER = (token: AuthenticationResult): BasicAuth => ({
|
||||
username: token.uniqueId,
|
||||
password: token.accessToken
|
||||
});
|
||||
|
||||
const DEFAULT_ERROR_HANDLER = (error: ReAuthenticationError) =>
|
||||
console.error('ReAuthenticationError', error);
|
Reference in New Issue
Block a user