-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.go
More file actions
575 lines (529 loc) · 21.4 KB
/
Copy pathaudit.go
File metadata and controls
575 lines (529 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// Audit log read methods for AxonFlow SDK
// These methods allow querying and retrieving audit logs from the AxonFlow platform.
package axonflow
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
)
// ============================================================================
// Audit Log Types
// ============================================================================
// AuditSearchRequest represents a request to search audit logs
type AuditSearchRequest struct {
// UserEmail filters logs by user email
UserEmail string `json:"user_email,omitempty"`
// ClientID filters logs by client/application ID
ClientID string `json:"client_id,omitempty"`
// StartTime is the beginning of the time range to search
StartTime *time.Time `json:"start_time,omitempty"`
// EndTime is the end of the time range to search
EndTime *time.Time `json:"end_time,omitempty"`
// Action filters by action/request type with verdict normalization on
// the server side. This is the filter the 9.x server actually reads
// (audit_read_handlers.go).
Action string `json:"action,omitempty"`
// RequestType filters by request type (e.g., "llm_chat", "policy_check").
//
// Deprecated: the 9.x server does not read this filter; a search
// filtered only by it returns unfiltered results. Use `action`.
// Scheduled for removal in the next major (#3254). The SDK keeps
// sending it (harmless, ignored). Note this deprecation is scoped to
// the SEARCH REQUEST only - AuditLogEntry.RequestType on the read
// model IS served and stays.
RequestType string `json:"request_type,omitempty"`
// DecisionID filters logs by the explainability decision ID (ADR-043).
// Useful for reconstructing everything tied to a single decision.
DecisionID string `json:"decision_id,omitempty"`
// PolicyName filters logs by the matched policy name (ADR-043).
PolicyName string `json:"policy_name,omitempty"`
// OverrideID filters logs by the session-override ID (ADR-042).
// Use this to reconstruct the full lifecycle of one override
// (override_created → override_used → override_expired | override_revoked).
OverrideID string `json:"override_id,omitempty"`
// Limit is the maximum number of results to return (default: 100, max: 1000)
Limit int `json:"limit,omitempty"`
// Offset is the pagination offset (default: 0)
Offset int `json:"offset,omitempty"`
}
// AuditQueryOptions provides options for GetAuditLogsByTenant
type AuditQueryOptions struct {
// Limit is the maximum number of results to return (default: 50)
Limit int `json:"limit,omitempty"`
// Offset is the pagination offset (default: 0)
Offset int `json:"offset,omitempty"`
}
// AuditLogEntry represents a single audit log entry
type AuditLogEntry struct {
// ID is the unique identifier for this audit entry
ID string `json:"id"`
// RequestID is the correlation ID for the original request
RequestID string `json:"request_id"`
// Timestamp is when the event occurred
Timestamp time.Time `json:"timestamp"`
// UserEmail is the email of the user who made the request
UserEmail string `json:"user_email"`
// ClientID is the client/application that made the request
ClientID string `json:"client_id"`
// TenantID is the tenant identifier
TenantID string `json:"tenant_id"`
// RequestType is the type of request (e.g., "llm_chat", "sql", "mcp-query")
RequestType string `json:"request_type"`
// PolicyDecision is the governance verdict for this entry as served by
// the 9.x orchestrator. Observed values include "allowed", "blocked",
// "redacted" and "error"; the set is OPEN, so treat this as a plain
// string, not an enum. Empty when an old server or a non-LLM plane
// omits the field.
PolicyDecision string `json:"policy_decision"`
// PolicyDetails carries verdict context as an object with arbitrary
// keys (e.g. tool_name, caller_name, error_message). Nil when the
// server omits it.
PolicyDetails map[string]interface{} `json:"policy_details"`
// ResponseTimeMs is the request latency in milliseconds as served by
// the 9.x orchestrator. Zero when the server omits it or did not
// measure it for this plane.
ResponseTimeMs int64 `json:"response_time_ms"`
// QuerySummary is a summary of the query/request.
//
// Deprecated: never populated on the 9.x line - the wire carries
// `query`/`query_hash`, not modeled in this interim
// (getaxonflow/axonflow-enterprise#3254). Read `policy_decision` for
// the verdict ("blocked" replaces `blocked=true`; "allowed" replaces
// `success=true`), `policy_details` for violation context, and
// `response_time_ms` for latency. Scheduled for removal in the next
// major.
QuerySummary string `json:"query_summary"`
// Success indicates whether the request succeeded.
//
// Deprecated: never populated on the 9.x line - the server has never
// sent this field (getaxonflow/axonflow-enterprise#3254). Read
// `policy_decision` for the verdict ("blocked" replaces
// `blocked=true`; "allowed" replaces `success=true`),
// `policy_details` for violation context, and `response_time_ms` for
// latency. Scheduled for removal in the next major.
Success bool `json:"success"`
// Blocked indicates whether the request was blocked by policy.
//
// Deprecated: never populated on the 9.x line - the server has never
// sent this field (getaxonflow/axonflow-enterprise#3254). Read
// `policy_decision` for the verdict ("blocked" replaces
// `blocked=true`; "allowed" replaces `success=true`),
// `policy_details` for violation context, and `response_time_ms` for
// latency. Scheduled for removal in the next major.
Blocked bool `json:"blocked"`
// RiskScore is the calculated risk score (0.0-1.0).
//
// Deprecated: never populated on the 9.x line - no wire equivalent
// (getaxonflow/axonflow-enterprise#3254). Read `policy_decision` for
// the verdict ("blocked" replaces `blocked=true`; "allowed" replaces
// `success=true`), `policy_details` for violation context, and
// `response_time_ms` for latency. Scheduled for removal in the next
// major.
RiskScore float64 `json:"risk_score"`
// Provider is the LLM provider used (if applicable)
Provider string `json:"provider"`
// Model is the model used (if applicable)
Model string `json:"model"`
// TokensUsed is the total tokens consumed
TokensUsed int `json:"tokens_used"`
// LatencyMs is the request latency in milliseconds.
//
// Deprecated: never populated on the 9.x line - the server has never
// sent this field (getaxonflow/axonflow-enterprise#3254). Read
// `policy_decision` for the verdict ("blocked" replaces
// `blocked=true`; "allowed" replaces `success=true`),
// `policy_details` for violation context, and `response_time_ms` for
// latency. Scheduled for removal in the next major.
LatencyMs int `json:"latency_ms"`
// PolicyViolations is a list of violated policy IDs (if any).
//
// Deprecated: never populated on the 9.x line - the server has never
// sent this field (getaxonflow/axonflow-enterprise#3254). Read
// `policy_decision` for the verdict ("blocked" replaces
// `blocked=true`; "allowed" replaces `success=true`),
// `policy_details` for violation context, and `response_time_ms` for
// latency. Scheduled for removal in the next major.
PolicyViolations []string `json:"policy_violations,omitempty"`
// Metadata contains additional context.
//
// Deprecated: never populated on the 9.x line - the wire carries
// `policy_details`/`security_metrics` instead
// (getaxonflow/axonflow-enterprise#3254). Read `policy_decision` for
// the verdict ("blocked" replaces `blocked=true`; "allowed" replaces
// `success=true`), `policy_details` for violation context, and
// `response_time_ms` for latency. Scheduled for removal in the next
// major.
Metadata map[string]interface{} `json:"metadata,omitempty"`
// DataResidency is the ISO 3166-1 alpha-2 country code where data is stored
DataResidency string `json:"data_residency,omitempty"`
// TransferBasis is the legal basis for cross-border data transfer under
// Indonesia UU PDP Pasal 56: adequacy, safeguards, pasal_56b_dpa, or consent.
// Surfaced verbatim — see the TransferBasis* constants in ojk.go for the
// recognized set and their Pasal 56 mapping.
TransferBasis string `json:"transfer_basis,omitempty"`
}
// AuditSearchResponse represents the response from an audit search
type AuditSearchResponse struct {
// Entries contains the audit log entries
Entries []AuditLogEntry `json:"entries"`
// Total is the total number of matching entries (for pagination)
Total int `json:"total"`
// Limit is the limit that was applied
Limit int `json:"limit"`
// Offset is the offset that was applied
Offset int `json:"offset"`
}
// ============================================================================
// Audit Tool Call Types
// ============================================================================
// AuditToolCallRequest represents a request to record a non-LLM tool call
// in the audit trail. ToolName is required; all other fields are optional.
type AuditToolCallRequest struct {
// ToolName is the name of the tool that was called (required)
ToolName string `json:"tool_name"`
// ToolType is the type of tool: "function", "mcp", or "api"
//
// Deprecated: ToolType was historically overloaded to identify which
// client made the call (e.g. "claude_code", "codex", "cursor"). Use
// CallerName for that purpose instead. ToolType is kept as a
// deprecated input fallback for backward compatibility and is not
// being removed.
ToolType string `json:"tool_type,omitempty"`
// CallerName identifies the client that made the tool call (e.g.
// "claude_code", "codex", "cursor", "openclaw"). This supersedes the
// deprecated ToolType field for that purpose. The server resolves
// caller identity as: CallerName if supplied -> legacy ToolType if
// supplied -> a default.
//
// Requires a platform with caller_name support (v9.11.0+); older
// platforms silently drop this field, so also set ToolType if you need
// attribution there.
CallerName string `json:"caller_name,omitempty"`
// Input is the input data passed to the tool
Input map[string]interface{} `json:"input,omitempty"`
// Output is the output data returned by the tool
Output map[string]interface{} `json:"output,omitempty"`
// WorkflowID is the workflow this tool call belongs to
WorkflowID string `json:"workflow_id,omitempty"`
// StepID is the step within the workflow
StepID string `json:"step_id,omitempty"`
// UserID identifies the user who initiated the tool call
UserID string `json:"user_id,omitempty"`
// DurationMs is the tool call duration in milliseconds
DurationMs int64 `json:"duration_ms,omitempty"`
// PoliciesApplied lists policy IDs that were applied to this call
PoliciesApplied []string `json:"policies_applied,omitempty"`
// Success indicates whether the tool call succeeded
Success *bool `json:"success,omitempty"`
// ErrorMessage contains the error message if the tool call failed
ErrorMessage string `json:"error_message,omitempty"`
}
// AuditToolCallResponse represents the response from recording a tool call
type AuditToolCallResponse struct {
// AuditID is the unique identifier for the audit entry
AuditID string `json:"audit_id"`
// Status is the recording status (e.g., "recorded")
Status string `json:"status"`
// Timestamp is when the audit entry was created
Timestamp string `json:"timestamp"`
}
// ============================================================================
// Audit Tool Call Methods
// ============================================================================
// AuditToolCall records a non-LLM tool call in the audit trail.
//
// This method is used to audit tool invocations that are not LLM calls,
// such as MCP tool calls, API calls, or custom function executions.
// Only ToolName is required; all other fields are optional.
//
// Example:
//
// success := true
// resp, err := client.AuditToolCall(ctx, axonflow.AuditToolCallRequest{
// ToolName: "getUserInfo",
// ToolType: "mcp",
// WorkflowID: "wf_abc123",
// StepID: "step-3",
// DurationMs: 45,
// Success: &success,
// })
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Audit recorded: %s\n", resp.AuditID)
func (c *AxonFlowClient) AuditToolCall(ctx context.Context, req AuditToolCallRequest) (*AuditToolCallResponse, error) {
if req.ToolName == "" {
return nil, fmt.Errorf("tool_name is required")
}
fullURL := c.config.Endpoint + "/api/v1/audit/tool-call"
var result AuditToolCallResponse
if err := c.makeJSONRequest(ctx, "POST", fullURL, req, &result); err != nil {
return nil, err
}
if c.config.Debug {
log.Printf("[AxonFlow] Audit tool call recorded - AuditID: %s, Tool: %s", result.AuditID, req.ToolName)
}
return &result, nil
}
// ============================================================================
// Audit Log Read Methods
// ============================================================================
// SearchAuditLogs searches audit logs with the specified filters.
//
// This method queries the AxonFlow orchestrator for audit logs matching
// the specified criteria. Use this for compliance dashboards, security
// investigations, and operational monitoring.
//
// Example:
//
// // Search for audit logs from a specific user in the last 24 hours
// yesterday := time.Now().Add(-24 * time.Hour)
// now := time.Now()
// req := &axonflow.AuditSearchRequest{
// UserEmail: "analyst@company.com",
// StartTime: &yesterday,
// EndTime: &now,
// Limit: 100,
// }
//
// result, err := client.SearchAuditLogs(context.Background(), req)
// if err != nil {
// log.Fatal(err)
// }
//
// for _, entry := range result.Entries {
// fmt.Printf("[%s] %s: %s (decision: %s, %dms)\n",
// entry.Timestamp.Format(time.RFC3339),
// entry.UserEmail,
// entry.RequestType,
// entry.PolicyDecision,
// entry.ResponseTimeMs)
// }
func (c *AxonFlowClient) SearchAuditLogs(ctx context.Context, req *AuditSearchRequest) (*AuditSearchResponse, error) {
if req == nil {
req = &AuditSearchRequest{}
}
// Apply defaults
if req.Limit == 0 {
req.Limit = 100
}
if req.Limit > 1000 {
req.Limit = 1000
}
// Build request body
reqBody := map[string]interface{}{}
if req.UserEmail != "" {
reqBody["user_email"] = req.UserEmail
}
if req.ClientID != "" {
reqBody["client_id"] = req.ClientID
}
if req.StartTime != nil {
reqBody["start_time"] = req.StartTime.Format(time.RFC3339)
}
if req.EndTime != nil {
reqBody["end_time"] = req.EndTime.Format(time.RFC3339)
}
if req.Action != "" {
reqBody["action"] = req.Action
}
// Deprecated request_type is still sent for now (harmless, the 9.x
// server ignores it); removal rides the next major (#3254).
if req.RequestType != "" {
reqBody["request_type"] = req.RequestType
}
if req.DecisionID != "" {
reqBody["decision_id"] = req.DecisionID
}
if req.PolicyName != "" {
reqBody["policy_name"] = req.PolicyName
}
if req.OverrideID != "" {
reqBody["override_id"] = req.OverrideID
}
reqBody["limit"] = req.Limit
if req.Offset > 0 {
reqBody["offset"] = req.Offset
}
bodyBytes, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal audit search request: %w", err)
}
fullURL := c.config.Endpoint + "/api/v1/audit/search"
httpReq, err := http.NewRequestWithContext(ctx, "POST", fullURL, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("failed to create audit search request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
c.addAuthHeaders(httpReq)
if c.config.Debug {
log.Printf("[AxonFlow] Audit search - Limit: %d, Offset: %d", req.Limit, req.Offset)
}
resp, err := c.doHttpRequest(c.httpClient, httpReq)
if err != nil {
return nil, fmt.Errorf("audit search request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read audit search response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, &httpError{
statusCode: resp.StatusCode,
message: string(body),
}
}
result, err := decodeAuditPage(body, req.Limit, req.Offset)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal audit search response: %w", err)
}
// The audit reads are in the same role-scoped family as decisions
// (platform/orchestrator applyReadScopeHeader), so they inherit the same
// rule: an empty page under scope `none` could not have contained a row,
// and reporting it as data is the vacuous read this SDK now refuses.
if scopeErr := refuseVacuousScopedPage(resp, "audit entries", len(result.Entries)); scopeErr != nil {
return nil, scopeErr
}
if c.config.Debug {
log.Printf("[AxonFlow] Audit search returned %d entries", len(result.Entries))
}
return result, nil
}
// decodeAuditPage reads an audit page in either shape the platform sends: a
// bare array, or the wrapped envelope with its own total/limit/offset.
//
// Extracted because both audit reads decoded it inline, identically, with a
// separate return per shape — four places for one rule to be applied in, and
// the scope refusal above would have had to be written in all four to hold.
func decodeAuditPage(body []byte, limit, offset int) (*AuditSearchResponse, error) {
var entries []AuditLogEntry
if err := json.Unmarshal(body, &entries); err != nil {
var wrapped AuditSearchResponse
if wrapErr := json.Unmarshal(body, &wrapped); wrapErr == nil {
return &wrapped, nil
}
return nil, err
}
return &AuditSearchResponse{
Entries: entries,
Total: len(entries), // the array shape carries no total; use the count
Limit: limit,
Offset: offset,
}, nil
}
// GetAuditLogsByTenant retrieves recent audit logs for a specific tenant.
//
// This is a convenience method for tenant-scoped audit queries. Use this
// when you need to view all recent activity for a specific tenant.
//
// Example:
//
// // Get the last 50 audit logs for a tenant
// result, err := client.GetAuditLogsByTenant(context.Background(), "tenant-abc", nil)
// if err != nil {
// log.Fatal(err)
// }
//
// fmt.Printf("Found %d audit entries for tenant\n", len(result.Entries))
// for _, entry := range result.Entries {
// fmt.Printf(" [%s] %s - %s\n",
// entry.Timestamp.Format(time.RFC3339),
// entry.RequestType,
// entry.PolicyDecision)
// }
//
// // With custom options
// opts := &axonflow.AuditQueryOptions{Limit: 100, Offset: 50}
// result, err = client.GetAuditLogsByTenant(context.Background(), "tenant-abc", opts)
func (c *AxonFlowClient) GetAuditLogsByTenant(ctx context.Context, tenantID string, opts *AuditQueryOptions) (*AuditSearchResponse, error) {
if tenantID == "" {
return nil, fmt.Errorf("tenantID is required")
}
// Apply defaults
limit := 50
offset := 0
if opts != nil {
if opts.Limit > 0 {
limit = opts.Limit
}
if opts.Limit > 1000 {
limit = 1000
}
if opts.Offset > 0 {
offset = opts.Offset
}
}
fullURL := fmt.Sprintf("%s/api/v1/audit/tenant/%s?limit=%d&offset=%d",
c.config.Endpoint, tenantID, limit, offset)
httpReq, err := http.NewRequestWithContext(ctx, "GET", fullURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create tenant audit request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
c.addAuthHeaders(httpReq)
if c.config.Debug {
log.Printf("[AxonFlow] Get audit logs for tenant: %s (limit: %d, offset: %d)", tenantID, limit, offset)
}
resp, err := c.doHttpRequest(c.httpClient, httpReq)
if err != nil {
return nil, fmt.Errorf("tenant audit request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read tenant audit response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, &httpError{
statusCode: resp.StatusCode,
message: string(body),
}
}
result, err := decodeAuditPage(body, limit, offset)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal tenant audit response: %w", err)
}
// Same rule, same family as SearchAuditLogs — see refuseVacuousScopedPage.
if scopeErr := refuseVacuousScopedPage(resp, "audit entries", len(result.Entries)); scopeErr != nil {
return nil, scopeErr
}
if c.config.Debug {
log.Printf("[AxonFlow] Tenant audit returned %d entries", len(result.Entries))
}
return result, nil
}
// addAuthHeaders adds OAuth2-style Basic auth header to the request.
// The server derives tenant context from the authenticated clientId.
//
// X-Client-ID (v9): every governed request also carries the effective
// client_id as a separate header so server-side identity decisions
// don't have to re-decode Basic auth. The agent's apiAuthMiddleware
// overwrites the header with its auth-derived value, so any caller-
// supplied X-Client-ID is harmless (no spoofing surface).
//
// It also stamps the per-user READ identity (X-User-Token) via
// applyReadIdentity. This is the SDK's ONE identity site: every method that
// builds a request calls this helper, and the platform likewise reads the
// header once in the middleware in front of every proxied route rather than
// per route. Adding it in a method instead would be a second copy of a
// decision that is made in one place on both sides. See read_identity.go.
func (c *AxonFlowClient) addAuthHeaders(req *http.Request) {
effectiveClientID := c.config.ClientID
if effectiveClientID == "" {
effectiveClientID = "community"
}
credentials := base64.StdEncoding.EncodeToString(
[]byte(effectiveClientID + ":" + c.config.ClientSecret),
)
req.Header.Set("Authorization", "Basic "+credentials)
req.Header.Set("X-Client-ID", effectiveClientID)
c.applyReadIdentity(req)
applyPEPHandshake(req)
}