Nyk commited on
Commit
1a8fd6d
·
1 Parent(s): 659dcd6

fix(agents): enforce attribution scope and add e2e coverage

Browse files
README.md CHANGED
@@ -202,6 +202,7 @@ All endpoints require authentication unless noted. Full reference below.
202
  | `GET` | `/api/agents` | viewer | List agents with task stats |
203
  | `POST` | `/api/agents` | operator | Register/update agent |
204
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
 
205
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
206
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
207
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
@@ -217,6 +218,14 @@ All endpoints require authentication unless noted. Full reference below.
217
 
218
  </details>
219
 
 
 
 
 
 
 
 
 
220
  <details>
221
  <summary><strong>Monitoring</strong></summary>
222
 
 
202
  | `GET` | `/api/agents` | viewer | List agents with task stats |
203
  | `POST` | `/api/agents` | operator | Register/update agent |
204
  | `GET` | `/api/agents/[id]` | viewer | Agent details |
205
+ | `GET` | `/api/agents/[id]/attribution` | viewer | Self-scope attribution/audit/cost report (`?privileged=1` admin override) |
206
  | `POST` | `/api/agents/sync` | operator | Sync agents from openclaw.json |
207
  | `GET/PUT` | `/api/agents/[id]/soul` | operator | Agent SOUL content (reads from workspace, writes to both) |
208
  | `GET/POST` | `/api/agents/comms` | operator | Agent inter-agent communication |
 
218
 
219
  </details>
220
 
221
+ ### Attribution Contract (`/api/agents/[id]/attribution`)
222
+
223
+ - Self-scope by default: requester identity must match target agent via `x-agent-name` (or matching authenticated username).
224
+ - Admin override requires explicit `?privileged=1`.
225
+ - Query params:
226
+ - `hours`: integer window `1..720` (default `24`)
227
+ - `section`: comma-separated subset of `identity,audit,mutations,cost` (default all)
228
+
229
  <details>
230
  <summary><strong>Monitoring</strong></summary>
231
 
openapi.json CHANGED
@@ -1016,6 +1016,86 @@
1016
  }
1017
  }
1018
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1019
  "/api/agents/{id}/heartbeat": {
1020
  "get": {
1021
  "tags": [
 
1016
  }
1017
  }
1018
  },
