Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 31 additions & 4 deletions packages/cli/src/lib/target-scope-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,15 @@ type LookUpFirst = {

/**
* A lookup to send, with its query; `widerQuery` is tried when the first
* names no project (an empty trace).
* names no project (an empty trace). A lookup of a project-filtered list
* sets `listed`, the ID its response must include.
*/
export type ScopeLookup = { path: string; query?: string; widerQuery?: string };
export type ScopeLookup = {
path: string;
query?: string;
widerQuery?: string;
listed?: string;
};

export type ScopeRule = {
pattern: string;
Expand Down Expand Up @@ -211,14 +217,19 @@ function catalogRules(

const CATALOG = catalogRules(operations);

/** Sentry declares it `org-metadata`, but {@link OVERRIDES} check it. */
const WORKFLOW_DETAIL = patternOf(
"/organizations/{organization_id_or_slug}/workflows/{workflow_id}/",
);

/**
* Read-only organization metadata a project scope may read: what Sentry
* declares `org-metadata`, and the reads its schema doesn't publish.
*/
export const ORG_READS: readonly SimpleRule[] = [
// getsentry's subscription details, outside Sentry's schema.
{ pattern: "customers/:org/" },
...CATALOG.orgReads,
...CATALOG.orgReads.filter(({ pattern }) => pattern !== WORKFLOW_DETAIL),
];

/**
Expand Down Expand Up @@ -285,7 +296,8 @@ function traceLookup(params: Record<string, string>, url: URL): ScopeLookup {
/**
* Rules the catalog can't give: endpoints Sentry's schema doesn't publish
* (short IDs, event IDs, share links, traces), endpoints that don't do what
* their schema says (`trace-logs` ignores `project`), and release writes.
* their schema says (`trace-logs` ignores `project`), release writes, and
* a workflow's detail, which names no project.
*/
const OVERRIDES: readonly ScopeRule[] = [
{
Expand Down Expand Up @@ -344,6 +356,21 @@ const OVERRIDES: readonly ScopeRule[] = [
.map((trace) => traceLookup({ ...params, trace }, url)),
},
},
{
// A workflow is in scope when the scope project's filtered list has it.
pattern: "organizations/:org/workflows/:workflow_id/",
subject: ({ workflow_id }) => `Alert ${workflow_id}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [
{
path: `organizations/${encodeURIComponent(params["org"] ?? "")}/workflows/`,
query: `id=${encodeURIComponent(params["workflow_id"] ?? "")}`,
listed: params["workflow_id"] ?? "",
},
],
},
},
{
// A release can span projects, so changing one reaches past the scope.
pattern: "organizations/:org/releases/:version/**",
Expand Down
44 changes: 32 additions & 12 deletions packages/cli/src/lib/target-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ const NOTHING_TO_VERIFY = async (): Promise<void> => {
/** Project slugs are never entirely numeric, so digits are a project ID. */
const NUMERIC_ID = /^\d+$/;

const API_ROOT = "/api/0/";

/** A scope project's numeric ID and slug. */
type ScopeProject = { id: string; slug?: string | undefined };

Expand All @@ -143,23 +145,25 @@ export function __resetScopeLookupsForTests(): void {
type RequestContext = {
scope: TargetScope & { project: string };
url: URL;
/** The API root the request went to, such as `https://host/sentry/api/0/`. */
api: string;
method: string;
send: Send;
};

function lookupKey({ scope, url }: RequestContext, path: string): string {
return `${scopeLabel(scope)}|${url.origin}/api/0/${path}`;
function lookupKey({ scope, api }: RequestContext, path: string): string {
return `${scopeLabel(scope)}|${api}${path}`;
}

/** The scope's project, looked up once per process. */
function lookUpScopeProject(context: RequestContext): Promise<ScopeProject> {
const { scope, url, send } = context;
const { scope, api, send } = context;
const path = `projects/${encodeURIComponent(scope.org)}/${encodeURIComponent(scope.project)}/`;
const key = lookupKey(context, path);
let pending = scopeProjects.get(key);
if (!pending) {
pending = (async () => {
const response = await send(`${url.origin}/api/0/${path}`);
const response = await send(`${api}${path}`);
const project = response.ok ? record(await readJson(response)) : {};
const { id, slug } = project;
if (typeof id !== "string" && typeof id !== "number") {
Expand Down Expand Up @@ -267,6 +271,14 @@ async function readJson(response: Response): Promise<unknown> {
}
}

/** Whether a list response includes the item with this ID. */
function lists(body: unknown, id: string): boolean {
return (
Array.isArray(body) &&
body.some((item) => String(record(item)["id"]) === id)
);
}

/**
* Look up what a request names before it reads or changes it, unless an
* earlier lookup found it in scope. The lookup goes through `send`, so its
Expand All @@ -276,19 +288,26 @@ async function readJson(response: Response): Promise<unknown> {
*/
async function lookUpFirst(
context: RequestContext,
{ path, query, widerQuery }: ScopeLookup,
{ path, query, widerQuery, listed }: ScopeLookup,
): Promise<Response | undefined> {
const key = lookupKey(context, path);
// A list lookup proves the listed item, not the list, in scope.
const key = lookupKey(
context,
listed === undefined ? path : `${path}${encodeURIComponent(listed)}/`,
);
if (foundInScope.has(key)) {
return;
}
for (const attempt of widerQuery ? [query, widerQuery] : [query]) {
const response = await context.send(
`${context.url.origin}/api/0/${path}${attempt ? `?${attempt}` : ""}`,
`${context.api}${path}${attempt ? `?${attempt}` : ""}`,
);
if (!response.ok) {
return response;
}
if (listed !== undefined && lists(await readJson(response), listed)) {
foundInScope.add(key);
}
if (foundInScope.has(key)) {
return;
}
Expand Down Expand Up @@ -391,12 +410,13 @@ export async function scopeRequest(
init?.method ?? (input instanceof Request ? input.method : "GET")
).toUpperCase();
const subject = `${method} ${url.pathname}`;
const path = url.pathname.startsWith("/api/0/")
? url.pathname.slice("/api/0/".length)
: undefined;
if (path === undefined) {
// Self-hosted installs can serve the API under a path, such as `/sentry`.
const apiAt = url.pathname.indexOf(API_ROOT);
if (apiAt === -1) {
throw outsideScope(subject, scope);
}
const api = `${url.origin}${url.pathname.slice(0, apiAt)}${API_ROOT}`;
const path = url.pathname.slice(apiAt + API_ROOT.length);
const segments = path.split("/").filter(Boolean).map(decodeURIComponent);

// Every organization path names the scope's organization.
Expand Down Expand Up @@ -424,7 +444,7 @@ export async function scopeRequest(
return await applyRule(
match.rule,
match.params,
{ scope: { ...scope, project: scope.project }, url, method, send },
{ scope: { ...scope, project: scope.project }, url, api, method, send },
input,
);
}
Expand Down
42 changes: 42 additions & 0 deletions packages/cli/test/lib/target-scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ const BODIES: Record<string, unknown> = {
"organizations/acme/detectors/8/": { projectId: "2" },
"organizations/acme/releases/1.0/": { projects: [API, WEB] },
"organizations/acme/releases/2.0/": { projects: [API] },
// Workflow 5 is connected to `web`; workflow 6 only to `api`.
"organizations/acme/workflows/5/": { id: "5" },
"organizations/acme/workflows/6/": { id: "6" },
"organizations/acme/workflows/?id=5&project=1": [{ id: "5" }],
"organizations/acme/workflows/?id=6&project=1": [],
};

type Sent = { method: string; path: string };
Expand Down Expand Up @@ -221,6 +226,11 @@ describe("a project scope", () => {
"organizations/acme/detectors/7/",
"organizations/acme/detectors/7/",
],
[
"GET",
"organizations/acme/workflows/5/",
"organizations/acme/workflows/?id=5&project=1",
],
])("looks up what %s %s names first", async (method, path, lookup) => {
const sent = await send(WEB_SCOPE, method, path);
expect(sent.map((request) => request.path)).toEqual([lookup, path]);
Expand All @@ -239,6 +249,17 @@ describe("a project scope", () => {
]);
});

test("looks up a workflow once", async () => {
const path = "organizations/acme/workflows/5/";
const first = await send(WEB_SCOPE, "GET", path);
const second = await send(WEB_SCOPE, "GET", path);
expect(first.map((request) => request.path)).toEqual([
"organizations/acme/workflows/?id=5&project=1",
path,
]);
expect(second.map((request) => request.path)).toEqual([path]);
});

test("looks up an issue once", async () => {
await send(WEB_SCOPE, "GET", "organizations/acme/issues/100/");
const sent = await send(WEB_SCOPE, "PUT", "organizations/acme/issues/100/");
Expand Down Expand Up @@ -267,6 +288,7 @@ describe("a project scope", () => {
["GET", "organizations/acme/detectors/8/", "another project's alert"],
["DELETE", "organizations/acme/detectors/8/", "a change to it"],
["GET", "organizations/acme/releases/2.0/", "a release without it"],
["GET", "organizations/acme/workflows/6/", "another project's workflow"],
["GET", "organizations/other/dsn-lookup/", "another org's DSN lookup"],
// Paths no rule covers.
["GET", "issues/200/", "an issue outside an organization path"],
Expand Down Expand Up @@ -370,6 +392,26 @@ describe("a project scope", () => {
expect(sent).toEqual([]);
});

test("sends to an API served under a path", async () => {
const sent: string[] = [];
const fetchScoped = withTargetScope(async (input, init) => {
const url = new URL(new Request(input, init).url);
sent.push(url.pathname + url.search);
return Response.json(url.pathname.endsWith("/web/") ? WEB : []);
});
await withEnv(
{ [SCOPE_ORG_ENV_VAR]: "acme", [SCOPE_PROJECT_ENV_VAR]: "web" },
() =>
fetchScoped(
"https://sentry.example.com/sentry/api/0/organizations/acme/issues/",
),
);
expect(sent).toEqual([
"/sentry/api/0/projects/acme/web/",
"/sentry/api/0/organizations/acme/issues/?project=1",
]);
});

test("refuses a URL outside the API", async () => {
const fetchScoped = withTargetScope(async () => Response.json({}));
await withEnv(
Expand Down
Loading