Skip to content

Commit ca21249

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
fix(webapp): query API runs API key queries in the key's own environment
Mono-RevId: 7851e344d82de18f9463f076c5544148ac103b58
1 parent 85a3dbc commit ca21249

6 files changed

Lines changed: 44 additions & 50 deletions

File tree

‎apps/webapp/app/v3/queryScope.ts‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,44 @@ import type { ApiAuthenticationResultSuccess } from "~/services/apiAuth.server";
22
import type { QueryScope } from "~/v3/querySchemas";
33

44
/**
5-
* The widest scope a credential may query at.
5+
* How a credential's requested query scope is handled on the query API.
66
*
7-
* `executeQuery` always isolates by organization and widens or narrows from there
8-
* on the caller's `scope`. That makes the request body, not the credential, the
9-
* ceiling — which is wrong for a public access token: it is minted for one
10-
* environment and handed to a browser, so anyone holding it could read the whole
11-
* organization's analytics by changing one field.
7+
* `executeQuery` always isolates by organization and widens or narrows from there on the
8+
* caller's `scope`. On the query API every credential reads its own environment:
9+
* - `environment`: public access tokens, the deprecated public key and run tokens. A
10+
* project or organization scope is refused.
11+
* - `unbounded`: secret API keys, including additional keys. A project or organization
12+
* scope is answered for the key's own environment. The query dashboards API also
13+
* accepts these credentials.
1214
*
13-
* A secret API key, including a restricted additional key, is deliberately NOT capped here. It is a server-side credential the
14-
* organization's own owner installs, and capping it would change the public API's
15-
* behaviour for callers who query at organization scope today. A session or PAT
16-
* caller (the Query page) never goes through this: it picks its scope in the UI,
17-
* authorized by organization membership.
15+
* A session or PAT caller (the Query page) never goes through this: it picks its scope in
16+
* the UI, authorized by organization membership.
1817
*/
1918
export type QueryScopeCeiling = "environment" | "unbounded";
2019

2120
export type QueryScopeDecision = { ok: true; scope: QueryScope } | { ok: false; error: string };
2221

2322
/**
24-
* Rejected rather than narrowed. Silently answering about one environment when the
25-
* caller asked about the organization gives them a number that means something else,
26-
* with nothing in the response to say so.
23+
* The scope an API query runs at: always the credential's own environment. A token capped
24+
* at `environment` that asks for a wider scope is refused; a secret key's wider request is
25+
* answered for its own environment. Wider scopes are available on the dashboard's Query page.
2726
*/
2827
export function resolveQueryScope(args: {
2928
ceiling: QueryScopeCeiling;
3029
requested: QueryScope;
3130
}): QueryScopeDecision {
32-
if (args.ceiling === "unbounded") return { ok: true, scope: args.requested };
33-
if (args.requested === "environment") return { ok: true, scope: "environment" };
31+
if (args.requested === "environment" || args.ceiling === "unbounded") {
32+
return { ok: true, scope: "environment" };
33+
}
3434
return {
3535
ok: false,
36-
error: `This token is scoped to one environment, so it can't run a ${args.requested}-scoped query. Use scope "environment", or a secret key.`,
36+
error: `This token is scoped to one environment, so it can't run a ${args.requested}-scoped query. Use scope "environment".`,
3737
};
3838
}
3939

