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
2 changes: 1 addition & 1 deletion apps/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Fill the local `.env` without committing it. PostgreSQL and Redis are required t

## Request telemetry

Request analytics use an anonymous allowlist with no payloads or person lookups.
Request analytics use an allowlist with no payloads or extra person lookups.
See the [event contract and PostHog privacy review](docs/request-telemetry.md) for
route grouping, dashboard migration and historical-data remediation.

Expand Down
48 changes: 33 additions & 15 deletions apps/server/docs/request-telemetry.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Request telemetry

The Server emits one anonymous `response` event after each response finishes.
The Server emits one `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.
Expand All @@ -10,26 +10,42 @@ 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:
Every event has a server-generated timestamp and disables GeoIP. A verified
JWT or API key uses the existing account ID and enables person-profile
processing. The authenticated account's role, public FRC team number, and
`userType: user` are the only person properties that this event updates. API key
events are attributed to the owner, not the key or the person using it.
Requests without verified account authentication use the fixed distinct ID
`lovat-server` with person-profile processing disabled. Collection verifies team
access or report ownership on some routes, but a shared team code and supplied
scouter UUID are not independent proof of a person's identity, so Collection
requests remain anonymous.

- `service`, `environment`, `railwayDeployment`: deployment configuration.
Event properties are limited to:

- `service`, `environment`, `railwayDeployment`, `railwayReplica`, `gitCommit`:
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.
`unmatched`. For matched patterns, `$pathname` is a compatibility alias.
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`.
- `appVersion`, `appBuild`, `$os_name`: unverified client hints in narrow
numeric release formats or a known OS label. Missing or invalid hints are
omitted; do not use these as evidence of authentication.
- `userType`, `authType`, `teamNumber`, `role`, `$set`: for verified account
authentication only. `$process_person_profile` is true only in that case.
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.
There are no request/response bodies, raw or full URLs, query strings, IPs,
names, emails, team codes, auth tokens, scouter IDs, device IDs, or identity
aliases. No raw header collection or extra PostgreSQL/Redis lookup is performed.
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
Expand All @@ -52,9 +68,11 @@ issue's historical-data acceptance item can be closed:
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.
4. Check event volume and retention after deployment. Prefer `route` for new
endpoint charts and verify endpoint totals, 5xx rate and latency. For
authenticated-account activity, filter `userType = user` and, if counting
only interactive account activity, `authType = jwt`. Request telemetry
cannot measure unique Collection users.

Do not paste captured payloads into an issue as review evidence. Record only
safe metadata, decisions and confirmation of completed remediation.
69 changes: 67 additions & 2 deletions apps/server/src/lib/middleware/posthogMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import type { Request, Response, NextFunction } from "express";
import { posthog } from "../../posthogClient.js";
import { ENVIRONMENT } from "../environment.js";
import type { AuthenticatedRequest } from "./requireAuth.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
Expand Down Expand Up @@ -35,6 +36,36 @@ const methods = new Set([
"OPTIONS",
]);

const operatingSystems = new Set([
"android",
"ios",
"web",
"macos",
"windows",
"linux",
"fuchsia",
]);

// These are untrusted app hints. Only report narrow release formats and
// supported platform labels; never record arbitrary client header strings.
const appVersionPattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/;
const appBuildPattern = /^\d{1,5}(?:\.\d{1,5}){0,2}$/;

function readReleaseHeader(
value: string | string[] | undefined,
pattern: RegExp,
): string | undefined {
return typeof value === "string" && pattern.test(value) ? value : undefined;
}

function readOperatingSystem(
value: string | string[] | undefined,
): string | undefined {
return typeof value === "string" && operatingSystems.has(value)
? value
: undefined;
}

