redact

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 23 Imported by: 0

README

运行时脱敏

redact 提供由 cmd/protoc-gen-go-redact 生成代码使用的运行时脱敏能力。

能力边界

  • RedactorApply:执行生成消息的脱敏方法。
  • PolicyResolverApplyWith:使用显式传入的解析器递归处理 Proto 消息;未传入时仅通过 WithPolicyResolver / PolicyResolverFromContext 使用当前请求的解析器,不保存进程级默认实例。WithOperationWithDirectionWithScene 可按接口、请求/响应方向及场景选择策略。
  • 动态脱敏支持非空 Proto Map:直接使用 Map 值描述符,消息值递归应用策略,标量值按字段策略转换。
  • NewFieldPolicy:将数据库中的规则类型和 JSON 配置转换为运行时策略。
  • MaskRegexEmailTruncateHashUUIDIPURLFixedLength:实现 Proto 规则对应的具体算法。
  • RegisterCustomRedactor:注册命名的自定义脱敏函数。
  • ServerStreamRedactorBidiStreamRedactorClientStreamRedactor:包装 gRPC 流式响应并在发送前执行脱敏。
  • StoragePolicyResolverStorageValueStoreRedactStorage:通过抽象策略和存储接口执行敏感字段的加密、脱敏值保存、原文恢复和摘要查询。

本模块不负责具体数据库表、Repository 和策略配置;具体数据库适配与规则管理由业务模块实现,代码生成由 cmd/protoc-gen-go-redact 完成。

依赖注入

宿主通过构造参数注入 PolicyResolver,在 HTTP、gRPC(含流式)和 MCP 请求入口将其写入请求上下文。 生成的服务包装器会保留此上下文,因此无需设置全局策略或修改生成产物;流式包装器也可直接设置自身的 Resolver 字段。 显式 ApplyWith(ctx, resolver, message) 优先于请求上下文;两者都未提供解析器时执行消息默认规则。 不同应用与请求不会互相覆盖解析器,WithPolicyResolver(ctx, nil) 可清除继承的请求解析器。

安装

go get github.com/liujitcn/kratos-kit/redact@latest

生成后的 *.pb.redact.go 会自动导入本模块。

Documentation

Overview

Package redact 提供运行时字段脱敏、敏感字段存储保护、接口上下文和 gRPC 流式响应包装。

Index

Constants

This section is empty.

Variables

View Source
var ErrStorageValueNotFound = errors.New("敏感值不存在")

ErrStorageValueNotFound 表示旁表中不存在对应的敏感值。

View Source
var Falsy = Wrapper(func(_ context.Context) bool {
	return false
})

Falsy 表示始终不允许绕过内部方法保护。

Functions

func Apply

func Apply(in any)

Apply 对实现 Redactor 的值执行脱敏;未实现该接口的值保持不变。

func ApplyCustomRedactor

func ApplyCustomRedactor(name, value string) string

ApplyCustomRedactor 执行指定名称的自定义脱敏函数;未注册时返回统一掩码。

func ApplyDynamic

func ApplyDynamic(ctx context.Context, resolver PolicyResolver, fieldRef string, value any) (any, bool)

ApplyDynamic 尝试对单个字段应用运行时策略。

func ApplyWith

func ApplyWith(ctx context.Context, resolver PolicyResolver, in any)

ApplyWith 优先使用显式解析器,其次使用请求解析器,均未提供时执行消息默认规则。

func Condition

func Condition(envVar, envVal string) bool

Condition 根据环境变量值判断是否执行条件规则。

func Email

func Email(value string, keepLocalFirst int, maskDomain bool, maskChar string) string

Email 按邮箱本地部分和域名分别执行掩码。

func FixedLength

func FixedLength(value, maskChar string) string

FixedLength 使用指定字符替换为与原值等长的字符串。

func HasCustomRedactor added in v0.0.2

func HasCustomRedactor(name string) bool

HasCustomRedactor 判断指定名称的自定义脱敏函数是否已注册。

func HashMD5

func HashMD5(value string) string

HashMD5 使用 MD5 生成十六进制摘要。

func HashSHA1

func HashSHA1(value string) string