4040
/**
41-
* Public credentials and run tokens are environment-bound. Additional keys retain their existing
42-
* query scope semantics; their abilities still gate query access. `PUBLIC` is the deprecated
41+
* Public credentials and run tokens are environment-bound. Additional keys are secret keys;
42+
* their abilities still gate query access. `PUBLIC` is the deprecated
4343
* `pk_*` key — same threat model as a public access token, so it caps the same way. It cannot
4444
* reach the query API today (the bearer resolver 401s `pk_*`), which is why capping it costs
4545
* no caller anything and why the helper must not promise it is uncapped.

‎apps/webapp/test/queryScope.test.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe("the query scope ceiling", () => {
1616
expect(queryScopeCeilingFor({ type: "PUBLIC" })).toBe("environment");
1717
});
1818

19-
it("leaves the secret key uncapped", () => {
19+
it("gives the secret key the unbounded ceiling", () => {
2020
expect(queryScopeCeilingFor({ type: "PRIVATE" })).toBe("unbounded");
2121
});
2222

@@ -27,7 +27,7 @@ describe("the query scope ceiling", () => {
2727
expect(resolveQueryScope({ ceiling, requested: "environment" }).ok).toBe(true);
2828
});
2929

30-
it("preserves restricted additional-key project and organization query scope", () => {
30+
it("answers additional-key project and organization queries", () => {
3131
const ceiling = queryScopeCeilingFor({ type: "PRIVATE", credentialKind: "additional_api_key" });
3232
expect(resolveQueryScope({ ceiling, requested: "organization" }).ok).toBe(true);
3333
expect(resolveQueryScope({ ceiling, requested: "project" }).ok).toBe(true);
@@ -64,12 +64,18 @@ describe("resolveQueryScope", () => {
6464
});
6565
});
6666

67-
// A secret key, a PAT-exchanged session or the Query page still query at org
68-
// scope: they are not environment-bound credentials.
69-
it("leaves an uncapped caller's organization scope alone", () => {
70-
expect(resolveQueryScope({ ceiling: "unbounded", requested: "organization" })).toEqual({
71-
ok: true,
72-
scope: "organization",
73-
});
74-
});
67+
// Every API key reads its own environment, whichever environment type it belongs to:
68+
// the key's type does not reach this decision.
69+
it.each(["environment", "project", "organization"] as const)(
70+
"runs a secret key's %s-scoped query in its own environment",
71+
(requested) => {
72+
for (const credentialKind of [undefined, "additional_api_key"] as const) {
73+
const ceiling = queryScopeCeilingFor({ type: "PRIVATE", credentialKind });
74+
expect(resolveQueryScope({ ceiling, requested })).toEqual({
75+
ok: true,
76+
scope: "environment",
77+
});
78+
}
79+
}
80+
);
7581
});

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,7 @@ describe("run-token API authorization", () => {
609609
expect(await (await call(key)).json()).toMatchObject({
610610
credentialKind: "additional_api_key",
611611
environmentScoped: true,
612-
scope: { ok: true, scope: "organization" },
612+
scope: { ok: true, scope: "environment" },
613613
});
614614
expect(await (await call(await tokenFor(environment))).json()).toMatchObject({
615615
credentialKind: "run_token",

‎docs/observability/query.mdx‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ The `metrics` table also records how the API rate limiter treated requests made
4242
- `api.rate_limit.limit.per_second` (`gauge`): the sustained rate your limit refills at, in requests per second
4343
- `api.rate_limit.limit.burst` (`gauge`): the most requests the limit admits at once
4444

45-
These rows have no run, task, or machine attributes (`run_id`, `task_identifier`, `machine_id` and so on are empty). Sum the counters over time, take `min()` of `api.rate_limit.remaining_min` and `max()` of the limit gauges. Total attempts in a bucket are `allowed + denied`. To draw the sustained limit for a bucket, multiply `api.rate_limit.limit.per_second` by that bucket's width in seconds; `timeBucket()` picks its width from the query's time range, so use a fixed `toStartOfMinute(bucket_start)` grouping when you want a known width (recording buckets never straddle a minute, so this grouping never splits a bucket; the example assumes a bucket width of at most one minute, which includes the default 10 seconds, and with a wider width you would group by that width and multiply by it instead). The limit gauges only exist in buckets that saw requests, and they follow any change to your limit, so a chart stays correct after an increase. Requests from preview branches share the parent preview environment's rate limit bucket and are recorded against that environment, so query at project scope to see them. Self-hosted instances enable recording with `API_RATE_LIMIT_METRICS_ENABLED=1`, or `allowlist` to record only organizations with the `apiRateLimitMetricsEnabled` feature flag.
45+
These rows have no run, task, or machine attributes (`run_id`, `task_identifier`, `machine_id` and so on are empty). Sum the counters over time, take `min()` of `api.rate_limit.remaining_min` and `max()` of the limit gauges. Total attempts in a bucket are `allowed + denied`. To draw the sustained limit for a bucket, multiply `api.rate_limit.limit.per_second` by that bucket's width in seconds; `timeBucket()` picks its width from the query's time range, so use a fixed `toStartOfMinute(bucket_start)` grouping when you want a known width (recording buckets never straddle a minute, so this grouping never splits a bucket; the example assumes a bucket width of at most one minute, which includes the default 10 seconds, and with a wider width you would group by that width and multiply by it instead). The limit gauges only exist in buckets that saw requests, and they follow any change to your limit, so a chart stays correct after an increase. Requests from preview branches share the parent preview environment's rate limit bucket and are recorded against that environment, so query them from the dashboard's Query page at project scope. Self-hosted instances enable recording with `API_RATE_LIMIT_METRICS_ENABLED=1`, or `allowlist` to record only organizations with the `apiRateLimitMetricsEnabled` feature flag.
4646

4747
```sql
4848
SELECT
@@ -150,8 +150,8 @@ typedResult.results.forEach((row) => {
150150
import { query } from "@trigger.dev/sdk";
151151

152152
const result = await query.execute("SELECT COUNT(*) as count FROM runs", {
153-
// Scope: "environment" (default), "project", or "organization"
154-
scope: "project",
153+
// Scope: "environment" (default). With an API key every scope reads the key's environment.
154+
scope: "environment",
155155
// Time period using shorthand (e.g., "7d", "30d", "1h")
156156
period: "7d",
157157
// Or use explicit time range
@@ -464,18 +464,9 @@ LIMIT 100
464464

465465
## Query scopes
466466

467-
Control what data your query can access:
467+
With an API key (the SDK or the REST API), a query reads the key's own environment. The default `scope` is `environment`, and that is what a `project` or `organization` scope runs at too.
468468

469-
- **`environment`** (default) - Query runs in the current environment only
470-
- **`project`** - Query runs across all environments in the project
471-
- **`organization`** - Query runs across all projects in the organization
472-
473-
```typescript
474-
// Query across all environments in a project
475-
const result = await query.execute("SELECT environment, count() FROM runs GROUP BY environment", {
476-
scope: "project",
477-
});
478-
```
469+
To query across all environments in a project, or across all projects in the organization, use the **Query** page in the dashboard and pick the scope there.
479470

480471
## Time ranges
481472

‎docs/v3-openapi.yaml‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1480,7 +1480,6 @@ paths:
14801480
const result = await query.execute(
14811481
"SELECT COUNT(*) as count FROM runs WHERE status = 'Failed'",
14821482
{
1483-
scope: "project", // Query across all environments
14841483
period: "7d", // Last 7 days
14851484
format: "json"
14861485
}
@@ -8500,7 +8499,7 @@ components:
85008499
type: string
85018500
enum: ["environment", "project", "organization"]
85028501
default: "environment"
8503-
description: The scope of data to query - environment (default), project, or organization
8502+
description: The scope of data to query. With an API key, every scope reads the key's own environment. Project and organization wide queries are available on the dashboard's Query page.
85048503
period:
85058504
type: string
85068505
nullable: true

‎packages/trigger-sdk/src/v3/query.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,8 @@ export type QueryFormat = "json" | "csv";
2828
*/
2929
export type QueryOptions = {
3030
/**
31-
* The scope of the query - determines what data is accessible
32-
* - "environment": Current environment only (default)
33-
* - "project": All environments in the project
34-
* - "organization": All projects in the organization
31+
* The scope of the query. With an API key, every scope reads the key's own environment.
32+
* Project and organization wide queries are available on the dashboard's Query page.
3533
*
3634
* @default "environment"
3735
*/

0 commit comments

Comments
 (0)