const posthogReporter = (
req: Request,
res: Response,
Expand All @@ -57,19 +88,53 @@ const posthogReporter = (
const cache = res.getHeader("X-Lovat-Cache");

try {
// Only requireAuth sets both fields, after validating a JWT or API key.
// Collection team membership checks do not authenticate an individual.
const { user, tokenType } = req as Partial<AuthenticatedRequest>;
const caller =
user?.id && (tokenType === "jwt" || tokenType === "apiKey")
? user
: undefined;
const os =
readOperatingSystem(req.headers["x-operating-system"]) ??
readOperatingSystem(req.headers["x-os-name"]);

posthog.capture({
distinctId: "lovat-server",
distinctId: caller?.id ?? "lovat-server",
event: "response",
timestamp: new Date(),
disableGeoip: true,
properties: {
$process_person_profile: false,
$process_person_profile: caller !== undefined,
service: "server",
environment: ENVIRONMENT,
requestId,
railwayDeployment: process.env.RAILWAY_DEPLOYMENT_ID,
railwayReplica: process.env.RAILWAY_REPLICA_ID,
gitCommit: process.env.RAILWAY_GIT_COMMIT_SHA,
method: methods.has(req.method) ? req.method : "OTHER",
route,
$pathname: route === "unmatched" ? undefined : route,
userType: caller ? "user" : undefined,
authType: caller ? tokenType : undefined,
teamNumber: caller?.teamNumber ?? undefined,
role: caller?.role,
$set: caller
? {
userType: "user",
teamNumber: caller.teamNumber,
role: caller.role,
}
: undefined,
appVersion: readReleaseHeader(
req.headers["x-app-version"],
appVersionPattern,
),
appBuild: readReleaseHeader(
req.headers["x-build-number"],
appBuildPattern,
),
$os_name: os,
statusCode: res.statusCode,
errorCode:
res.statusCode >= 500
Expand Down
122 changes: 112 additions & 10 deletions apps/server/test/posthogReporter.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,33 @@ vi.mock("../src/prismaClient.js", () => ({
},
}));
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 secret = "private-password-api-key-token-team-code-email-scouting-note";
const callerId = "auth0|000000000000000000000001";
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) => {
const tokenType = {
"Bearer test-verified-jwt": "jwt",
"Bearer test-verified-key": "apiKey",
}[req.headers.authorization ?? ""];
if (tokenType) {
// Simulate requireAuth succeeding after the reporter installs its listener.
Object.assign(req, {
tokenType,
user: {
id: callerId,
username: secret,
email: secret,
teamNumber: 8033,
role: "SCOUTING_LEAD",
},
});
}
res.set("X-Lovat-Cache", "miss");
res.status(Number(req.query.status) || 200).json({ error: secret });
});
Expand Down Expand Up @@ -73,6 +82,11 @@ it.each([200, 400, 401, 403, 500])(
"captures only anonymous operational fields for HTTP %s",
async (status) => {
vi.stubEnv("RAILWAY_DEPLOYMENT_ID", "deployment-123");
vi.stubEnv("RAILWAY_REPLICA_ID", "replica-123");
vi.stubEnv(
"RAILWAY_GIT_COMMIT_SHA",
"1234567890123456789012345678901234567890",
);
const response = await request(app)
.post(`/v1/manager/reports/${secret}?status=${status}&token=${secret}`)
.set("Authorization", `Bearer ${secret}`)
Expand All @@ -98,8 +112,19 @@ it.each([200, 400, 401, 403, 500])(
environment: expect.any(String),
requestId: expect.stringMatching(/^[0-9a-f-]{36}$/),
railwayDeployment: "deployment-123",
railwayReplica: "replica-123",
gitCommit: "1234567890123456789012345678901234567890",
method: "POST",
route: "/v1/manager/reports/:uuid",
$pathname: "/v1/manager/reports/:uuid",
userType: undefined,
authType: undefined,
teamNumber: undefined,
role: undefined,
$set: undefined,
appVersion: undefined,
appBuild: undefined,
$os_name: undefined,
statusCode: status,
errorCode:
status >= 500
Expand All @@ -119,6 +144,80 @@ it.each([200, 400, 401, 403, 500])(
},
);

it.each([
["jwt", "Bearer test-verified-jwt"],
["apiKey", "Bearer test-verified-key"],
])(
"uses the authenticated %s caller without capturing private fields",
async (authType, authorization) => {
const response = await request(app)
.post(`/v1/manager/reports/${secret}?status=400&code=${secret}`)
.set("Authorization", authorization)
.set("X-Team-Code", secret)
.set("X-Scouter-Uuid", secret)
.set("X-Device-Id", secret)
.set("X-App-Version", "26.0.4")
.set("X-Build-Number", "33")
.set("X-Operating-System", "web")
.send({ password: secret, privateReport: secret });

expect(response.status).toBe(400);
expect(mocks.capture).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
distinctId: callerId,
disableGeoip: true,
properties: expect.objectContaining({
$process_person_profile: true,
route: "/v1/manager/reports/:uuid",
$pathname: "/v1/manager/reports/:uuid",
userType: "user",
authType,
teamNumber: 8033,
role: "SCOUTING_LEAD",
$set: {
userType: "user",
teamNumber: 8033,
role: "SCOUTING_LEAD",
},
appVersion: "26.0.4",
appBuild: "33",
$os_name: "web",
}),
}),
);
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret);
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(
authorization,
);
expect(mocks.alias).not.toHaveBeenCalled();
},
);

it("keeps Collection-style requests anonymous and rejects code-shaped build hints", async () => {
const teamCode = "012345";
await request(app)
.get(`/status?code=${teamCode}`)
.set("X-Team-Code", teamCode)
.set("X-Scouter-Uuid", "eafd426c-1d70-4d38-8994-912dd9671246")
.set("X-Device-Id", "cabbcaf6-161c-42e1-917d-d3f046dc3a59")
.set("X-App-Version", "26.1.0")
.set("X-Build-Number", teamCode)
.set("X-Os-Name", "android");

expect(mocks.capture).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
distinctId: "lovat-server",
properties: expect.objectContaining({
$process_person_profile: false,
appVersion: "26.1.0",
appBuild: undefined,
$os_name: "android",
}),
}),
);
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(teamCode);
});

it.each([
`/missing/${secret}?token=${secret}`,
`/private/${secret}/reports/${secret}`,
Expand All @@ -128,7 +227,10 @@ it.each([
await request(app).get(path);
expect(mocks.capture).toHaveBeenCalledWith(
expect.objectContaining({
properties: expect.objectContaining({ route: "unmatched" }),
properties: expect.objectContaining({
route: "unmatched",
$pathname: undefined,
}),
}),
);
expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain(secret);
Expand Down
Loading