Skip to content

Commit 21c2085

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat(auth): attribute default SDK selections to HTTP routes
Attribute default SDK credential selections to normalized HTTP methods and server route IDs. Record bounded SDK version diagnostics without raw requests, query strings, concrete resource IDs or credential material. Mono-RevId: 13cc54ff9d8bf943b25054d66414f25e4e42f3b5
1 parent ed01478 commit 21c2085

6 files changed

Lines changed: 224 additions & 8 deletions

File tree

‎apps/webapp/app/entry.server.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ export { deploymentRateLimiter } from "./services/deploymentRateLimit.server";
405405
export { engineRateLimiter } from "./services/engineRateLimit.server";
406406
export { otlpRateLimiter } from "./services/otlpRateLimit.server";
407407
export { runWithHttpContext } from "./services/httpAsyncStorage.server";
408+
export { configureSdkDefaultAttribution } from "./services/sdkDefaultAttribution.server";
408409
export { tenantContextMiddleware } from "./services/tenantContextResolver.server";
409410
export { socketIo } from "./v3/handleSocketIo.server";
410411
export { wss } from "./v3/handleWebsockets.server";

‎apps/webapp/app/services/authTelemetry.server.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { getMeter } from "@internal/tracing";
2+
import { ROOT_CONTEXT } from "@opentelemetry/api";
23
import { isAdditionalApiKey } from "@trigger.dev/core/v3/apiKeys";
34
import {
45
isSdkCredentialTelemetryOperation,
@@ -24,6 +25,8 @@ import { isRunTokenFormat } from "~/services/oidc/runTokenVerify";
2425
import { logger } from "~/services/logger.server";
2526
import { rbac } from "~/services/rbac.server";
2627
import { singleton } from "~/utils/singleton";
28+
import { sdkDefaultAttribution } from "./sdkDefaultAttribution.server";
29+
import { SEMINTATTRS_FORCE_RECORDING, tracer } from "~/v3/tracer.server";
2730

2831
type ApiAuthResult = "success" | "invalid" | "forbidden" | "error";
2932

@@ -41,7 +44,16 @@ const telemetry = singleton("apiAuthTelemetry", () => {
4144
description: "SDK credential selections reported on API authentication attempts",
4245
});
4346

44-
return { attempts, duration, sdkCredentialSelections };
47+
const sdkDefaultDestinations = meter.createCounter("api_auth.sdk_default_destinations", {
48+
description: "SDK default credential selections by matched HTTP destination",
49+
});
50+
51+
return {
52+
attempts,
53+
duration,
54+
sdkCredentialSelections,
55+
sdkDefaultDestinations,
56+
};
4557
});
4658

4759
export async function authenticateBearerWithTelemetry(
@@ -200,6 +212,32 @@ function recordSdkCredentialSelection(request: Request, credentialKind: BearerCr
200212
reason,
201213
credential_kind: credentialKind,
202214
});
215+
216+
if (operation === "default") {
217+
const { attributes, diagnostic } = sdkDefaultAttribution(request);
218+
telemetry.sdkDefaultDestinations.add(1, {
219+
...attributes,
220+
reason,
221+
credential_kind: credentialKind,
222+
});
223+
if (diagnostic) {
224+
tracer
225+
.startSpan(
226+
"api_auth.sdk_default_destination",
227+
{
228+
attributes: {
229+
[SEMINTATTRS_FORCE_RECORDING]: true,
230+
...diagnostic,
231+
operation,
232+
reason,
233+
credential_kind: credentialKind,
234+
},
235+
},
236+
ROOT_CONTEXT
237+
)
238+
.end();
239+
}
240+
}
203241
}
204242

