Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/openstatusHQ/openstatus. ๐ซ Status page with uptime monitoring & API monitoring as code ๐ซ openstatus.dev
bun drizzle-orm monitoring monitoring-as-code nextjs observability on-call open-source shadcn-ui status-page statuspage synthetic-monitoring tinybird turso uptime uptime-checker uptime-monitor
Something went wrong. Try again.
TypeScript
at incident-api
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import { Code, ConnectError } from "@connectrpc/connect";import type { Workspace } from "@openstatus/db/src/schema";import { ConflictError, ForbiddenError, NotFoundError, type ServiceContext, ValidationError,} from "@openstatus/services";import { createApiKey } from "@openstatus/services/api-key";import { createWorkspaceFixture, withTestTransaction,} from "@openstatus/services/test/helpers";import { expect } from "@std/expect";import { beforeAll, describe, test } from "@std/testing/bdd";
import { toConnectError, toServiceCtx } from "./adapter";
const wsStub = { id: 1, slug: "ws", name: "ws" } as unknown as Workspace;
describe("toServiceCtx (RPC)", () => { test("propagates apiKey.scopes onto actor.scopes", () => { const ctx = toServiceCtx({ workspace: wsStub, requestId: "req-1", apiKey: { id: "k1", createdById: 7, scopes: ["read"] }, }); expect(ctx.actor.type).toBe("apiKey"); if (ctx.actor.type === "apiKey") { expect(ctx.actor.scopes).toEqual(["read"]); expect(ctx.actor.keyId).toBe("k1"); expect(ctx.actor.userId).toBe(7); } });
test("propagates ['*'] super-admin scopes intact", () => { const ctx = toServiceCtx({ workspace: wsStub, requestId: "req-2", apiKey: { id: "sa", scopes: ["*"] }, }); if (ctx.actor.type === "apiKey") { expect(ctx.actor.scopes).toEqual(["*"]); } });});
/** * `toConnectError` is the only RPC-specific layer between a thrown * `ServiceError` and what the wire surfaces. The unique RBAC concern * here is the FORBIDDEN โ PermissionDenied mapping; the other branches * are exercised below for sanity (so the FORBIDDEN test would catch a * future refactor that flattens every code into Internal). *//** * `toConnectError` always throws โ capture the thrown value and * assert on it. Avoids `expect.unreachable` (typed `never`, which * trips TS's unreachable-code analysis on the catch block). */function captureThrow(fn: () => void): unknown { try { fn(); } catch (err) { return err; } throw new Error("expected fn to throw, but it returned");}
describe("toConnectError", () => { test("ForbiddenError โ ConnectError(PermissionDenied)", () => { const err = captureThrow(() => toConnectError(new ForbiddenError("API key lacks required scope: write")), ); expect(err).toBeInstanceOf(ConnectError); expect((err as ConnectError).code).toBe(Code.PermissionDenied); expect((err as ConnectError).rawMessage).toContain( "API key lacks required scope", ); });
test("NotFoundError โ ConnectError(NotFound)", () => { const err = captureThrow(() => toConnectError(new NotFoundError("monitor", 42)), ); expect((err as ConnectError).code).toBe(Code.NotFound); });
test("ValidationError โ ConnectError(InvalidArgument)", () => { const err = captureThrow(() => toConnectError(new ValidationError("bad input")), ); expect((err as ConnectError).code).toBe(Code.InvalidArgument); });
test("ConflictError โ ConnectError(FailedPrecondition)", () => { const err = captureThrow(() => toConnectError(new ConflictError("Incident #1 is closed")), ); expect((err as ConnectError).code).toBe(Code.FailedPrecondition); });
test("re-throws an existing ConnectError unchanged", () => { const original = new ConnectError("custom", Code.Aborted); const err = captureThrow(() => toConnectError(original)); expect(err).toBe(original); });
// Unclassified errors propagate raw so `errorInterceptor` โ the only // layer holding the request id โ can log and redact them in one place. // The redaction itself is covered in `interceptors/__tests__/error.test.ts`. test("rethrows an unclassified error untouched", () => { const drizzleish = new Error("Failed query: insert into ..."); const err = captureThrow(() => toConnectError(drizzleish)); expect(err).toBe(drizzleish); expect(err).not.toBeInstanceOf(ConnectError); });});
/** * RPC runtime sample (per the plan's test plan #8). End-to-end through * the layers a real request would hit: * 1. Build an apiKey-actor `ServiceContext` via the RPC adapter * (with `['read']` scopes) โ the same shape `authInterceptor` would * produce for a read-only key. * 2. Invoke a service write verb (`createApiKey` is convenient โ same * package, no foreign-key fixtures). * 3. Catch the `ForbiddenError` and pipe it through `toConnectError`, * assert the wire code is `PermissionDenied`. * * One representative method is enough โ service-level enforcement * covers the rest, this test pins the *RPC translation* of the * denial. */describe("RPC runtime โ read-only key on a write service verb", () => { let teamWorkspace: Workspace;
beforeAll(async () => { teamWorkspace = (await createWorkspaceFixture("team")).workspace; });
test("throws ForbiddenError โ ConnectError(PermissionDenied)", async () => { await withTestTransaction(async (tx) => { const ctx: ServiceContext = { ...toServiceCtx({ workspace: teamWorkspace, requestId: "req-rpc-runtime", apiKey: { id: "read-only-key", createdById: 1, scopes: ["read"] }, }), db: tx, };
let captured: unknown; try { await createApiKey({ ctx, input: { name: "rpc-runtime-test" }, }); } catch (err) { captured = err; }
expect(captured).toBeInstanceOf(ForbiddenError);
// Pipe the service error through the RPC mapper โ the same // path the Connect handler in production takes. const mapped = captureThrow(() => toConnectError(captured)); expect(mapped).toBeInstanceOf(ConnectError); expect((mapped as ConnectError).code).toBe(Code.PermissionDenied); }); });});