diff --git a/apps/server/README.md b/apps/server/README.md index 22f0cf79..61f94d18 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -23,6 +23,12 @@ npm run dev Fill the local `.env` without committing it. PostgreSQL and Redis are required to start the service; external integrations are optional only when the exercised code path permits. +## Request telemetry + +Request analytics use an anonymous allowlist with no payloads or person lookups. +See the [event contract and PostHog privacy review](docs/request-telemetry.md) for +route grouping, dashboard migration and historical-data remediation. + ## Redis cache maintenance Every Redis key uses `REDIS_KEY_PREFIX` (default `lovat:`). The example local diff --git a/apps/server/docs/request-telemetry.md b/apps/server/docs/request-telemetry.md new file mode 100644 index 00000000..300783cd --- /dev/null +++ b/apps/server/docs/request-telemetry.md @@ -0,0 +1,60 @@ +# Request telemetry + +The Server emits one anonymous `response` event after each response finishes. +Use `route`, `method`, `statusCode` and `responseTime` for endpoint counts, error +rates and latency. Counts include anonymous callers and polling requests; this +changes the volume and meaning of older identity-dependent `response` events. +Static files served before the reporter, rejected JSON bodies and CORS failures +are outside this middleware's coverage. Compare trends across the deployment +boundary with that change in coverage in mind. + +## Event contract + +The event has a server-generated timestamp and the fixed distinct ID +`lovat-server`. Person-profile processing and GeoIP are disabled. Its properties +are limited to: + +- `service`, `environment`, `railwayDeployment`: deployment configuration. +- `requestId`: fresh random UUID, independent of caller headers and identity. +- `method`: standard HTTP method or `OTHER`. +- `route`: registered Express route pattern under a known literal mount, or + `unmatched`. Parameter values, query strings and unknown paths never appear. +- `statusCode`, `responseTime`: HTTP status and elapsed milliseconds. +- `errorCode`: `SERVER_ERROR` for 5xx, `REQUEST_ERROR` for 4xx, absent on success. + These are coarse classifications, never application error messages or bodies. +- `cache`: `hit`, `miss` or `unknown`. +- `$process_person_profile: false`; the shared client also adds + `eventSource: server` and the configured `environment`. + +There are no request/response bodies, headers, URLs, IPs, user or scouter +identifiers, team codes, person properties or aliases. Telemetry performs no +PostgreSQL/Redis lookup. SDK capture failures log a constant message and cannot +change the HTTP response. + +Mounts are explicitly allowlisted in `posthogMiddleware.ts`. Keep this list in +sync when adding literal router mounts. Parameterized and unknown mounts +intentionally aggregate under `unmatched`; never normalize by copying `baseUrl` +or `originalUrl` into an event. Route patterns must remain source-code constants. + +## Post-deployment privacy review (LVT-334) + +The code change prevents new request events from carrying sensitive data. It +does not delete historical events or change hosted PostHog permissions. A Lovat +PostHog project administrator must complete and record the following before the +issue's historical-data acceptance item can be closed: + +1. Identify the actual project receiving `POSTHOG_PROJECT_API_KEY`, without + copying the key into tickets or logs. Record project ID and reviewer/date. +2. Review historical `response` properties (`reqBody`, `resBody`, `query`, `path`, + `$set`, `$ip`, team codes and person/alias associations), retention, exports, + destinations and any downstream copies. Record the affected time range and + approved remediation; verify deletion through the provider's supported tools. +3. Review project members, organization administrators, roles and service/API + tokens. Record who retains access and why; restrict to the people operating + Lovat. No live access policy has been verified by this implementation. +4. Check event volume and retention after deployment. Migrate existing charts + from `path`/`$pathname` to `route`, remove person-level breakdowns, and verify + endpoint totals, 5xx rate and latency using the anonymous schema. + +Do not paste captured payloads into an issue as review evidence. Record only +safe metadata, decisions and confirmation of completed remediation. diff --git a/apps/server/src/lib/middleware/posthogMiddleware.ts b/apps/server/src/lib/middleware/posthogMiddleware.ts index 2fc23c12..2b4bf272 100644 --- a/apps/server/src/lib/middleware/posthogMiddleware.ts +++ b/apps/server/src/lib/middleware/posthogMiddleware.ts @@ -1,215 +1,92 @@ -import { Request, Response, NextFunction } from "express"; -import { AuthenticatedRequest } from "./requireAuth.js"; +import { randomUUID } from "node:crypto"; +import type { Request, Response, NextFunction } from "express"; import { posthog } from "../../posthogClient.js"; -import { kv } from "../../redisClient.js"; -import prisma from "../../prismaClient.js"; -import z from "zod"; -import { runBackgroundTask } from "../errors.js"; - -const ALIAS_TTL_SECONDS = 60 * 60 * 24 * 30; -const getAliasCacheKey = (deviceId: string, scouterUuid: string) => - `posthog:alias:${deviceId}:${scouterUuid}`; - -const posthogReporter = async ( - req: Request | AuthenticatedRequest, +import { ENVIRONMENT } from "../environment.js"; + +// Only literal mounts declared by app.ts and routes/*.routes.ts are safe. +// Express baseUrl contains actual values for parameterized mounts, so new or +// dynamic mounts fall back to an aggregate instead of exposing those values. +const telemetryMounts = new Set([ + "/v1", + "/v1/slack", + "/v1/manager", + "/v1/analysis", + ...[ + "onboarding", + "picklists", + "mutablepicklists", + "registeredteams", + "scoutershifts", + "tournament", + "scoutreports", + "settings", + "apikey", + ].map((mount) => `/v1/manager/${mount}`), + "/collection", + "/v2/collection", +]); +const methods = new Set([ + "GET", + "POST", + "PUT", + "PATCH", + "DELETE", + "HEAD", + "OPTIONS", +]); + +const posthogReporter = ( + req: Request, res: Response, next: NextFunction, -): Promise => { - const t0 = performance.now(); - const shouldSkipEvent = (statusCode: number) => { - if (statusCode >= 500) { - return false; - } - - if (req.method !== "GET") { - return false; - } - - const routePath = req.route?.path; - if (!routePath) { - return false; +): void => { + const started = performance.now(); + // Never trust a caller-supplied request ID as telemetry. + const requestId = randomUUID(); + + res.once("finish", () => { + const routePath: unknown = req.route?.path; + // Express can clear baseUrl when an error unwinds a router. Count those + // responses as unmatched unless the request matches a literal root route. + const route = + typeof routePath === "string" && + (telemetryMounts.has(req.baseUrl) || + (req.baseUrl === "" && req.path === routePath)) + ? `${req.baseUrl}${routePath}` + : "unmatched"; + const cache = res.getHeader("X-Lovat-Cache"); + + try { + posthog.capture({ + distinctId: "lovat-server", + event: "response", + timestamp: new Date(), + disableGeoip: true, + properties: { + $process_person_profile: false, + service: "server", + environment: ENVIRONMENT, + requestId, + railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID, + method: methods.has(req.method) ? req.method : "OTHER", + route, + statusCode: res.statusCode, + errorCode: + res.statusCode >= 500 + ? "SERVER_ERROR" + : res.statusCode >= 400 + ? "REQUEST_ERROR" + : undefined, + responseTime: Math.round(performance.now() - started), + cache: cache === "hit" || cache === "miss" ? cache : "unknown", + }, + }); + } catch { + // Analytics must never affect the response or log an SDK error that may + // contain a serialized payload or provider credentials. + console.error("Request analytics failed"); } - - const path = `${req.baseUrl}${routePath}`; - return ( - path === "/v1/manager/scouters/:uuid/tournaments" || - path === "/v1/manager/scouters" || - path === "/v1/manager/scouterschedules/:tournament" - ); - }; - const getHeaderValue = (headerName: string) => { - const value = req.headers[headerName]; - - return Array.isArray(value) ? value[0] : value; - }; - - let resBody: unknown; - const originalSend = res.send.bind(res); - res.send = function (body?: unknown) { - if (res.statusCode >= 400) { - try { - resBody = typeof body === "string" ? JSON.parse(body) : body; - } catch { - resBody = body; - } - } - return originalSend(body); - }; - - res.once("finish", () => - runBackgroundTask(async () => { - const t1 = performance.now(); - - const user = "user" in req && req.user; - const teamCode = getHeaderValue("x-team-code"); - const appVersion = getHeaderValue("x-app-version"); - const osName = getHeaderValue("x-os-name"); - const scouterUuid = getHeaderValue("x-scouter-uuid"); - const deviceId = getHeaderValue("x-device-id"); - const appBuild = getHeaderValue("x-build-number"); - - let userProps; - - if (user) { - userProps = { - name: user.username, - email: user.email, - role: user.role, - userType: "user", // as opposed to scouter - teamNumber: user.teamNumber, - $ip: req.ips[0] || req.ip, - }; - } else { - try { - const parsedTeamCode = z.string().optional().parse(teamCode); - const parsedScouterUuid = z.string().optional().parse(scouterUuid); - - if (parsedScouterUuid) { - const scouter = await prisma.scouter.findUnique({ - where: { - uuid: parsedScouterUuid, - }, - }); - - if (scouter) { - userProps = { - uuid: scouter.uuid, - name: scouter.name, - userType: "scouter", - teamNumber: scouter.sourceTeamNumber, - teamCode: parsedTeamCode, - }; - } - } - - if (!userProps && parsedTeamCode) { - const team = await prisma.registeredTeam.findUnique({ - where: { - code: parsedTeamCode, - }, - }); - - userProps = { - teamCode: parsedTeamCode, - userType: "scouter", - teamNumber: team?.number, - }; - } - } catch (error) { - console.error(error); - } - } - - if (userProps?.userType === "user") { - if (shouldSkipEvent(res.statusCode)) { - return; - } - - posthog.capture({ - distinctId: user.id, - event: "response", - properties: { - $ip: req.ips[0] || req.ip, - $set: userProps, - $pathname: req.baseUrl + req.route?.path, - method: req.method, - cache: res.getHeader("X-Lovat-Cache"), - authType: req["tokenType"], - $os_name: osName, - appVersion, - appBuild, - path: req.originalUrl, - query: req.query, - reqBody: req.body, - resBody, - statusCode: res.statusCode, - railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID, - railwayReplica: process.env.RAILWAY_REPLICA_ID, - gitCommit: process.env.RAILWAY_GIT_COMMIT_SHA, - responseTime: Math.round(t1 - t0), - }, - disableGeoip: false, - }); - } - if (userProps?.userType === "scouter") { - if (shouldSkipEvent(res.statusCode)) { - return; - } - - const distinctId = - userProps.uuid ?? - deviceId ?? - (req.ip ? `scouter:ip:${req.ip}` : "scouter:unknown"); - - if (deviceId && userProps.uuid) { - const aliasKey = getAliasCacheKey(deviceId, userProps.uuid); - const alreadyAliased = await kv.get(aliasKey); - - if (!alreadyAliased) { - posthog.alias({ - distinctId: deviceId, - alias: userProps.uuid, - }); - await kv.setEx(aliasKey, "1", ALIAS_TTL_SECONDS); - } - } - - posthog.capture({ - distinctId, - event: "response", - properties: { - $ip: req.ips[0] || req.ip, - $set: userProps, - $pathname: req.baseUrl + req.route?.path, - method: req.method, - cache: res.getHeader("X-Lovat-Cache"), - $os_name: osName, - appVersion, - appBuild, - path: req.originalUrl, - query: req.query, - reqBody: req.body, - resBody, - statusCode: res.statusCode, - railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID, - railwayReplica: process.env.RAILWAY_REPLICA_ID, - gitCommit: process.env.RAILWAY_GIT_COMMIT_SHA, - responseTime: Math.round(t1 - t0), - }, - disableGeoip: false, - }); - } - if (process.env.NODE_ENV === "development") { - console.log( - "%s %s: %d ms, HTTP %d", - req.method, - req.originalUrl, - Math.round(t1 - t0), - res.statusCode, - ); - } - }, "Request analytics failed"), - ); + }); next(); }; diff --git a/apps/server/test/errors.unit.test.ts b/apps/server/test/errors.unit.test.ts index 929e2374..34d4c4aa 100644 --- a/apps/server/test/errors.unit.test.ts +++ b/apps/server/test/errors.unit.test.ts @@ -2,12 +2,32 @@ import express from "express"; import type { Request, Response } from "express"; import request from "supertest"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { AppError, errorHandler, normalizeError } from "../src/lib/errors.js"; +import { + AppError, + errorHandler, + normalizeError, + runBackgroundTask, +} from "../src/lib/errors.js"; afterEach(() => { vi.restoreAllMocks(); }); +it("contains and sanitizes a rejected background task", async () => { + const failure = new Error("private provider details"); + const log = vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + runBackgroundTask(() => Promise.reject(failure), "Socket polling failed"), + ).resolves.toBeUndefined(); + + expect(log).toHaveBeenCalledExactlyOnceWith( + "Socket polling failed", + expect.objectContaining({ name: "Error" }), + ); + expect(JSON.stringify(log.mock.calls)).not.toContain(failure.message); +}); + describe("central error handling", () => { it.each(["constructor", "toString", "__proto__", "unrecognized"])( "treats unknown library error type %s as a generic server failure", diff --git a/apps/server/test/posthogReporter.unit.test.ts b/apps/server/test/posthogReporter.unit.test.ts index 5884e60b..88b0ad45 100644 --- a/apps/server/test/posthogReporter.unit.test.ts +++ b/apps/server/test/posthogReporter.unit.test.ts @@ -1,229 +1,209 @@ +import express, { Router } from "express"; +import type { ErrorRequestHandler } from "express"; +import request from "supertest"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import type { Request, Response } from "express"; -import type { AuthenticatedRequest } from "../src/lib/middleware/requireAuth.js"; -import { testUser } from "./helpers/handlerHarness.js"; -const db = vi.hoisted(() => ({ - scouter: { findUnique: vi.fn() }, - registeredTeam: { findUnique: vi.fn() }, - get: vi.fn(), - setEx: vi.fn(), + +const mocks = vi.hoisted(() => ({ capture: vi.fn(), alias: vi.fn(), -})); -vi.mock("../src/prismaClient.js", () => ({ default: db })); -vi.mock("../src/redisClient.js", () => ({ - kv: { get: db.get, setEx: db.setEx }, + findUnique: vi.fn(), + get: vi.fn(), + setEx: vi.fn(), })); vi.mock("../src/posthogClient.js", () => ({ - posthog: { capture: db.capture, alias: db.alias }, + posthog: { capture: mocks.capture, alias: mocks.alias }, +})); +vi.mock("../src/prismaClient.js", () => ({ + default: { + scouter: { findUnique: mocks.findUnique }, + registeredTeam: { findUnique: mocks.findUnique }, + }, })); +vi.mock("../src/redisClient.js", () => ({ kv: mocks })); +import type { AuthenticatedRequest } from "../src/lib/middleware/requireAuth.js"; import reporter from "../src/lib/middleware/posthogMiddleware.js"; -const run = async ( - overrides: Record = {}, - statusCode = 200, - body: unknown = "ok", -) => { - let finish: () => Promise = async () => undefined; - const req = { - method: "POST", - headers: {}, - ips: [], - ip: "127.0.0.1", - route: { path: "/reports" }, - baseUrl: "/v1/manager", - originalUrl: "/v1/manager/reports", - body: {}, - query: {}, - ...overrides, - } as unknown as Request | AuthenticatedRequest; - const res = { - statusCode, - send: vi.fn(), - once: vi.fn((_event: string, callback: () => Promise) => { - finish = callback; - }), - getHeader: vi.fn().mockReturnValue("MISS"), - }; - const next = vi.fn(); - await reporter(req, res as unknown as Response, next); - expect(next).toHaveBeenCalledTimes(1); - res.send(body); - await finish(); - return res; + +const secret = "private-password-api-key-token-team-code-email-scouting-note"; +const app = express(); +app.use(express.json()); +app.use((req, _res, next) => { + if (req.headers.authorization) { + Object.assign(req as AuthenticatedRequest, { + user: { id: secret, username: secret, email: secret, teamNumber: 8033 }, + }); + } + next(); +}); +app.use(reporter); +app.get("/status", (_req, res) => res.send("ok")); +const manager = Router(); +manager.all("/reports/:uuid", (req, res) => { + res.set("X-Lovat-Cache", "miss"); + res.status(Number(req.query.status) || 200).json({ error: secret }); +}); +manager.get("/failure/:uuid", () => { + throw new Error(secret); +}); +manager.get("/cache/:value", (req, res) => { + res.set("X-Lovat-Cache", req.params.value).send("ok"); +}); +app.use("/v1/manager", manager); +const dynamic = Router(); +dynamic.get("/reports/:uuid", (_req, res) => res.send("ok")); +dynamic.get("/failure/:uuid", () => { + throw new Error(secret); +}); +manager.use("/private/:tenant", dynamic); +app.use("/private/:tenant", dynamic); +app.use((_req, res) => res.status(404).send(secret)); +const errors: ErrorRequestHandler = (_error, _req, res, _next) => { + res.status(500).json({ error: secret }); }; +app.use(errors); + beforeEach(() => { vi.resetAllMocks(); - vi.spyOn(console, "error").mockImplementation(() => undefined); - vi.spyOn(console, "log").mockImplementation(() => undefined); - db.get.mockResolvedValue(null); - db.scouter.findUnique.mockResolvedValue({ - uuid: "s", - name: "Scout", - sourceTeamNumber: 8033, - }); - db.registeredTeam.findUnique.mockResolvedValue({ number: 8033 }); }); afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); }); -it("reports asynchronous analytics failures without rejecting the finish callback", async () => { - db.get.mockRejectedValueOnce(new Error("private redis connection details")); - await expect( - run({ headers: { "x-scouter-uuid": "s", "x-device-id": "d" } }), - ).resolves.toBeDefined(); - expect(console.error).toHaveBeenCalledWith( - "Request analytics failed", - expect.objectContaining({ name: "Error" }), - ); - expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain( - "private redis connection details", - ); - expect(db.capture).not.toHaveBeenCalled(); -}); -it("captures authenticated responses with proxy IP, cache, and client headers", async () => { - await run( - { - user: testUser, - ips: ["192.0.2.1"], - headers: { - "x-app-version": ["26.0", "ignored"], - "x-os-name": "test", - "x-build-number": "10", + +it.each([200, 400, 401, 403, 500])( + "captures only anonymous operational fields for HTTP %s", + async (status) => { + vi.stubEnv("RAILWAY_DEPLOYMENT_ID", "deployment-123"); + const response = await request(app) + .post(`/v1/manager/reports/${secret}?status=${status}&token=${secret}`) + .set("Authorization", `Bearer ${secret}`) + .set("X-Team-Code", secret) + .set("X-Scouter-Uuid", secret) + .set("X-Device-Id", secret) + .set("X-Request-Id", secret) + .set("X-App-Version", secret) + .set("X-Os-Name", secret) + .set("X-Build-Number", secret) + .send({ password: secret, apiKey: secret, privateReport: secret }); + + expect(response.status).toBe(status); + expect(response.body).toEqual({ error: secret }); + expect(mocks.capture).toHaveBeenCalledExactlyOnceWith({ + distinctId: "lovat-server", + event: "response", + timestamp: expect.any(Date), + disableGeoip: true, + properties: { + $process_person_profile: false, + service: "server", + environment: expect.any(String), + requestId: expect.stringMatching(/^[0-9a-f-]{36}$/), + railwayDeployment: "deployment-123", + method: "POST", + route: "/v1/manager/reports/:uuid", + statusCode: status, + errorCode: + status >= 500 + ? "SERVER_ERROR" + : status >= 400 + ? "REQUEST_ERROR" + : undefined, + responseTime: expect.any(Number), + cache: "miss", }, - tokenType: "jwt", - }, - 400, - '{"error":"bad"}', - ); - expect(db.capture).toHaveBeenCalledWith( - expect.objectContaining({ - distinctId: testUser.id, - properties: expect.objectContaining({ - $ip: "192.0.2.1", - appVersion: "26.0", - appBuild: "10", - authType: "jwt", - resBody: { error: "bad" }, - cache: "MISS", - $set: expect.objectContaining({ userType: "user", teamNumber: 8033 }), + }); + expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret); + expect(mocks.findUnique).not.toHaveBeenCalled(); + expect(mocks.get).not.toHaveBeenCalled(); + expect(mocks.setEx).not.toHaveBeenCalled(); + expect(mocks.alias).not.toHaveBeenCalled(); + }, +); + +it.each([ + `/missing/${secret}?token=${secret}`, + `/private/${secret}/reports/${secret}`, +])( + "never falls back to raw paths or dynamic mount values: %s", + async (path) => { + await request(app).get(path); + expect(mocks.capture).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ route: "unmatched" }), }), - }), + ); + expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret); + }, +); + +it("counts anonymous requests with stable routes and independent request IDs", async () => { + await request(app).get("/v1/manager/reports/one"); + await request(app).get("/v1/manager/reports/two"); + const events = mocks.capture.mock.calls.map(([event]) => event); + expect(events).toHaveLength(2); + expect(events[0].properties.route).toBe(events[1].properties.route); + expect(events[0].properties.requestId).not.toBe( + events[1].properties.requestId, ); }); -it.each(["plain error", { error: "bad" }])( - "preserves non-JSON error payloads %j", - async (body) => { - await run({ user: testUser }, 500, body); - expect(db.capture).toHaveBeenCalledWith( + +it.each(["hit", "miss", secret])( + "allowlists cache status %s", + async (value) => { + await request(app).get(`/v1/manager/cache/${value}`); + expect(mocks.capture).toHaveBeenCalledWith( expect.objectContaining({ - properties: expect.objectContaining({ resBody: body }), + properties: expect.objectContaining({ + cache: value === secret ? "unknown" : value, + }), }), ); }, ); -it.each([ - "/scouters/:uuid/tournaments", - "/scouters", - "/scouterschedules/:tournament", -])("skips successful polling responses for %s", async (path) => { - await run({ user: testUser, method: "GET", route: { path } }); - expect(db.capture).not.toHaveBeenCalled(); -}); -it("captures polling failures and unknown routes", async () => { - await run( - { user: testUser, method: "GET", route: { path: "/scouters" } }, - 500, - ); - await run({ user: testUser, method: "GET", route: undefined }); - expect(db.capture).toHaveBeenCalledTimes(2); -}); -it("aliases a device to its scouter once and caches the alias", async () => { - await run({ - headers: { - "x-scouter-uuid": "s", - "x-team-code": "synthetic", - "x-device-id": "device", - }, + +it("keeps responses working and logs no SDK details when capture fails", async () => { + mocks.capture.mockImplementation(() => { + throw new Error(secret); }); - expect(db.alias).toHaveBeenCalledWith({ distinctId: "device", alias: "s" }); - expect(db.setEx).toHaveBeenCalledWith("posthog:alias:device:s", "1", 2592000); - expect(db.capture).toHaveBeenCalledWith( + const log = vi.spyOn(console, "error").mockImplementation(() => undefined); + const response = await request(app).get("/v1/manager/reports/one"); + expect(response.status).toBe(200); + expect(log).toHaveBeenCalledExactlyOnceWith("Request analytics failed"); + expect(JSON.stringify(log.mock.calls)).not.toContain(secret); +}); + +it("counts literal root routes without query values", async () => { + await request(app).get(`/status?token=${secret}`); + expect(mocks.capture).toHaveBeenCalledWith( expect.objectContaining({ - distinctId: "s", - properties: expect.objectContaining({ - $set: expect.objectContaining({ - userType: "scouter", - teamNumber: 8033, - }), - }), + properties: expect.objectContaining({ route: "/status" }), }), ); + expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret); }); -it("does not alias a device again when its cache entry exists", async () => { - db.get.mockResolvedValue("1"); - await run({ headers: { "x-scouter-uuid": "s", "x-device-id": "device" } }); - expect(db.alias).not.toHaveBeenCalled(); -}); -it("captures a scouter without a device identifier", async () => { - await run({ headers: { "x-scouter-uuid": "s" } }); - expect(db.capture).toHaveBeenCalledWith( - expect.objectContaining({ distinctId: "s" }), - ); -}); + it.each([ - [ - { "x-team-code": "synthetic", "x-device-id": "device" }, - "127.0.0.1", - "device", - ], - [{ "x-team-code": "synthetic" }, "127.0.0.1", "scouter:ip:127.0.0.1"], - [{ "x-team-code": "synthetic" }, undefined, "scouter:unknown"], -])( - "falls back to team-code identity when no scouter is present %j", - async (headers, ip, distinctId) => { - await run({ headers, ip }); - expect(db.capture).toHaveBeenCalledWith( - expect.objectContaining({ distinctId }), - ); - }, -); -it("falls back to a team code when the scouter was deleted", async () => { - db.scouter.findUnique.mockResolvedValue(null); - db.registeredTeam.findUnique.mockResolvedValue(null); - await run({ - headers: { "x-scouter-uuid": "deleted", "x-team-code": "synthetic" }, - }); - expect(db.capture).toHaveBeenCalledWith( + `/v1/manager/failure/${secret}`, + `/private/${secret}/failure/${secret}`, + `/v1/manager/private/${secret}/failure/${secret}`, +])("keeps an unwound router unmatched: %s", async (path) => { + const response = await request(app).get(path); + expect(response.status).toBe(500); + expect(mocks.capture).toHaveBeenCalledWith( expect.objectContaining({ properties: expect.objectContaining({ - $set: expect.objectContaining({ teamNumber: undefined }), + route: "unmatched", + statusCode: 500, }), }), ); + expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret); }); -it("skips scouter polling responses", async () => { - await run({ - method: "GET", - route: { path: "/scouters" }, - headers: { "x-scouter-uuid": "s" }, - }); - expect(db.capture).not.toHaveBeenCalled(); -}); -it("keeps anonymous requests working after identity lookup fails", async () => { - db.scouter.findUnique.mockRejectedValue(new Error("database")); - await run({ headers: { "x-scouter-uuid": "s" } }); - expect(db.capture).not.toHaveBeenCalled(); - expect(console.error).toHaveBeenCalled(); -}); -it("logs development requests even without an analytics identity", async () => { - vi.stubEnv("NODE_ENV", "development"); - await run(); - expect(console.log).toHaveBeenCalledWith( - "%s %s: %d ms, HTTP %d", - "POST", - "/v1/manager/reports", - expect.any(Number), - 200, + +it("groups methods outside the telemetry allowlist without copying them", async () => { + await request(app).trace("/v1/manager/reports/one"); + expect(mocks.capture).toHaveBeenCalledWith( + expect.objectContaining({ + properties: expect.objectContaining({ method: "OTHER" }), + }), ); });