-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathauth.ts
More file actions
233 lines (199 loc) · 7.34 KB
/
auth.ts
File metadata and controls
233 lines (199 loc) · 7.34 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
import { ApiKeyRepository } from "@domain/api-keys"
import { OrganizationId, UnauthorizedError, UserId } from "@domain/shared"
import { ApiKeyRepositoryLive, SqlClientLive } from "@platform/db-postgres"
import type { PostgresClient } from "@platform/db-postgres"
import { hashToken } from "@repo/utils"
import { Effect, Option } from "effect"
import type { Context, MiddlewareHandler, Next } from "hono"
import { getAdminPostgresClient } from "../clients.ts"
import type { AuthContext } from "../types.ts"
import { createTouchBuffer } from "./touch-buffer.ts"
/**
* Minimum time for API key validation in milliseconds.
* This ensures all code paths take consistent time to prevent timing attacks.
*/
const MIN_VALIDATION_TIME_MS = 50
/**
* Cache TTL constants
*/
const VALID_KEY_TTL_SECONDS = 300 // 5 minutes for valid keys
const INVALID_KEY_TTL_SECONDS = 5 // 5 seconds for invalid keys (prevents timing attacks)
const REDIS_OPERATION_TIMEOUT_MS = 50
const withTimeout = <T>(operation: Promise<T>, fallback: T): Promise<T> => {
return Promise.race([
operation,
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), REDIS_OPERATION_TIMEOUT_MS)),
])
}
const getApiKeyCacheKey = (tokenHash: string): string => `apikey:${tokenHash}`
const isCachedApiKeyResult = (value: unknown): value is { organizationId: string; keyId: string } | null => {
if (value === null) {
return true
}
if (typeof value !== "object" || value === null) {
return false
}
if (!("organizationId" in value) || !("keyId" in value)) {
return false
}
return typeof value.organizationId === "string" && typeof value.keyId === "string"
}
/**
* Get cached API key result from Redis (keyed by token hash).
*/
const getCachedApiKey = (
redis: Context["var"]["redis"],
tokenHash: string,
): Effect.Effect<{ organizationId: string; keyId: string } | null | undefined, never> => {
const cacheKey = getApiKeyCacheKey(tokenHash)
return Effect.tryPromise({
try: async () => {
const cached = await withTimeout(redis.get(cacheKey), null)
if (!cached) return undefined
const parsed = JSON.parse(cached)
return isCachedApiKeyResult(parsed) ? parsed : undefined
},
catch: () => undefined,
}).pipe(Effect.orDie)
}
/**
* Cache API key result in Redis (keyed by token hash).
*/
const cacheApiKeyResult = (
redis: Context["var"]["redis"],
tokenHash: string,
result: { organizationId: string; keyId: string } | null,
ttl: number,
): Effect.Effect<void, never> => {
const cacheKey = getApiKeyCacheKey(tokenHash)
return Effect.tryPromise({
try: () => withTimeout(redis.setex(cacheKey, ttl, JSON.stringify(result)), undefined),
catch: () => undefined,
}).pipe(Effect.orDie)
}
/**
* Validate API key with Redis caching and constant-time execution.
*
* Security features:
* - Incoming token is hashed (SHA-256) before any lookup — raw tokens never touch cache or DB queries
* - All code paths take at least MIN_VALIDATION_TIME_MS (~50ms) to prevent timing attacks
* - Redis cache provides consistent lookup time for both valid and invalid keys
* - Invalid keys are cached briefly to prevent repeated DB hits and timing enumeration
* - Graceful degradation: continues without cache if Redis unavailable
*/
const validateApiKey = (
c: Context,
token: string,
options?: AuthMiddlewareOptions,
): Effect.Effect<{ organizationId: string; keyId: string } | null, never> => {
const redis = c.get("redis")
const adminClient = options?.adminClient ?? getAdminPostgresClient()
const touchBuffer = createTouchBuffer(adminClient)
return Effect.gen(function* () {
const startTime = Date.now()
const tokenHash = yield* hashToken(token)
// Try cache first for consistent lookup time (keyed by hash)
const cached = yield* getCachedApiKey(redis, tokenHash)
if (cached !== undefined) {
// Cache hit - enforce minimum time and return
yield* enforceMinimumTime(startTime, MIN_VALIDATION_TIME_MS)
return cached
}
const apiKeyRepository = yield* ApiKeyRepository
const apiKeyOption = yield* Effect.option(apiKeyRepository.findByTokenHash(tokenHash))
if (Option.isNone(apiKeyOption)) {
yield* cacheApiKeyResult(redis, tokenHash, null, INVALID_KEY_TTL_SECONDS)
yield* enforceMinimumTime(startTime, MIN_VALIDATION_TIME_MS)
return null
}
const apiKey = apiKeyOption.value
const result = {
organizationId: apiKey.organizationId,
keyId: apiKey.id,
}
// Cache successful validation for 5 minutes (keyed by hash)
yield* cacheApiKeyResult(redis, tokenHash, result, VALID_KEY_TTL_SECONDS)
// Use TouchBuffer for batched updates instead of fire-and-forget
// This reduces database writes by 90%+ by batching updates
touchBuffer.touch(apiKey.id)
// Enforce minimum time before returning
yield* enforceMinimumTime(startTime, MIN_VALIDATION_TIME_MS)
return result
}).pipe(Effect.provide(ApiKeyRepositoryLive), Effect.provide(SqlClientLive(adminClient)), Effect.orDie)
}
/**
* Enforce minimum processing time to prevent timing attacks.
* Calculates elapsed time and delays if necessary to reach minimum threshold.
*/
const enforceMinimumTime = (startTime: number, minMs: number): Effect.Effect<void, never> => {
const elapsed = Date.now() - startTime
if (elapsed < minMs) {
return Effect.tryPromise({
try: () => new Promise<void>((resolve) => setTimeout(resolve, minMs - elapsed)),
catch: () => undefined,
}).pipe(Effect.orDie)
}
return Effect.void
}
const extractBearerToken = (c: Context): string | undefined => {
const authHeader = c.req.header("Authorization")
if (!authHeader?.startsWith("Bearer ")) {
return undefined
}
return authHeader.slice(7)
}
/**
* Authenticate via API key.
*/
const authenticateWithApiKey = (
c: Context,
token: string,
options?: AuthMiddlewareOptions,
): Effect.Effect<AuthContext | null, never> => {
return Effect.gen(function* () {
const result = yield* validateApiKey(c, token, options)
if (result) {
const authContext: AuthContext = {
userId: UserId(`api-key:${result.keyId}`),
organizationId: OrganizationId(result.organizationId),
method: "api-key",
}
return authContext
}
return null
}).pipe(Effect.orDie)
}
/**
* Main authentication effect that validates API key from Authorization header.
*/
const authenticate = (c: Context, options?: AuthMiddlewareOptions): Effect.Effect<AuthContext, UnauthorizedError> => {
return Effect.gen(function* () {
const bearerToken = extractBearerToken(c)
if (!bearerToken) {
return yield* new UnauthorizedError({
message: "Authentication required",
})
}
const authContext = yield* authenticateWithApiKey(c, bearerToken, options)
if (authContext) return authContext
return yield* new UnauthorizedError({
message: "Invalid API key",
})
})
}
/**
* Create authentication middleware.
*
* Validates API keys sent via the Authorization: Bearer header.
* Public routes should be excluded from this middleware.
*/
interface AuthMiddlewareOptions {
readonly adminClient?: PostgresClient
}
export const createAuthMiddleware = (options?: AuthMiddlewareOptions): MiddlewareHandler => {
return async (c: Context, next: Next) => {
const authContext = await Effect.runPromise(authenticate(c, options))
c.set("auth", authContext)
await next()
}
}