SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(audittypes): align types with revised schema doc (#10826)
Pandey726948db9e3d
diff --git a/pkg/auditor/auditorserver/server_test.go b/pkg/auditor/auditorserver/server_test.goindex 4bd6cb1627..666fd1f651 100644--- a/pkg/auditor/auditorserver/server_test.go+++ b/pkg/auditor/auditorserver/server_test.go@@ -28,7 +28,7 @@ func newTestEvent(resource string, action audittypes.Action) audittypes.AuditEveOutcome: audittypes.OutcomeSuccess,},ResourceAttributes: audittypes.ResourceAttributes{- ResourceName: resource,+ ResourceKind: resource,},}}diff --git a/pkg/http/handler/option.go b/pkg/http/handler/option.goindex 9c19d0fbee..f8dbf6c92a 100644--- a/pkg/http/handler/option.go+++ b/pkg/http/handler/option.go@@ -8,7 +8,7 @@ import (type Option func(*handler)type AuditDef struct {- ResourceName string // AuthZ Typeable.Name() value, e.g. "dashboard", "user".+ ResourceKind string // AuthZ Typeable.Kind() value, e.g. "dashboard", "user".Action audittypes.Action // create, update, delete, login, etc.Category audittypes.ActionCategory // access_control, configuration_change, etc.ResourceIDParam string // Gorilla mux path param name for the resource ID.diff --git a/pkg/http/middleware/audit.go b/pkg/http/middleware/audit.goindex d8147f2f08..7cb635ca58 100644--- a/pkg/http/middleware/audit.go+++ b/pkg/http/middleware/audit.go@@ -125,7 +125,7 @@ func (middleware *Audit) emitAuditEvent(req *http.Request, writer responseCapturdef.Category,claims,resourceIDFromRequest(req, def.ResourceIDParam),- def.ResourceName,+ def.ResourceKind,errorType,errorCode,)diff --git a/pkg/types/audittypes/attributes.go b/pkg/types/audittypes/attributes.goindex 4462d0589e..1c2b10056b 100644--- a/pkg/types/audittypes/attributes.go+++ b/pkg/types/audittypes/attributes.go@@ -68,20 +68,24 @@ func (attributes PrincipalAttributes) Put(dest pcommon.Map) {}// Audit attributes — Resource (On What).+// These are OTel resource attributes (placed on the Resource, not event attributes).type ResourceAttributes struct {ResourceID string- ResourceName string // guaranteed to be present+ ResourceKind string // guaranteed to be present}-func NewResourceAttributes(resourceID, resourceName string) ResourceAttributes {+func NewResourceAttributes(resourceID, resourceKind string) ResourceAttributes {return ResourceAttributes{ResourceID: resourceID,- ResourceName: resourceName,+ ResourceKind: resourceKind,}}-func (attributes ResourceAttributes) Put(dest pcommon.Map) {- putStrIfNotEmpty(dest, "signoz.audit.resource.name", attributes.ResourceName)+// PutResource writes the resource attributes to an OTel Resource's attribute map.+// These are resource-level attributes (stored in the resource JSON column),+// not event-level attributes (stored in attributes_string).+func (attributes ResourceAttributes) PutResource(dest pcommon.Map) {+ putStrIfNotEmpty(dest, "signoz.audit.resource.kind", attributes.ResourceKind)putStrIfNotEmpty(dest, "signoz.audit.resource.id", attributes.ResourceID)}@@ -108,26 +112,40 @@ func (attributes ErrorAttributes) Put(dest pcommon.Map) {// Audit attributes — Transport Context (Where/How).type TransportAttributes struct {- HTTPMethod string- HTTPRoute string- HTTPStatusCode int- URLPath string- ClientAddress string- UserAgent string+ NetworkProtocolName string+ NetworkProtocolVersion string+ URLScheme string+ HTTPMethod string+ HTTPRoute string+ HTTPStatusCode int+ URLPath string+ ClientAddress string+ UserAgent string}func NewTransportAttributesFromHTTP(req *http.Request, route string, statusCode int) TransportAttributes {+ scheme := "http"+ if req.TLS != nil {+ scheme = "https"+ }+return TransportAttributes{- HTTPMethod: req.Method,- HTTPRoute: route,- HTTPStatusCode: statusCode,- URLPath: req.URL.Path,- ClientAddress: req.RemoteAddr,- UserAgent: req.UserAgent(),+ NetworkProtocolName: "http",+ NetworkProtocolVersion: req.Proto,+ URLScheme: scheme,+ HTTPMethod: req.Method,+ HTTPRoute: route,+ HTTPStatusCode: statusCode,+ URLPath: req.URL.Path,+ ClientAddress: req.RemoteAddr,+ UserAgent: req.UserAgent(),}}func (attributes TransportAttributes) Put(dest pcommon.Map) {+ putStrIfNotEmpty(dest, string(semconv.NetworkProtocolNameKey), attributes.NetworkProtocolName)+ putStrIfNotEmpty(dest, string(semconv.NetworkProtocolVersionKey), attributes.NetworkProtocolVersion)+ putStrIfNotEmpty(dest, string(semconv.URLSchemeKey), attributes.URLScheme)putStrIfNotEmpty(dest, string(semconv.HTTPRequestMethodKey), attributes.HTTPMethod)putStrIfNotEmpty(dest, string(semconv.HTTPRouteKey), attributes.HTTPRoute)if attributes.HTTPStatusCode != 0 {@@ -172,9 +190,9 @@ func newBody(auditAttributes AuditAttributes, principalAttributes PrincipalAttrib.WriteString(auditAttributes.Action.StringValue())}- // Resource: " name (id)" or " name".+ // Resource: " kind (id)" or " kind".b.WriteString(" ")- b.WriteString(resourceAttributes.ResourceName)+ b.WriteString(resourceAttributes.ResourceKind)if resourceAttributes.ResourceID != "" {b.WriteString(" (")b.WriteString(resourceAttributes.ResourceID)diff --git a/pkg/types/audittypes/attributes_test.go b/pkg/types/audittypes/attributes_test.goindex 26f6ee9ad8..a3cef9f1ca 100644--- a/pkg/types/audittypes/attributes_test.go+++ b/pkg/types/audittypes/attributes_test.go@@ -63,7 +63,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{},expectedBody: "[email protected] (019a1234-abcd-7000-8000-567800000001) deleted dashboard",@@ -81,7 +81,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "abd",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{},expectedBody: "019a1234-abcd-7000-8000-567800000001 deleted dashboard (abd)",@@ -99,7 +99,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "abd",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{},expectedBody: "deleted dashboard (abd)",@@ -117,7 +117,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "019b-5678",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{},expectedBody: "[email protected] (019a1234-abcd-7000-8000-567800000001) created dashboard (019b-5678)",@@ -131,7 +131,7 @@ func TestNewBody(t *testing.T) {},principalAttributes: PrincipalAttributes{},resourceAttributes: ResourceAttributes{- ResourceName: "alert-rule",+ ResourceKind: "alert-rule",},errorAttributes: ErrorAttributes{},expectedBody: "updated alert-rule",@@ -149,7 +149,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "019b-5678",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{ErrorType: "forbidden",@@ -168,7 +168,7 @@ func TestNewBody(t *testing.T) {PrincipalEmail: valuer.MustNewEmail("[email protected]"),},resourceAttributes: ResourceAttributes{- ResourceName: "user",+ ResourceKind: "user",},errorAttributes: ErrorAttributes{ErrorType: "not-found",@@ -187,7 +187,7 @@ func TestNewBody(t *testing.T) {},resourceAttributes: ResourceAttributes{ResourceID: "019b-5678",- ResourceName: "dashboard",+ ResourceKind: "dashboard",},errorAttributes: ErrorAttributes{},expectedBody: "[email protected] (019a1234-abcd-7000-8000-567800000001) failed to create dashboard (019b-5678)",diff --git a/pkg/types/audittypes/event.go b/pkg/types/audittypes/event.goindex 19f3facbde..d2c194ae50 100644--- a/pkg/types/audittypes/event.go+++ b/pkg/types/audittypes/event.go@@ -53,13 +53,13 @@ func NewAuditEventFromHTTPRequest(actionCategory ActionCategory,claims authtypes.Claims,resourceID string,- resourceName string,+ resourceKind string,errorType string,errorCode string,) AuditEvent {auditAttributes := NewAuditAttributesFromHTTP(statusCode, action, actionCategory, claims)principalAttributes := NewPrincipalAttributesFromClaims(claims)- resourceAttributes := NewResourceAttributes(resourceID, resourceName)+ resourceAttributes := NewResourceAttributes(resourceID, resourceKind)errorAttributes := NewErrorAttributes(errorType, errorCode)transportAttributes := NewTransportAttributesFromHTTP(req, route, statusCode)@@ -68,7 +68,7 @@ func NewAuditEventFromHTTPRequest(TraceID: traceID,SpanID: spanID,Body: newBody(auditAttributes, principalAttributes, resourceAttributes, errorAttributes),- EventName: NewEventName(resourceAttributes.ResourceName, auditAttributes.Action),+ EventName: NewEventName(resourceAttributes.ResourceKind, auditAttributes.Action),AuditAttributes: auditAttributes,PrincipalAttributes: principalAttributes,ResourceAttributes: resourceAttributes,@@ -80,14 +80,34 @@ func NewAuditEventFromHTTPRequest(func NewPLogsFromAuditEvents(events []AuditEvent, name string, version string, scope string) plog.Logs {logs := plog.NewLogs()- resourceLogs := logs.ResourceLogs().AppendEmpty()- resourceLogs.Resource().Attributes().PutStr(string(semconv.ServiceNameKey), name)- resourceLogs.Resource().Attributes().PutStr(string(semconv.ServiceVersionKey), version)- scopeLogs := resourceLogs.ScopeLogs().AppendEmpty()- scopeLogs.Scope().SetName(scope)+ // Group events by target resource so each ResourceLogs has uniform resource attributes.+ type resourceKey struct {+ kind string+ id string+ }+ groups := make(map[resourceKey][]int)+ order := make([]resourceKey, 0)+ for i, event := range events {+ key := resourceKey{kind: event.ResourceAttributes.ResourceKind, id: event.ResourceAttributes.ResourceID}+ if _, exists := groups[key]; !exists {+ order = append(order, key)+ }+ groups[key] = append(groups[key], i)+ }++ for _, key := range order {+ resourceLogs := logs.ResourceLogs().AppendEmpty()+ resourceAttrs := resourceLogs.Resource().Attributes()+ resourceAttrs.PutStr(string(semconv.ServiceNameKey), name)+ resourceAttrs.PutStr(string(semconv.ServiceVersionKey), version)+ events[groups[key][0]].ResourceAttributes.PutResource(resourceAttrs)++ scopeLogs := resourceLogs.ScopeLogs().AppendEmpty()+ scopeLogs.Scope().SetName(scope)- for i := range events {- events[i].ToLogRecord(scopeLogs.LogRecords().AppendEmpty())+ for _, idx := range groups[key] {+ events[idx].ToLogRecord(scopeLogs.LogRecords().AppendEmpty())+ }}return logs@@ -123,8 +143,8 @@ func (event AuditEvent) ToLogRecord(dest plog.LogRecord) {// Principal attributesevent.PrincipalAttributes.Put(attrs)- // Resource attributes- event.ResourceAttributes.Put(attrs)+ // Resource attributes are set at the ResourceLogs level, not per-LogRecord.+ // See NewPLogsFromAuditEvents.// Error attributesevent.ErrorAttributes.Put(attrs)diff --git a/pkg/types/audittypes/event_name.go b/pkg/types/audittypes/event_name.goindex fe91b0e09b..df4fdb3eee 100644--- a/pkg/types/audittypes/event_name.go+++ b/pkg/types/audittypes/event_name.go@@ -6,16 +6,16 @@ type EventName struct {s string}-// NewEventName derives the audit event name from a resource name and action.-// Format: {resource_name}.{pastTense(action)}+// NewEventName derives the audit event name from a resource kind and action.+// Format: {resource_kind}.{pastTense(action)}//// Examples://// NewEventName("dashboard", ActionCreate) → "dashboard.created"// NewEventName("dashboard", ActionUpdate) → "dashboard.updated"// NewEventName("user.role", ActionUpdate) → "user.role.updated"-func NewEventName(resourceName string, action Action) EventName {- return EventName{s: resourceName + "." + action.PastTense()}+func NewEventName(resourceKind string, action Action) EventName {+ return EventName{s: resourceKind + "." + action.PastTense()}}// String returns the string representation of the event name.diff --git a/pkg/types/audittypes/event_test.go b/pkg/types/audittypes/event_test.goindex 8fdd6a8eb0..b04547668c 100644--- a/pkg/types/audittypes/event_test.go+++ b/pkg/types/audittypes/event_test.go@@ -24,7 +24,7 @@ func TestNewAuditEventFromHTTPRequest(t *testing.T) {category ActionCategoryclaims authtypes.ClaimsresourceID string- resourceName string+ resourceKind stringerrorType stringerrorCode stringexpectedOutcome Outcome@@ -40,7 +40,7 @@ func TestNewAuditEventFromHTTPRequest(t *testing.T) {category: ActionCategoryConfigurationChange,claims: authtypes.Claims{UserID: "019a1234-abcd-7000-8000-567800000001", Email: "[email protected]", OrgID: "019a-0000-0000-0001", IdentNProvider: authtypes.IdentNProviderTokenizer},resourceID: "019b-5678-efgh-9012",- resourceName: "dashboard",+ resourceKind: "dashboard",expectedOutcome: OutcomeSuccess,expectedBody: "[email protected] (019a1234-abcd-7000-8000-567800000001) created dashboard (019b-5678-efgh-9012)",},@@ -54,7 +54,7 @@ func TestNewAuditEventFromHTTPRequest(t *testing.T) {category: ActionCategoryConfigurationChange,claims: authtypes.Claims{UserID: "019aaaaa-bbbb-7000-8000-cccc00000002", Email: "[email protected]", OrgID: "019a-0000-0000-0001", IdentNProvider: authtypes.IdentNProviderTokenizer},resourceID: "019b-5678-efgh-9012",- resourceName: "dashboard",+ resourceKind: "dashboard",errorType: "forbidden",errorCode: "authz_forbidden",expectedOutcome: OutcomeFailure,@@ -76,14 +76,14 @@ func TestNewAuditEventFromHTTPRequest(t *testing.T) {testCase.category,testCase.claims,testCase.resourceID,- testCase.resourceName,+ testCase.resourceKind,testCase.errorType,testCase.errorCode,)assert.Equal(t, testCase.expectedOutcome, event.AuditAttributes.Outcome)assert.Equal(t, testCase.expectedBody, event.Body)- assert.Equal(t, testCase.resourceName, event.ResourceAttributes.ResourceName)+ assert.Equal(t, testCase.resourceKind, event.ResourceAttributes.ResourceKind)assert.Equal(t, testCase.resourceID, event.ResourceAttributes.ResourceID)assert.Equal(t, testCase.action, event.AuditAttributes.Action)assert.Equal(t, testCase.category, event.AuditAttributes.ActionCategory)@@ -97,3 +97,141 @@ func TestNewAuditEventFromHTTPRequest(t *testing.T) {})}}++func newTestEvent(resourceKind, resourceID string, action Action) AuditEvent {+ return AuditEvent{+ Body: resourceKind + "." + action.PastTense(),+ EventName: NewEventName(resourceKind, action),+ AuditAttributes: AuditAttributes{+ Action: action,+ ActionCategory: ActionCategoryConfigurationChange,+ Outcome: OutcomeSuccess,+ },+ ResourceAttributes: ResourceAttributes{+ ResourceKind: resourceKind,+ ResourceID: resourceID,+ },+ }+}++func TestNewPLogsFromAuditEvents(t *testing.T) {+ testCases := []struct {+ name string+ events []AuditEvent+ expectedResourceLogs int+ expectedResourceKinds []string+ expectedResourceIDs []string+ expectedLogRecordCounts []int+ }{+ {+ name: "Empty",+ events: []AuditEvent{},+ expectedResourceLogs: 0,+ },+ {+ name: "SingleEvent",+ events: []AuditEvent{+ newTestEvent("dashboard", "d-001", ActionCreate),+ },+ expectedResourceLogs: 1,+ expectedResourceKinds: []string{"dashboard"},+ expectedResourceIDs: []string{"d-001"},+ expectedLogRecordCounts: []int{1},+ },+ {+ name: "SameResource_MultipleEvents",+ events: []AuditEvent{+ newTestEvent("dashboard", "d-001", ActionCreate),+ newTestEvent("dashboard", "d-001", ActionUpdate),+ newTestEvent("dashboard", "d-001", ActionDelete),+ },+ expectedResourceLogs: 1,+ expectedResourceKinds: []string{"dashboard"},+ expectedResourceIDs: []string{"d-001"},+ expectedLogRecordCounts: []int{3},+ },+ {+ name: "DifferentResources_SeparateGroups",+ events: []AuditEvent{+ newTestEvent("dashboard", "d-001", ActionUpdate),+ newTestEvent("user", "u-001", ActionDelete),+ },+ expectedResourceLogs: 2,+ expectedResourceKinds: []string{"dashboard", "user"},+ expectedResourceIDs: []string{"d-001", "u-001"},+ expectedLogRecordCounts: []int{1, 1},+ },+ {+ name: "SameKind_DifferentIDs_SeparateGroups",+ events: []AuditEvent{+ newTestEvent("dashboard", "d-001", ActionUpdate),+ newTestEvent("dashboard", "d-002", ActionDelete),+ },+ expectedResourceLogs: 2,+ expectedResourceKinds: []string{"dashboard", "dashboard"},+ expectedResourceIDs: []string{"d-001", "d-002"},+ expectedLogRecordCounts: []int{1, 1},+ },+ {+ name: "InterleavedResources_GroupedCorrectly",+ events: []AuditEvent{+ newTestEvent("dashboard", "d-001", ActionCreate),+ newTestEvent("user", "u-001", ActionUpdate),+ newTestEvent("dashboard", "d-001", ActionUpdate),+ newTestEvent("user", "u-001", ActionDelete),+ newTestEvent("dashboard", "d-001", ActionDelete),+ },+ expectedResourceLogs: 2,+ expectedResourceKinds: []string{"dashboard", "user"},+ expectedResourceIDs: []string{"d-001", "u-001"},+ expectedLogRecordCounts: []int{3, 2},+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ logs := NewPLogsFromAuditEvents(testCase.events, "signoz", "0.90.0", "signoz.audit")++ assert.Equal(t, testCase.expectedResourceLogs, logs.ResourceLogs().Len())++ for i := 0; i < logs.ResourceLogs().Len(); i++ {+ resourceLogs := logs.ResourceLogs().At(i)+ resourceAttrs := resourceLogs.Resource().Attributes()++ // Verify service resource attributes+ serviceName, exists := resourceAttrs.Get("service.name")+ assert.True(t, exists)+ assert.Equal(t, "signoz", serviceName.Str())++ serviceVersion, exists := resourceAttrs.Get("service.version")+ assert.True(t, exists)+ assert.Equal(t, "0.90.0", serviceVersion.Str())++ // Verify audit resource attributes on Resource (not event attributes)+ kind, exists := resourceAttrs.Get("signoz.audit.resource.kind")+ assert.True(t, exists)+ assert.Equal(t, testCase.expectedResourceKinds[i], kind.Str())++ id, exists := resourceAttrs.Get("signoz.audit.resource.id")+ assert.True(t, exists)+ assert.Equal(t, testCase.expectedResourceIDs[i], id.Str())++ // Verify scope+ assert.Equal(t, 1, resourceLogs.ScopeLogs().Len())+ assert.Equal(t, "signoz.audit", resourceLogs.ScopeLogs().At(0).Scope().Name())++ // Verify log record count per group+ assert.Equal(t, testCase.expectedLogRecordCounts[i], resourceLogs.ScopeLogs().At(0).LogRecords().Len())++ // Verify resource attrs are NOT in log record event attributes+ for j := 0; j < resourceLogs.ScopeLogs().At(0).LogRecords().Len(); j++ {+ recordAttrs := resourceLogs.ScopeLogs().At(0).LogRecords().At(j).Attributes()+ _, hasKind := recordAttrs.Get("signoz.audit.resource.kind")+ _, hasID := recordAttrs.Get("signoz.audit.resource.id")+ assert.False(t, hasKind, "resource.kind must not be in log record attributes")+ assert.False(t, hasID, "resource.id must not be in log record attributes")+ }+ }+ })+ }+}