Merge pull request #2317 from codeflash-ai/codeflash/optimize-checkForValidAPIKey-mkwv868t

️ Speed up function `checkForValidAPIKey` by 30%
This commit is contained in:
Aseem Saxena 2026-03-18 12:13:42 -07:00 committed by GitHub
commit c5e8b56c6f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -42,7 +42,10 @@ export async function checkForValidAPIKey(
return next(missingAuthorizationHeader({ requestId: req.requestId, endpoint: req.path }))
}
const apiKey = authHeader.replace(/^Bearer\s+/, "")
// Optimized Bearer token extraction - avoid regex overhead
const apiKey = authHeader.startsWith("Bearer ")
? authHeader.substring(7)
: authHeader
try {
const authResult = await AuthStrategyFactory.getStrategy(apiKey).authenticate()
@ -62,29 +65,6 @@ export async function checkForValidAPIKey(
req.userId = userId
req.organizationId = authResult.organizationId
if (userId == null) {
// Log invalid API key - logger handles environment filtering automatically
// Production: WARN level (important security event), Development: WARN level (important security event)
logger.warn("Invalid API key provided", {
requestId: req.requestId,
traceId: req.traceId,
endpoint: req.path,
operation: "authentication",
apiKeyLength: apiKey.length,
})
posthog?.capture({
distinctId: "null-user-with-invalid-api-key",
event: `cfapi-endpoint-called-with-invalid-api-key`,
properties: {
apiKeyLength: apiKey.length,
},
disableGeoip: false,
})
return next(invalidApiKey({ requestId: req.requestId, endpoint: req.path }))
}
// Success - attach userId to request
req.userId = userId