205243
function recordAuthAttempt(
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import type { ServerBuild } from "@remix-run/server-runtime";
2+
import { parse as parseVersion } from "semver";
3+
import { createKeyedAllowance, createRouteIdMatcher } from "./ingressBodyCap.server";
4+
5+
const DIAGNOSTICS_PER_MINUTE = 5;
6+
const MAX_SDK_VERSION_LENGTH = 128;
7+
const HTTP_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
8+
9+
export function createSdkDefaultAttribution(
10+
routes: ServerBuild["routes"],
11+
now: () => number = Date.now
12+
) {
13+
const routeIdFor = createRouteIdMatcher(routes);
14+
const allowance = createKeyedAllowance({ limit: DIAGNOSTICS_PER_MINUTE, windowMs: 60_000, now });
15+
16+
return (request: Request) => {
17+
const attributes = {
18+
http_method: HTTP_METHODS.has(request.method) ? request.method : "OTHER",
19+
route: routeIdFor(new URL(request.url).pathname) ?? "unmatched",
20+
};
21+
// One process-wide budget, never keyed by caller-controlled headers or versions.
22+
const { allowed, heldBack } = allowance("default");
23+
return {
24+
attributes,
25+
diagnostic: allowed
26+
? {
27+
...attributes,
28+
sdk_version: sdkReleaseVersion(request.headers.get("trigger-version")),
29+
linesHeldBack: heldBack,
30+
}
31+
: undefined,
32+
};
33+
};
34+
}
35+
36+
// Retain only the numeric release version. Prerelease/build suffixes can contain arbitrary
37+
// caller-controlled text and are deliberately excluded from diagnostics and metric labels.
38+
function sdkReleaseVersion(version: string | null): string {
39+
if (!version) return "missing";
40+
if (version.length > MAX_SDK_VERSION_LENGTH) return "invalid";
41+
const parsed = parseVersion(version);
42+
return parsed ? `${parsed.major}.${parsed.minor}.${parsed.patch}` : "invalid";
43+
}
44+
45+
let configuredRoutes: ServerBuild["routes"] | undefined;
46+
let attribution = createSdkDefaultAttribution({});
47+
48+
export function configureSdkDefaultAttribution(routes: ServerBuild["routes"]) {
49+
if (configuredRoutes === routes) return;
50+
configuredRoutes = routes;
51+
attribution = createSdkDefaultAttribution(routes);
52+
}
53+
54+
export function sdkDefaultAttribution(request: Request) {
55+
return attribution(request);
56+
}

‎apps/webapp/server.ts‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -188,13 +188,14 @@ async function startServer() {
188188
? `node webapp-worker-${cluster.isWorker ? cluster.worker?.id : "solo"}`
189189
: "node webapp-server";
190190

191-
const loadBuild = () => {
192-
if (viteDevServer) {
193-
return viteDevServer.ssrLoadModule("virtual:remix/server-build");
194-
}
195-
return dynamicImport(
196-
pathToFileURL(path.join(process.cwd(), "build", "server", "index.mjs")).href
197-
);
191+
const loadBuild = async () => {
192+
const build = viteDevServer
193+
? await viteDevServer.ssrLoadModule("virtual:remix/server-build")
194+
: await dynamicImport(
195+
pathToFileURL(path.join(process.cwd(), "build", "server", "index.mjs")).href
196+
);
197+
build.entry.module.configureSdkDefaultAttribution(build.routes);
198+
return build;
198199
};
199200

200201
// Boots the entry.server singletons (socket.io, wss, rate limiters).

‎apps/webapp/test/runTokenApiAuthorization.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,56 @@ describe("run-token API authorization", () => {
10081008
);
10091009
});
10101010

1011+
// Catches: legacy auth losing default attribution or nested auth wrappers double-counting it.
1012+
it("attributes default selections from bearer and legacy authentication once per request", async () => {
1013+
const { environment } = await seedDeployedEnvironment();
1014+
const { authenticateBearerWithTelemetry, observeLegacyBearerAuthentication } =
1015+
await import("~/services/authTelemetry.server");
1016+
const { authenticateApiRequestWithFailure } = await import("~/services/apiAuth.server");
1017+
const { configureSdkDefaultAttribution } =
1018+
await import("~/services/sdkDefaultAttribution.server");
1019+
configureSdkDefaultAttribution({
1020+
test: { id: "routes/test.$id", path: "test/:id", module: {} },
1021+
});
1022+
const request = () =>
1023+
new Request("https://api.example.com/test/private-id?secret=private", {
1024+
headers: {
1025+
Authorization: `Bearer ${environment.apiKey}`,
1026+
"x-trigger-sdk-operation": "default",
1027+
"x-trigger-sdk-credential-reason": "unsupported_operation",
1028+
"trigger-version": "4.8.5",
1029+
},
1030+
});
1031+
try {
1032+
const bearerRequest = request();
1033+
await observeLegacyBearerAuthentication(bearerRequest, () =>
1034+
authenticateBearerWithTelemetry(bearerRequest, {})
1035+
);
1036+
await authenticateApiRequestWithFailure(request());
1037+
const points = (await telemetryMetrics.getMetrics())
1038+
.slice(-1)
1039+
.flatMap((resource) => resource.scopeMetrics)
1040+
.flatMap((scope) => scope.metrics)
1041+
.filter((metric) => metric.descriptor.name === "api_auth.sdk_default_destinations")
1042+
.flatMap((metric) => metric.dataPoints);
1043+
expect(points.map((point) => ({ attributes: point.attributes, value: point.value }))).toEqual(
1044+
[
1045+
{
1046+
attributes: {
1047+
http_method: "GET",
1048+
route: "routes/test.$id",
1049+
reason: "unsupported_operation",
1050+
credential_kind: "root_api_key",
1051+
},
1052+
value: 2,
1053+
},
1054+
]
1055+
);
1056+
} finally {
1057+
configureSdkDefaultAttribution({});
1058+
}
1059+
});
1060+
10111061
it("round-trips an offloaded packet with an admin run token", async () => {
10121062
const { environment } = await seedDeployedEnvironment();
10131063
const token = await tokenFor(environment);
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type { ServerBuild } from "@remix-run/server-runtime";
2+
import { describe, expect, it } from "vitest";
3+
import { createSdkDefaultAttribution } from "~/services/sdkDefaultAttribution.server";
4+
5+
const routes = {
6+
root: { id: "root", path: "", module: {} },
7+
runs: { id: "routes/api.runs.$runId", parentId: "root", path: "api/runs/:runId", module: {} },
8+
packets: { id: "routes/api.packets.$", parentId: "root", path: "api/packets/*", module: {} },
9+
} satisfies ServerBuild["routes"];
10+
11+
// Catches: concrete IDs, query data, or arbitrary version suffixes leaking into default attribution.
12+
describe("SDK default destination attribution", () => {
13+
it("uses manifest route IDs and numeric SDK release versions without request data", () => {
14+
const attribute = createSdkDefaultAttribution(routes);
15+
const result = attribute(
16+
new Request("https://example.com/api/runs/run_secret?token=secret", {
17+
method: "POST",
18+
headers: { "trigger-version": "4.5.0-beta.secret+private", Authorization: "Bearer secret" },
19+
})
20+
);
21+
expect(result).toEqual({
22+
attributes: { http_method: "POST", route: "routes/api.runs.$runId" },
23+
diagnostic: {
24+
http_method: "POST",
25+
route: "routes/api.runs.$runId",
26+
sdk_version: "4.5.0",
27+
linesHeldBack: 0,
28+
},
29+
});
30+
expect(
31+
attribute(new Request("https://example.com/api/packets/private/nested")).attributes.route
32+
).toBe("routes/api.packets.$");
33+
expect(attribute(new Request("https://example.com/private")).attributes.route).toBe(
34+
"unmatched"
35+
);
36+
expect(
37+
attribute(new Request("https://example.com/private", { method: "CUSTOM" })).attributes
38+
.http_method
39+
).toBe("OTHER");
40+
});
41+
42+
it("bounds diagnostics globally even when callers vary routes and versions", () => {
43+
let now = 0;
44+
const attribute = createSdkDefaultAttribution(routes, () => now);
45+
for (let i = 0; i < 5; i++) {
46+
expect(
47+
attribute(
48+
new Request(`https://example.com/api/runs/${i}`, {
49+
headers: { "trigger-version": `4.0.${i}` },
50+
})
51+
).diagnostic
52+
).toBeDefined();
53+
}
54+
const suppressed = attribute(new Request("https://example.com/api/packets/secret"));
55+
expect(suppressed.attributes.route).toBe("routes/api.packets.$");
56+
expect(suppressed.diagnostic).toBeUndefined();
57+
now = 60_000;
58+
expect(attribute(new Request("https://example.com/api/runs/next")).diagnostic).toMatchObject({
59+
sdk_version: "missing",
60+
linesHeldBack: 1,
61+
});
62+
expect(
63+
attribute(
64+
new Request("https://example.com/api/runs/next", {
65+
headers: { "trigger-version": "arbitrary-secret" },
66+
})
67+
).diagnostic?.sdk_version
68+
).toBe("invalid");
69+
});
70+
});

0 commit comments

Comments
 (0)