auth

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 42 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	CloudHandoffURLEnv   = "KORA_ENGINE_CLOUD_IDENTITY_URL"
	CloudHandoffTokenEnv = "KORA_ENGINE_CLOUD_IDENTITY_TOKEN"
)

Environment variables that configure Cloud handoff; both are required.

View Source
const (
	DefaultSessionCacheBudgetBytes uint64 = 256 << 20
	MaxSessionCacheBudgetBytes     uint64 = 4 << 30
)
View Source
const DefaultSessionCacheMaxBytes uint64 = 8 << 20
View Source
const KoraCloudIssuerEnv = "KORA_CLOUD_OIDC_ISSUER"

KoraCloudIssuerEnv names Kora Cloud's OIDC issuer. When set, every tenant offers "Log in with Kora Cloud" as soon as its client secret is stored at secret://auth/oidc/kora-cloud/client-secret.

View Source
const KoraCloudProviderID = "kora-cloud"

KoraCloudProviderID is the built-in provider for signing in with Kora Cloud.

View Source
const LocalSignInSettingKey = "auth.allow_local_sign_in"

LocalSignInSettingKey stores whether a tenant still accepts local sign-in (magic links) in _kora_site_setting. Absent means allowed.

View Source
const MaxConsoleSessions = 8192
View Source
const PasswordSignInDisabledContextKey = "auth_password_sign_in_disabled"

PasswordSignInDisabledContextKey is set by tenant sign-in policy (for example single-sign-on-only workspaces) to refuse local password sign-in.

Variables

View Source
var (
	ErrInvalidCredentials        = errors.New("invalid credentials")
	ErrSessionExpired            = errors.New("session expired")
	ErrDisabledAccount           = errors.New("account disabled")
	ErrEmailVerificationRequired = errors.New("email verification required")
	ErrNoDBConnection            = errors.New("no database connection available")
	ErrMagicLinkExpired          = errors.New("magic link expired")
	ErrMagicLinkUsed             = errors.New("magic link already used")
	ErrMagicLinkRevoked          = errors.New("magic link revoked")
	ErrAuthRateLimited           = errors.New("authentication rate limited")
)
View Source
var (
	ErrRecentAuthRequired = errors.New("auth: recent authentication required")
	ErrIdentityCollision  = errors.New("auth: identity link already bound to another identity")
	ErrLinkNotFound       = errors.New("auth: identity link not found")
)

Typed reconciliation sentinels. Callers match via errors.Is, never string matching.

View Source
var CSRFSecure = false

CSRFSecure controls the Secure flag on CSRF cookies. Set true in production with TLS. Deprecated: SetSecureCookie auto-detects TLS; this is kept for explicit config overrides.

View Source
var ErrConsoleSessionCapacity = errors.New("console session capacity exhausted")
View Source
var ErrProviderNotFound = errors.New("auth: sign-in provider not found")

ErrProviderNotFound reports an unknown or disabled sign-in provider.

View Source
var SessionLifetime = 24 * time.Hour

SessionLifetime is the duration for which sessions are valid. Set before creating SessionManagers.

Functions

func AuthenticateExtension

func AuthenticateExtension(ctx context.Context, verifier ExtensionTokenVerifier, tenantID contract.TenantID, siteName, token string) (policy.Execution, []doctype.Permission, error)

AuthenticateExtension is AuthenticateExtensionExecution over an injected verifier.

func AuthenticateExtensionExecution

func AuthenticateExtensionExecution(ctx context.Context, database *sql.DB, dialect kdb.QueryDialect, tenantID contract.TenantID, siteName, token string) (policy.Execution, []doctype.Permission, error)

AuthenticateExtensionExecution verifies an active tenant extension token and returns its current, exact resource-operation grants. Call it per operation when a long-lived adapter must observe token revocation and permission changes. Credentials are never included in returned errors.

func BackfillExtensionTokenHashes

func BackfillExtensionTokenHashes(ctx context.Context, database *sql.DB, dialect kdb.QueryDialect) error

BackfillExtensionTokenHashes replaces plaintext tokens stored before access_token_hash existed with their verifier. It is idempotent.

