Implement audit logging functionality across services and middleware
- Introduced a new `auditlog` package to handle audit logging for user actions, including creation, updates, deletions, and authentication events. - Enhanced existing services (customer, user) to log relevant actions using the new audit logger, capturing details such as actor ID, action type, target type, and success status. - Added middleware to enrich request context with metadata for audit logging, ensuring comprehensive tracking of user interactions. - Integrated Elasticsearch for persistent storage of audit logs, with fallback to file-only logging if Elasticsearch is unavailable. - Updated API documentation to include new audit log endpoints for administrative access. This update significantly improves the system's ability to track and audit user actions, enhancing security and accountability within the application.
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package audit
|
||||
|
||||
const ActionPasswordReset = "auth.password.reset"
|
||||
|
||||
const (
|
||||
ActorTypeAdmin = "admin"
|
||||
ActorTypeCustomer = "customer"
|
||||
ActorTypeSystem = "system"
|
||||
)
|
||||
|
||||
const (
|
||||
TargetTypeAdmin = "admin"
|
||||
TargetTypeCustomer = "customer"
|
||||
TargetTypeUser = "user"
|
||||
)
|
||||
|
||||
const (
|
||||
ActionAuthLoginSuccess = "auth.login.success"
|
||||
ActionAuthLoginFailure = "auth.login.failure"
|
||||
ActionAuthLogout = "auth.logout"
|
||||
ActionAuthPasswordChange = "auth.password.change"
|
||||
ActionAuthPasswordResetRequest = "auth.password.reset.request"
|
||||
|
||||
ActionUserCreate = "user.create"
|
||||
ActionUserUpdate = "user.update"
|
||||
ActionUserDelete = "user.delete"
|
||||
ActionUserStatusChange = "user.status.change"
|
||||
ActionUserRead = "user.read"
|
||||
ActionUserList = "user.list"
|
||||
|
||||
ActionCustomerCreate = "customer.create"
|
||||
ActionCustomerUpdate = "customer.update"
|
||||
ActionCustomerDelete = "customer.delete"
|
||||
ActionCustomerStatusChange = "customer.status.change"
|
||||
ActionCustomerRead = "customer.read"
|
||||
ActionCustomerList = "customer.list"
|
||||
)
|
||||
+49
-9
@@ -7,21 +7,19 @@ import (
|
||||
"tm/pkg/logger"
|
||||
)
|
||||
|
||||
const ActionPasswordReset = "password.reset"
|
||||
|
||||
// TargetType values for audit entries.
|
||||
const (
|
||||
TargetTypeAdmin = "admin"
|
||||
TargetTypeCustomer = "customer"
|
||||
)
|
||||
|
||||
// Entry represents a security-relevant audit event.
|
||||
type Entry struct {
|
||||
ActorID string
|
||||
ActorType string
|
||||
TargetType string
|
||||
TargetID string
|
||||
Action string
|
||||
At int64
|
||||
IP string
|
||||
RequestID string
|
||||
UserAgent string
|
||||
Success bool
|
||||
Metadata map[string]string
|
||||
}
|
||||
|
||||
// Logger records audit events.
|
||||
@@ -33,12 +31,13 @@ type auditLogger struct {
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// NewLogger creates an audit logger backed by structured application logs.
|
||||
// NewLogger creates an audit logger backed by structured application logs only.
|
||||
func NewLogger(log logger.Logger) Logger {
|
||||
return &auditLogger{logger: log}
|
||||
}
|
||||
|
||||
func (a *auditLogger) Log(ctx context.Context, entry Entry) {
|
||||
entry = enrichEntry(ctx, entry)
|
||||
if entry.At == 0 {
|
||||
entry.At = time.Now().Unix()
|
||||
}
|
||||
@@ -46,9 +45,50 @@ func (a *auditLogger) Log(ctx context.Context, entry Entry) {
|
||||
a.logger.Info("audit event", map[string]interface{}{
|
||||
"audit": true,
|
||||
"actor_id": entry.ActorID,
|
||||
"actor_type": entry.ActorType,
|
||||
"target_type": entry.TargetType,
|
||||
"target_id": entry.TargetID,
|
||||
"action": entry.Action,
|
||||
"at": entry.At,
|
||||
"ip": entry.IP,
|
||||
"request_id": entry.RequestID,
|
||||
"user_agent": entry.UserAgent,
|
||||
"success": entry.Success,
|
||||
"metadata": entry.Metadata,
|
||||
})
|
||||
}
|
||||
|
||||
type compositeLogger struct {
|
||||
fileLogger Logger
|
||||
store Store
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// NewCompositeLogger writes audit events to structured logs and an optional store.
|
||||
func NewCompositeLogger(log logger.Logger, store Store) Logger {
|
||||
if store == nil {
|
||||
store = NoopStore()
|
||||
}
|
||||
return &compositeLogger{
|
||||
fileLogger: NewLogger(log),
|
||||
store: store,
|
||||
logger: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *compositeLogger) Log(ctx context.Context, entry Entry) {
|
||||
entry = enrichEntry(ctx, entry)
|
||||
if entry.At == 0 {
|
||||
entry.At = time.Now().Unix()
|
||||
}
|
||||
|
||||
c.fileLogger.Log(ctx, entry)
|
||||
|
||||
doc := entryToDocument(entry)
|
||||
if err := c.store.Save(ctx, doc); err != nil {
|
||||
c.logger.Error("Failed to persist audit event", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"action": entry.Action,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type contextKey int
|
||||
|
||||
const (
|
||||
keyRequestMeta contextKey = iota
|
||||
keyActor
|
||||
)
|
||||
|
||||
type RequestMeta struct {
|
||||
IP string
|
||||
RequestID string
|
||||
UserAgent string
|
||||
}
|
||||
|
||||
type Actor struct {
|
||||
ID string
|
||||
Type string
|
||||
}
|
||||
|
||||
func WithRequestMeta(ctx context.Context, meta RequestMeta) context.Context {
|
||||
return context.WithValue(ctx, keyRequestMeta, meta)
|
||||
}
|
||||
|
||||
func WithActor(ctx context.Context, actor Actor) context.Context {
|
||||
return context.WithValue(ctx, keyActor, actor)
|
||||
}
|
||||
|
||||
func RequestMetaFromContext(ctx context.Context) (RequestMeta, bool) {
|
||||
meta, ok := ctx.Value(keyRequestMeta).(RequestMeta)
|
||||
return meta, ok
|
||||
}
|
||||
|
||||
func ActorFromContext(ctx context.Context) (Actor, bool) {
|
||||
actor, ok := ctx.Value(keyActor).(Actor)
|
||||
return actor, ok
|
||||
}
|
||||
|
||||
func enrichEntry(ctx context.Context, entry Entry) Entry {
|
||||
if entry.At == 0 {
|
||||
entry.At = time.Now().Unix()
|
||||
}
|
||||
|
||||
if meta, ok := RequestMetaFromContext(ctx); ok {
|
||||
if entry.IP == "" {
|
||||
entry.IP = meta.IP
|
||||
}
|
||||
if entry.RequestID == "" {
|
||||
entry.RequestID = meta.RequestID
|
||||
}
|
||||
if entry.UserAgent == "" {
|
||||
entry.UserAgent = meta.UserAgent
|
||||
}
|
||||
}
|
||||
|
||||
if entry.ActorID == "" || entry.ActorType == "" {
|
||||
if actor, ok := ActorFromContext(ctx); ok {
|
||||
if entry.ActorID == "" {
|
||||
entry.ActorID = actor.ID
|
||||
}
|
||||
if entry.ActorType == "" {
|
||||
entry.ActorType = actor.Type
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entry
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnrichEntryFromContext(t *testing.T) {
|
||||
ctx := WithRequestMeta(context.Background(), RequestMeta{
|
||||
IP: "127.0.0.1",
|
||||
RequestID: "req-1",
|
||||
UserAgent: "test-agent",
|
||||
})
|
||||
ctx = WithActor(ctx, Actor{ID: "actor-1", Type: ActorTypeAdmin})
|
||||
|
||||
entry := enrichEntry(ctx, Entry{
|
||||
Action: ActionAuthLoginSuccess,
|
||||
TargetType: TargetTypeAdmin,
|
||||
TargetID: "actor-1",
|
||||
Success: true,
|
||||
})
|
||||
|
||||
if entry.ActorID != "actor-1" {
|
||||
t.Fatalf("expected actor_id actor-1, got %s", entry.ActorID)
|
||||
}
|
||||
if entry.IP != "127.0.0.1" {
|
||||
t.Fatalf("expected ip 127.0.0.1, got %s", entry.IP)
|
||||
}
|
||||
if entry.RequestID != "req-1" {
|
||||
t.Fatalf("expected request_id req-1, got %s", entry.RequestID)
|
||||
}
|
||||
if entry.At == 0 {
|
||||
t.Fatal("expected timestamp to be set")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package audit
|
||||
|
||||
import "strconv"
|
||||
|
||||
// MergeMetadata combines multiple metadata maps into one.
|
||||
func MergeMetadata(parts ...map[string]string) map[string]string {
|
||||
merged := make(map[string]string)
|
||||
for _, part := range parts {
|
||||
for key, value := range part {
|
||||
if value != "" {
|
||||
merged[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(merged) == 0 {
|
||||
return nil
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
// FlagMetadata returns a single boolean flag metadata entry when condition is true.
|
||||
func FlagMetadata(key string, condition bool) map[string]string {
|
||||
if !condition {
|
||||
return nil
|
||||
}
|
||||
return map[string]string{key: "true"}
|
||||
}
|
||||
|
||||
// StringMetadata returns metadata for a non-empty string value.
|
||||
func StringMetadata(key, value string) map[string]string {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return map[string]string{key: value}
|
||||
}
|
||||
|
||||
// OptionalStringMetadata returns metadata when a pointer string is set and non-empty.
|
||||
func OptionalStringMetadata(key string, value *string) map[string]string {
|
||||
if value == nil || *value == "" {
|
||||
return nil
|
||||
}
|
||||
return map[string]string{key: *value}
|
||||
}
|
||||
|
||||
// PaginationMetadata returns safe pagination metadata for list audit events.
|
||||
func PaginationMetadata(limit, offset int, totalCount int64) map[string]string {
|
||||
return map[string]string{
|
||||
"limit": strconv.Itoa(limit),
|
||||
"offset": strconv.Itoa(offset),
|
||||
"result_count": strconv.FormatInt(totalCount, 10),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMergeMetadata(t *testing.T) {
|
||||
merged := MergeMetadata(
|
||||
map[string]string{"status": "active"},
|
||||
map[string]string{"role": "admin"},
|
||||
nil,
|
||||
)
|
||||
|
||||
if merged["status"] != "active" || merged["role"] != "admin" {
|
||||
t.Fatalf("unexpected merged metadata: %#v", merged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagMetadata(t *testing.T) {
|
||||
if FlagMetadata("has_search", false) != nil {
|
||||
t.Fatal("expected nil metadata for false flag")
|
||||
}
|
||||
|
||||
meta := FlagMetadata("has_search", true)
|
||||
if meta["has_search"] != "true" {
|
||||
t.Fatalf("unexpected flag metadata: %#v", meta)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// RequestMetaMiddleware injects request metadata into the request context for audit logging.
|
||||
func RequestMetaMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
requestID := c.Response().Header().Get(echo.HeaderXRequestID)
|
||||
if requestID == "" {
|
||||
requestID = c.Request().Header.Get(echo.HeaderXRequestID)
|
||||
}
|
||||
|
||||
ctx := WithRequestMeta(c.Request().Context(), RequestMeta{
|
||||
IP: c.RealIP(),
|
||||
RequestID: requestID,
|
||||
UserAgent: c.Request().UserAgent(),
|
||||
})
|
||||
c.SetRequest(c.Request().WithContext(ctx))
|
||||
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EnrichEchoContext copies Echo actor values into the Go context when present.
|
||||
func EnrichEchoContext(c echo.Context, actorType string) {
|
||||
actorID := ""
|
||||
if actorType == ActorTypeAdmin {
|
||||
if id, ok := c.Get("user_id").(string); ok {
|
||||
actorID = id
|
||||
}
|
||||
}
|
||||
if actorType == ActorTypeCustomer {
|
||||
if id, ok := c.Get("customer_id").(string); ok {
|
||||
actorID = id
|
||||
}
|
||||
}
|
||||
|
||||
ctx := c.Request().Context()
|
||||
if actorID != "" {
|
||||
ctx = WithActor(ctx, Actor{ID: actorID, Type: actorType})
|
||||
}
|
||||
c.SetRequest(c.Request().WithContext(ctx))
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package audit
|
||||
|
||||
import "context"
|
||||
|
||||
// Document is the persisted audit log shape stored in Elasticsearch.
|
||||
type Document struct {
|
||||
ActorID string `json:"actor_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
Action string `json:"action"`
|
||||
TargetType string `json:"target_type"`
|
||||
TargetID string `json:"target_id"`
|
||||
At int64 `json:"at"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Metadata map[string]string `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// SearchFilter defines query filters for audit log search.
|
||||
type SearchFilter struct {
|
||||
ActorID string
|
||||
ActorType string
|
||||
Action string
|
||||
TargetType string
|
||||
TargetID string
|
||||
From int64
|
||||
To int64
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// SearchResult holds paginated audit log search results.
|
||||
type SearchResult struct {
|
||||
Items []Document
|
||||
TotalCount int64
|
||||
}
|
||||
|
||||
// Store persists and queries audit documents.
|
||||
type Store interface {
|
||||
Save(ctx context.Context, doc Document) error
|
||||
Search(ctx context.Context, filter SearchFilter) (*SearchResult, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
// noopStore discards audit documents when Elasticsearch is disabled.
|
||||
type noopStore struct{}
|
||||
|
||||
func (noopStore) Save(context.Context, Document) error { return nil }
|
||||
|
||||
func (noopStore) Search(context.Context, SearchFilter) (*SearchResult, error) {
|
||||
return &SearchResult{Items: []Document{}}, nil
|
||||
}
|
||||
|
||||
func (noopStore) Close() error { return nil }
|
||||
|
||||
// NoopStore returns a store that performs no persistence.
|
||||
func NoopStore() Store {
|
||||
return noopStore{}
|
||||
}
|
||||
|
||||
func entryToDocument(entry Entry) Document {
|
||||
return Document{
|
||||
ActorID: entry.ActorID,
|
||||
ActorType: entry.ActorType,
|
||||
Action: entry.Action,
|
||||
TargetType: entry.TargetType,
|
||||
TargetID: entry.TargetID,
|
||||
At: entry.At,
|
||||
IP: entry.IP,
|
||||
RequestID: entry.RequestID,
|
||||
UserAgent: entry.UserAgent,
|
||||
Success: entry.Success,
|
||||
Metadata: entry.Metadata,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user