Skip to content
314 changes: 156 additions & 158 deletions packages/cli/src/lib/target-scope-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,18 @@
* by `scopeRequest` in `target-scope.ts`. Paths are relative to `/api/0/`:
* `:name` is one segment, `**` is any number of them.
*
* In a project scope, a request no rule matches is refused. Add a rule when
* a command needs a new endpoint, and pick how it stays in the project.
* Most rules come from Sentry's schema: endpoints declare how they stay in
* a project with the `x-sentry-project-scope` OpenAPI extension, which the
* `@sentry/api` catalog carries as `projectScope` (see
* {@link catalogRules}). The rest are written here ({@link OVERRIDES}).
*
* In a project scope, a request no rule matches is refused. When a command
* needs a new endpoint, declare its scope in Sentry; write a rule here only
* when the schema can't say it.
*/

import { type ApiOperation, operations } from "@sentry/api/operations";

/** How a matched request stays in the scope's project. */
type ScopeEnforcement =
/** The path names the scope's project, as `:project`. */
Expand All @@ -28,7 +36,9 @@ type ScopeEnforcement =
/** The path the response proves in scope, for {@link LookUpFirst}. */
path?: (params: Record<string, string>) => string;
}
| LookUpFirst;
| LookUpFirst
/** Refused even though a broader rule would cover it. */
| { kind: "refused" };

/**
* A request that reads or changes something an ID names, without saying
Expand Down Expand Up @@ -77,43 +87,6 @@ export const ACCOUNT_READS: readonly SimpleRule[] = [
{ pattern: "seer/models/" },
];

/**
* Read-only organization metadata a project scope may read: settings,
* members, integrations and saved views, with no project's issues, events
* or other data in them.
*/
export const ORG_READS: readonly SimpleRule[] = [
{ pattern: "organizations/:org/" },
{ pattern: "organizations/:org/projects/" },
{ pattern: "organizations/:org/teams/" },
{ pattern: "organizations/:org/user-teams/" },
{ pattern: "organizations/:org/members/" },
{ pattern: "organizations/:org/members/:member/" },
{ pattern: "organizations/:org/environments/" },
// The project a DSN belongs to: its ID, slug and name.
{ pattern: "organizations/:org/dsn-lookup/" },
{ pattern: "organizations/:org/chunk-upload/" },
{ pattern: "organizations/:org/integrations/" },
{ pattern: "organizations/:org/integrations/:integration/**" },
{ pattern: "organizations/:org/config/integrations/" },
{ pattern: "organizations/:org/available-actions/" },
{ pattern: "organizations/:org/sentry-apps/" },
{ pattern: "organizations/:org/sentry-app-installations/" },
{ pattern: "organizations/:org/sentry-app-components/" },
{ pattern: "organizations/:org/repos/" },
{ pattern: "organizations/:org/repos/:repo/commits/" },
{ pattern: "organizations/:org/code-mappings/" },
{ pattern: "organizations/:org/dashboards/" },
{ pattern: "organizations/:org/dashboards/:dashboard/" },
{ pattern: "organizations/:org/dashboards/:dashboard/revisions/" },
{ pattern: "organizations/:org/discover/saved/" },
{ pattern: "organizations/:org/discover/saved/:query/" },
{ pattern: "organizations/:org/group-search-views/" },
{ pattern: "organizations/:org/workflows/:workflow/" },
{ pattern: "teams/:org/:team/**" },
{ pattern: "customers/:org/" },
];