func CSRFMiddleware

func CSRFMiddleware() gin.HandlerFunc

CSRFMiddleware protects state-changing requests with a double-submit cookie pattern. On first GET, a CSRF token is set as a cookie (HttpOnly=false so JS can read it). On POST/PUT/DELETE, the X-Kora-CSRF-Token header must match the cookie value. Token comparison uses constant-time comparison to prevent timing attacks.

func ClientSecretKeyFor

func ClientSecretKeyFor(providerID string) string

ClientSecretKeyFor is the secret-store key holding a provider's client secret; its reference form is secret://auth/oidc/<id>/client-secret.

func ContextWithSessionCreatedAt

func ContextWithSessionCreatedAt(ctx context.Context, createdAt time.Time) context.Context

ContextWithSessionCreatedAt returns a context that carries when the caller's session was created, so downstream code can require a recent sign-in for sensitive operations.

func HasExtensionPermission

func HasExtensionPermission(perms []doctype.Permission, doctype, operation string) bool

HasExtensionPermission checks whether the extension's scoped permissions grant the requested operation on the given doctype. Returns false for empty/nil permissions (secure by default).

func HashExtensionAccessToken

func HashExtensionAccessToken(token string) string

HashExtensionAccessToken returns the stored verifier for an extension or managed channel bearer token. Tokens are 256-bit random values, so an unsalted SHA-256 digest is sufficient and keeps lookups indexable.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword creates a bcrypt hash of a password.

func LocalSignInAllowed

func LocalSignInAllowed(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string) (bool, error)

LocalSignInAllowed reports the tenant's local sign-in policy (default true).

func MagicLinkTokenHash

func MagicLinkTokenHash(token string) string

MagicLinkTokenHash returns the persisted token digest, never the token.

func NewAuditID

func NewAuditID() string

func NewMagicLinkToken

func NewMagicLinkToken() (string, error)

NewMagicLinkToken creates a cryptographically random token for a durable management invitation operation. Callers persist only its hash.

func NotifyExtensionTokensChanged

func NotifyExtensionTokensChanged(c *gin.Context, site string)

NotifyExtensionTokensChanged reports that extension credentials for site were created, rotated, revoked or deleted on this request.

func RegisterAuthRoutes

func RegisterAuthRoutes(router *gin.Engine, sm *SessionManager, db *sql.DB, mailer MagicLinkMailer)

func RegisterAuthRoutesWithPublicAppBaseURL

func RegisterAuthRoutesWithPublicAppBaseURL(router *gin.Engine, sm *SessionManager, db *sql.DB, mailer MagicLinkMailer, publicAppBaseURL string) error

RegisterAuthRoutesWithPublicAppBaseURL registers authentication routes that send sign-in links through the configured public app origin. This is needed for path-routed workspaces where request Host may identify Engine or a tenant vanity hostname rather than the browser-facing application.

func RegisterCloudHandoffRoute

func RegisterCloudHandoffRoute(router *gin.Engine, sm *SessionManager, db *sql.DB, cfg CloudHandoffConfig) error

RegisterCloudHandoffRoute adds the tenant-routed, one-time Cloud identity exchange. Engine receives only Cloud identity metadata and creates its own tenant session; the session ID is returned only in the HttpOnly cookie.

func RevalidateRealtimeIdentity

func RevalidateRealtimeIdentity(c *gin.Context) (bool, error)

RevalidateRealtimeIdentity refreshes the credential and policy context for a long-lived realtime connection. It performs no response writes; false means the stream must close, while err reports a human-session storage failure.

func RevokeChannelSession

func RevokeChannelSession(db *sql.DB, dialect kdb.QueryDialect, id string, reason string) error

func SessionCreatedAt

func SessionCreatedAt(ctx context.Context) (time.Time, bool)

SessionCreatedAt returns the session creation time stored by ContextWithSessionCreatedAt.

func SetCSRFSecure

func SetCSRFSecure(secure bool)

SetCSRFSecure sets the Secure flag for CSRF cookies.

