audit-go/audit/api/api_mock.go
2024-10-30 15:41:48 +01:00

97 lines
2.6 KiB
Go

package api
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"strings"
"google.golang.org/protobuf/proto"
auditV1 "dev.azure.com/schwarzit/schwarzit.stackit-public/audit-go.git/gen/go/audit/v1"
"github.com/bufbuild/protovalidate-go"
)
// MockAuditApi is an implementation of AuditApi that does nothing and has no dependency to external systems.
type MockAuditApi struct {
tracer trace.Tracer
validator *ProtobufValidator
}
func NewMockAuditApi() (*AuditApi, error) {
validator, err := protovalidate.New()
if err != nil {
return nil, err
}
var protobufValidator ProtobufValidator = validator
var auditApi AuditApi = &MockAuditApi{
tracer: otel.Tracer("mock-audit-api"),
validator: &protobufValidator,
}
return &auditApi, nil
}
// Log implements AuditApi.Log.
// Validates and serializes the event but doesn't send it.
func (a *MockAuditApi) Log(
ctx context.Context,
event *auditV1.AuditLogEntry,
visibility auditV1.Visibility,
routableIdentifier *RoutableIdentifier,
) error {
_, err := a.ValidateAndSerialize(ctx, event, visibility, routableIdentifier)
return err
}
// ValidateAndSerialize implements AuditApi.ValidateAndSerialize
func (a *MockAuditApi) ValidateAndSerialize(
ctx context.Context,
event *auditV1.AuditLogEntry,
visibility auditV1.Visibility,
routableIdentifier *RoutableIdentifier,
) (*CloudEvent, error) {
ctx, span := a.tracer.Start(ctx, "validate-and-serialize")
defer span.End()
routableEvent, err := validateAndSerializePartially(a.validator, event, visibility, routableIdentifier)
if err != nil {
return nil, err
}
// Reject event type data-access as the downstream services
// cannot handle it at the moment
if strings.HasSuffix(event.LogName, string(EventTypeDataAccess)) {
return nil, ErrUnsupportedEventTypeDataAccess
}
routableEventBytes, err := proto.Marshal(routableEvent)
if err != nil {
return nil, err
}
traceParent, traceState := TraceParentAndStateFromContext(ctx)
message := CloudEvent{
SpecVersion: "1.0",
Source: event.ProtoPayload.ServiceName,
Id: event.InsertId,
Time: event.ProtoPayload.RequestMetadata.RequestAttributes.Time.AsTime(),
DataContentType: "application/cloudevents+protobuf",
DataType: fmt.Sprintf("%v", routableEvent.ProtoReflect().Descriptor().FullName()),
Subject: event.ProtoPayload.ResourceName,
Data: routableEventBytes,
TraceParent: &traceParent,
TraceState: &traceState,
}
return &message, nil
}
// Send implements AuditApi.Send
func (a *MockAuditApi) Send(context.Context, *RoutableIdentifier, *CloudEvent) error {
return nil
}