Skip to content

Commit 64fd9ad

Browse files
authored
feat(analytics): add admin analytics for hosted sites (#262)
* feat(analytics): add admin analytics for hosted sites Serve GET /api/v2/admin/analytics/sites for administrators: publishing activity, publishers, current site states, endings, TTL extensions, lifetimes, visibility, and the largest live sites. The endpoint reads existing site, version, and audit records and adds no migrations. * fix(analytics): harden Sites analytics filters and ending times Reject NUL characters in Sites filters, end expired sites at their expiry time rather than the cleanup time, and keep negative lifetimes in the first bin. * refactor(analytics): drop a narrating comment
1 parent 9f4dba3 commit 64fd9ad

8 files changed

Lines changed: 1153 additions & 0 deletions

File tree

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Copyright 2026 GoodRx, Inc.
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6+
* Unless required by applicable law or agreed to in writing, software
7+
* distributed under the License is distributed on an "AS IS" BASIS,
8+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
* See the License for the specific language governing permissions and
10+
* limitations under the License.
11+
*/
12+
13+
import { NextRequest } from 'next/server';
14+
15+
const mockGetUser = jest.fn();
16+
const mockIdentity = jest.fn();
17+
const mockSummary = jest.fn();
18+
19+
jest.mock('server/lib/dependencies', () => ({ defaultDb: {} }));
20+
jest.mock('server/lib/get-user', () => ({
21+
getUser: (...args: unknown[]) => mockGetUser(...args),
22+
getRequestUserIdentity: (...args: unknown[]) => mockIdentity(...args),
23+
}));
24+
jest.mock('server/services/analytics/SitesAnalyticsService', () => ({
25+
...jest.requireActual('server/services/analytics/SitesAnalyticsService'),
26+
__esModule: true,
27+
default: jest.fn().mockImplementation(() => ({ getSummary: mockSummary })),
28+
}));
29+
30+
import { GET } from './route';
31+
32+
function request(query = ''): NextRequest {
33+
return {
34+
headers: new Headers([['x-request-id', 'sites-analytics-test']]),
35+
nextUrl: new URL(`http://localhost/api/v2/admin/analytics/sites${query}`),
36+
} as unknown as NextRequest;
37+
}
38+
39+
describe('GET /api/v2/admin/analytics/sites', () => {
40+
const originalAuth = process.env.ENABLE_AUTH;
41+
beforeEach(() => {
42+
jest.clearAllMocks();
43+
process.env.ENABLE_AUTH = 'true';
44+
mockGetUser.mockReturnValue({ sub: 'admin', realm_access: { roles: ['admin'] } });
45+
mockIdentity.mockReturnValue({ userId: 'admin', roles: ['admin'] });
46+
mockSummary.mockResolvedValue({ totals: { published: 1 } });
47+
});
48+
afterEach(() => {
49+
if (originalAuth === undefined) delete process.env.ENABLE_AUTH;
50+
else process.env.ENABLE_AUTH = originalAuth;
51+
});
52+
53+
it('returns the summary without caching and passes parsed filters', async () => {
54+
const response = await GET(request('?visibility=private&ownerKind=user'));
55+
expect(response.status).toBe(200);
56+
expect(response.headers.get('Cache-Control')).toBe('private, no-store');
57+
expect(mockSummary).toHaveBeenCalledWith(expect.objectContaining({ visibility: 'private', ownerKind: 'user' }));
58+
});
59+
60+
it('rejects invalid filters with 400 before data access', async () => {
61+
expect((await GET(request('?visibility=internal'))).status).toBe(400);
62+
expect(mockSummary).not.toHaveBeenCalled();
63+
});
64+
65+
it('rejects unauthenticated requests before data access', async () => {
66+
mockIdentity.mockReturnValue(null);
67+
expect((await GET(request())).status).toBe(401);
68+
expect(mockSummary).not.toHaveBeenCalled();
69+
});
70+
71+
it('rejects non-admin requests before data access', async () => {
72+
mockGetUser.mockReturnValue({ sub: 'user', realm_access: { roles: ['user'] } });
73+
mockIdentity.mockReturnValue({ userId: 'user', roles: ['user'] });
74+
expect((await GET(request())).status).toBe(403);
75+
expect(mockSummary).not.toHaveBeenCalled();
76+
});
77+
78+
it('rejects API-key bearer credentials', async () => {
79+
const req = request();
80+
req.headers.set('authorization', 'Bearer lfc_test');
81+
expect((await GET(req)).status).toBe(403);
82+
expect(mockSummary).not.toHaveBeenCalled();
83+
});
84+
});
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Copyright 2026 GoodRx, Inc.
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6+
* Unless required by applicable law or agreed to in writing, software
7+
* distributed under the License is distributed on an "AS IS" BASIS,
8+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
* See the License for the specific language governing permissions and
10+
* limitations under the License.
11+
*/
12+
13+
import { NextRequest } from 'next/server';
14+
import { createApiHandler } from 'server/lib/createApiHandler';
15+
import { successResponse, withNoStore } from 'server/lib/response';
16+
import SitesAnalyticsService, { parseSitesAnalyticsQuery } from 'server/services/analytics/SitesAnalyticsService';
17+
18+
export const runtime = 'nodejs';
19+
20+
/**
21+
* @openapi
22+
* /api/v2/admin/analytics/sites:
23+
* get:
24+
* summary: Summarize hosted site publishing, state, and retention
25+
* description: Administrator-only aggregation over retained site records, site versions, and the site audit trail. Current state uses the request time; publishing, endings, extensions, and lifetimes use the calendar window.
26+
* operationId: getSitesAnalytics
27+
* tags: [Admin Analytics]
28+
* parameters:
29+
* - {in: query, name: from, schema: {type: string, format: date}, description: Inclusive local calendar date.}
30+
* - {in: query, name: to, schema: {type: string, format: date}, description: Exclusive local calendar date.}
31+
* - {in: query, name: timezone, schema: {type: string, default: UTC}, description: IANA timezone.}
32+
* - {in: query, name: compare, schema: {type: boolean, default: true}}
33+
* - {in: query, name: interval, schema: {type: string, enum: [day, week], default: day}}
34+
* - {in: query, name: ownerKind, schema: {type: string, enum: [user, service_key, unresolved]}}
35+
* - {in: query, name: visibility, schema: {type: string, enum: [private, public]}}
36+
* - {in: query, name: owner, schema: {type: string, maxLength: 2400}, description: Publisher key from publisherOptions.}
37+
* responses:
38+
* '200':
39+
* description: Bounded aggregate data and coverage metadata.
40+
* content:
41+
* application/json:
42+
* schema: {$ref: '#/components/schemas/GetSitesAnalyticsSuccessResponse'}
43+
* '400': { description: Invalid calendar range or scope, content: { application/json: { schema: { $ref: '#/components/schemas/ApiErrorResponse' } } } }
44+
* '401': { description: Authentication required, content: { application/json: { schema: { $ref: '#/components/schemas/ApiErrorResponse' } } } }
45+
* '403': { description: Administrator role required, content: { application/json: { schema: { $ref: '#/components/schemas/ApiErrorResponse' } } } }
46+
* '503': { description: 'Analytics request did not complete before the time limit. Error code: analytics_timeout.', content: { application/json: { schema: { $ref: '#/components/schemas/ApiErrorResponse' } } } }
47+
*/
48+
export const GET = createApiHandler(
49+
async (req: NextRequest) => {
50+
const result = await new SitesAnalyticsService().getSummary(parseSitesAnalyticsQuery(req.nextUrl.searchParams));
51+
return withNoStore(successResponse(result, { status: 200 }, req));
52+
},
53+
{ auth: 'session', roles: ['admin'] }
54+
);

‎src/server/lib/v2RoutePolicyManifest.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ export const V2_ROUTE_POLICY_MANIFEST: readonly V2RoutePolicyEntry[] = [
4545
{ method: 'GET', route: '/api/v2/admin/analytics/lifetimes/scatter', policy: 'session', roles: ['admin'] },
4646
{ method: 'GET', route: '/api/v2/admin/analytics/options', policy: 'session', roles: ['admin'] },
4747
{ method: 'GET', route: '/api/v2/admin/analytics/services', policy: 'session', roles: ['admin'] },
48+
{ method: 'GET', route: '/api/v2/admin/analytics/sites', policy: 'session', roles: ['admin'] },
4849
{ method: 'GET', route: '/api/v2/admin/analytics/telemetry', policy: 'session', roles: ['admin'] },
4950
{ method: 'GET', route: '/api/v2/ai/admin/agent/capabilities', policy: 'session', roles: ['admin'] },
5051
{ method: 'PUT', route: '/api/v2/ai/admin/agent/capabilities', policy: 'session', roles: ['admin'] },

0 commit comments

Comments
 (0)