1019
+ "/api/agents/{id}/attribution": {
1020
+ "get": {
1021
+ "tags": [
1022
+ "Agents"
1023
+ ],
1024
+ "summary": "Get attribution report for an agent",
1025
+ "description": "Self-scope by default. Requester must match target agent (`x-agent-name` or username), unless admin uses `?privileged=1`.",
1026
+ "operationId": "getAgentAttribution",
1027
+ "parameters": [
1028
+ {
1029
+ "name": "id",
1030
+ "in": "path",
1031
+ "required": true,
1032
+ "schema": {
1033
+ "type": "string"
1034
+ }
1035
+ },
1036
+ {
1037
+ "name": "hours",
1038
+ "in": "query",
1039
+ "required": false,
1040
+ "description": "Time window in hours, integer range 1..720. Defaults to 24.",
1041
+ "schema": {
1042
+ "type": "integer",
1043
+ "minimum": 1,
1044
+ "maximum": 720,
1045
+ "default": 24
1046
+ }
1047
+ },
1048
+ {
1049
+ "name": "section",
1050
+ "in": "query",
1051
+ "required": false,
1052
+ "description": "Comma-separated subset of identity,audit,mutations,cost. Defaults to all.",
1053
+ "schema": {
1054
+ "type": "string",
1055
+ "example": "identity,audit"
1056
+ }
1057
+ },
1058
+ {
1059
+ "name": "privileged",
1060
+ "in": "query",
1061
+ "required": false,
1062
+ "description": "Set to 1 for admin override of self-scope checks.",
1063
+ "schema": {
1064
+ "type": "string",
1065
+ "enum": [
1066
+ "1"
1067
+ ]
1068
+ }
1069
+ },
1070
+ {
1071
+ "name": "x-agent-name",
1072
+ "in": "header",
1073
+ "required": false,
1074
+ "description": "Attribution identity header used for self-scope authorization.",
1075
+ "schema": {
1076
+ "type": "string"
1077
+ }
1078
+ }
1079
+ ],
1080
+ "responses": {
1081
+ "200": {
1082
+ "description": "Attribution report"
1083
+ },
1084
+ "400": {
1085
+ "$ref": "#/components/responses/BadRequest"
1086
+ },
1087
+ "401": {
1088
+ "$ref": "#/components/responses/Unauthorized"
1089
+ },
1090
+ "403": {
1091
+ "$ref": "#/components/responses/Forbidden"
1092
+ },
1093
+ "404": {
1094
+ "$ref": "#/components/responses/NotFound"
1095
+ }
1096
+ }
1097
+ }
1098
+ },
1099
  "/api/agents/{id}/heartbeat": {
1100
  "get": {
1101
  "tags": [
src/app/api/agents/[id]/attribution/route.ts CHANGED
@@ -3,6 +3,8 @@ import { getDatabase } from '@/lib/db';
3
  import { requireRole } from '@/lib/auth';
4
  import { logger } from '@/lib/logger';
5
 
 
 
6
  /**
7
  * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution
8
  *
@@ -46,9 +48,28 @@ export async function GET(
46
  }
47
 
48
  const { searchParams } = new URL(request.url);
49
- const hours = Math.min(Math.max(parseInt(searchParams.get('hours') || '24', 10) || 24, 1), 720);
50
- const sectionParam = searchParams.get('section') || 'identity,audit,mutations,cost';
51
- const sections = new Set(sectionParam.split(',').map(s => s.trim()));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  const now = Math.floor(Date.now() / 1000);
54
  const since = now - hours * 3600;
@@ -56,21 +77,22 @@ export async function GET(
56
  const result: Record<string, any> = {
57
  agent_name: agent.name,
58
  timeframe: { hours, since, until: now },
 
59
  };
60
 
61
- if (sections.has('identity')) {
62
  result.identity = buildIdentity(db, agent, workspaceId);
63
  }
64
 
65
- if (sections.has('audit')) {
66
  result.audit = buildAuditTrail(db, agent.name, workspaceId, since);
67
  }
68
 
69
- if (sections.has('mutations')) {
70
  result.mutations = buildMutations(db, agent.name, workspaceId, since);
71
  }
72
 
73
- if (sections.has('cost')) {
74
  result.cost = buildCostAttribution(db, agent.name, workspaceId, since);
75
  }
76
 
@@ -83,7 +105,7 @@ export async function GET(
83
 
84
  /** Agent identity and profile info */
85
  function buildIdentity(db: any, agent: any, workspaceId: number) {
86
- const config = agent.config ? JSON.parse(agent.config) : {};
87
 
88
  // Count total tasks ever assigned
89
  const taskStats = db.prepare(`
@@ -155,11 +177,11 @@ function buildAuditTrail(db: any, agentName: string, workspaceId: number, since:
155
  by_type: byType,
156
  activities: activities.map(a => ({
157
  ...a,
158
- data: a.data ? JSON.parse(a.data) : null,
159
  })),
160
  audit_log_entries: auditEntries.map(e => ({
161
  ...e,
162
- detail: e.detail ? JSON.parse(e.detail) : null,
163
  })),
164
  };
165
  }
@@ -201,16 +223,16 @@ function buildMutations(db: any, agentName: string, workspaceId: number, since:
201
  return {
202
  task_mutations: taskMutations.map(m => ({
203
  ...m,
204
- data: m.data ? JSON.parse(m.data) : null,
205
  })),
206
  comments: comments.map(c => ({
207
  ...c,
208
- mentions: c.mentions ? JSON.parse(c.mentions) : [],
209
  content_preview: c.content?.substring(0, 200) || '',
210
  })),
211
  status_changes: statusChanges.map(s => ({
212
  ...s,
213
- data: s.data ? JSON.parse(s.data) : null,
214
  })),
215
  summary: {
216
  task_mutations_count: taskMutations.length,
@@ -294,3 +316,41 @@ function buildCostAttribution(db: any, agentName: string, workspaceId: number, s
294
  return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] };
295
  }
296
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import { requireRole } from '@/lib/auth';
4
  import { logger } from '@/lib/logger';
5
 
6
+ const ALLOWED_SECTIONS = new Set(['identity', 'audit', 'mutations', 'cost']);
7
+
8
  /**
9
  * GET /api/agents/[id]/attribution - Agent-Level Identity & Attribution
10
  *
 
48
  }
49
 
50
  const { searchParams } = new URL(request.url);
51
+ const privileged = searchParams.get('privileged') === '1';
52
+ const isSelfByHeader = auth.user.agent_name === agent.name;
53
+ const isSelfByUsername = auth.user.username === agent.name;
54
+ const isSelf = isSelfByHeader || isSelfByUsername;
55
+ const isPrivileged = auth.user.role === 'admin' && privileged;
56
+ if (!isSelf && !isPrivileged) {
57
+ return NextResponse.json(
58
+ { error: 'Forbidden: attribution is self-scope by default. Admin can use ?privileged=1 override.' },
59
+ { status: 403 }
60
+ );
61
+ }
62
+
63
+ const hoursRaw = searchParams.get('hours');
64
+ const hours = parseHours(hoursRaw);
65
+ if (!hours) {
66
+ return NextResponse.json({ error: 'Invalid hours. Expected integer 1..720.' }, { status: 400 });
67
+ }
68
+
69
+ const sections = parseSections(searchParams.get('section'));
70
+ if ('error' in sections) {
71
+ return NextResponse.json({ error: sections.error }, { status: 400 });
72
+ }
73
 
74
  const now = Math.floor(Date.now() / 1000);
75
  const since = now - hours * 3600;
 
77
  const result: Record<string, any> = {
78
  agent_name: agent.name,
79
  timeframe: { hours, since, until: now },
80
+ access_scope: isSelf ? 'self' : 'privileged',
81
  };
82
 
83
+ if (sections.sections.has('identity')) {
84
  result.identity = buildIdentity(db, agent, workspaceId);
85
  }
86
 
87
+ if (sections.sections.has('audit')) {
88
  result.audit = buildAuditTrail(db, agent.name, workspaceId, since);
89
  }
90
 
91
+ if (sections.sections.has('mutations')) {
92
  result.mutations = buildMutations(db, agent.name, workspaceId, since);
93
  }
94
 
95
+ if (sections.sections.has('cost')) {
96
  result.cost = buildCostAttribution(db, agent.name, workspaceId, since);
97
  }
98
 
 
105
 
106
  /** Agent identity and profile info */
107
  function buildIdentity(db: any, agent: any, workspaceId: number) {
108
+ const config = safeParseJson(agent.config, {});
109
 
110
  // Count total tasks ever assigned
111
  const taskStats = db.prepare(`
 
177
  by_type: byType,
178
  activities: activities.map(a => ({
179
  ...a,
180
+ data: safeParseJson(a.data, null),
181
  })),
182
  audit_log_entries: auditEntries.map(e => ({
183
  ...e,
184
+ detail: safeParseJson(e.detail, null),
185
  })),
186
  };
187
  }
 
223
  return {
224
  task_mutations: taskMutations.map(m => ({
225
  ...m,
226
+ data: safeParseJson(m.data, null),
227
  })),
228
  comments: comments.map(c => ({
229
  ...c,
230
+ mentions: safeParseJson(c.mentions, []),
231
  content_preview: c.content?.substring(0, 200) || '',
232
  })),
233
  status_changes: statusChanges.map(s => ({
234
  ...s,
235
+ data: safeParseJson(s.data, null),
236
  })),
237
  summary: {
238
  task_mutations_count: taskMutations.length,
 
316
  return { by_model: [], total: { input_tokens: 0, output_tokens: 0, requests: 0 }, daily_trend: [] };
317
  }
318
  }
319
+
320
+ function parseHours(hoursRaw: string | null): number | null {
321
+ if (!hoursRaw || hoursRaw.trim() === '') return 24;
322
+ if (!/^\d+$/.test(hoursRaw)) return null;
323
+ const hours = Number(hoursRaw);
324
+ if (!Number.isInteger(hours) || hours < 1 || hours > 720) return null;
325
+ return hours;
326
+ }
327
+
328
+ function parseSections(
329
+ sectionRaw: string | null
330
+ ): { sections: Set<string> } | { error: string } {
331
+ const value = (sectionRaw || 'identity,audit,mutations,cost').trim();
332
+ const parsed = value
333
+ .split(',')
334
+ .map((section) => section.trim())
335
+ .filter(Boolean);
336
+
337
+ if (parsed.length === 0) {
338
+ return { error: 'Invalid section. Expected one or more of identity,audit,mutations,cost.' };
339
+ }
340
+
341
+ const invalid = parsed.filter((section) => !ALLOWED_SECTIONS.has(section));
342
+ if (invalid.length > 0) {
343
+ return { error: `Invalid section value(s): ${invalid.join(', ')}` };
344
+ }
345
+
346
+ return { sections: new Set(parsed) };
347
+ }
348
+
349
+ function safeParseJson<T>(raw: string | null | undefined, fallback: T): T {
350
+ if (!raw) return fallback;
351
+ try {
352
+ return JSON.parse(raw) as T;
353
+ } catch {
354
+ return fallback;
355
+ }
356
+ }
tests/agent-attribution.spec.ts ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { expect, test } from '@playwright/test'
2
+ import { API_KEY_HEADER, createTestAgent, deleteTestAgent } from './helpers'
3
+
4
+ test.describe('Agent Attribution 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('allows self-scope access using x-agent-name attribution header', async ({ request }) => {
15
+ const { id, name } = await createTestAgent(request)
16
+ cleanup.push(id)
17
+
18
+ const res = await request.get(`/api/agents/${id}/attribution`, {
19
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
20
+ })
21
+ expect(res.status()).toBe(200)
22
+ const body = await res.json()
23
+ expect(body.agent_name).toBe(name)
24
+ expect(body.access_scope).toBe('self')
25
+ })
26
+
27
+ test('denies cross-agent attribution access by default', async ({ request }) => {
28
+ const primary = await createTestAgent(request)
29
+ const other = await createTestAgent(request)
30
+ cleanup.push(primary.id, other.id)
31
+
32
+ const res = await request.get(`/api/agents/${primary.id}/attribution`, {
33
+ headers: { ...API_KEY_HEADER, 'x-agent-name': other.name },
34
+ })
35
+
36
+ expect(res.status()).toBe(403)
37
+ })
38
+
39
+ test('allows privileged override for admin caller', async ({ request }) => {
40
+ const primary = await createTestAgent(request)
41
+ const other = await createTestAgent(request)
42
+ cleanup.push(primary.id, other.id)
43
+
44
+ const res = await request.get(`/api/agents/${primary.id}/attribution?privileged=1`, {
45
+ headers: { ...API_KEY_HEADER, 'x-agent-name': other.name },
46
+ })
47
+ expect(res.status()).toBe(200)
48
+ const body = await res.json()
49
+ expect(body.access_scope).toBe('privileged')
50
+ })
51
+
52
+ test('validates section parameter and timeframe hours', async ({ request }) => {
53
+ const { id, name } = await createTestAgent(request)
54
+ cleanup.push(id)
55
+
56
+ const sectionRes = await request.get(`/api/agents/${id}/attribution?section=identity&hours=48`, {
57
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
58
+ })
59
+ expect(sectionRes.status()).toBe(200)
60
+ const sectionBody = await sectionRes.json()
61
+ expect(sectionBody.timeframe.hours).toBe(48)
62
+ expect(sectionBody.identity).toBeDefined()
63
+ expect(sectionBody.audit).toBeUndefined()
64
+ expect(sectionBody.mutations).toBeUndefined()
65
+ expect(sectionBody.cost).toBeUndefined()
66
+
67
+ const invalidSection = await request.get(`/api/agents/${id}/attribution?section=unknown`, {
68
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
69
+ })
70
+ expect(invalidSection.status()).toBe(400)
71
+
72
+ const invalidHours = await request.get(`/api/agents/${id}/attribution?hours=0`, {
73
+ headers: { ...API_KEY_HEADER, 'x-agent-name': name },
74
+ })
75
+ expect(invalidHours.status()).toBe(400)
76
+ })
77
+ })