HashSHA1 使用 SHA-1 生成十六进制摘要。

func HashSHA256

func HashSHA256(value string) string

HashSHA256 使用 SHA-256 生成十六进制摘要。

func IP

func IP(value string, keepOctets int, maskChar string) string

IP 保留 IP 地址前指定数量的网段,其余部分替换为掩码字符。

func Mask

func Mask(value string, keepFirst, keepLast int, maskChar string) string

Mask 保留字符串首尾指定数量的字节,并用掩码字符替换中间内容。

func OperationFromContext added in v0.0.2

func OperationFromContext(ctx context.Context) string

OperationFromContext 从上下文读取 RPC 完整操作名。

func Regex

func Regex(value, pattern, replacement string) string

Regex 根据正则表达式替换字符串内容。

func RegisterCustomRedactor

func RegisterCustomRedactor(name string, redactor CustomRedactor)

RegisterCustomRedactor 注册命名脱敏函数。

func RuleFingerprint added in v0.0.2

func RuleFingerprint(ruleType, ruleJSON string) string

RuleFingerprint 根据规则类型和参数生成稳定规则指纹。

func SanitizeText added in v0.0.2

func SanitizeText(value string) string

SanitizeText 脱敏自由文本中的常见手机号、邮箱和凭据键值。

func SceneFromContext

func SceneFromContext(ctx context.Context) string

SceneFromContext 从上下文读取脱敏场景,未设置时返回全局场景标识。

func Truncate

func Truncate(value string, length int, suffix string) string

Truncate 保留字符串前指定长度的字节,并追加后缀。

func URL

func URL(value string, maskQuery bool, maskChar string) string

URL 对 URL 查询参数值执行掩码。

func UUID

func UUID(value string) string

UUID 根据字符串生成稳定的 UUID v5 格式值。

func WithDirection added in v0.0.2

func WithDirection(ctx context.Context, direction Direction) context.Context

WithDirection 将脱敏方向写入上下文。

func WithOperation added in v0.0.2

func WithOperation(ctx context.Context, operation string) context.Context

WithOperation 将 RPC 完整操作名写入上下文。

func WithPolicyResolver added in v0.0.6

func WithPolicyResolver(ctx context.Context, resolver PolicyResolver) context.Context

WithPolicyResolver 将应用实例的策略解析器传入当前请求,不影响其他请求或应用。

func WithScene

func WithScene(ctx context.Context, sceneCode string) context.Context

WithScene 将脱敏场景写入上下文,解析器会优先匹配该场景的策略。

Types

type BidiStreamRedactor

type BidiStreamRedactor[Req any, Res any] struct {
	grpc.BidiStreamingServer[Req, Res]
	Resolver  PolicyResolver
	Operation string
}

BidiStreamRedactor 包装 gRPC 双向流并在发送前脱敏响应。

func (*BidiStreamRedactor[Req, Res]) Send

func (s *BidiStreamRedactor[Req, Res]) Send(message *Res) error

Send 脱敏响应后发送给客户端。

type Bypass

type Bypass interface {
	CheckInternal(ctx context.Context) bool
}

Bypass 判断当前请求是否允许绕过内部方法保护。

type ClientStreamRedactor

type ClientStreamRedactor[Req any, Res any] struct {
	grpc.ClientStreamingServer[Req, Res]
	Resolver  PolicyResolver
	Operation string
}

ClientStreamRedactor 包装 gRPC 客户端流并在发送前脱敏响应。

func (*ClientStreamRedactor[Req, Res]) SendAndClose

func (s *ClientStreamRedactor[Req, Res]) SendAndClose(message *Res) error

SendAndClose 脱敏响应后发送给客户端并关闭流。

type CustomRedactor

type CustomRedactor func(string) string

CustomRedactor 表示用户注册的字符串脱敏函数。

type Direction added in v0.0.2

type Direction uint8

Direction 表示脱敏策略作用于请求还是响应。

const (
	// DirectionRequest 表示请求参数方向。
	DirectionRequest Direction = iota + 1
	// DirectionResponse 表示响应数据方向。
	DirectionResponse
)

func DirectionFromContext added in v0.0.2

func DirectionFromContext(ctx context.Context) Direction

