audit-go/audit/api/api_mock.go
Christian Schaible dff37867e5 Add event source, region and container reference to audit event and
replace wrapping protobuf message type with cloud event wrapper
2024-07-18 14:09:07 +02:00

77 lines
2.1 KiB
Go

package api
import (
"context"
"fmt"
"github.com/google/uuid"
"google.golang.org/protobuf/proto"
auditV1 "dev.azure.com/schwarzit/schwarzit.stackit-core-platform/common-audit.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 {
validator *ProtobufValidator
}
func NewMockAuditApi() (*AuditApi, error) {
validator, err := protovalidate.New()
if err != nil {
return nil, err
}
var protobufValidator ProtobufValidator = validator
var auditApi AuditApi = &MockAuditApi{validator: &protobufValidator}
return &auditApi, nil
}
// Log implements AuditApi.Log.
// Validates and serializes the event but doesn't send it.
func (a *MockAuditApi) Log(
_ context.Context,
event *auditV1.AuditEvent,
visibility auditV1.Visibility,
routingIdentifier *RoutingIdentifier,
objectIdentifier *auditV1.ObjectIdentifier,
) error {
_, err := a.ValidateAndSerialize(event, visibility, routingIdentifier, objectIdentifier)
return err
}
// ValidateAndSerialize implements AuditApi.ValidateAndSerialize
func (a *MockAuditApi) ValidateAndSerialize(
event *auditV1.AuditEvent,
visibility auditV1.Visibility,
routingIdentifier *RoutingIdentifier,
objectIdentifier *auditV1.ObjectIdentifier,
) (*CloudEvent, error) {
routableEvent, err := validateAndSerializePartially(a.validator, event, visibility, routingIdentifier, objectIdentifier)
if err != nil {
return nil, err
}
routableEventBytes, err := proto.Marshal(routableEvent)
if err != nil {
return nil, err
}
message := CloudEvent{
specVersion: "1.0",
source: event.EventSource,
id: uuid.NewString(),
time: event.EventTimeStamp.AsTime(),
dataContentType: "application/cloudevents+protobuf",
dataType: fmt.Sprintf("%v", routableEvent.ProtoReflect().Descriptor().FullName()),
data: routableEventBytes,
}
return &message, nil
}
// Send implements AuditApi.Send
func (a *MockAuditApi) Send(context.Context, *RoutingIdentifier, *CloudEvent) error {
return nil
}