/** `value` as an object, or `{}` when it is not one. */
export function record(value: unknown): Record<string, unknown> {
return typeof value === "object" && value !== null
Expand All @@ -127,6 +100,124 @@ function ref(value: unknown): string | undefined {
: undefined;
}

/**
* The values at a JSON pointer (RFC 6901), where a `*` segment is every
* element of an array, such as each of a release's `projects`.
*/
function valuesAt(body: unknown, pointer: string): unknown[] {
let values = [body];
for (const raw of pointer.split("/").slice(1)) {
const segment = raw.replaceAll("~1", "/").replaceAll("~0", "~");
values = values.flatMap((value) => {
if (segment === "*") {
return Array.isArray(value) ? value : [];
}
return Array.isArray(value)
? [value[Number(segment)]]
: [record(value)[segment]];
});
}
return values;
}

/** The rule pattern of a catalog path: `{name}` becomes `:name`. */
function patternOf(path: string): string {
return path.replace(/^\//, "").replace(/\{([^}]+)\}/g, ":$1");
}

/**
* What a lookup's last path param names, for errors: `Issue 200` for
* `organizations/:org/issues/:issue_id/`.
*/
function subjectOf(pattern: string) {
const parts = pattern.split("/").filter(Boolean);
const param = parts.at(-1)?.slice(1) ?? "";
const kind = (parts.at(-2) ?? "").replace(/s$/, "").replaceAll("-", " ");
const label = kind.charAt(0).toUpperCase() + kind.slice(1);
return (params: Record<string, string>): string =>
`${label} ${params[param] ?? ""}`;
}

/** The concrete path a pattern names, from a rule's params. */
function pathFrom(pattern: string) {
return (params: Record<string, string>): string =>
pattern.replace(/:([^/]+)/g, (_, name: string) =>
encodeURIComponent(params[name] ?? ""),
);
}

const RESPONSE_PREFIX = "response:";

/**
* The rules Sentry declares for its endpoints with `x-sentry-project-scope`:
*
* - `org-metadata`: an organization read with no project's data in it.
* - `filter`: an organization endpoint filtered to the scope's project.
* - `response:<pointer>`: a lookup by an ID alone, checked by the project
* IDs at the pointer of its response. A request under its path (`PUT`
* of the same path, or any sub-resource) looks it up first.
*/
function catalogRules(
catalog: readonly Pick<ApiOperation, "method" | "path" | "projectScope">[],
): {
orgReads: SimpleRule[];
rules: ScopeRule[];
} {
const orgReads: SimpleRule[] = [];
const checked: ScopeRule[] = [];
const lookedUpFirst: ScopeRule[] = [];
for (const { method, path, projectScope: scope } of catalog) {
if (!scope) {
continue;
}
const pattern = patternOf(path);
const methods = method === "GET" ? READS : [method];
if (scope === "org-metadata" && method === "GET") {
orgReads.push({ pattern, methods });
} else if (scope === "filter") {
checked.push({ pattern, methods, enforce: { kind: "project-filter" } });
} else if (scope.startsWith(RESPONSE_PREFIX) && method === "GET") {
const pointer = scope.slice(RESPONSE_PREFIX.length);
const own = pathFrom(pattern);
const subject = subjectOf(pattern);
checked.push({
pattern,
subject,
enforce: {
kind: "response",
projects: (body) => {
const refs = valuesAt(body, pointer).map(ref);
return refs.length > 0 ? refs : [undefined];
},
path: own,
},
});
lookedUpFirst.push({
pattern: `${pattern}**`,
methods: ANY_METHOD,
subject,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: own(params) }],
},
});
}
}
return { orgReads, rules: [...checked, ...lookedUpFirst] };
}

const CATALOG = catalogRules(operations);

/**
* 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,
];

/**
* One project's ref: its slug when it has one, which the scope can check
* without looking up its own project's ID.
Expand All @@ -135,7 +226,7 @@ function refOf(slug: unknown, id: unknown): string | undefined {
return ref(slug) ?? ref(id);
}

/** `{ project: { slug, id } }`, as issues and monitors carry it. */
/** `{ project: { slug, id } }`, as an issue carries it. */
function projectOf(body: unknown): (string | undefined)[] {
const project = record(record(body)["project"]);
return [refOf(project["slug"], project["id"])];
Expand All @@ -157,17 +248,7 @@ function traceProjects(spans: unknown): (string | undefined)[] {
});
}

/** `organizations/<org>/<kind>/<id>/`, from a rule's params. */
function orgPath(kind: string, param: string) {
return (params: Record<string, string>): string =>
`organizations/${encodeURIComponent(params["org"] ?? "")}/${kind}/${encodeURIComponent(params[param] ?? "")}/`;
}

const issuePath = orgPath("issues", "issue");
const tracePath = orgPath("trace", "trace");
const monitorPath = orgPath("monitors", "monitor");
const detectorPath = orgPath("detectors", "detector");
const releasePath = orgPath("releases", "version");
const tracePath = pathFrom("organizations/:org/trace/:trace/");

