Documentation
¶
Overview ¶
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Package auth provides authentication and authorization for the schema registry.
Index ¶
- Constants
- func ConstantTimeCompare(a, b string) bool
- func CreateClientTLSConfig(certFile, keyFile, caFile string, insecureSkipVerify bool) (*tls.Config, error)
- func CreateServerTLSConfig(cfg config.TLSConfig) (*tls.Config, error)
- func GetRole(ctx context.Context) string
- func GetUserID(ctx context.Context) int64
- func HashAPIKey(rawKey string) string
- func HashPassword(password string) (string, error)
- func ValidRole(role string) bool
- type APIKey
- type AuditEvent
- type AuditEventType
- type AuditLogger
- type Authenticator
- func (a *Authenticator) AddAPIKey(key *APIKey)
- func (a *Authenticator) Middleware(next http.Handler) http.Handler
- func (a *Authenticator) SetJWTProvider(p *JWTProvider)
- func (a *Authenticator) SetLDAPProvider(p *LDAPProvider)
- func (a *Authenticator) SetOIDCProvider(p *OIDCProvider)
- func (a *Authenticator) SetService(svc *Service)
- type Authorizer
- func (a *Authorizer) AuthorizeEndpoint(permissions []EndpointPermission) func(http.Handler) http.Handler
- func (a *Authorizer) HasPermission(user *User, perm Permission) bool
- func (a *Authorizer) IsSuperAdmin(username string) bool
- func (a *Authorizer) RequirePermission(perm Permission) func(http.Handler) http.Handler
- type BootstrapResult
- type ContextKey
- type CreateAPIKeyRequest
- type CreateAPIKeyResponse
- type CreateUserRequest
- type EndpointPermission
- type JWTProvider
- type LDAPProvider
- type OIDCProvider
- type Permission
- type RateLimiter
- type Role
- type Service
- func (s *Service) BootstrapAdmin(ctx context.Context, username, password, email string) (*BootstrapResult, error)
- func (s *Service) ChangePassword(ctx context.Context, id int64, oldPassword, newPassword string) error
- func (s *Service) Close()
- func (s *Service) CreateAPIKey(ctx context.Context, req CreateAPIKeyRequest) (*CreateAPIKeyResponse, error)
- func (s *Service) CreateUser(ctx context.Context, req CreateUserRequest) (*storage.UserRecord, error)
- func (s *Service) DeleteAPIKey(ctx context.Context, id int64) error
- func (s *Service) DeleteUser(ctx context.Context, id int64) error
- func (s *Service) GetAPIKeyByID(ctx context.Context, id int64) (*storage.APIKeyRecord, error)
- func (s *Service) GetUserByID(ctx context.Context, id int64) (*storage.UserRecord, error)
- func (s *Service) GetUserByUsername(ctx context.Context, username string) (*storage.UserRecord, error)
- func (s *Service) ListAPIKeys(ctx context.Context) ([]*storage.APIKeyRecord, error)
- func (s *Service) ListAPIKeysByUserID(ctx context.Context, userID int64) ([]*storage.APIKeyRecord, error)
- func (s *Service) ListUsers(ctx context.Context) ([]*storage.UserRecord, error)
- func (s *Service) RevokeAPIKey(ctx context.Context, id int64) error
- func (s *Service) RotateAPIKey(ctx context.Context, id int64, newExpiresAt time.Time) (*CreateAPIKeyResponse, error)
- func (s *Service) UpdateAPIKey(ctx context.Context, id int64, updates map[string]interface{}) (*storage.APIKeyRecord, error)
- func (s *Service) UpdateUser(ctx context.Context, id int64, updates map[string]interface{}) (*storage.UserRecord, error)
- func (s *Service) ValidateAPIKey(ctx context.Context, rawKey string) (*storage.APIKeyRecord, error)
- func (s *Service) ValidateCredentials(ctx context.Context, username, password string) (*storage.UserRecord, error)
- type ServiceConfig
- type TLSManager
- type User
Constants ¶
const DefaultCacheRefreshInterval = 1 * time.Minute
DefaultCacheRefreshInterval is the default interval for refreshing the API key cache.
const DefaultUserCacheTTL = 60 * time.Second
DefaultUserCacheTTL is the default TTL for cached user credentials.
Variables ¶
This section is empty.
Functions ¶
func ConstantTimeCompare ¶
ConstantTimeCompare performs a constant-time string comparison.
func CreateClientTLSConfig ¶
func CreateClientTLSConfig(certFile, keyFile, caFile string, insecureSkipVerify bool) (*tls.Config, error)
CreateClientTLSConfig creates a TLS config for client connections.
func CreateServerTLSConfig ¶
CreateServerTLSConfig creates a TLS config for an HTTPS server.
func HashAPIKey ¶
HashAPIKey returns the SHA-256 hash of an API key (for lookup). Deprecated: Use Service.hashAPIKey instead for HMAC support.
func HashPassword ¶
HashPassword creates a bcrypt hash of a password.
Types ¶
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time `json:"timestamp"`
EventType AuditEventType `json:"event_type"`
User string `json:"user,omitempty"`
Role string `json:"role,omitempty"`
ClientIP string `json:"client_ip"`
Method string `json:"method"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
Duration time.Duration `json:"duration_ms"`
Subject string `json:"subject,omitempty"`
Version int `json:"version,omitempty"`
SchemaID int64 `json:"schema_id,omitempty"`
RequestBody string `json:"request_body,omitempty"`
Error string `json:"error,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
AuditEvent represents an audit log entry.
func (*AuditEvent) MarshalJSON ¶
func (e *AuditEvent) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling for AuditEvent.
type AuditEventType ¶
type AuditEventType string
AuditEventType represents the type of audit event.
const ( // Schema events AuditEventSchemaRegister AuditEventType = "schema_register" AuditEventSchemaDelete AuditEventType = "schema_delete" AuditEventSchemaGet AuditEventType = "schema_get" AuditEventSchemaLookup AuditEventType = "schema_lookup" // Config events AuditEventConfigGet AuditEventType = "config_get" AuditEventConfigUpdate AuditEventType = "config_update" AuditEventConfigDelete AuditEventType = "config_delete" // Mode events AuditEventModeGet AuditEventType = "mode_get" AuditEventModeUpdate AuditEventType = "mode_update" // Auth events AuditEventAuthSuccess AuditEventType = "auth_success" AuditEventAuthFailure AuditEventType = "auth_failure" AuditEventAuthForbidden AuditEventType = "auth_forbidden" // Subject events AuditEventSubjectDelete AuditEventType = "subject_delete" AuditEventSubjectList AuditEventType = "subject_list" )
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger handles audit logging.
func NewAuditLogger ¶
func NewAuditLogger(cfg config.AuditConfig) (*AuditLogger, error)
NewAuditLogger creates a new audit logger.
func (*AuditLogger) LogEvent ¶
func (al *AuditLogger) LogEvent(eventType AuditEventType, r *http.Request, statusCode int, err error)
LogEvent is a convenience function for logging events.
func (*AuditLogger) Middleware ¶
func (al *AuditLogger) Middleware(next http.Handler) http.Handler
Middleware returns HTTP middleware for audit logging.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator handles authentication.
func NewAuthenticator ¶
func NewAuthenticator(cfg config.AuthConfig) *Authenticator
NewAuthenticator creates a new authenticator.
func (*Authenticator) AddAPIKey ¶
func (a *Authenticator) AddAPIKey(key *APIKey)
AddAPIKey adds an API key (for legacy/config-based auth).
func (*Authenticator) Middleware ¶
func (a *Authenticator) Middleware(next http.Handler) http.Handler
Middleware returns HTTP middleware for authentication.
func (*Authenticator) SetJWTProvider ¶ added in v0.1.0
func (a *Authenticator) SetJWTProvider(p *JWTProvider)
SetJWTProvider sets the JWT authentication provider.
func (*Authenticator) SetLDAPProvider ¶
func (a *Authenticator) SetLDAPProvider(p *LDAPProvider)
SetLDAPProvider sets the LDAP authentication provider.
func (*Authenticator) SetOIDCProvider ¶
func (a *Authenticator) SetOIDCProvider(p *OIDCProvider)
SetOIDCProvider sets the OIDC authentication provider.
func (*Authenticator) SetService ¶
func (a *Authenticator) SetService(svc *Service)
SetService sets the database-backed auth service.
type Authorizer ¶
type Authorizer struct {
// contains filtered or unexported fields
}
Authorizer handles authorization.
func NewAuthorizer ¶
func NewAuthorizer(cfg config.RBACConfig) *Authorizer
NewAuthorizer creates a new authorizer.
func (*Authorizer) AuthorizeEndpoint ¶
func (a *Authorizer) AuthorizeEndpoint(permissions []EndpointPermission) func(http.Handler) http.Handler
AuthorizeEndpoint returns middleware that checks endpoint-based permissions.
func (*Authorizer) HasPermission ¶
func (a *Authorizer) HasPermission(user *User, perm Permission) bool
HasPermission checks if a user has a specific permission.
func (*Authorizer) IsSuperAdmin ¶
func (a *Authorizer) IsSuperAdmin(username string) bool
IsSuperAdmin checks if a user is a super admin.
func (*Authorizer) RequirePermission ¶
func (a *Authorizer) RequirePermission(perm Permission) func(http.Handler) http.Handler
RequirePermission returns middleware that requires a specific permission.
type BootstrapResult ¶
type BootstrapResult struct {
Created bool // Whether a new user was created
Username string // Username of the created/existing admin
Message string // Human-readable message
}
BootstrapResult contains the result of bootstrapping the initial admin user.
type ContextKey ¶
type ContextKey string
ContextKey is used for storing auth info in context.
const ( // UserContextKey is the context key for the authenticated user. UserContextKey ContextKey = "auth_user" // RoleContextKey is the context key for the user's role. RoleContextKey ContextKey = "auth_role" // UserIDContextKey is the context key for the user's database ID. UserIDContextKey ContextKey = "auth_user_id" )
type CreateAPIKeyRequest ¶
type CreateAPIKeyRequest struct {
UserID int64 // Required: user who owns this key
Name string // Required: must be unique per user
Role string // Required: role for this API key
ExpiresAt time.Time // Required: when the key expires
}
CreateAPIKeyRequest contains the data needed to create an API key.
type CreateAPIKeyResponse ¶
type CreateAPIKeyResponse struct {
ID int64 `json:"id"`
Key string `json:"key"` // Raw key, only returned on creation
KeyPrefix string `json:"key_prefix"`
Name string `json:"name"`
Role string `json:"role"`
UserID int64 `json:"user_id"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
CreateAPIKeyResponse contains the created API key details including the raw key.
type CreateUserRequest ¶
type CreateUserRequest struct {
Username string
Email string
Password string
Role string
Enabled bool
}
CreateUserRequest contains the data needed to create a user.
type EndpointPermission ¶
type EndpointPermission struct {
Method string
PathPrefix string
Permission Permission
}
EndpointPermission maps HTTP methods and paths to required permissions.
func DefaultEndpointPermissions ¶
func DefaultEndpointPermissions() []EndpointPermission
DefaultEndpointPermissions returns the default endpoint permission mappings.
type JWTProvider ¶ added in v0.1.0
type JWTProvider struct {
// contains filtered or unexported fields
}
JWTProvider handles JWT authentication.
func NewJWTProvider ¶ added in v0.1.0
func NewJWTProvider(cfg config.JWTConfig) (*JWTProvider, error)
NewJWTProvider creates a new JWT authentication provider.
func (*JWTProvider) VerifyToken ¶ added in v0.1.0
VerifyToken verifies a JWT token and returns the authenticated user.
type LDAPProvider ¶
type LDAPProvider struct {
// contains filtered or unexported fields
}
LDAPProvider handles LDAP authentication.
func NewLDAPProvider ¶
func NewLDAPProvider(cfg config.LDAPConfig) (*LDAPProvider, error)
NewLDAPProvider creates a new LDAP authentication provider.
func (*LDAPProvider) Authenticate ¶
Authenticate validates user credentials against LDAP and returns the user if valid.
func (*LDAPProvider) Close ¶
func (p *LDAPProvider) Close() error
Close closes any resources held by the LDAP provider.
type OIDCProvider ¶
type OIDCProvider struct {
// contains filtered or unexported fields
}
OIDCProvider handles OpenID Connect authentication.
func NewOIDCProvider ¶
func NewOIDCProvider(ctx context.Context, cfg config.OIDCConfig) (*OIDCProvider, error)
NewOIDCProvider creates a new OIDC authentication provider.
func (*OIDCProvider) VerifyToken ¶
VerifyToken validates an OIDC/JWT token and returns the user if valid.
type Permission ¶
type Permission string
Permission represents an action on a resource.
const ( // Schema permissions PermissionSchemaRead Permission = "schema:read" PermissionSchemaWrite Permission = "schema:write" PermissionSchemaDelete Permission = "schema:delete" // Config permissions PermissionConfigRead Permission = "config:read" PermissionConfigWrite Permission = "config:write" // Mode permissions PermissionModeRead Permission = "mode:read" PermissionModeWrite Permission = "mode:write" // Import permissions (for migration) PermissionImport Permission = "import:write" // Encryption permissions (KEK/DEK management) PermissionEncryptionRead Permission = "encryption:read" PermissionEncryptionWrite Permission = "encryption:write" // Exporter permissions PermissionExporterRead Permission = "exporter:read" PermissionExporterWrite Permission = "exporter:write" // Admin permissions PermissionAdminRead Permission = "admin:read" PermissionAdminWrite Permission = "admin:write" )
func GetRolePermissions ¶
func GetRolePermissions(role Role) []Permission
GetRolePermissions returns the permissions for a role.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements token bucket rate limiting.
func NewRateLimiter ¶
func NewRateLimiter(cfg config.RateLimitConfig) *RateLimiter
NewRateLimiter creates a new rate limiter.
func (*RateLimiter) CleanupStaleClients ¶
func (rl *RateLimiter) CleanupStaleClients(maxAge time.Duration)
CleanupStaleClients removes client buckets that haven't been used recently.
func (*RateLimiter) Middleware ¶
func (rl *RateLimiter) Middleware(next http.Handler) http.Handler
Middleware returns HTTP middleware for rate limiting.
type Role ¶
type Role string
Role represents a user role.
const ( // RoleSuperAdmin has full access to everything. RoleSuperAdmin Role = "super_admin" // RoleAdmin can manage schemas and configuration. RoleAdmin Role = "admin" // RoleDeveloper can register and read schemas. RoleDeveloper Role = "developer" // RoleReadOnly can only read schemas. RoleReadOnly Role = "readonly" )
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides user and API key management operations.
func NewService ¶
func NewService(store storage.AuthStorage) *Service
NewService creates a new auth service with default configuration.
func NewServiceWithConfig ¶
func NewServiceWithConfig(store storage.AuthStorage, cfg ServiceConfig) *Service
NewServiceWithConfig creates a new auth service with configuration. Note: CacheRefreshInterval and UserCacheTTL of 0 will disable caching. Use DefaultCacheRefreshInterval and DefaultUserCacheTTL for default behavior.
func (*Service) BootstrapAdmin ¶
func (s *Service) BootstrapAdmin(ctx context.Context, username, password, email string) (*BootstrapResult, error)
BootstrapAdmin creates the initial admin user if the users table is empty. This solves the chicken-and-egg problem where you need an admin to create users, but there are no users when the system is first deployed.
The function will: - Return immediately if the users table is not empty - Create an admin user with the provided credentials if the table is empty - Return an error if the credentials are not provided
This function is idempotent: if there are existing users, it does nothing.
func (*Service) ChangePassword ¶
func (s *Service) ChangePassword(ctx context.Context, id int64, oldPassword, newPassword string) error
ChangePassword changes a user's password.
func (*Service) Close ¶
func (s *Service) Close()
Close stops the background cache refresh goroutine. Should be called when shutting down the server.
func (*Service) CreateAPIKey ¶
func (s *Service) CreateAPIKey(ctx context.Context, req CreateAPIKeyRequest) (*CreateAPIKeyResponse, error)
CreateAPIKey creates a new API key and returns the raw key.
func (*Service) CreateUser ¶
func (s *Service) CreateUser(ctx context.Context, req CreateUserRequest) (*storage.UserRecord, error)
CreateUser creates a new user with the given details.
func (*Service) DeleteAPIKey ¶
DeleteAPIKey deletes an API key by ID.
func (*Service) DeleteUser ¶
DeleteUser deletes a user by ID.
func (*Service) GetAPIKeyByID ¶
GetAPIKeyByID retrieves an API key by ID.
func (*Service) GetUserByID ¶
GetUserByID retrieves a user by ID.
func (*Service) GetUserByUsername ¶
func (s *Service) GetUserByUsername(ctx context.Context, username string) (*storage.UserRecord, error)
GetUserByUsername retrieves a user by username.
func (*Service) ListAPIKeys ¶
ListAPIKeys returns all API keys.
func (*Service) ListAPIKeysByUserID ¶
func (s *Service) ListAPIKeysByUserID(ctx context.Context, userID int64) ([]*storage.APIKeyRecord, error)
ListAPIKeysByUserID returns all API keys for a specific user.
func (*Service) RevokeAPIKey ¶
RevokeAPIKey disables an API key.
func (*Service) RotateAPIKey ¶
func (s *Service) RotateAPIKey(ctx context.Context, id int64, newExpiresAt time.Time) (*CreateAPIKeyResponse, error)
RotateAPIKey creates a new API key with same settings and revokes the old one. The new key will have a fresh expiry based on the remaining duration of the old key.
func (*Service) UpdateAPIKey ¶
func (s *Service) UpdateAPIKey(ctx context.Context, id int64, updates map[string]interface{}) (*storage.APIKeyRecord, error)
UpdateAPIKey updates an existing API key.
func (*Service) UpdateUser ¶
func (s *Service) UpdateUser(ctx context.Context, id int64, updates map[string]interface{}) (*storage.UserRecord, error)
UpdateUser updates an existing user.
func (*Service) ValidateAPIKey ¶
ValidateAPIKey validates an API key and returns the record if valid. First checks the in-memory cache for performance, then falls back to the database if the key is not found in cache. The cache is refreshed periodically from the database to ensure cluster consistency.
func (*Service) ValidateCredentials ¶
func (s *Service) ValidateCredentials(ctx context.Context, username, password string) (*storage.UserRecord, error)
ValidateCredentials validates user credentials and returns the user if valid. Results are cached for performance; cache entries expire after UserCacheTTL.
type ServiceConfig ¶
type ServiceConfig struct {
// APIKeySecret is the secret used for HMAC-SHA256 hashing of API keys.
// This provides defense-in-depth: even if the database is compromised,
// the attacker cannot verify API keys without this secret.
// Should be at least 32 bytes of cryptographically random data.
// If empty, falls back to plain SHA-256 (backward compatible but less secure).
APIKeySecret string
// APIKeyPrefix is prepended to generated API keys (e.g., "sr_live_").
// This helps identify keys and their purpose.
APIKeyPrefix string
// CacheRefreshInterval is how often the background process refreshes
// cached API keys from the database. This ensures cluster consistency
// as all nodes will eventually converge to the same state.
// Set to 0 to disable caching entirely. Default is 1 minute.
CacheRefreshInterval time.Duration
// UserCacheTTL is how long validated user credentials are cached.
// This reduces database load for frequently authenticating users.
// Set to 0 to disable user credential caching. Default is 60 seconds.
UserCacheTTL time.Duration
}
ServiceConfig contains configuration for the auth service.
type TLSManager ¶
type TLSManager struct {
// contains filtered or unexported fields
}
TLSManager manages TLS configuration with optional certificate reloading.
func NewTLSManager ¶
func NewTLSManager(cfg config.TLSConfig) (*TLSManager, error)
NewTLSManager creates a new TLS manager.
func (*TLSManager) GetCertificate ¶
func (tm *TLSManager) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)
GetCertificate returns the current certificate for TLS handshake.
func (*TLSManager) Reload ¶
func (tm *TLSManager) Reload() error
Reload reloads certificates from disk.
func (*TLSManager) TLSConfig ¶
func (tm *TLSManager) TLSConfig() *tls.Config
TLSConfig returns the TLS configuration.