Nyk commited on
Commit
be0bb92
·
1 Parent(s): 255b4ea

fix(agents): enforce diagnostics self-scope and validation

Browse files
README.md CHANGED
@@ -418,6 +418,24 @@ pnpm test:e2e # Playwright E2E
418
  pnpm quality:gate # All checks
419
  ```
420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  ## Roadmap
422
 
423
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
 
418
  pnpm quality:gate # All checks
419
  ```
420
 
421
+ ## Agent Diagnostics Contract
422
+
423
+ `GET /api/agents/{id}/diagnostics` is self-scoped by default.
424
+
425
+ - Self access:
426
+ - Session user where `username === agent.name`, or
427
+ - API-key request with `x-agent-name` matching `{id}` agent name
428
+ - Cross-agent access:
429
+ - Allowed only with explicit `?privileged=1` and admin auth
430
+ - Query validation:
431
+ - `hours` must be an integer between `1` and `720`
432
+ - `section` must be a comma-separated subset of `summary,tasks,errors,activity,trends,tokens`
433
+
434
+ Trend alerts in the `trends.alerts` response are derived from current-vs-previous window comparisons:
435
+
436
+ - `warning`: error spikes or severe activity drop
437
+ - `info`: throughput drops or potential stall patterns
438
+
439
  ## Roadmap
440
 
441
  See [open issues](https://github.com/builderz-labs/mission-control/issues) for planned work and the [v1.0.0 release notes](https://github.com/builderz-labs/mission-control/releases/tag/v1.0.0) for what shipped.
openapi.json CHANGED
@@ -1362,6 +1362,126 @@
1362
  }
1363
  }
1364
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1365
  "/api/agents/message": {
1366
  "post": {
1367
  "tags": [
 
1362
  }
1363
  }
1364
  },