func SetLocalSignInAllowed

func SetLocalSignInAllowed(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string, allowed bool) error

SetLocalSignInAllowed stores the tenant's local sign-in policy.

func SetSecureCookie

func SetSecureCookie(c *gin.Context, name, value string, maxAge int, path string, httpOnly bool)

SetSecureCookie sets a cookie with Secure auto-detected from the request's TLS state and appends SameSite=Lax. Use this instead of c.SetCookie for security-sensitive cookies.

func SiteDB

func SiteDB(c *gin.Context) *sql.DB

SiteDB returns the site's database from the request context.

func TenantMagicLinkURL

func TenantMagicLinkURL(host, token string) (string, error)

TenantMagicLinkURL creates a link on a tenant-owned DNS alias. Non-loopback tenant hosts always use HTTPS so an enrollment token is never sent in clear.

func TenantPathMagicLinkURL

func TenantPathMagicLinkURL(appBaseURL, tenant, token string) (string, error)

TenantPathMagicLinkURL creates a sign-in link through the public application origin and the tenant path used by the standalone workspace. The configured origin is trusted operator configuration; it is never taken from a request or a tenant-provided value.

func ValidatePublicAppBaseURL

func ValidatePublicAppBaseURL(value string) error

ValidatePublicAppBaseURL rejects ambiguous or unsafe origins before an invitation worker is started. An empty value keeps host-based deployments on TenantMagicLinkURL; path-based deployments must configure this origin.

Types

type ChannelSession

type ChannelSession struct {
	ID              string
	Site            string
	ClientName      string
	ConversationKey string
	Provider        string
	SenderAddress   string
	TokenHash       string
	Permissions     []doctype.Permission
	PermissionsRaw  string
	TrustedUntil    time.Time
	SensitiveUntil  sql.NullTime
	RevokedAt       sql.NullTime
	RevokedReason   string
	CreatedAt       time.Time
	LastUsedAt      sql.NullTime
}

func AuthenticateChannelSession

func AuthenticateChannelSession(db *sql.DB, dialect kdb.QueryDialect, token string) (*ChannelSession, error)

func CreateChannelSession

func CreateChannelSession(db *sql.DB, dialect kdb.QueryDialect, params ChannelSessionCreateParams) (string, *ChannelSession, error)

type ChannelSessionCreateParams

type ChannelSessionCreateParams struct {
	Site            string
	ClientName      string
	ConversationKey string
	Provider        string
	SenderAddress   string
	Permissions     []doctype.Permission
	TrustedUntil    time.Time
	SensitiveUntil  *time.Time
}

type CloudHandoffConfig

type CloudHandoffConfig struct {
	RedeemURL    string
	ServiceToken string
	HTTPClient   *http.Client
}

type ConsoleSession

