-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathrunAuth.ts
More file actions
811 lines (715 loc) · 24.2 KB
/
runAuth.ts
File metadata and controls
811 lines (715 loc) · 24.2 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import {
type BaseExecutionContext,
canUseProjectStrict,
getAppById,
getPoWErrorMessage,
isSlackUserToken,
updateAppLastUsed,
validateAndGetApiKey,
validateOrigin,
validateTargetAgent,
verifyPoW,
verifyServiceToken,
verifySlackUserToken,
verifyTempToken,
} from '@inkeep/agents-core';
import { trace } from '@opentelemetry/api';
import { createMiddleware } from 'hono/factory';
import { HTTPException } from 'hono/http-exception';
import { errors, jwtVerify } from 'jose';
import runDbClient from '../data/db/runDbClient';
import { getAnonJwtSecret } from '../domains/run/routes/auth';
import { env } from '../env';
import { getLogger } from '../logger';
import { createBaseExecutionContext } from '../types/runExecutionContext';
import { isCopilotAgent } from '../utils/copilot';
const logger = getLogger('env-key-auth');
// ============================================================================
// Supported auth strategies
// ============================================================================
// 1. JWT temp token: generated with user session cookies
// 2. Bypass secret: override used for development purposes
// 3. Database API key: validated against database, created in the dashboard
// 4. Team agent token: used for intra-tenant team-agent delegation
// ============================================================================
/**
* Common request data extracted once at the start of auth
*/
interface RequestData {
request: Request;
authHeader?: string;
apiKey?: string;
tenantId?: string;
projectId?: string;
agentId?: string;
subAgentId?: string;
ref?: string;
baseUrl: string;
runAsUserId?: string;
appId?: string;
origin?: string;
}
/**
* Partial context data returned by auth strategies
* These fields will be merged with RequestData to create the final context
*/
type AuthResult = Pick<
BaseExecutionContext,
'apiKey' | 'tenantId' | 'projectId' | 'agentId' | 'apiKeyId' | 'metadata'
>;
type AuthAttempt = {
authResult: AuthResult | null;
failureMessage?: string;
};
/**
* Extract common request data from the Hono context
*/
function extractRequestData(c: { req: any }): RequestData {
const authHeader = c.req.header('Authorization');
const tenantId = c.req.header('x-inkeep-tenant-id');
const projectId = c.req.header('x-inkeep-project-id');
const agentId = c.req.header('x-inkeep-agent-id');
const subAgentId = c.req.header('x-inkeep-sub-agent-id');
const runAsUserId = c.req.header('x-inkeep-run-as-user-id');
const appId = c.req.header('x-inkeep-app-id');
const origin = c.req.header('Origin');
const proto = c.req.header('x-forwarded-proto')?.split(',')[0].trim();
const fwdHost = c.req.header('x-forwarded-host')?.split(',')[0].trim();
const host = fwdHost ?? c.req.header('host');
const reqUrl = new URL(c.req.url);
const ref = c.req.query('ref');
const baseUrl =
proto && host
? `${proto}://${host}`
: host
? `${reqUrl.protocol}//${host}`
: `${reqUrl.origin}`;
return {
request: c.req.raw,
authHeader,
apiKey: authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : undefined,
tenantId,
projectId,
agentId,
subAgentId,
ref,
baseUrl,
runAsUserId,
appId,
origin,
};
}
/**
* Build the final execution context from auth result and request data
*/
function buildExecutionContext(authResult: AuthResult, reqData: RequestData): BaseExecutionContext {
// For team delegation, use the parent agent ID from the request header (x-inkeep-agent-id)
// instead of the JWT's audience (which is the sub-agent being called).
// The parent agent ID is needed for project lookup (project.agents[agentId].subAgents[subAgentId]).
const agentId =
authResult.metadata?.teamDelegation && reqData.agentId ? reqData.agentId : authResult.agentId;
if (
!authResult.metadata?.teamDelegation &&
reqData.agentId &&
reqData.agentId !== authResult.agentId &&
authResult.apiKeyId &&
!authResult.apiKeyId.startsWith('temp-') &&
!authResult.apiKeyId.startsWith('app:') &&
authResult.apiKeyId !== 'bypass' &&
authResult.apiKeyId !== 'slack-user-token' &&
authResult.apiKeyId !== 'team-agent-token' &&
authResult.apiKeyId !== 'test-key'
) {
logger.warn(
{
requestedAgentId: reqData.agentId,
apiKeyAgentId: authResult.agentId,
apiKeyId: authResult.apiKeyId,
},
'API key agent scope mismatch: ignoring x-inkeep-agent-id header, using key-bound agent'
);
}
return createBaseExecutionContext({
apiKey: authResult.apiKey,
tenantId: authResult.tenantId,
projectId: authResult.projectId,
agentId,
apiKeyId: authResult.apiKeyId,
baseUrl: reqData.baseUrl,
subAgentId: reqData.subAgentId,
ref: reqData.ref,
metadata: authResult.metadata,
});
}
// ============================================================================
// Auth Strategies
// ============================================================================
/**
* Attempts to authenticate using a JWT temporary token
*
* Throws HTTPException(403) if the JWT is valid but the user lacks permission.
* Returns null if the token is not a temp JWT (allowing fallback to other auth methods).
*/
async function tryTempJwtAuth(apiKey: string): Promise<AuthAttempt> {
if (!apiKey.startsWith('eyJ')) {
return { authResult: null, failureMessage: 'not a JWT' };
}
if (!env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY) {
return { authResult: null, failureMessage: 'no public key configured' };
}
try {
const publicKeyPem = Buffer.from(env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY, 'base64').toString(
'utf-8'
);
const payload = await verifyTempToken(publicKeyPem, apiKey);
const userId = payload.sub;
const projectId = payload.projectId;
const agentId = payload.agentId;
if (!projectId || !agentId) {
logger.warn({ userId }, 'Missing projectId or agentId in JWT');
throw new HTTPException(400, {
message: 'Invalid token: missing projectId or agentId',
});
}
const isCopilotToken = isCopilotAgent({
tenantId: payload.tenantId,
projectId,
agentId,
});
if (isCopilotToken) {
logger.info({ userId, projectId, agentId }, 'Copilot bypass: skipping SpiceDB check');
}
if (!isCopilotToken) {
let canUse: boolean;
try {
canUse = await canUseProjectStrict({ userId, tenantId: payload.tenantId, projectId });
} catch (error) {
logger.error({ error, userId, projectId }, 'SpiceDB permission check failed');
throw new HTTPException(503, {
message: 'Authorization service temporarily unavailable',
});
}
if (!canUse) {
logger.warn({ userId, projectId }, 'User does not have use permission on project');
throw new HTTPException(403, {
message: 'Access denied: insufficient permissions',
});
}
}
logger.info({ projectId, agentId }, 'JWT temp token authenticated successfully');
return {
authResult: {
apiKey,
tenantId: payload.tenantId,
projectId,
agentId,
apiKeyId: 'temp-jwt',
metadata: { initiatedBy: payload.initiatedBy },
},
};
} catch (error) {
if (error instanceof HTTPException) {
throw error;
}
logger.debug({ error }, 'JWT verification failed');
return { authResult: null, failureMessage: 'JWT verification failed' };
}
}
/**
* Authenticate using a regular API key
*/
async function tryApiKeyAuth(apiKey: string): Promise<AuthAttempt> {
const apiKeyRecord = await validateAndGetApiKey(apiKey, runDbClient);
if (!apiKeyRecord) {
return { authResult: null, failureMessage: 'not found' };
}
logger.debug(
{
tenantId: apiKeyRecord.tenantId,
projectId: apiKeyRecord.projectId,
agentId: apiKeyRecord.agentId,
},
'API key authenticated successfully'
);
return {
authResult: {
apiKey,
tenantId: apiKeyRecord.tenantId,
projectId: apiKeyRecord.projectId,
agentId: apiKeyRecord.agentId,
apiKeyId: apiKeyRecord.id,
},
};
}
/**
* Authenticate using a Slack user JWT token (for Slack work app delegation)
*/
async function trySlackUserJwtAuth(token: string, reqData: RequestData): Promise<AuthAttempt> {
if (!isSlackUserToken(token)) {
return { authResult: null };
}
const result = await verifySlackUserToken(token);
if (!result.valid || !result.payload) {
logger.warn({ error: result.error }, 'Invalid Slack user JWT token');
return {
authResult: null,
failureMessage: `Invalid Slack user token: ${result.error || 'Invalid token'}`,
};
}
const payload = result.payload;
if (!reqData.projectId || !reqData.agentId) {
logger.warn(
{ hasProjectId: !!reqData.projectId, hasAgentId: !!reqData.agentId },
'Slack user JWT requires x-inkeep-project-id and x-inkeep-agent-id headers'
);
return {
authResult: null,
failureMessage: 'Slack user token requires x-inkeep-project-id and x-inkeep-agent-id headers',
};
}
// Channel/workspace authorization bypass (D2, D8)
// If the Slack work app determined the user is authorized via channel or workspace config,
// AND the requested project matches the project the bypass was granted for,
// skip the SpiceDB project membership check.
const slackAuthorized =
payload.slack.authorized === true && payload.slack.authorizedProjectId === reqData.projectId;
if (!slackAuthorized) {
logger.debug(
{
slackAuthorizedClaim: payload.slack.authorized,
slackAuthorizedProjectId: payload.slack.authorizedProjectId,
requestedProjectId: reqData.projectId,
projectMatch: payload.slack.authorizedProjectId === reqData.projectId,
},
'Slack channel auth bypass not applied, falling through to SpiceDB'
);
// Verify the requested projectId belongs to the authenticated tenant
try {
const canUse = await canUseProjectStrict({
userId: payload.sub,
tenantId: payload.tenantId,
projectId: reqData.projectId,
});
if (!canUse) {
logger.warn(
{
userId: payload.sub,
tenantId: payload.tenantId,
projectId: reqData.projectId,
},
'Slack user JWT: user does not have access to requested project'
);
return {
authResult: null,
failureMessage: 'Access denied: insufficient permissions for the requested project',
};
}
} catch (error) {
logger.error(
{ error, userId: payload.sub, projectId: reqData.projectId },
'SpiceDB permission check failed for Slack JWT'
);
throw new HTTPException(503, {
message: 'Authorization service temporarily unavailable',
});
}
}
logger.info(
{
inkeepUserId: payload.sub,
tenantId: payload.tenantId,
slackTeamId: payload.slack.teamId,
slackUserId: payload.slack.userId,
projectId: reqData.projectId,
agentId: reqData.agentId,
slackAuthorized,
slackAuthSource: payload.slack.authSource,
slackChannelId: payload.slack.channelId,
slackAuthorizedProjectId: payload.slack.authorizedProjectId,
},
'Slack user JWT token authenticated successfully'
);
return {
authResult: {
apiKey: token,
tenantId: payload.tenantId,
projectId: reqData.projectId,
agentId: reqData.agentId,
apiKeyId: 'slack-user-token',
metadata: {
initiatedBy: {
type: 'user',
id: payload.sub,
},
...(slackAuthorized && {
slack: {
authorized: true,
authSource: payload.slack.authSource ?? 'channel',
channelId: payload.slack.channelId,
teamId: payload.slack.teamId,
},
}),
},
},
};
}
/**
* Authenticate using a team agent JWT token (for intra-tenant delegation)
*/
async function tryTeamAgentAuth(token: string, expectedSubAgentId?: string): Promise<AuthAttempt> {
const result = await verifyServiceToken(token);
if (!result.valid || !result.payload) {
logger.warn({ error: result.error }, 'Invalid team agent JWT token');
return {
authResult: null,
failureMessage: `Invalid team agent token: ${result.error || 'Invalid token'}`,
};
}
const payload = result.payload;
if (expectedSubAgentId && !validateTargetAgent(payload, expectedSubAgentId)) {
logger.error(
{
tokenTargetAgentId: payload.aud,
expectedSubAgentId,
originAgentId: payload.sub,
},
'Team agent token target mismatch'
);
throw new HTTPException(403, {
message: 'Token not valid for the requested agent',
});
}
logger.info(
{
originAgentId: payload.sub,
targetAgentId: payload.aud,
tenantId: payload.tenantId,
projectId: payload.projectId,
},
'Team agent JWT token authenticated successfully'
);
return {
authResult: {
apiKey: token,
tenantId: payload.tenantId,
projectId: payload.projectId,
agentId: payload.aud,
apiKeyId: 'team-agent-token',
metadata: {
teamDelegation: true,
originAgentId: payload.sub,
...(payload.initiatedBy ? { initiatedBy: payload.initiatedBy } : {}),
},
},
};
}
/**
* Authenticate using bypass secret (production mode bypass)
*/
function tryBypassAuth(apiKey: string, reqData: RequestData): AuthAttempt {
if (!env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET) {
return { authResult: null, failureMessage: 'no bypass secret configured' };
}
if (apiKey !== env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET) {
return { authResult: null, failureMessage: 'no match' };
}
if (!reqData.tenantId || !reqData.projectId || !reqData.agentId) {
throw new HTTPException(401, {
message: 'Missing or invalid tenant, project, or agent ID',
});
}
logger.info({}, 'Bypass secret authenticated successfully');
return {
authResult: {
apiKey,
tenantId: reqData.tenantId,
projectId: reqData.projectId,
agentId: reqData.agentId,
apiKeyId: 'bypass',
...(reqData.runAsUserId
? { metadata: { initiatedBy: { type: 'user' as const, id: reqData.runAsUserId } } }
: {}),
},
};
}
/**
* Authenticate using an app credential (X-Inkeep-App-Id header).
* Supports web_client (end-user JWT) and api (app secret) types.
*/
async function tryAppCredentialAuth(reqData: RequestData): Promise<AuthAttempt> {
const { appId: appIdHeader, apiKey: bearerToken, origin, agentId: requestedAgentId } = reqData;
if (!appIdHeader) {
return { authResult: null };
}
const app = await getAppById(runDbClient)(appIdHeader);
if (!app) {
return { authResult: null, failureMessage: 'App not found' };
}
if (!app.enabled) {
return { authResult: null, failureMessage: 'App is disabled' };
}
let endUserId: string | undefined;
let authMethod: 'app_credential_web_client' | 'app_credential_api';
if (app.type === 'web_client') {
authMethod = 'app_credential_web_client';
const config = app.config as {
type: 'web_client';
webClient: {
allowedDomains: string[];
};
};
if (!validateOrigin(origin, config.webClient.allowedDomains)) {
logger.warn(
{ origin, allowedDomains: config.webClient.allowedDomains, appId: app.id },
'App credential auth: origin not allowed'
);
return { authResult: null, failureMessage: 'Origin not allowed for this app' };
}
const pow = await verifyPoW(reqData.request, env.INKEEP_POW_HMAC_SECRET);
if (!pow.ok) {
throw new HTTPException(400, { message: getPoWErrorMessage(pow.error) });
}
if (!bearerToken) {
return { authResult: null, failureMessage: 'Bearer token required for web_client app' };
}
try {
const secret = getAnonJwtSecret();
const { payload } = await jwtVerify(bearerToken, secret, { issuer: 'inkeep' });
if (payload.app !== appIdHeader) {
return { authResult: null, failureMessage: 'JWT app claim does not match request app ID' };
}
endUserId = payload.sub;
} catch (err) {
const errorType =
err instanceof errors.JWTExpired
? 'expired'
: err instanceof errors.JWSSignatureVerificationFailed
? 'signature_invalid'
: 'unknown';
logger.debug({ errorType, appId: appIdHeader }, 'Anonymous JWT verification failed');
return { authResult: null, failureMessage: 'Invalid end-user JWT' };
}
} else {
return { authResult: null, failureMessage: 'Unsupported app type' };
}
const agentId = requestedAgentId || app.defaultAgentId || '';
if (Math.random() < 0.1) {
updateAppLastUsed(runDbClient)(app.id).catch((err) => {
logger.error({ error: err, appId: app.id }, 'Failed to update app lastUsedAt');
});
}
logger.info(
{ appId: app.id, appType: app.type, agentId, endUserId, authMethod },
'App credential authenticated successfully'
);
return {
authResult: {
apiKey: bearerToken || appIdHeader,
tenantId: app.tenantId || reqData.tenantId || '',
projectId: app.projectId || reqData.projectId || '',
agentId,
apiKeyId: `app:${app.id}`,
metadata: {
endUserId,
authMethod,
},
},
};
}
/**
* Create default development context
*/
function createDevContext(reqData: RequestData): AuthResult {
const result: AuthResult = {
apiKey: 'development',
tenantId: reqData.tenantId || 'test-tenant',
projectId: reqData.projectId || 'test-project',
agentId: reqData.agentId || 'test-agent',
apiKeyId: 'test-key',
...(reqData.runAsUserId
? { metadata: { initiatedBy: { type: 'user' as const, id: reqData.runAsUserId } } }
: {}),
};
// Log when falling back to test values to help debug auth issues
if (!reqData.tenantId || !reqData.projectId) {
logger.warn(
{
hasTenantId: !!reqData.tenantId,
hasProjectId: !!reqData.projectId,
hasApiKey: !!reqData.apiKey,
apiKeyPrefix: reqData.apiKey?.substring(0, 10),
resultTenantId: result.tenantId,
resultProjectId: result.projectId,
},
'createDevContext: Using fallback test values due to missing tenant/project in request'
);
}
return result;
}
// ============================================================================
// Main Middleware
// ============================================================================
/**
* Try all auth strategies in order, returning the first successful result
*/
async function authenticateRequest(reqData: RequestData): Promise<AuthAttempt> {
const { apiKey, subAgentId } = reqData;
if (reqData.appId) {
if (!apiKey) {
return { authResult: null, failureMessage: 'Bearer token required for app credential auth' };
}
return tryAppCredentialAuth(reqData);
}
if (!apiKey) {
return { authResult: null, failureMessage: 'No API key provided' };
}
const failures: Array<{ strategy: string; reason: string }> = [];
const jwtAttempt = await tryTempJwtAuth(apiKey);
if (jwtAttempt.authResult) return jwtAttempt;
if (jwtAttempt.failureMessage) {
failures.push({ strategy: 'JWT temp token', reason: jwtAttempt.failureMessage });
}
const bypassAttempt = tryBypassAuth(apiKey, reqData);
if (bypassAttempt.authResult) return bypassAttempt;
if (bypassAttempt.failureMessage) {
failures.push({ strategy: 'bypass secret', reason: bypassAttempt.failureMessage });
}
const slackAttempt = await trySlackUserJwtAuth(apiKey, reqData);
if (slackAttempt.authResult) return slackAttempt;
if (slackAttempt.failureMessage) return slackAttempt;
failures.push({ strategy: 'Slack user JWT', reason: 'not a Slack token' });
const apiKeyAttempt = await tryApiKeyAuth(apiKey);
if (apiKeyAttempt.authResult) return apiKeyAttempt;
if (apiKeyAttempt.failureMessage) {
failures.push({ strategy: 'API key', reason: apiKeyAttempt.failureMessage });
}
const teamAttempt = await tryTeamAgentAuth(apiKey, subAgentId);
if (teamAttempt.authResult) return teamAttempt;
if (teamAttempt.failureMessage) {
failures.push({ strategy: 'team agent token', reason: teamAttempt.failureMessage });
}
logger.debug({ failures }, 'All auth strategies exhausted');
return { authResult: null };
}
/**
* Core authentication handler that can be reused across middleware
*/
async function runApiKeyAuthHandler(
c: { req: any; set: (key: 'executionContext', value: BaseExecutionContext) => void },
next: () => Promise<void>
): Promise<void> {
if (c.req.method === 'OPTIONS') {
await next();
return;
}
const reqData = extractRequestData(c);
const isDev = process.env.ENVIRONMENT === 'development' || process.env.ENVIRONMENT === 'test';
if (reqData.runAsUserId === 'system' || reqData.runAsUserId?.startsWith('apikey:')) {
throw new HTTPException(400, {
message: 'x-inkeep-run-as-user-id cannot be a system identifier',
});
}
// Development/test environment handling
if (isDev) {
logger.info({}, 'development environment');
const attempt = await authenticateRequest(reqData);
if (attempt.authResult) {
c.set('executionContext', buildExecutionContext(attempt.authResult, reqData));
} else {
logger.info(
{},
reqData.apiKey
? 'Development/test environment - fallback to default context due to invalid API key'
: 'Development/test environment - no API key provided, using default context'
);
c.set('executionContext', buildExecutionContext(createDevContext(reqData), reqData));
}
if (reqData.appId && attempt.authResult) {
trace.getActiveSpan()?.setAttribute('app.id', reqData.appId);
}
await next();
return;
}
// Production environment - require valid auth
if (!reqData.authHeader || !reqData.authHeader.startsWith('Bearer ')) {
throw new HTTPException(401, {
message: 'Missing or invalid authorization header. Expected: Bearer <api_key>',
});
}
if (!reqData.apiKey || reqData.apiKey.length < 16) {
throw new HTTPException(401, {
message: 'Invalid API key format',
});
}
let attempt: AuthAttempt = { authResult: null };
try {
attempt = await authenticateRequest(reqData);
} catch (error) {
if (error instanceof HTTPException) {
throw error;
}
logger.error({ error }, 'Authentication failed');
throw new HTTPException(500, { message: 'Authentication failed' });
}
if (!attempt.authResult) {
logger.error(
{ failureMessage: attempt.failureMessage },
'API key authentication error - no valid auth method found'
);
throw new HTTPException(401, {
message: 'Invalid Token',
});
}
logger.debug(
{
tenantId: attempt.authResult.tenantId,
projectId: attempt.authResult.projectId,
agentId: attempt.authResult.agentId,
subAgentId: reqData.subAgentId,
},
'API key authenticated successfully'
);
c.set('executionContext', buildExecutionContext(attempt.authResult, reqData));
if (reqData.appId) {
trace.getActiveSpan()?.setAttribute('app.id', reqData.appId);
}
await next();
}
export const runApiKeyAuth = () =>
createMiddleware<{
Variables: {
executionContext: BaseExecutionContext;
};
}>(runApiKeyAuthHandler);
/**
* Creates a middleware that applies API key authentication except for specified route patterns
* @param skipRouteCheck - Function that returns true if the route should skip authentication
*/
export const runApiKeyAuthExcept = (skipRouteCheck: (path: string) => boolean) =>
createMiddleware<{
Variables: {
executionContext: BaseExecutionContext;
};
}>(async (c, next) => {
if (skipRouteCheck(c.req.path)) {
return next();
}
return runApiKeyAuthHandler(c, next);
});
/**
* Helper middleware for endpoints that optionally support API key authentication
* If no auth header is present, it continues without setting the executionContext
*/
export const runOptionalAuth = () =>
createMiddleware<{
Variables: {
executionContext?: BaseExecutionContext;
};
}>(async (c, next) => {
const authHeader = c.req.header('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
await next();
return;
}
return runApiKeyAuthHandler(c, next);
});