1365
+ "/api/agents/{id}/diagnostics": {
1366
+ "get": {
1367
+ "tags": [
1368
+ "Agents"
1369
+ ],
1370
+ "summary": "Get self diagnostics for an agent",
1371
+ "description": "Self-scoped diagnostics by default. Cross-agent access requires `privileged=1` with admin credentials. Trend alerts are informational signals derived from current-vs-previous window deltas (error spikes, throughput drops, activity stalls).",
1372
+ "operationId": "getAgentDiagnostics",
1373
+ "parameters": [
1374
+ {
1375
+ "name": "id",
1376
+ "in": "path",
1377
+ "required": true,
1378
+ "schema": {
1379
+ "type": "string"
1380
+ },
1381
+ "description": "Agent numeric ID or name."
1382
+ },
1383
+ {
1384
+ "name": "hours",
1385
+ "in": "query",
1386
+ "required": false,
1387
+ "schema": {
1388
+ "type": "integer",
1389
+ "minimum": 1,
1390
+ "maximum": 720,
1391
+ "default": 24
1392
+ },
1393
+ "description": "Diagnostics window in hours."
1394
+ },
1395
+ {
1396
+ "name": "section",
1397
+ "in": "query",
1398
+ "required": false,
1399
+ "schema": {
1400
+ "type": "string"
1401
+ },
1402
+ "description": "Comma-separated sections: summary,tasks,errors,activity,trends,tokens."
1403
+ },
1404
+ {
1405
+ "name": "privileged",
1406
+ "in": "query",
1407
+ "required": false,
1408
+ "schema": {
1409
+ "type": "string",
1410
+ "enum": [
1411
+ "1"
1412
+ ]
1413
+ },
1414
+ "description": "Set to `1` to allow explicit admin cross-agent diagnostics access."
1415
+ }
1416
+ ],
1417
+ "responses": {
1418
+ "200": {
1419
+ "description": "Diagnostics payload",
1420
+ "content": {
1421
+ "application/json": {
1422
+ "schema": {
1423
+ "type": "object",
1424
+ "properties": {
1425
+ "agent": {
1426
+ "type": "object",
1427
+ "properties": {
1428
+ "id": { "type": "integer" },
1429
+ "name": { "type": "string" },
1430
+ "role": { "type": "string" },
1431
+ "status": { "type": "string" }
1432
+ }
1433
+ },
1434
+ "timeframe": {
1435
+ "type": "object",
1436
+ "properties": {
1437
+ "hours": { "type": "integer" },
1438
+ "since": { "type": "integer" },
1439
+ "until": { "type": "integer" }
1440
+ }
1441
+ },
1442
+ "summary": { "type": "object" },
1443
+ "tasks": { "type": "object" },
1444
+ "errors": { "type": "object" },
1445
+ "activity": { "type": "object" },
1446
+ "trends": {
1447
+ "type": "object",
1448
+ "properties": {
1449
+ "current_period": { "type": "object" },
1450
+ "previous_period": { "type": "object" },
1451
+ "change": { "type": "object" },
1452
+ "alerts": {
1453
+ "type": "array",
1454
+ "items": {
1455
+ "type": "object",
1456
+ "properties": {
1457
+ "level": { "type": "string", "enum": ["info", "warning"] },
1458
+ "message": { "type": "string" }
1459
+ }
1460
+ }
1461
+ }
1462
+ }
1463
+ },
1464
+ "tokens": { "type": "object" }
1465
+ }
1466
+ }
1467
+ }
1468
+ }
1469
+ },
1470
+ "400": {
1471
+ "$ref": "#/components/responses/BadRequest"
1472
+ },
1473
+ "401": {
1474
+ "$ref": "#/components/responses/Unauthorized"
1475
+ },
1476
+ "403": {
1477
+ "$ref": "#/components/responses/Forbidden"
1478
+ },
1479
+ "404": {
1480
+ "$ref": "#/components/responses/NotFound"
1481
+ }
1482
+ }
1483
+ }
1484
+ },
1485
  "/api/agents/message": {
1486
  "post": {
1487
  "tags": [
src/app/api/agents/[id]/diagnostics/route.ts CHANGED
@@ -3,6 +3,43 @@ import { getDatabase } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
  import { logger } from '@/lib/logger';
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  /**
7
  * GET /api/agents/[id]/diagnostics - Agent Self-Diagnostics API
8
  *
@@ -48,9 +85,30 @@ export async function GET(
48
  }
49
 
50
  const { searchParams } = new URL(request.url);
51
- const hours = Math.min(Math.max(parseInt(searchParams.get('hours') || '24', 10) || 24, 1), 720);
52
- const sectionParam = searchParams.get('section') || 'summary,tasks,errors,activity,trends,tokens';
53
- const sections = new Set(sectionParam.split(',').map(s => s.trim()));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  const now = Math.floor(Date.now() / 1000);
56
  const since = now - hours * 3600;
 
3
  import { requireRole } from '@/lib/auth';
4
  import { logger } from '@/lib/logger';
5
 
6
+ const ALLOWED_SECTIONS = ['summary', 'tasks', 'errors', 'activity', 'trends', 'tokens'] as const;
7
+ type DiagnosticsSection = (typeof ALLOWED_SECTIONS)[number];
8
+
9
+ function parseHoursParam(raw: string | null): { value?: number; error?: string } {
10
+ if (raw === null) return { value: 24 };
11
+ const parsed = Number(raw);
12
+ if (!Number.isInteger(parsed)) {
13
+ return { error: 'hours must be an integer between 1 and 720' };
14
+ }
15
+ if (parsed < 1 || parsed > 720) {
16
+ return { error: 'hours must be between 1 and 720' };
17
+ }
18
+ return { value: parsed };
19
+ }
20
+
21
+ function parseSectionsParam(raw: string | null): { value?: Set<DiagnosticsSection>; error?: string } {
22
+ if (!raw || raw.trim().length === 0) {
23
+ return { value: new Set(ALLOWED_SECTIONS) };
24
+ }
25
+
26
+ const requested = raw
27
+ .split(',')
28
+ .map((section) => section.trim())
29
+ .filter(Boolean);
30
+
31
+ if (requested.length === 0) {
32
+ return { error: 'section must include at least one valid value' };
33
+ }
34
+
35
+ const invalid = requested.filter((section) => !ALLOWED_SECTIONS.includes(section as DiagnosticsSection));
36
+ if (invalid.length > 0) {
37
+ return { error: `Invalid section value(s): ${invalid.join(', ')}` };
38
+ }
39
+
40
+ return { value: new Set(requested as DiagnosticsSection[]) };
41
+ }
42
+
43
  /**
44
  * GET /api/agents/[id]/diagnostics - Agent Self-Diagnostics API
45
  *
 
85
  }
86
 
87
  const { searchParams } = new URL(request.url);
88
+ const requesterAgentName = (request.headers.get('x-agent-name') || '').trim();
89
+ const privileged = searchParams.get('privileged') === '1';
90
+ const isSelfRequest = (requesterAgentName || auth.user.username) === agent.name;
91
+
92
+ // Self-only by default. Cross-agent access requires explicit privileged override.
93
+ if (!isSelfRequest && !(privileged && auth.user.role === 'admin')) {
94
+ return NextResponse.json(
95
+ { error: 'Diagnostics are self-scoped. Use privileged=1 with admin role for cross-agent access.' },
96
+ { status: 403 }
97
+ );
98
+ }
99
+
100
+ const parsedHours = parseHoursParam(searchParams.get('hours'));
101
+ if (parsedHours.error) {
102
+ return NextResponse.json({ error: parsedHours.error }, { status: 400 });
103
+ }
104
+
105
+ const parsedSections = parseSectionsParam(searchParams.get('section'));
106
+ if (parsedSections.error) {
107
+ return NextResponse.json({ error: parsedSections.error }, { status: 400 });
108
+ }
109
+
110
+ const hours = parsedHours.value as number;
111
+ const sections = parsedSections.value as Set<DiagnosticsSection>;
112
 
113
  const now = Math.floor(Date.now() / 1000);
114
  const since = now - hours * 3600;
tests/agent-diagnostics.spec.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from '@playwright/test'
2
+ import { API_KEY_HEADER, createTestAgent, deleteTestAgent } from './helpers'
3
+
4
+ test.describe('Agent Diagnostics API', () => {
5
+ const cleanup: number[] = []
6
+
7
+ test.afterEach(async ({ request }) => {
8
+ for (const id of cleanup) {
9
+ await deleteTestAgent(request, id).catch(() => {})
10
+ }
11
+ cleanup.length = 0
12
+ })
13
+
14
+ test('self access is allowed with x-agent-name', async ({ request }) => {
15
+ const { id, name } = await createTestAgent(request)
16
+ cleanup.push(id)
17
+
18
+ const res = await request.get(`/api/agents/${name}/diagnostics?section=summary`, {
19
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
20
+ })
21
+
22
+ expect(res.status()).toBe(200)
23
+ const body = await res.json()
24
+ expect(body.agent.name).toBe(name)
25
+ expect(body.summary).toBeDefined()
26
+ })
27
+
28
+ test('cross-agent access is denied by default', async ({ request }) => {
29
+ const a = await createTestAgent(request)
30
+ const b = await createTestAgent(request)
31
+ cleanup.push(a.id, b.id)
32
+
33
+ const res = await request.get(`/api/agents/${a.name}/diagnostics?section=summary`, {
34
+ headers: { ...API_KEY_HEADER, 'x-agent-name': b.name },
35
+ })
36
+
37
+ expect(res.status()).toBe(403)
38
+ })
39
+
40
+ test('cross-agent access is allowed with privileged=1 for admin', async ({ request }) => {
41
+ const a = await createTestAgent(request)
42
+ const b = await createTestAgent(request)
43
+ cleanup.push(a.id, b.id)
44
+
45
+ const res = await request.get(`/api/agents/${a.name}/diagnostics?section=summary&privileged=1`, {
46
+ headers: { ...API_KEY_HEADER, 'x-agent-name': b.name },
47
+ })
48
+
49
+ expect(res.status()).toBe(200)
50
+ const body = await res.json()
51
+ expect(body.agent.name).toBe(a.name)
52
+ expect(body.summary).toBeDefined()
53
+ })
54
+
55
+ test('invalid section query is rejected', async ({ request }) => {
56
+ const { id, name } = await createTestAgent(request)
57
+ cleanup.push(id)
58
+
59
+ const res = await request.get(`/api/agents/${name}/diagnostics?section=summary,invalid`, {
60
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
61
+ })
62
+
63
+ expect(res.status()).toBe(400)
64
+ })
65
+
66
+ test('invalid hours query is rejected', async ({ request }) => {
67
+ const { id, name } = await createTestAgent(request)
68
+ cleanup.push(id)
69
+
70
+ const res = await request.get(`/api/agents/${name}/diagnostics?hours=0`, {
71
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
72
+ })
73
+
74
+ expect(res.status()).toBe(400)
75
+ })
76
+ })