DirectionFromContext 从上下文读取脱敏方向,未设置时默认为响应方向。

type DynamicRedactor

type DynamicRedactor interface {
	RedactWith(ctx context.Context, resolver PolicyResolver)
}

DynamicRedactor 提供可按请求上下文选择策略的消息脱敏方法。

type EntityFieldAccessor added in v0.0.3

type EntityFieldAccessor interface {
	ValueOf(context.Context, any, string) (any, bool, error)
	Set(context.Context, any, string, any) error
}

EntityFieldAccessor 提供通用实体字段读写能力。

type FieldPolicy

type FieldPolicy struct {
	Mode        PolicyMode
	Transform   func(value any) any
	RuleID      int64
	RuleVersion int32
	Fingerprint string
}

FieldPolicy 表示单个字段的运行时脱敏策略。

func NewFieldPolicy

func NewFieldPolicy(mode PolicyMode, ruleType, ruleJSON string) (FieldPolicy, error)

NewFieldPolicy 根据数据库中的策略模式、规则类型和 JSON 规则创建字段策略。

func (FieldPolicy) Apply

func (p FieldPolicy) Apply(value any) any

Apply 将运行时策略应用到字段值。

type PolicyMode

type PolicyMode uint8

PolicyMode 表示运行时策略对字段值的处理方式。

const (
	// PolicyModeApplyRule 表示执行 Transform 规则。
	PolicyModeApplyRule PolicyMode = iota + 1
	// PolicyModeHide 表示将字段替换为对应类型的零值。
	PolicyModeHide
	// PolicyModeFull 表示保留字段原值。
	PolicyModeFull
)

type PolicyResolver

type PolicyResolver interface {
	Resolve(ctx context.Context, fieldRef string) (FieldPolicy, bool)
}

PolicyResolver 按字段完整标识和上下文场景解析运行时策略。

func PolicyResolverFromContext added in v0.0.6

func PolicyResolverFromContext(ctx context.Context) PolicyResolver

PolicyResolverFromContext 读取当前请求的策略解析器,未注入时返回空值。

type RedactStorage added in v0.0.3

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

RedactStorage 提供通用敏感字段入库保护和查询原文恢复能力。

func NewRedactStorage added in v0.0.3

func NewRedactStorage(
	valueStore StorageValueStore,
	policyResolver StoragePolicyResolver,
	protector *StorageProtector,
	fieldAccessor EntityFieldAccessor,
) *RedactStorage

NewRedactStorage 创建通用敏感字段存储保护实例。

func (*RedactStorage) DeletePrepared added in v0.0.3

func (s *RedactStorage) DeletePrepared(ctx context.Context, storagePolicyID, recordID int64) error

DeletePrepared 删除指定入库策略和业务记录对应的旁表敏感值。

func (*RedactStorage) FindRecordIDsByDigest added in v0.0.5

func (s *RedactStorage) FindRecordIDsByDigest(ctx context.Context, policy StorageFieldPolicy, plainValue string) ([]int64, error)

FindRecordIDsByDigest 按敏感字段明文查询对应的业务记录ID。

func (*RedactStorage) PrepareEntity added in v0.0.3

func (s *RedactStorage) PrepareEntity(ctx context.Context, tableName string, entity any) (map[int64]*StorageValue, error)

PrepareEntity 根据物理表入库策略批量处理模型中的敏感字符串字段。

func (*RedactStorage) PrepareEntityWithPolicies added in v0.0.5

func (s *RedactStorage) PrepareEntityWithPolicies(ctx context.Context, entity any, policies []StorageFieldPolicy) (map[int64]*StorageValue, error)

PrepareEntityWithPolicies 按指定入库策略批量处理模型中的敏感字符串字段。

func (*RedactStorage) PrepareString added in v0.0.3

func (s *RedactStorage) PrepareString(ctx context.Context, policy StorageFieldPolicy, value string) (string, *StorageValue, error)

PrepareString 根据入库策略生成主表脱敏值和待写入的旁表记录。

func (*RedactStorage) RestoreEntities added in v0.0.5

func (s *RedactStorage) RestoreEntities(ctx context.Context, policies []StorageFieldPolicy, entities []ResponseEntity) error

RestoreEntities 按入库策略批量恢复实体中的敏感字段原文。

func (*RedactStorage) RestoreString added in v0.0.3

func (s *RedactStorage) RestoreString(ctx context.Context, policy StorageFieldPolicy, recordID int64, stored string) (string, bool, error)

RestoreString 根据入库策略恢复字段原文;无法恢复时返回主表值并标记未恢复。

func (*RedactStorage) SavePrepared added in v0.0.3

func (s *RedactStorage) SavePrepared(ctx context.Context, value *StorageValue, recordID int64) error

SavePrepared 保存创建或更新后已经生成主键的旁表敏感值。

func (*RedactStorage) SavePreparedValues added in v0.0.3

func (s *RedactStorage) SavePreparedValues(ctx context.Context, values map[int64]*StorageValue, recordID int64) error

SavePreparedValues 保存实体处理后生成的全部旁表敏感值。

type Redactor

type Redactor interface {
	Redact()
}

Redactor 提供消息脱敏方法。

type ResponseEntity added in v0.0.5

type ResponseEntity struct {
	RecordID int64
	Entity   any
}

ResponseEntity 描述一个需要恢复数据库敏感原文的业务实体。

type ServerStreamRedactor

type ServerStreamRedactor[Res any] struct {
	grpc.ServerStreamingServer[Res]
	Resolver  PolicyResolver
	Operation string
}

ServerStreamRedactor 包装 gRPC 服务端流并在发送前脱敏响应。

func (*ServerStreamRedactor[Res]) Send

func (s *ServerStreamRedactor[Res]) Send(message *Res) error

Send 脱敏响应后发送给客户端。

type StorageFieldPolicy added in v0.0.3

type StorageFieldPolicy struct {
	ID         int64
	TableName  string
	ColumnName string
	Rule       FieldPolicy
}

StorageFieldPolicy 描述一个数据库字段的入库脱敏策略。

type StoragePolicyResolver added in v0.0.3

type StoragePolicyResolver interface {
	ListStoragePolicies(context.Context, string) []StorageFieldPolicy
}

StoragePolicyResolver 提供数据库字段入库策略解析能力。

type StorageProtector added in v0.0.2

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

StorageProtector 提供可恢复密文和精确查询摘要能力。

func NewStorageProtector added in v0.0.2

func NewStorageProtector(secret string) (*StorageProtector, error)

NewStorageProtector 根据服务端密钥创建存储保护器。

func (*StorageProtector) Decrypt added in v0.0.2

func (p *StorageProtector) Decrypt(value, associatedData string) (string, error)

Decrypt 解密 AES-GCM 字段原文,并校验关联数据。

func (*StorageProtector) Digest added in v0.0.2

func (p *StorageProtector) Digest(value, associatedData string) ([]byte, error)

Digest 使用 HMAC-SHA256 生成字段精确查询摘要。

func (*StorageProtector) Encrypt added in v0.0.2

func (p *StorageProtector) Encrypt(value, associatedData string) (string, error)

Encrypt 使用 AES-GCM 加密字段原文,并返回自描述密文。

type StorageValue added in v0.0.3

type StorageValue struct {
	ID              int64
	StoragePolicyID int64
	RecordID        int64
	Ciphertext      []byte
	Digest          []byte
}

StorageValue 表示旁表中保存的敏感字段加密原文和查询摘要。

type StorageValueStore added in v0.0.3

type StorageValueStore interface {
	Find(context.Context, int64, int64) (*StorageValue, error)
	ListByRecords(context.Context, int64, []int64) ([]*StorageValue, error)
	ListByDigest(context.Context, int64, []byte) ([]*StorageValue, error)
	Save(context.Context, *StorageValue) error
	Delete(context.Context, *StorageValue) error
}

StorageValueStore 提供敏感值旁表的持久化能力。

type Wrapper

type Wrapper func(ctx context.Context) bool

Wrapper 将函数适配为 Bypass。

func (Wrapper) CheckInternal

func (w Wrapper) CheckInternal(ctx context.Context) bool

CheckInternal 执行绕过判断函数。

Jump to

Keyboard shortcuts

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