security

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ContextKeyUserID is the gin context key for the authenticated user ID.
	ContextKeyUserID = "userID"
	// ContextKeyClientID is the gin context key for the agent client ID.
	ContextKeyClientID = "clientID"
	// ContextKeyRoles is the gin context key for resolved caller roles.
	ContextKeyRoles = "roles"
	// ContextKeyIsAdmin is the gin context key for admin authorization.
	ContextKeyIsAdmin = "isAdmin"
)
View Source
const (
	RoleAdmin   = "admin"
	RoleAuditor = "auditor"
	RoleIndexer = "indexer"
)

Variables

View Source
var (

	// StoreLatency can be used by store implementations to record operation latency.
	StoreLatency *prometheus.HistogramVec

	CacheHitsTotal   prometheus.Counter
	CacheMissesTotal prometheus.Counter

	// DBPoolOpenConnections tracks the number of currently open database connections.
	DBPoolOpenConnections prometheus.Gauge

	// DBPoolMaxConnections tracks the configured maximum database connections.
	DBPoolMaxConnections prometheus.Gauge

	// SSEConnectionsActive tracks the number of currently active SSE connections.
	SSEConnectionsActive prometheus.Gauge

	// EventBusPublishedTotal counts total events published to the event bus.
	EventBusPublishedTotal prometheus.Counter

	// EventBusDeliveredTotal counts total events delivered to SSE clients.
	EventBusDeliveredTotal prometheus.Counter

	// EventBusDroppedTotal counts total events dropped (slow consumers or publish failures).
	EventBusDroppedTotal prometheus.Counter

	// EventBusSubscriberEvictionsTotal counts total slow subscribers evicted.
	EventBusSubscriberEvictionsTotal prometheus.Counter
)

Functions

func AccessLogMiddleware

func AccessLogMiddleware(skipPaths ...string) gin.HandlerFunc

AccessLogMiddleware logs each HTTP request with method, path, status, and duration. Paths listed in skipPaths are silently passed through without logging.

func AdminAuditMiddleware

func AdminAuditMiddleware(requireJustification bool) gin.HandlerFunc

AdminAuditMiddleware logs admin API calls with caller identity and target resource. When requireJustification is true, admin requests must include a justification via query param (?justification=...) or X-Justification header.

func AuthMiddleware

func AuthMiddleware(resolver *TokenResolver) gin.HandlerFunc

AuthMiddleware returns a gin middleware that extracts user identity from the Authorization header using the provided TokenResolver.

func ClientIDMiddleware

func ClientIDMiddleware() gin.HandlerFunc

ClientIDMiddleware extracts the X-Client-ID header and sets it in context.

func EffectiveAdminRole

func EffectiveAdminRole(c *gin.Context) string

EffectiveAdminRole returns the highest resolved admin role.

func GRPCStreamInterceptor

func GRPCStreamInterceptor(resolver *TokenResolver) grpc.StreamServerInterceptor

GRPCStreamInterceptor returns a gRPC stream server interceptor that resolves caller identity.

func GRPCUnaryInterceptor

func GRPCUnaryInterceptor(resolver *TokenResolver) grpc.UnaryServerInterceptor

GRPCUnaryInterceptor returns a gRPC unary server interceptor that resolves caller identity.

func GetClientID

func GetClientID(c *gin.Context) string

GetClientID returns the agent client ID from the gin context.

func GetUserID

func GetUserID(c *gin.Context) string

GetUserID returns the authenticated user ID from the gin context.

func HasRole

func HasRole(c *gin.Context, role string) bool

HasRole returns true if the caller has the given role.

func InitMetrics

func InitMetrics(constLabels prometheus.Labels)

InitMetrics registers all Prometheus metrics with the given constant labels. Must be called before starting the HTTP server or any store/cache initialization that records metrics. Safe to call multiple times; only the first call registers.

func IsAdmin

func IsAdmin(c *gin.Context) bool

IsAdmin returns true if the request is from an admin.

func MetricsMiddleware

func MetricsMiddleware() gin.HandlerFunc

MetricsMiddleware records HTTP request metrics for Prometheus.

func ParseMetricsLabels

func ParseMetricsLabels(s string) (prometheus.Labels, error)

ParseMetricsLabels parses a comma-separated list of key=value pairs into Prometheus labels. Values support ${VAR} / $VAR environment variable expansion. Label values may not contain commas. Returns nil for an empty string.

func RequireAdminRole

func RequireAdminRole() gin.HandlerFunc

RequireAdminRole requires the caller to have admin role.

func RequireAuditorRole

func RequireAuditorRole() gin.HandlerFunc

RequireAuditorRole requires the caller to have auditor or admin role.

Types

type Identity

type Identity struct {
	UserID   string
	ClientID string
	Roles    map[string]bool
	IsAdmin  bool
}

Identity holds the resolved caller identity from a bearer token.

func IdentityFromContext

func IdentityFromContext(ctx context.Context) *Identity

IdentityFromContext retrieves the Identity stored in a context by the gRPC interceptor.

type TokenResolver

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

TokenResolver resolves bearer tokens to caller identities. It is initialized once at startup and shared by both the HTTP middleware and gRPC interceptors.

func NewTokenResolver

func NewTokenResolver(cfg *config.Config) *TokenResolver

NewTokenResolver creates a TokenResolver from the application config. It performs one-time OIDC provider discovery if OIDCIssuer is configured.

func (*TokenResolver) Resolve

func (r *TokenResolver) Resolve(ctx context.Context, bearerToken, apiKey, clientIDHeader string) (*Identity, error)

Resolve resolves a bearer token (and optional API key / client ID header) into a caller Identity. bearerToken is the raw token value (without the "Bearer " prefix). apiKey is the value of the X-API-Key header (may be empty). clientIDHeader is the value of the X-Client-ID header (may be empty; only used in testing mode).

Jump to

Keyboard shortcuts

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