-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathapiRateLimit.server.ts
More file actions
115 lines (104 loc) · 4.47 KB
/
Copy pathapiRateLimit.server.ts
File metadata and controls
115 lines (104 loc) · 4.47 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
import { tryCatch } from "@trigger.dev/core/v3";
import { env } from "~/env.server";
import { batchStreamGrants } from "~/runEngine/concerns/batchStreamGrantsInstance.server";
import { authenticateAuthorizationHeader } from "./apiAuth.server";
import { authorizationRateLimitMiddleware } from "./authorizationRateLimitMiddleware.server";
import type { Duration } from "./rateLimiter.server";
const BATCH_STREAM_ITEMS_PATH = /^\/api\/v3\/batches\/([^/]+)\/items$/;
export const apiRateLimiter = authorizationRateLimitMiddleware({
redis: {
port: env.RATE_LIMIT_REDIS_PORT,
host: env.RATE_LIMIT_REDIS_HOST,
username: env.RATE_LIMIT_REDIS_USERNAME,
password: env.RATE_LIMIT_REDIS_PASSWORD,
tlsDisabled: env.RATE_LIMIT_REDIS_TLS_DISABLED === "true",
clusterMode: env.RATE_LIMIT_REDIS_CLUSTER_MODE_ENABLED === "1",
},
keyPrefix: "api",
defaultLimiter: {
type: "tokenBucket",
refillRate: env.API_RATE_LIMIT_REFILL_RATE,
interval: env.API_RATE_LIMIT_REFILL_INTERVAL as Duration,
maxTokens: env.API_RATE_LIMIT_MAX,
},
limiterCache: {
fresh: 60_000 * 10, // Data is fresh for 10 minutes
stale: 60_000 * 20, // Date is stale after 20 minutes
maxItems: 1000,
},
limiterConfigOverride: async (authorizationValue) => {
const authenticatedEnv = await authenticateAuthorizationHeader(authorizationValue, {
allowPublicKey: true,
allowJWT: true,
});
if (!authenticatedEnv || !authenticatedEnv.ok) {
return;
}
if (authenticatedEnv.type === "PUBLIC_JWT") {
return {
type: "fixedWindow",
window: env.API_RATE_LIMIT_JWT_WINDOW,
tokens: env.API_RATE_LIMIT_JWT_TOKENS,
};
} else {
return authenticatedEnv.environment.organization.apiRateLimiterConfig;
}
},
pathMatchers: [/^\/api/],
// Allow /api/v1/tasks/:id/callback/:secret
pathWhiteList: [
"/api/internal/stripe_webhooks",
// Keep allowlisted: these CLI endpoints are intentionally unauthenticated,
// so this Authorization-header-keyed limiter would 401 them. They are
// throttled separately by authCodeRateLimiter.server.ts.
"/api/v1/authorization-code",
"/api/v1/token",
"/api/v1/usage/ingest",
"/api/v1/plain/customer-cards",
/^\/api\/v1\/tasks\/[^/]+\/callback\/[^/]+$/, // /api/v1/tasks/$id/callback/$secret
/^\/api\/v1\/runs\/[^/]+\/tasks\/[^/]+\/callback\/[^/]+$/, // /api/v1/runs/$runId/tasks/$id/callback/$secret
/^\/api\/v1\/http-endpoints\/[^/]+\/env\/[^/]+\/[^/]+$/, // /api/v1/http-endpoints/$httpEndpointId/env/$envType/$shortcode
/^\/api\/v1\/sources\/http\/[^/]+$/, // /api/v1/sources/http/$id
/^\/api\/v1\/endpoints\/[^/]+\/[^/]+\/index\/[^/]+$/, // /api/v1/endpoints/$environmentId/$endpointSlug/index/$indexHookIdentifier
"/api/v1/timezones",
"/api/v1/usage/ingest",
"/api/v1/auth/jwt/claims",
/^\/api\/v1\/runs\/[^/]+\/attempts$/, // /api/v1/runs/$runFriendlyId/attempts
/^\/api\/v1\/waitpoints\/tokens\/[^/]+\/callback\/[^/]+$/, // /api/v1/waitpoints/tokens/$waitpointFriendlyId/callback/$hash
/^\/api\/v\d+\/deployments/, // /api/v{1,2,3,n}/deployments/*
// Internal SDK plumbing — packets are presigned-URL handshakes for
// payload uploads (v2 PUT) and downloads (v1 GET), authenticated via
// run-scoped JWT, called once per task/turn boundary by the runtime.
// Same shape as `/api/v1/runs/$runFriendlyId/attempts` above; not a
// customer-facing surface so customer rate limits shouldn't apply.
/^\/api\/v1\/packets\//,
/^\/api\/v2\/packets\//,
/^\/api\/v1\/sessions\/[^/]+\/snapshot-url$/,
],
bypass: async (req) => {
const match = BATCH_STREAM_ITEMS_PATH.exec(req.path);
if (!match) {
return false;
}
const batchFriendlyId = match[1];
const authorizationValue = req.headers.authorization;
if (!batchFriendlyId || !authorizationValue) {
return false;
}
const [authError, authenticated] = await tryCatch(
authenticateAuthorizationHeader(authorizationValue, {
allowPublicKey: true,
})
);
if (authError || !authenticated || !authenticated.ok) {
return false;
}
return batchStreamGrants.spend(authenticated.environment.id, batchFriendlyId);
},
log: {
rejections: env.API_RATE_LIMIT_REJECTION_LOGS_ENABLED === "1",
requests: env.API_RATE_LIMIT_REQUEST_LOGS_ENABLED === "1",
limiter: env.API_RATE_LIMIT_LIMITER_LOGS_ENABLED === "1",
},
});
export type RateLimitMiddleware = ReturnType<typeof authorizationRateLimitMiddleware>;