type ConsoleSession struct {
	Email     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

ConsoleSession represents an authenticated console session stored server-side.

type ExtensionTokenOpener

type ExtensionTokenOpener func(*sql.DB, kdb.QueryDialect) ExtensionTokenVerifier

ExtensionTokenOpener binds an ExtensionTokenVerifier to a tenant database.

type ExtensionTokenVerifier

type ExtensionTokenVerifier interface {
	VerifyAccessToken(ctx context.Context, site, tokenHash string) (extension.Credential, error)
}

ExtensionTokenVerifier resolves the active extension owning a token verifier.

func OpenSQLExtensionTokens

func OpenSQLExtensionTokens(database *sql.DB, dialect kdb.QueryDialect) ExtensionTokenVerifier

OpenSQLExtensionTokens is the default ExtensionTokenOpener.

type Identity

type Identity struct {
	ID   string
	Site string
}

Identity is a canonical, site-scoped principal. It is the target that IdentityLinks resolve to.

type IdentityLink struct {
	ProviderInstanceID string
	Issuer             string
	Subject            string
	IdentityID         string
	Email              string
	LinkedAt           time.Time
}

IdentityLink binds one provider identity (provider_instance, issuer, subject) to a canonical Identity. Email is retained only as a verification hint; it is not a merge key.

type IdentityReconciliation

type IdentityReconciliation struct {
	Matches []IdentityLink
	Action  ReconcileAction
	Reason  string
}

IdentityReconciliation reports what a link/unlink operation did.

type IdentityStore

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

IdentityStore is the in-memory reference implementation of the identity-link store. The SQL-backed implementation (over _kora_identity_link) must satisfy the same semantics; this store is the conformance target.

func NewIdentityStore

func NewIdentityStore() *IdentityStore

NewIdentityStore returns an empty identity-link store.

func (s *IdentityStore) Link(identityID string, link IdentityLink, recentAuth bool) (IdentityReconciliation, error)

Link binds link to identityID. recentAuth must be true; otherwise it fails with ErrRecentAuthRequired. If the triple is already bound to a different identity, it returns ErrIdentityCollision with a conflict reconciliation. Re-linking the same triple to the same identity is a no-op.

func (*IdentityStore) LinksFor

func (s *IdentityStore) LinksFor(identityID string) []IdentityLink

LinksFor returns the links bound to an identity, in insertion order.

func (*IdentityStore) Resolve

func (s *IdentityStore) Resolve(key linkKey) (IdentityLink, bool)

Resolve returns the link for a triple and whether it exists.

func (s *IdentityStore) Unlink(identityID string, key linkKey, recentAuth bool) (IdentityReconciliation, error)

Unlink removes a link for identityID. recentAuth must be true. A link bound to a different identity returns ErrLinkNotFound (no cross-identity leak).

type MagicLinkMailer

type MagicLinkMailer interface {
	SendContext(context.Context, *email.Message) error
}

RegisterAuthRoutes registers authentication endpoints.

type MagicLinkRecord

type MagicLinkRecord struct {
	ID        string     `json:"id"`
	Email     string     `json:"email"`
	CreatedAt time.Time  `json:"created_at"`
	ExpiresAt time.Time  `json:"expires_at"`
	UsedAt    *time.Time `json:"used_at,omitempty"`
	RevokedAt *time.Time `json:"revoked_at,omitempty"`
}

type OIDCLogin

type OIDCLogin struct {
	HTTPClient       *http.Client
	Now              func() time.Time
	PublicAppBaseURL string
	// CloudIssuer enables the built-in kora-cloud provider when set.
	CloudIssuer string
	// Deps builds the per-tenant stores for a request. When nil, SQL stores on
	// the routed tenant database are used.
	Deps func(c *gin.Context) (oidcLoginDeps, error)
	// contains filtered or unexported fields
}

OIDCLogin serves the OpenID Connect authorization-code + PKCE sign-in flow. The Engine stays the session authority: a successful login creates the same tenant session as a magic link.

func (*OIDCLogin) Register

func (l *OIDCLogin) Register(group *gin.RouterGroup)

Register mounts the OIDC routes on the public /api/v1/auth group.

type OIDCProvider

type OIDCProvider struct {
	ID              string   `json:"id"`
	DisplayName     string   `json:"display_name"`
	Issuer          string   `json:"issuer"`
	ClientID        string   `json:"client_id"`
	ClientSecretKey string   `json:"-"`
	Scopes          []string `json:"scopes"`
	Enabled         bool     `json:"enabled"`
}

OIDCProvider is a tenant's OpenID Connect sign-in configuration. The client secret itself lives in the secret store under ClientSecretKey.

func (OIDCProvider) Normalize

func (p OIDCProvider) Normalize() OIDCProvider

Normalize trims fields, fills defaults and always requests the openid scope.

func (OIDCProvider) Validate

func (p OIDCProvider) Validate() error

Validate rejects configurations the login flow cannot use safely.

type Provider

type Provider struct {
	Name        string `json:"name"`
	Label       string `json:"label"`
	Status      string `json:"status"`
	Description string `json:"description,omitempty"`
}

Provider is the public discovery projection for a sign-in provider. It is deliberately secret-free: no secret reference, token, or credential ever crosses this struct's JSON boundary.

type ProviderConfig

type ProviderConfig struct {
	Name        string
	Label       string
	Status      string
	Family      contract.ProviderFamily
	Scopes      []string
	SecretRef   string // e.g. secret://auth/oidc/<id>/client-secret
	Description string
}

ProviderConfig is the internal configuration for a provider. It may carry a SecretRef (an opaque secret-store identifier, never a value) and other provider-specific settings that must not reach discovery.

func DefaultProviderConfigs

func DefaultProviderConfigs() []ProviderConfig

DefaultProviderConfigs returns the built-in provider configuration. OIDC is marked planned: it must not be advertised as supported until the AUTH-006 acceptance suite passes.

type ProviderRegistry

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

ProviderRegistry is the normalized source of auth provider discovery. The providers map holds only safe discovery projections; configs holds the full internal configuration (including secret references) for provider flows.

func NewProviderRegistry

func NewProviderRegistry() *ProviderRegistry

NewProviderRegistry returns the default registry (password + magic-link supported, oidc planned). It is retained for backward compatibility.

func NewProviderRegistryFromConfig

func NewProviderRegistryFromConfig(configs []ProviderConfig) (*ProviderRegistry, error)

NewProviderRegistryFromConfig builds a registry from typed configuration. Unknown provider status is rejected at load (fail closed): the registry returns an error rather than silently accepting an invalid capability.

func (*ProviderRegistry) Config

func (r *ProviderRegistry) Config(name string) (ProviderConfig, bool)

Config returns the internal configuration for a provider, including its secret reference. It is intended for provider flows (AUTH-002+), not for discovery or logging; callers must never serialize SecretRef to a client.

func (*ProviderRegistry) List

func (r *ProviderRegistry) List() []Provider

List returns the secret-free discovery projection, sorted by name.

func (*ProviderRegistry) Register

func (r *ProviderRegistry) Register(provider Provider)

Register adds a discovery projection. It is retained for callers that manage providers directly (no secret refs are involved).

type ReconcileAction

type ReconcileAction string

ReconcileAction is the outcome of a link/unlink reconciliation.

const (
	ActionLinked   ReconcileAction = "linked"
	ActionUnlinked ReconcileAction = "unlinked"
	ActionConflict ReconcileAction = "conflict"
	ActionNoop     ReconcileAction = "noop"
)

type SQLAuthProviders

type SQLAuthProviders struct {
	DB      *sql.DB
	Dialect kdb.Dialect
}

SQLAuthProviders persists tenant sign-in providers in _kora_auth_provider.

func (SQLAuthProviders) Delete

func (s SQLAuthProviders) Delete(ctx context.Context, site, id string) error

Delete removes a provider. Existing identity links are kept so re-adding the same issuer restores access without re-linking.

func (SQLAuthProviders) Get

func (s SQLAuthProviders) Get(ctx context.Context, site, id string) (OIDCProvider, error)

Get returns one provider, or ErrProviderNotFound.

func (SQLAuthProviders) List

func (s SQLAuthProviders) List(ctx context.Context, site string) ([]OIDCProvider, error)

List returns every provider configured for site, enabled or not.

func (SQLAuthProviders) Put

Put creates or replaces a provider after normalizing and validating it.

type SQLIdentityLinks struct {
	DB      *sql.DB
	Dialect kdb.QueryDialect
}

SQLIdentityLinks persists external sign-in identities in _kora_user_identity. A link is keyed by (site, issuer, subject); email is stored only as the address that was verified when the link was made and never resolves a user.

func (s SQLIdentityLinks) Link(ctx context.Context, site, user, issuer, subject, email string, linkedAt time.Time) error

Link binds (issuer, subject) to user. Re-linking the same pair to the same user is a no-op. It fails with ErrIdentityCollision when the pair belongs to another user or the user already has a different subject for this issuer.

func (SQLIdentityLinks) Resolve

func (s SQLIdentityLinks) Resolve(ctx context.Context, site, issuer, subject string) (string, error)

Resolve returns the user linked to (issuer, subject) on site, or ErrLinkNotFound.

func (SQLIdentityLinks) SubjectFor

func (s SQLIdentityLinks) SubjectFor(ctx context.Context, site, user, issuer string) (string, error)

SubjectFor returns the subject already linked for user and issuer on site, or ErrLinkNotFound.

type SQLLoginStates

type SQLLoginStates struct {
	DB      *sql.DB
	Dialect kdb.QueryDialect
}

SQLLoginStates keeps pending OIDC logins in _kora_oidc_login so any Engine replica can complete a login another replica started.

func (SQLLoginStates) Consume

func (s SQLLoginStates) Consume(ctx context.Context, site, stateHash string, now time.Time) (oidcLoginState, error)

Consume returns and deletes a pending login. Exactly one caller can consume a state; later attempts get oidc.ErrStateReplayed.

func (SQLLoginStates) Save

func (s SQLLoginStates) Save(ctx context.Context, stateHash string, st oidcLoginState) error

Save stores a pending login and drops expired ones.

type SessionCacheBudget

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

SessionCacheBudget caps retained session snapshots shared by the Engine's process and tenant session managers. A full budget disables new cache retention until existing entries expire or are evicted; authentication still proceeds from the database result for that request.

func NewSessionCacheBudget

func NewSessionCacheBudget(maxBytes uint64) (*SessionCacheBudget, error)

func (*SessionCacheBudget) Snapshot

type SessionCacheBudgetSnapshot

type SessionCacheBudgetSnapshot struct {
	Bytes    uint64
	MaxBytes uint64
}

type SessionCacheSnapshot

type SessionCacheSnapshot struct {
	Entries    int
	Bytes      uint64
	MaxEntries int
	MaxBytes   uint64
}

type SessionManager

type SessionManager struct {
	DB *sql.DB
	// contains filtered or unexported fields
}

SessionManager manages user sessions with an in-memory TTL cache.

func NewOwnedSessionManager

func NewOwnedSessionManager(db *sql.DB) *SessionManager

NewOwnedSessionManager constructs a tenant-owned manager. Its sweeper is stopped and joined by Close when the runtime is retired.

func NewOwnedSessionManagerPaused

func NewOwnedSessionManagerPaused(db *sql.DB) *SessionManager

NewOwnedSessionManagerPaused creates a tenant-owned manager without starting its sweeper. Engine.Run or a live tenant activation calls StartCleanup.

func NewSessionManager

func NewSessionManager(db *sql.DB) *SessionManager

NewSessionManager constructs an independently owned session manager. Callers that retain it must call Close when its database/runtime is retired. Routed Engine requests should use the manager pinned in request context instead.

func SessionManagerForRequest

func SessionManagerForRequest(c *gin.Context, db *sql.DB) *SessionManager

SessionManagerForRequest returns the session manager pinned to the routed tenant request, the one validateSession uses, so handlers revoke through the same cache that serves authentication.

func (*SessionManager) CacheSnapshot

func (sm *SessionManager) CacheSnapshot() SessionCacheSnapshot

func (*SessionManager) Close

func (sm *SessionManager) Close() error

Close stops and joins the session cache cleanup worker.

func (*SessionManager) CreateSession

func (sm *SessionManager) CreateSession(site string, user *User) (string, error)

CreateSession creates a new session for a user and returns the session ID.

func (*SessionManager) DeleteSession

func (sm *SessionManager) DeleteSession(sid string)

DeleteSession removes a session.

func (*SessionManager) FindUserByCloudSubject

func (sm *SessionManager) FindUserByCloudSubject(site, subject string) (*User, error)

FindUserByCloudSubject resolves the immutable Cloud subject to the passwordless tenant principal created during provisioning.

func (*SessionManager) FindUserByEmail

func (sm *SessionManager) FindUserByEmail(site, emailAddr string) (*User, error)

func (*SessionManager) FindUserByEmailContext

func (sm *SessionManager) FindUserByEmailContext(parent context.Context, site, emailAddr string) (*User, error)

FindUserByEmailContext looks up an enabled user while honoring the owning request or worker cancellation. The compatibility method above remains for older callers that do not carry a context.

func (*SessionManager) GetSession

func (sm *SessionManager) GetSession(site, sid string) (*User, time.Time, error)

GetSession validates a session ID for a given site and returns the associated user plus the session creation timestamp. Uses an in-memory TTL cache to avoid hitting the database on every request.

func (*SessionManager) InvalidateSession

func (sm *SessionManager) InvalidateSession(sid string)

InvalidateSession removes a session from the cache without deleting it from the database. Use this when user state changes (role change, password change, disable) to force re-validation.

func (*SessionManager) IsEmailVerified

func (sm *SessionManager) IsEmailVerified(site, emailAddr string) (bool, error)
func (sm *SessionManager) ListMagicLinks(site, emailAddr string) ([]MagicLinkRecord, error)

func (*SessionManager) MarkEmailVerified

func (sm *SessionManager) MarkEmailVerified(site, emailAddr string) error

func (*SessionManager) PurgeUserCache

func (sm *SessionManager) PurgeUserCache(site, user string)

PurgeUserCache drops this instance's cached sessions of a user in a site.

func (sm *SessionManager) RevokeAllMagicLinks(site, emailAddr string) error
func (sm *SessionManager) RevokeMagicLink(site, emailAddr, id string) error

func (*SessionManager) RevokeUserSessions

func (sm *SessionManager) RevokeUserSessions(ctx context.Context, site, user string) error

RevokeUserSessions deletes every session of a user in a site and drops the matching cache entries on this instance.

Other instances keep a validated session in their in-memory cache for up to sessionCacheTTL (30s) before re-reading _kora_session, so a revoked session can stay usable there for at most that long. This is an accepted bound.

func (*SessionManager) RevokeUserSessionsTx

func (sm *SessionManager) RevokeUserSessionsTx(ctx context.Context, tx *sql.Tx, site, user string) error

RevokeUserSessionsTx deletes a user's sessions inside the caller's transaction, so a role or enabled change and the revocation commit together. Call PurgeUserCache after a successful commit (same 30s cross-instance bound as RevokeUserSessions).

func (*SessionManager) SetCacheBudget

func (sm *SessionManager) SetCacheBudget(budget *SessionCacheBudget)

SetCacheBudget attaches a process-shared retained-byte budget. It clears entries populated before attachment so accounting begins from a known state.

func (*SessionManager) SetCleanupAdmission

func (sm *SessionManager) SetCleanupAdmission(admission interface {
	Acquire(context.Context) (func(), error)
})

SetCleanupAdmission attaches the Engine endpoint work budget to the periodic database cleanup pass. Compatibility callers without an Engine owner retain the historical unshared behavior.

func (*SessionManager) SetDialect

func (sm *SessionManager) SetDialect(dialect kdb.Dialect) *SessionManager

SetDialect binds the SQL dialect of DB. Call it before the manager serves requests; without it queries keep MySQL-style '?' placeholders.

func (*SessionManager) StartCleanup

func (sm *SessionManager) StartCleanup()

StartCleanup starts the owned session-cache sweeper exactly once.

type SignInOption

type SignInOption struct {
	ID          string `json:"id"`
	Type        string `json:"type"`
	DisplayName string `json:"display_name"`
	StartURL    string `json:"start_url"`
}

SignInOption is one way to sign in to a tenant, as shown on the login page. It never carries issuer secrets or client credentials.

type SiteGuard

type SiteGuard struct {

	// ExtensionTokens opens the tenant's extension credential verifier. Nil
	// uses the SQL store.
	ExtensionTokens ExtensionTokenOpener
	// ExtensionTokensChanged, when set, is told about credential writes for a
	// site so cached verifications are dropped. Handlers reach it through
	// NotifyExtensionTokensChanged.
	ExtensionTokensChanged func(site string)
	// contains filtered or unexported fields
}

SiteGuard is a unified middleware that enforces authentication, CSRF, and site context resolution for workspace and API routes. It wraps AuthMiddleware + CSRFMiddleware + site context injection.

func NewSiteGuardWithSessionManager

func NewSiteGuardWithSessionManager(manager *SessionManager) *SiteGuard

NewSiteGuardWithSessionManager binds request authentication to an explicitly owned session manager. The caller remains responsible for closing it.

func (*SiteGuard) Close

func (g *SiteGuard) Close() error

Close joins the session cache worker owned by this compatibility guard. Guards created with NewSiteGuardWithSessionManager do not close the supplied manager; its tenant/process owner remains responsible for that manager.

func (*SiteGuard) Middleware

func (g *SiteGuard) Middleware(skipCSRF bool) gin.HandlerFunc

Middleware returns the combined site guard middleware. It runs: Bearer (extension) auth → Session auth → CSRF → handler.

type SystemCredentials

type SystemCredentials struct {
	SystemAdmin struct {
		Email    string `yaml:"email"`
		Password string `yaml:"password"` // plaintext — hashed on startup
	} `yaml:"system_admin"`
}

SystemCredentials holds the system admin credential loaded from YAML.

type SystemGuard

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

SystemGuard authenticates system administrator requests for /console.

func LoadSystemGuardFromEnvPaused

func LoadSystemGuardFromEnvPaused() *SystemGuard

LoadSystemGuardFromEnvPaused loads environment credentials without starting the cleanup worker; Engine.Run activates that worker.

func LoadSystemGuardPaused

func LoadSystemGuardPaused(path string) (*SystemGuard, error)

LoadSystemGuardPaused loads credentials without starting its cleanup worker. Engine owns that worker and starts it from Engine.Run.

func (*SystemGuard) Close

func (g *SystemGuard) Close() error

Close cancels and joins the system-session cleanup worker.

func (*SystemGuard) CreateSession

func (g *SystemGuard) CreateSession(email string) string

CreateSession creates a new console session for the given email. Returns a cryptographically random session ID.

func (*SystemGuard) CreateSessionBounded

func (g *SystemGuard) CreateSessionBounded(email string) (string, error)

CreateSessionBounded creates a console session after removing expired entries if the bounded in-memory store is full.

func (*SystemGuard) DeleteSession

func (g *SystemGuard) DeleteSession(sid string)

DeleteSession removes a console session.

func (*SystemGuard) Middleware

func (g *SystemGuard) Middleware() gin.HandlerFunc

Middleware returns a Gin middleware that enforces system admin authentication. It accepts two authentication methods:

  1. Cookie: "kora_console_sid" with a server-validated session ID.
  2. Authorization header: "Basic <base64(email:password)>" for API clients.

func (*SystemGuard) StartCleanup

func (g *SystemGuard) StartCleanup()

StartCleanup starts the owned console-session cleanup worker once.

func (*SystemGuard) UpdatePassword

func (g *SystemGuard) UpdatePassword(newPassword string) error

UpdatePassword replaces the stored password hash. Used for first-login forced change.

func (*SystemGuard) ValidateSession

func (g *SystemGuard) ValidateSession(sid string) string

ValidateSession checks whether a session ID is valid and returns the associated email. Returns empty string if the session is invalid or expired.

func (*SystemGuard) ValidateSessionBool

func (g *SystemGuard) ValidateSessionBool(sid string) bool

ValidateSessionBool returns true if the session token is valid.

func (*SystemGuard) ValidateWithChangeCheck

func (g *SystemGuard) ValidateWithChangeCheck(email, password string) (valid bool, needsChange bool)

ValidateWithChangeCheck validates credentials and returns whether a password change is required. Password change is required when using the baked-in default credentials.

func (*SystemGuard) VerifyCredentials

func (g *SystemGuard) VerifyCredentials(email, password string) error

VerifyCredentials checks if the given email and password match the system credentials.

type User

type User struct {
	Name     string   `json:"name"`
	Email    string   `json:"email"`
	FullName string   `json:"full_name"`
	Roles    []string `json:"roles"`
	Enabled  bool     `json:"enabled"`
}

User represents an authenticated user.

Directories

Path Synopsis
Package oidc implements the OIDC authorization-code + PKCE profile (AUTH-002).
Package oidc implements the OIDC authorization-code + PKCE profile (AUTH-002).

Jump to

Keyboard shortcuts

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