audit

package
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package audit 提供操作审计日志:结构化记录"谁在何时对什么资源做了什么操作", 仅记录成功的请求(失败请求走普通日志),用于合规与运维审计。

设计要点:

  • gRPC/HTTP 拦截器在 handler 成功后写一条 AuditEntry;
  • Entry 含 Resource + Action 枚举 + UserID + 结构化 Metadata;
  • 仅 err==nil 且状态码 < 500 才记(失败由 logger 负责);
  • 异步写入 Sink(如 DB/文件),不阻塞响应。

与 pkg/logger 的区别:logger 记运行时事件(含错误),audit 只记"成功的敏感操作" 且字段固定(Resource/Action),便于按操作类型检索与合规导出。

零值不可用,用 New 构造。Audit 并发安全。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func UserIDFromCtx

func UserIDFromCtx(ctx context.Context) string

UserIDFromCtx 从 ctx 读出 WithUserID 注入的 userID。无则返回空串。

func WithUserID

func WithUserID(ctx context.Context, uid string) context.Context

WithUserID 把 userID 注入 ctx,供中间件读取。

Types

type Action

type Action int

Action 操作类型。常用值预定义,业务可扩展。

const (
	ActionCreate Action = iota + 1
	ActionUpdate
	ActionDelete
	ActionRead
)

type Audit

type Audit struct {
	// contains filtered or unexported fields
}

Audit 管理审计条目的收集与异步分发。

func New

func New(sink Sink, opts ...Option) *Audit

New 创建审计器。sink 为 nil 时仅内存计数(不落盘)。

func (*Audit) HTTPMiddleware

func (a *Audit) HTTPMiddleware(resolver func(*http.Request) (Resource, string, string)) func(http.Handler) http.Handler

HTTPMiddleware 返回 HTTP 中间件:仅在响应状态码 < 500 时记一条审计。 resource/resourceID 由 resolver 从请求中提取;resolver 为 nil 则不记录。

func (*Audit) Record

func (a *Audit) Record(ctx context.Context, e Entry)

Record 记录一条审计条目。非阻塞:队列满时丢弃。 仅在业务确认操作成功后调用(仅记 err==nil)。

func (*Audit) Stop

func (a *Audit) Stop()

Stop 关闭异步队列并等待落盘完成。

type Entry

type Entry struct {
	ID         int64     // 单调递增
	Time       time.Time // 操作发生时间
	UserID     string    // 操作者
	Resource   Resource  // 被操作资源类型
	ResourceID string    // 被操作资源 ID(如用户 ID、配置名)
	Action     Action    // 操作类型
	Method     string    // HTTP 方法 / gRPC 方法
	Path       string    // HTTP 路径 / gRPC FullMethod
	Status     int       // HTTP 状态码 / gRPC OK=0
	Metadata   string    // 业务自定义 JSON 等编码
}

Entry 是一条审计记录。创建后不可变。

type Option

type Option func(*config)

Option 配置 Audit。

func WithQueueSize

func WithQueueSize(n int) Option

WithQueueSize 设置异步队列长度。满时丢弃最旧条目并记一条丢弃计数(默认 1024)。

type Resource

type Resource int

Resource 资源类型(业务自定义枚举值)。用 int 避免字符串拼写差异,便于索引。

type Sink

type Sink interface {
	Write(ctx context.Context, e Entry) error
}

Sink 接收审计条目。实现可以是 DB 写入、文件追加、远程聚合等。 必须并发安全。返回 error 仅用于记录失败(不影响主流程)。

type SinkFunc

type SinkFunc func(ctx context.Context, e Entry) error

SinkFunc 函数适配器。

func (SinkFunc) Write

func (f SinkFunc) Write(ctx context.Context, e Entry) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL