Documentation
¶
Overview ¶
Package interceptors 提供服务级 ACL 权限控制拦截器
Package interceptors 提供审计日志和监控指标拦截器 ¶
Package interceptors 提供客户端认证拦截器 ¶
Package interceptors 提供通用 gRPC 拦截器 ¶
Package interceptors 提供凭证验证拦截器 ¶
Package interceptors 提供通用的 gRPC 拦截器 ¶
此包提供可复用的 gRPC 拦截器,适用于任何 gRPC 服务。 设计为可提取到 component-base 的独立模块。
包含的拦截器:
- mTLS 认证拦截器
- 凭证验证拦截器 (Bearer/HMAC/API Key)
- 审计日志拦截器
- 监控指标拦截器
使用示例:
server := grpc.NewServer(
grpc.ChainUnaryInterceptor(
interceptors.MTLSInterceptor(),
interceptors.CredentialInterceptor(extractor, validator),
interceptors.AuditInterceptor(nil),
),
)
Package interceptors 提供 mTLS 认证拦截器 ¶
Package interceptors 提供通用 gRPC 拦截器类型和工具 ¶
本包定义了可复用的认证授权类型,用于构建 gRPC 安全拦截器链。 这些类型与具体业务逻辑解耦,可被不同的服务项目引用。
Index ¶
- Constants
- func ACLInterceptor(acl AccessChecker, opts ...ACLOption) grpc.UnaryServerInterceptor
- func ACLStreamInterceptor(acl AccessChecker, opts ...ACLOption) grpc.StreamServerInterceptor
- func AuditInterceptor(logger AuditLogger, opts ...AuditOption) grpc.UnaryServerInterceptor
- func AuditStreamInterceptor(logger AuditLogger, opts ...AuditOption) grpc.StreamServerInterceptor
- func ClientCredentialInterceptor(provider ClientCredentialProvider) grpc.UnaryClientInterceptor
- func ClientCredentialStreamInterceptor(provider ClientCredentialProvider) grpc.StreamClientInterceptor
- func ClientLogInterceptor(logger InterceptorLogger) grpc.UnaryClientInterceptor
- func ClientRetryInterceptor(opt *RetryOption) grpc.UnaryClientInterceptor
- func ClientTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor
- func ComputeHMACSignature(accessKey, secretKey string, timestamp int64, nonce string) string
- func ContextWithCredential(ctx context.Context, cred *ServiceCredential) context.Context
- func ContextWithServiceIdentity(ctx context.Context, identity *ServiceIdentity) context.Context
- func CredentialInterceptor(extractor CredentialExtractor, validator CredentialValidator, ...) grpc.UnaryServerInterceptor
- func CredentialStreamInterceptor(extractor CredentialExtractor, validator CredentialValidator, ...) grpc.StreamServerInterceptor
- func DefaultRequestIDGenerator() string
- func DefaultSkipMethods() []string
- func GenerateHMACCredentials(accessKey, secretKey, nonce string) map[string]string
- func GetClientIP(ctx context.Context) string
- func GetMetadataValue(ctx context.Context, key string) string
- func GetUserAgent(ctx context.Context) string
- func LoggingInterceptor(logger InterceptorLogger, opts ...LoggingOption) grpc.UnaryServerInterceptor
- func LoggingStreamInterceptor(logger InterceptorLogger, opts ...LoggingOption) grpc.StreamServerInterceptor
- func MTLSInterceptor(opts ...MTLSOption) grpc.UnaryServerInterceptor
- func MTLSStreamInterceptor(opts ...MTLSOption) grpc.StreamServerInterceptor
- func MatchMethod(method, pattern string) bool
- func MetricsInterceptor(metrics *AuthMetrics) grpc.UnaryServerInterceptor
- func PermissionInterceptor(checker *MethodPermissionChecker) grpc.UnaryServerInterceptor
- func RecoveryInterceptor(opts ...RecoveryOption) grpc.UnaryServerInterceptor
- func RecoveryStreamInterceptor(opts ...RecoveryOption) grpc.StreamServerInterceptor
- func RequestIDFromContext(ctx context.Context) string
- func RequestIDInterceptor(opts ...RequestIDOption) grpc.UnaryServerInterceptor
- func RequestIDStreamInterceptor(opts ...RequestIDOption) grpc.StreamServerInterceptor
- func TLSClientConfig(caCert, clientCert, clientKey []byte, serverName string) (*tls.Config, error)
- func TLSServerConfig(caCert, serverCert, serverKey []byte, clientAuth tls.ClientAuthType) (*tls.Config, error)
- type ACLConfig
- type ACLOption
- type APIKeyInfo
- type APIKeyProvider
- type APIKeyStore
- type APIKeyValidator
- type AccessChecker
- type AlertChecker
- type AlertRule
- type AuditEvent
- type AuditLogger
- type AuditOption
- type AuthMetrics
- func (m *AuthMetrics) GetMetrics() map[string]interface{}
- func (m *AuthMetrics) RecordACLResult(allowed bool)
- func (m *AuthMetrics) RecordAuthFailure(authType string)
- func (m *AuthMetrics) RecordAuthSuccess(authType string)
- func (m *AuthMetrics) RecordServiceRequest(serviceName string, success bool, duration time.Duration)
- type BearerTokenProvider
- type ClientCredentialProvider
- type CompositeValidator
- type CredentialExtractor
- type CredentialOption
- type CredentialType
- type CredentialValidator
- type DefaultAuditLogger
- type HMACCredentialProvider
- type HMACValidator
- type IdentityExtractor
- type IdentityValidator
- type InMemoryAPIKeyStore
- type InMemoryNonceStore
- type InMemorySecretStore
- type InterceptorLogger
- type LoggingOption
- type MTLSOption
- type MetadataCredentialExtractor
- type MethodMatcher
- type MethodPermission
- type MethodPermissionChecker
- type NonceStore
- type RecoveryOption
- type RequestIDOption
- type RetryOption
- type ServiceACL
- func (a *ServiceACL) AddServicePermission(perms *ServicePermissions)
- func (a *ServiceACL) CheckAccess(serviceName, method string) error
- func (a *ServiceACL) GetServicePermissions(serviceName string) (*ServicePermissions, bool)
- func (a *ServiceACL) ListServices() []string
- func (a *ServiceACL) RemoveServicePermission(serviceName string)
- func (a *ServiceACL) UpdateServiceMethods(serviceName string, methods []string) error
- type ServiceCredential
- type ServiceIdentity
- type ServiceMetrics
- type ServicePermissions
- type SkipMethodMatcher
- type WrappedServerStream
Constants ¶
const ( // ServiceIdentityKey 服务身份上下文键 ServiceIdentityKey contextKey = "grpc_service_identity" // ServiceCredentialKey 服务凭证上下文键 ServiceCredentialKey contextKey = "grpc_service_credential" )
const RequestIDContextKey contextKey = "grpc_request_id"
RequestIDContextKey 请求ID上下文键
Variables ¶
This section is empty.
Functions ¶
func ACLInterceptor ¶
func ACLInterceptor(acl AccessChecker, opts ...ACLOption) grpc.UnaryServerInterceptor
ACLInterceptor 服务 ACL 授权拦截器
func ACLStreamInterceptor ¶
func ACLStreamInterceptor(acl AccessChecker, opts ...ACLOption) grpc.StreamServerInterceptor
ACLStreamInterceptor 流式 ACL 授权拦截器
func AuditInterceptor ¶
func AuditInterceptor(logger AuditLogger, opts ...AuditOption) grpc.UnaryServerInterceptor
AuditInterceptor 审计日志拦截器
func AuditStreamInterceptor ¶
func AuditStreamInterceptor(logger AuditLogger, opts ...AuditOption) grpc.StreamServerInterceptor
AuditStreamInterceptor 流式审计日志拦截器
func ClientCredentialInterceptor ¶
func ClientCredentialInterceptor(provider ClientCredentialProvider) grpc.UnaryClientInterceptor
ClientCredentialInterceptor 客户端凭证注入拦截器
func ClientCredentialStreamInterceptor ¶
func ClientCredentialStreamInterceptor(provider ClientCredentialProvider) grpc.StreamClientInterceptor
ClientCredentialStreamInterceptor 流式客户端凭证注入拦截器
func ClientLogInterceptor ¶
func ClientLogInterceptor(logger InterceptorLogger) grpc.UnaryClientInterceptor
ClientLogInterceptor 客户端日志拦截器
func ClientRetryInterceptor ¶
func ClientRetryInterceptor(opt *RetryOption) grpc.UnaryClientInterceptor
ClientRetryInterceptor 客户端重试拦截器
func ClientTimeoutInterceptor ¶
func ClientTimeoutInterceptor(timeout time.Duration) grpc.UnaryClientInterceptor
ClientTimeoutInterceptor 客户端超时拦截器
func ComputeHMACSignature ¶
ComputeHMACSignature 计算 HMAC 签名
func ContextWithCredential ¶
func ContextWithCredential(ctx context.Context, cred *ServiceCredential) context.Context
ContextWithCredential 将凭证注入上下文
func ContextWithServiceIdentity ¶
func ContextWithServiceIdentity(ctx context.Context, identity *ServiceIdentity) context.Context
ContextWithServiceIdentity 将服务身份注入上下文
func CredentialInterceptor ¶
func CredentialInterceptor(extractor CredentialExtractor, validator CredentialValidator, opts ...CredentialOption) grpc.UnaryServerInterceptor
CredentialInterceptor 应用层凭证验证拦截器
func CredentialStreamInterceptor ¶
func CredentialStreamInterceptor(extractor CredentialExtractor, validator CredentialValidator, opts ...CredentialOption) grpc.StreamServerInterceptor
CredentialStreamInterceptor 流式凭证验证拦截器
func DefaultRequestIDGenerator ¶
func DefaultRequestIDGenerator() string
DefaultRequestIDGenerator 默认请求ID生成器
func GenerateHMACCredentials ¶
GenerateHMACCredentials 生成 HMAC 认证凭证(供客户端使用)
func GetMetadataValue ¶
GetMetadataValue 获取 metadata 中的值
func LoggingInterceptor ¶
func LoggingInterceptor(logger InterceptorLogger, opts ...LoggingOption) grpc.UnaryServerInterceptor
LoggingInterceptor 日志拦截器
func LoggingStreamInterceptor ¶
func LoggingStreamInterceptor(logger InterceptorLogger, opts ...LoggingOption) grpc.StreamServerInterceptor
LoggingStreamInterceptor 流式日志拦截器
func MTLSInterceptor ¶
func MTLSInterceptor(opts ...MTLSOption) grpc.UnaryServerInterceptor
MTLSInterceptor mTLS 认证拦截器 从 TLS 连接中提取客户端证书信息,验证服务身份
func MTLSStreamInterceptor ¶
func MTLSStreamInterceptor(opts ...MTLSOption) grpc.StreamServerInterceptor
MTLSStreamInterceptor mTLS 流式认证拦截器
func MetricsInterceptor ¶
func MetricsInterceptor(metrics *AuthMetrics) grpc.UnaryServerInterceptor
MetricsInterceptor 监控指标拦截器
func PermissionInterceptor ¶
func PermissionInterceptor(checker *MethodPermissionChecker) grpc.UnaryServerInterceptor
PermissionInterceptor 权限检查拦截器(用于更细粒度的权限控制)
func RecoveryInterceptor ¶
func RecoveryInterceptor(opts ...RecoveryOption) grpc.UnaryServerInterceptor
RecoveryInterceptor 恢复拦截器,防止 panic 导致服务崩溃
func RecoveryStreamInterceptor ¶
func RecoveryStreamInterceptor(opts ...RecoveryOption) grpc.StreamServerInterceptor
RecoveryStreamInterceptor 流式恢复拦截器
func RequestIDFromContext ¶
RequestIDFromContext 从上下文获取请求ID
func RequestIDInterceptor ¶
func RequestIDInterceptor(opts ...RequestIDOption) grpc.UnaryServerInterceptor
RequestIDInterceptor 请求ID拦截器,为每个请求生成唯一ID
func RequestIDStreamInterceptor ¶
func RequestIDStreamInterceptor(opts ...RequestIDOption) grpc.StreamServerInterceptor
RequestIDStreamInterceptor 流式请求ID拦截器
func TLSClientConfig ¶
TLSClientConfig 创建客户端 TLS 配置
func TLSServerConfig ¶
func TLSServerConfig(caCert, serverCert, serverKey []byte, clientAuth tls.ClientAuthType) (*tls.Config, error)
TLSServerConfig 创建服务端 TLS 配置
Types ¶
type ACLConfig ¶
type ACLConfig struct {
// 默认策略
DefaultPolicy string `json:"default_policy" yaml:"default_policy"` // "deny" or "allow"
// 服务权限列表
Services []*ServicePermissions `json:"services" yaml:"services"`
}
ACLConfig ACL 配置
type ACLOption ¶
type ACLOption func(*aclOptions)
ACLOption ACL 拦截器选项函数
func WithACLSkipMethods ¶
WithACLSkipMethods 设置跳过检查的方法
func WithoutCredentialIdentity ¶
func WithoutCredentialIdentity() ACLOption
WithoutCredentialIdentity 禁用凭证身份
type APIKeyInfo ¶
APIKeyInfo API Key 信息
type APIKeyProvider ¶
type APIKeyProvider struct {
APIKey string
}
APIKeyProvider API Key 提供者
func (*APIKeyProvider) GetMetadata ¶
GetMetadata 实现 ClientCredentialProvider 接口
type APIKeyStore ¶
type APIKeyStore interface {
// Get 根据 API Key 获取服务信息
Get(ctx context.Context, apiKey string) (*APIKeyInfo, error)
}
APIKeyStore API Key 存储接口
type APIKeyValidator ¶
type APIKeyValidator struct {
KeyStore APIKeyStore
}
APIKeyValidator API Key 验证器
func NewAPIKeyValidator ¶
func NewAPIKeyValidator(store APIKeyStore) *APIKeyValidator
NewAPIKeyValidator 创建 API Key 验证器
func (*APIKeyValidator) Validate ¶
func (v *APIKeyValidator) Validate(ctx context.Context, cred *ServiceCredential) (*ServiceCredential, error)
Validate 验证 API Key
type AccessChecker ¶
type AccessChecker interface {
// CheckAccess 检查服务是否有权访问指定方法
CheckAccess(serviceName, method string) error
}
AccessChecker 访问权限检查器接口
type AlertChecker ¶
type AlertChecker struct {
// contains filtered or unexported fields
}
AlertChecker 告警检查器
func NewAlertChecker ¶
func NewAlertChecker(metrics *AuthMetrics, handler func(rule *AlertRule)) *AlertChecker
NewAlertChecker 创建告警检查器
func (*AlertChecker) StartPeriodicCheck ¶
func (c *AlertChecker) StartPeriodicCheck(interval time.Duration, stopCh <-chan struct{})
StartPeriodicCheck 启动定期检查
type AlertRule ¶
type AlertRule struct {
Name string
Description string
Condition func(metrics *AuthMetrics) bool
Severity string // critical, warning, info
}
AlertRule 告警规则
type AuditEvent ¶
type AuditEvent struct {
// 时间信息
Timestamp time.Time `json:"timestamp"`
// 请求信息
Method string `json:"method"`
RequestID string `json:"request_id,omitempty"`
// 调用方信息
ServiceName string `json:"service_name"`
ServiceNamespace string `json:"service_namespace,omitempty"`
CertCN string `json:"cert_cn,omitempty"`
CertOU []string `json:"cert_ou,omitempty"`
// 凭证信息
CredentialType string `json:"credential_type,omitempty"`
CredentialSubject string `json:"credential_subject,omitempty"`
// 结果信息
StatusCode string `json:"status_code"`
StatusMsg string `json:"status_msg,omitempty"`
Duration time.Duration `json:"duration"`
// 客户端信息
ClientAddr string `json:"client_addr,omitempty"`
// 错误信息
Error string `json:"error,omitempty"`
}
AuditEvent 审计事件
type AuditLogger ¶
type AuditLogger interface {
// Log 记录审计事件
Log(event *AuditEvent)
}
AuditLogger 审计日志记录器接口
type AuditOption ¶
type AuditOption func(*auditOptions)
AuditOption 审计选项函数
func WithAuditSkipMethods ¶
func WithAuditSkipMethods(methods ...string) AuditOption
WithAuditSkipMethods 设置跳过审计的方法
func WithRequestIDExtractor ¶
func WithRequestIDExtractor(extractor func(context.Context) string) AuditOption
WithRequestIDExtractor 设置请求 ID 提取器
type AuthMetrics ¶
type AuthMetrics struct {
// 认证统计
AuthSuccess uint64 // 认证成功次数
AuthFailure uint64 // 认证失败次数
MTLSSuccess uint64 // mTLS 认证成功
MTLSFailure uint64 // mTLS 认证失败
TokenSuccess uint64 // Token 验证成功
TokenFailure uint64 // Token 验证失败
// 授权统计
ACLAllowed uint64 // ACL 允许次数
ACLDenied uint64 // ACL 拒绝次数
// contains filtered or unexported fields
}
AuthMetrics 认证授权监控指标
func (*AuthMetrics) GetMetrics ¶
func (m *AuthMetrics) GetMetrics() map[string]interface{}
GetMetrics 获取指标快照
func (*AuthMetrics) RecordACLResult ¶
func (m *AuthMetrics) RecordACLResult(allowed bool)
RecordACLResult 记录 ACL 结果
func (*AuthMetrics) RecordAuthFailure ¶
func (m *AuthMetrics) RecordAuthFailure(authType string)
RecordAuthFailure 记录认证失败
func (*AuthMetrics) RecordAuthSuccess ¶
func (m *AuthMetrics) RecordAuthSuccess(authType string)
RecordAuthSuccess 记录认证成功
func (*AuthMetrics) RecordServiceRequest ¶
func (m *AuthMetrics) RecordServiceRequest(serviceName string, success bool, duration time.Duration)
RecordServiceRequest 记录服务请求
type BearerTokenProvider ¶
BearerTokenProvider Bearer Token 提供者
func (*BearerTokenProvider) GetMetadata ¶
GetMetadata 实现 ClientCredentialProvider 接口
type ClientCredentialProvider ¶
type ClientCredentialProvider interface {
// GetMetadata 获取要附加到请求的 metadata
GetMetadata(ctx context.Context) (map[string]string, error)
}
ClientCredentialProvider 客户端凭证提供者接口
type CompositeValidator ¶
type CompositeValidator struct {
// contains filtered or unexported fields
}
CompositeValidator 组合验证器(支持多种凭证类型)
func NewCompositeValidator ¶
func NewCompositeValidator() *CompositeValidator
NewCompositeValidator 创建组合验证器
func (*CompositeValidator) Register ¶
func (v *CompositeValidator) Register(credType CredentialType, validator CredentialValidator)
Register 注册验证器
func (*CompositeValidator) Validate ¶
func (v *CompositeValidator) Validate(ctx context.Context, cred *ServiceCredential) (*ServiceCredential, error)
Validate 验证凭证
type CredentialExtractor ¶
type CredentialExtractor interface {
// Extract 从上下文提取凭证
Extract(ctx context.Context) (*ServiceCredential, error)
}
CredentialExtractor 凭证提取器接口
type CredentialOption ¶
type CredentialOption func(*credentialOptions)
CredentialOption 凭证拦截器选项函数
func WithCredentialLogger ¶
func WithCredentialLogger(logger InterceptorLogger) CredentialOption
WithCredentialLogger 设置日志记录器
func WithCredentialSkipMethods ¶
func WithCredentialSkipMethods(methods ...string) CredentialOption
WithCredentialSkipMethods 设置跳过验证的方法
func WithOptionalCredential ¶
func WithOptionalCredential() CredentialOption
WithOptionalCredential 设置凭证为可选
func WithoutIdentityMatch ¶
func WithoutIdentityMatch() CredentialOption
WithoutIdentityMatch 禁用身份匹配检查
type CredentialType ¶
type CredentialType string
CredentialType 凭证类型
const ( CredentialTypeBearer CredentialType = "bearer" CredentialTypeHMAC CredentialType = "hmac" CredentialTypeAPIKey CredentialType = "api_key" )
type CredentialValidator ¶
type CredentialValidator interface {
// Validate 验证凭证,返回验证后的凭证信息
Validate(ctx context.Context, cred *ServiceCredential) (*ServiceCredential, error)
}
CredentialValidator 凭证验证器接口
type DefaultAuditLogger ¶
type DefaultAuditLogger struct {
// contains filtered or unexported fields
}
DefaultAuditLogger 默认审计日志记录器(使用 InterceptorLogger 接口)
func NewDefaultAuditLogger ¶
func NewDefaultAuditLogger(logger InterceptorLogger) *DefaultAuditLogger
NewDefaultAuditLogger 创建默认审计日志记录器
type HMACCredentialProvider ¶
HMACCredentialProvider HMAC 凭证提供者
func (*HMACCredentialProvider) GetMetadata ¶
GetMetadata 实现 ClientCredentialProvider 接口
type HMACValidator ¶
type HMACValidator struct {
// 获取服务密钥的回调
GetSecretKey func(accessKey string) (string, error)
// 时间戳有效期
TimestampValidity time.Duration
// Nonce 存储(防重放)
NonceStore NonceStore
}
HMACValidator HMAC 签名验证器
func NewHMACValidator ¶
func NewHMACValidator(getSecretKey func(accessKey string) (string, error)) *HMACValidator
NewHMACValidator 创建 HMAC 验证器
func (*HMACValidator) Validate ¶
func (v *HMACValidator) Validate(ctx context.Context, cred *ServiceCredential) (*ServiceCredential, error)
Validate 验证 HMAC 签名
type IdentityExtractor ¶
type IdentityExtractor interface {
// Extract 从上下文提取服务身份
Extract(ctx context.Context) (*ServiceIdentity, error)
}
IdentityExtractor 服务身份提取器接口
type IdentityValidator ¶
type IdentityValidator interface {
// Validate 验证服务身份
Validate(identity *ServiceIdentity) error
}
IdentityValidator 服务身份验证器接口
type InMemoryAPIKeyStore ¶
type InMemoryAPIKeyStore struct {
// contains filtered or unexported fields
}
InMemoryAPIKeyStore 内存 API Key 存储
func NewInMemoryAPIKeyStore ¶
func NewInMemoryAPIKeyStore() *InMemoryAPIKeyStore
NewInMemoryAPIKeyStore 创建内存 API Key 存储
func (*InMemoryAPIKeyStore) Get ¶
func (s *InMemoryAPIKeyStore) Get(ctx context.Context, apiKey string) (*APIKeyInfo, error)
Get 获取 API Key 信息
func (*InMemoryAPIKeyStore) Register ¶
func (s *InMemoryAPIKeyStore) Register(apiKey string, info *APIKeyInfo)
Register 注册 API Key
func (*InMemoryAPIKeyStore) Revoke ¶
func (s *InMemoryAPIKeyStore) Revoke(apiKey string) error
Revoke 撤销 API Key
type InMemoryNonceStore ¶
type InMemoryNonceStore struct {
// contains filtered or unexported fields
}
InMemoryNonceStore 内存 Nonce 存储
func NewInMemoryNonceStore ¶
func NewInMemoryNonceStore() *InMemoryNonceStore
NewInMemoryNonceStore 创建内存 Nonce 存储
type InMemorySecretStore ¶
type InMemorySecretStore struct {
// contains filtered or unexported fields
}
InMemorySecretStore 内存密钥存储(用于 HMAC)
func NewInMemorySecretStore ¶
func NewInMemorySecretStore() *InMemorySecretStore
NewInMemorySecretStore 创建内存密钥存储
func (*InMemorySecretStore) GetSecretKey ¶
func (s *InMemorySecretStore) GetSecretKey(accessKey string) (string, error)
GetSecretKey 获取密钥
func (*InMemorySecretStore) Register ¶
func (s *InMemorySecretStore) Register(accessKey, secretKey string)
Register 注册密钥
type InterceptorLogger ¶
type InterceptorLogger interface {
LogInfo(msg string, fields map[string]interface{})
LogError(msg string, fields map[string]interface{})
}
InterceptorLogger 拦截器日志接口
type LoggingOption ¶
type LoggingOption func(*loggingOptions)
LoggingOption 日志拦截器选项函数
func WithContextPreprocess ¶
func WithContextPreprocess(fn func(ctx context.Context) context.Context) LoggingOption
WithContextPreprocess 设置上下文预处理钩子(用于注入追踪上下文等)
func WithLogResponse ¶
func WithLogResponse(logResponse bool) LoggingOption
WithLogResponse 设置是否记录响应
func WithLoggingSkipMethods ¶
func WithLoggingSkipMethods(methods ...string) LoggingOption
WithLoggingSkipMethods 设置跳过日志记录的方法
func WithMaxResponseLen ¶
func WithMaxResponseLen(maxLen int) LoggingOption
WithMaxResponseLen 设置响应摘要最大长度
type MTLSOption ¶
type MTLSOption func(*mtlsOptions)
MTLSOption mTLS 拦截器选项函数
func WithAllowedServices ¶
func WithAllowedServices(services ...string) MTLSOption
WithAllowedServices 设置允许的服务列表
func WithMTLSLogger ¶
func WithMTLSLogger(logger InterceptorLogger) MTLSOption
WithMTLSLogger 设置日志记录器
func WithMTLSSkipMethods ¶
func WithMTLSSkipMethods(methods ...string) MTLSOption
WithMTLSSkipMethods 设置跳过认证的方法列表
func WithMTLSValidator ¶
func WithMTLSValidator(validator IdentityValidator) MTLSOption
WithMTLSValidator 设置服务身份验证器
type MetadataCredentialExtractor ¶
type MetadataCredentialExtractor struct {
// 支持的 header 名称
AuthorizationHeader string // 默认 "authorization"
APIKeyHeader string // 默认 "x-api-key"
SignatureHeader string // 默认 "x-api-signature"
TimestampHeader string // 默认 "x-api-timestamp"
NonceHeader string // 默认 "x-api-nonce"
}
MetadataCredentialExtractor 从 gRPC metadata 提取凭证
func NewMetadataCredentialExtractor ¶
func NewMetadataCredentialExtractor() *MetadataCredentialExtractor
NewMetadataCredentialExtractor 创建 metadata 凭证提取器
func (*MetadataCredentialExtractor) Extract ¶
func (e *MetadataCredentialExtractor) Extract(ctx context.Context) (*ServiceCredential, error)
Extract 从上下文提取凭证
type MethodMatcher ¶
MethodMatcher 方法匹配接口
type MethodPermission ¶
type MethodPermission struct {
Method string `json:"method" yaml:"method"`
Permissions []string `json:"permissions" yaml:"permissions"`
Description string `json:"description" yaml:"description"`
}
MethodPermission 方法级权限
type MethodPermissionChecker ¶
type MethodPermissionChecker struct {
// contains filtered or unexported fields
}
MethodPermissionChecker 方法级权限检查器
func NewMethodPermissionChecker ¶
func NewMethodPermissionChecker() *MethodPermissionChecker
NewMethodPermissionChecker 创建方法级权限检查器
func (*MethodPermissionChecker) Check ¶
func (c *MethodPermissionChecker) Check(method string, userPermissions []string) error
Check 检查是否有足够的权限
func (*MethodPermissionChecker) Register ¶
func (c *MethodPermissionChecker) Register(method string, permissions ...string)
Register 注册方法所需的权限
type NonceStore ¶
type NonceStore interface {
// Exists 检查 nonce 是否已存在
Exists(ctx context.Context, nonce string) (bool, error)
// Store 存储 nonce
Store(ctx context.Context, nonce string, ttl time.Duration) error
}
NonceStore Nonce 存储接口(防重放攻击)
type RecoveryOption ¶
type RecoveryOption func(*recoveryOptions)
RecoveryOption 恢复拦截器选项函数
func WithRecoveryContextPreprocess ¶
func WithRecoveryContextPreprocess(fn func(ctx context.Context) context.Context) RecoveryOption
WithRecoveryContextPreprocess 设置恢复拦截器的上下文预处理钩子
func WithRecoveryLogger ¶
func WithRecoveryLogger(logger InterceptorLogger) RecoveryOption
WithRecoveryLogger 设置恢复拦截器的日志记录器
type RequestIDOption ¶
type RequestIDOption func(*requestIDOptions)
RequestIDOption 请求ID拦截器选项函数
func WithMetadataInjector ¶
func WithMetadataInjector(injector func(ctx context.Context, requestID string) context.Context) RequestIDOption
WithMetadataInjector 设置 metadata 注入回调
func WithRequestIDGenerator ¶
func WithRequestIDGenerator(generator func() string) RequestIDOption
WithRequestIDGenerator 设置请求ID生成器
type RetryOption ¶
type RetryOption struct {
MaxRetries int
InitialWait time.Duration
MaxWait time.Duration
Multiplier float64
// 判断是否应该重试的函数
ShouldRetry func(err error) bool
}
RetryOption 重试选项
type ServiceACL ¶
type ServiceACL struct {
// contains filtered or unexported fields
}
ServiceACL 服务级访问控制列表
func (*ServiceACL) AddServicePermission ¶
func (a *ServiceACL) AddServicePermission(perms *ServicePermissions)
AddServicePermission 添加服务权限
func (*ServiceACL) CheckAccess ¶
func (a *ServiceACL) CheckAccess(serviceName, method string) error
CheckAccess 检查服务是否有权访问指定方法
func (*ServiceACL) GetServicePermissions ¶
func (a *ServiceACL) GetServicePermissions(serviceName string) (*ServicePermissions, bool)
GetServicePermissions 获取服务权限配置
func (*ServiceACL) ListServices ¶
func (a *ServiceACL) ListServices() []string
ListServices 列出所有配置的服务
func (*ServiceACL) RemoveServicePermission ¶
func (a *ServiceACL) RemoveServicePermission(serviceName string)
RemoveServicePermission 移除服务权限
func (*ServiceACL) UpdateServiceMethods ¶
func (a *ServiceACL) UpdateServiceMethods(serviceName string, methods []string) error
UpdateServiceMethods 更新服务允许的方法
type ServiceCredential ¶
type ServiceCredential struct {
// 凭证类型
Type CredentialType `json:"type"`
// Bearer Token 相关
Token string `json:"token,omitempty"`
TokenType string `json:"token_type,omitempty"` // jwt, opaque
// HMAC 相关
AccessKey string `json:"access_key,omitempty"`
Signature string `json:"signature,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Nonce string `json:"nonce,omitempty"`
// 解析后的信息
Subject string `json:"subject,omitempty"` // 凭证主体(服务名)
Permissions []string `json:"permissions,omitempty"` // 权限列表
ExpiresAt time.Time `json:"expires_at,omitempty"` // 过期时间
Claims map[string]string `json:"claims,omitempty"` // 额外声明
}
ServiceCredential 服务凭证(用于应用层鉴权)
func CredentialFromContext ¶
func CredentialFromContext(ctx context.Context) (*ServiceCredential, bool)
CredentialFromContext 从上下文获取服务凭证
type ServiceIdentity ¶
type ServiceIdentity struct {
// 服务名称(从证书 CN 或 SAN 中的服务标识提取)
ServiceName string `json:"service_name"`
// 服务命名空间(如 production, staging)
ServiceNamespace string `json:"service_namespace,omitempty"`
// 证书通用名称
CommonName string `json:"common_name,omitempty"`
// 组织单元列表
OrganizationalUnits []string `json:"organizational_units,omitempty"`
// 证书序列号(用于追踪和撤销)
CertSerialNumber string `json:"cert_serial_number,omitempty"`
// DNS SANs
DNSSANs []string `json:"dns_sans,omitempty"`
// URI SANs
URISANs []string `json:"uri_sans,omitempty"`
// 证书有效期
NotBefore time.Time `json:"not_before,omitempty"`
NotAfter time.Time `json:"not_after,omitempty"`
}
ServiceIdentity 服务身份信息(从 mTLS 证书或应用层凭证提取)
func ExtractServiceIdentityFromTLS ¶
func ExtractServiceIdentityFromTLS(ctx context.Context) (*ServiceIdentity, error)
ExtractServiceIdentityFromTLS 从 TLS 连接提取服务身份
func ParseCertificateIdentity ¶
func ParseCertificateIdentity(cert *x509.Certificate) (*ServiceIdentity, error)
ParseCertificateIdentity 从证书解析服务身份
func ServiceIdentityFromContext ¶
func ServiceIdentityFromContext(ctx context.Context) (*ServiceIdentity, bool)
ServiceIdentityFromContext 从上下文获取服务身份
type ServiceMetrics ¶
type ServiceMetrics struct {
ServiceName string
RequestCount uint64
SuccessCount uint64
FailureCount uint64
TotalDuration int64 // 纳秒
LastRequestAt int64 // Unix 时间戳
}
ServiceMetrics 服务级指标
type ServicePermissions ¶
type ServicePermissions struct {
// 服务名称
ServiceName string `json:"service_name" yaml:"service_name"`
// 允许调用的方法列表(支持通配符)
AllowedMethods []string `json:"allowed_methods" yaml:"allowed_methods"`
// 拒绝调用的方法列表(优先级高于允许)
DeniedMethods []string `json:"denied_methods" yaml:"denied_methods"`
// 方法级权限(更细粒度)
MethodPermissions map[string][]string `json:"method_permissions" yaml:"method_permissions"`
// 是否启用
Enabled bool `json:"enabled" yaml:"enabled"`
// 描述
Description string `json:"description" yaml:"description"`
}
ServicePermissions 服务权限配置
type SkipMethodMatcher ¶
type SkipMethodMatcher struct {
// contains filtered or unexported fields
}
SkipMethodMatcher 跳过方法匹配器
func NewSkipMethodMatcher ¶
func NewSkipMethodMatcher(methods ...string) *SkipMethodMatcher
NewSkipMethodMatcher 创建跳过方法匹配器
func (*SkipMethodMatcher) Match ¶
func (m *SkipMethodMatcher) Match(method string) bool
Match 检查方法是否应该被跳过
type WrappedServerStream ¶
type WrappedServerStream struct {
grpc.ServerStream
Ctx context.Context
}
WrappedServerStream 包装 ServerStream 以注入自定义上下文
func (*WrappedServerStream) Context ¶
func (w *WrappedServerStream) Context() context.Context
Context 返回自定义上下文