@@ -29,6 +29,9 @@ let tokenRefreshInterval: NodeJS.Timeout | null = null;
2929async function initializeRedisClient ( ) : Promise < RedisClientType > {
3030 let client : RedisClientType ;
3131
32+ // Store IAM auth details for later use
33+ let iamAuthDetails : { host : string ; port : number ; username : string ; isServerless : boolean ; token : string } | null = null ;
34+
3235 if ( useIAMAuth ) {
3336 // Parse endpoint from REDIS_URL for IAM authentication
3437 const url = new URL ( redisUrl ) ;
@@ -69,12 +72,15 @@ async function initializeRedisClient(): Promise<RedisClientType> {
6972 console . log ( 'Token includes ResourceType=ServerlessCache parameter' ) ;
7073 }
7174
75+ // Store for manual AUTH after connection
76+ iamAuthDetails = { host, port, username, isServerless, token } ;
77+
7278 // Create Redis client with IAM credentials and TLS
7379 // TLS is REQUIRED for IAM authentication with AWS ElastiCache
7480 //
75- // Based on AWS documentation and examples (Python, Java, Go):
76- // Both username and password (IAM token) must be provided for AUTH
77- // The redis client will send: AUTH username token
81+ // IMPORTANT: For IAM auth, we DON'T pass username/password to createClient
82+ // Instead, we'll manually call AUTH after connection is established
83+ // This ensures the AUTH command is sent exactly as needed by ElastiCache
7884 client = createClient ( {
7985 socket : {
8086 host,
@@ -93,10 +99,8 @@ async function initializeRedisClient(): Promise<RedisClientType> {
9399 return Math . min ( retries * 100 , 3000 ) ; // Exponential backoff, max 3s
94100 } ,
95101 } ,
96- // Provide both username and IAM-generated token for authentication
97- // This matches AWS documentation for IAM auth with ElastiCache
98- username,
99- password : token ,
102+ // DON'T pass username/password here for IAM auth
103+ // We'll call AUTH manually after connection
100104 } ) ;
101105
102106 // Set up token refresh every 10 minutes
@@ -168,6 +172,14 @@ async function initializeRedisClient(): Promise<RedisClientType> {
168172 try {
169173 await client . connect ( ) ;
170174 console . log ( 'Valkey Client: Connected successfully' ) ;
175+
176+ // For IAM auth, manually send AUTH command after connection
177+ if ( iamAuthDetails ) {
178+ console . log ( 'Sending manual AUTH command with IAM token...' ) ;
179+ console . log ( `AUTH ${ iamAuthDetails . username } <token>` ) ;
180+ await client . auth ( { username : iamAuthDetails . username , password : iamAuthDetails . token } ) ;
181+ console . log ( '✓ AUTH command successful' ) ;
182+ }
171183 } catch ( error ) {
172184 console . error ( 'Failed to connect to Redis:' , error ) ;
173185 throw error ;
0 commit comments