auth

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

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

View Source
const DefaultCacheRefreshInterval = 1 * time.Minute

DefaultCacheRefreshInterval is the default interval for refreshing the API key cache.

View Source
const DefaultUserCacheTTL = 60 * time.Second

DefaultUserCacheTTL is the default TTL for cached user credentials.

Variables

This section is empty.

Functions

func ConstantTimeCompare

func ConstantTimeCompare(a, b string) bool

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

func CreateServerTLSConfig(cfg config.TLSConfig) (*tls.Config, error)

CreateServerTLSConfig creates a TLS config for an HTTPS server.

func GetRole

func GetRole(ctx context.Context) string

GetRole retrieves the role from context.

func GetUserID

func GetUserID(ctx context.Context) int64

GetUserID retrieves the user ID from context.

func HashAPIKey

func HashAPIKey(rawKey string) string

HashAPIKey returns the SHA-256 hash of an API key (for lookup). Deprecated: Use Service.hashAPIKey instead for HMAC support.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword creates a bcrypt hash of a password.

func ValidRole

func ValidRole(role string) bool

ValidRole checks if a role is valid.

Types

type APIKey

type APIKey struct {
	Key         string
	Name        string
	Username    string
	Role        string
	Description string
}

APIKey represents an API key.

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) Close

func (al *AuditLogger) Close() error

Close closes the audit logger.

func (*AuditLogger) Log

func (al *AuditLogger) Log(event *AuditEvent)

Log logs an audit event.

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

func (p *JWTProvider) VerifyToken(ctx context.Context, rawToken string) (*User, bool)

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

func (p *LDAPProvider) Authenticate(ctx context.Context, username, password string) (*User, error)

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

func (p *OIDCProvider) VerifyToken(ctx context.Context, rawToken string) (*User, bool)

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

func (s *Service) DeleteAPIKey(ctx context.Context, id int64) error

DeleteAPIKey deletes an API key by ID.

func (*Service) DeleteUser

func (s *Service) DeleteUser(ctx context.Context, id int64) error

DeleteUser deletes a user by ID.

func (*Service) GetAPIKeyByID

func (s *Service) GetAPIKeyByID(ctx context.Context, id int64) (*storage.APIKeyRecord, error)

GetAPIKeyByID retrieves an API key by ID.

func (*Service) GetUserByID

func (s *Service) GetUserByID(ctx context.Context, id int64) (*storage.UserRecord, error)

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

func (s *Service) ListAPIKeys(ctx context.Context) ([]*storage.APIKeyRecord, error)

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) ListUsers

func (s *Service) ListUsers(ctx context.Context) ([]*storage.UserRecord, error)

ListUsers returns all users.

func (*Service) RevokeAPIKey

func (s *Service) RevokeAPIKey(ctx context.Context, id int64) error

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

func (s *Service) ValidateAPIKey(ctx context.Context, rawKey string) (*storage.APIKeyRecord, error)

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.

type User

type User struct {
	ID       int64
	Username string
	Role     string
	Method   string // basic, api_key, jwt, oidc, mtls
}

User represents an authenticated user.

func GetUser

func GetUser(ctx context.Context) *User

GetUser retrieves the authenticated user from context.

Jump to

Keyboard shortcuts

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