/** A trace lookup for `trace-meta` and `trace-logs`, over the same period. */
function traceLookup(
Expand All @@ -187,54 +268,12 @@ function traceLookup(
return { path: tracePath(params), query: query.toString() };
}

const PROJECT_FILTERED = [
"issues/",
"events/",
"events-timeseries/",
"events-dropped/",
"trace-items/attributes/",
"replays/",
"replay-count/",
"monitors/",
"detectors/",
"workflows/",
"releases/",
"agents/conversations/",
].map((path): ScopeRule => ({
pattern: `organizations/:org/${path}`,
// Bulk issue changes (`PUT issues/?id=...`) are filtered the same way.
methods: path === "issues/" ? ["GET", "HEAD", "PUT", "DELETE"] : READS,
enforce: { kind: "project-filter" },
}));

/** The rules of a project scope, first match wins. */
export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [
{
pattern: "projects/:org/:project/**",
methods: ANY_METHOD,
subject: ({ org, project }) => `Project ${org}/${project}`,
enforce: { kind: "project-path" },
},
{
pattern: "organizations/:org/projects/:project/**",
methods: ANY_METHOD,
subject: ({ org, project }) => `Project ${org}/${project}`,
enforce: { kind: "project-path" },
},
{
pattern: "organizations/:org/issues/:issue/",
subject: ({ issue }) => `Issue ${issue}`,
enforce: { kind: "response", projects: projectOf, path: issuePath },
},
{
pattern: "organizations/:org/issues/:issue/**",
methods: ANY_METHOD,
subject: ({ issue }) => `Issue ${issue}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: issuePath(params) }],
},
},
/**
* 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.
*/
const OVERRIDES: readonly ScopeRule[] = [
{
pattern: "organizations/:org/shortids/:issue/",
subject: ({ issue }) => `Issue ${issue?.toUpperCase()}`,
Expand Down Expand Up @@ -292,71 +331,30 @@ export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [
},
},
{
pattern: "organizations/:org/replays/:replay/",
subject: ({ replay }) => `Replay ${replay}`,
enforce: {
kind: "response",
projects: (body) => [ref(record(record(body)["data"])["project_id"])],
},
},
{
pattern: "organizations/:org/monitors/:monitor/",
subject: ({ monitor }) => `Monitor ${monitor}`,
enforce: { kind: "response", projects: projectOf, path: monitorPath },
// A release can span projects, so changing one reaches past the scope.
pattern: "organizations/:org/releases/:version/**",
methods: ["POST", "PUT", "PATCH", "DELETE"],
subject: ({ version }) => `Release ${version}`,
enforce: { kind: "refused" },
},
];

/** The rules of a project scope, first match wins. */
export const PROJECT_SCOPE_RULES: readonly ScopeRule[] = [
{
pattern: "organizations/:org/monitors/:monitor/**",
pattern: "projects/:org/:project/**",
methods: ANY_METHOD,
subject: ({ monitor }) => `Monitor ${monitor}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: monitorPath(params) }],
},
},
{
pattern: "organizations/:org/detectors/:detector/",
subject: ({ detector }) => `Alert ${detector}`,
enforce: {
kind: "response",
projects: (body) => [ref(record(body)["projectId"])],
path: detectorPath,
},
subject: ({ org, project }) => `Project ${org}/${project}`,
enforce: { kind: "project-path" },
},
{
pattern: "organizations/:org/detectors/:detector/**",
pattern: "organizations/:org/projects/:project/**",
methods: ANY_METHOD,
subject: ({ detector }) => `Alert ${detector}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: detectorPath(params) }],
},
},
{
// A release can span projects; one with the scope's project is in it.
pattern: "organizations/:org/releases/:version/",
subject: ({ version }) => `Release ${version}`,
enforce: {
kind: "response",
projects: (body) => {
const projects = record(body)["projects"];
return Array.isArray(projects)
? projects.map((project) =>
refOf(record(project)["slug"], record(project)["id"]),
)
: [undefined];
},
path: releasePath,
},
},
{
pattern: "organizations/:org/releases/:version/**",
subject: ({ version }) => `Release ${version}`,
enforce: {
kind: "look-up-first",
lookups: (params) => [{ path: releasePath(params) }],
},
subject: ({ org, project }) => `Project ${org}/${project}`,
enforce: { kind: "project-path" },
},
...PROJECT_FILTERED,
...OVERRIDES,
...CATALOG.rules,
];

type Match<T> = { rule: T; params: Record<string, string> };
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/test/lib/sdk-limit-to-target.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ function sentryApi(): typeof fetch {
if (path === "/api/0/organizations/acme/") {
return Response.json({ id: "9", slug: "acme", name: "Acme" });
}
if (path === "/api/0/projects/acme/web/") {
return Response.json({ id: "1", slug: "web" });
}
if (path === "/api/0/organizations/acme/issues/200/") {
return Response.json(API_ISSUE);
}
Expand Down
Loading
Loading