Documentation
¶
Index ¶
- Constants
- Variables
- func AuthenticateExtension(ctx context.Context, verifier ExtensionTokenVerifier, ...) (policy.Execution, []doctype.Permission, error)
- func AuthenticateExtensionExecution(ctx context.Context, database *sql.DB, dialect kdb.QueryDialect, ...) (policy.Execution, []doctype.Permission, error)
- func BackfillExtensionTokenHashes(ctx context.Context, database *sql.DB, dialect kdb.QueryDialect) error
- func CSRFMiddleware() gin.HandlerFunc
- func ClientSecretKeyFor(providerID string) string
- func ContextWithSessionCreatedAt(ctx context.Context, createdAt time.Time) context.Context
- func HasExtensionPermission(perms []doctype.Permission, doctype, operation string) bool
- func HashExtensionAccessToken(token string) string
- func HashPassword(password string) (string, error)
- func LocalSignInAllowed(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string) (bool, error)
- func MagicLinkTokenHash(token string) string
- func NewAuditID() string
- func NewMagicLinkToken() (string, error)
- func NotifyExtensionTokensChanged(c *gin.Context, site string)
- func RegisterAuthRoutes(router *gin.Engine, sm *SessionManager, db *sql.DB, mailer MagicLinkMailer)
- func RegisterAuthRoutesWithPublicAppBaseURL(router *gin.Engine, sm *SessionManager, db *sql.DB, mailer MagicLinkMailer, ...) error
- func RegisterCloudHandoffRoute(router *gin.Engine, sm *SessionManager, db *sql.DB, cfg CloudHandoffConfig) error
- func RevalidateRealtimeIdentity(c *gin.Context) (bool, error)
- func RevokeChannelSession(db *sql.DB, dialect kdb.QueryDialect, id string, reason string) error
- func SessionCreatedAt(ctx context.Context) (time.Time, bool)
- func SetCSRFSecure(secure bool)
- func SetLocalSignInAllowed(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string, ...) error
- func SetSecureCookie(c *gin.Context, name, value string, maxAge int, path string, httpOnly bool)
- func SiteDB(c *gin.Context) *sql.DB
- func TenantMagicLinkURL(host, token string) (string, error)
- func TenantPathMagicLinkURL(appBaseURL, tenant, token string) (string, error)
- func ValidatePublicAppBaseURL(value string) error
- type ChannelSession
- type ChannelSessionCreateParams
- type CloudHandoffConfig
- type ConsoleSession
- type ExtensionTokenOpener
- type ExtensionTokenVerifier
- type Identity
- type IdentityLink
- type IdentityReconciliation
- type IdentityStore
- func (s *IdentityStore) Link(identityID string, link IdentityLink, recentAuth bool) (IdentityReconciliation, error)
- func (s *IdentityStore) LinksFor(identityID string) []IdentityLink
- func (s *IdentityStore) Resolve(key linkKey) (IdentityLink, bool)
- func (s *IdentityStore) Unlink(identityID string, key linkKey, recentAuth bool) (IdentityReconciliation, error)
- type MagicLinkMailer
- type MagicLinkRecord
- type OIDCLogin
- type OIDCProvider
- type Provider
- type ProviderConfig
- type ProviderRegistry
- type ReconcileAction
- type SQLAuthProviders
- func (s SQLAuthProviders) Delete(ctx context.Context, site, id string) error
- func (s SQLAuthProviders) Get(ctx context.Context, site, id string) (OIDCProvider, error)
- func (s SQLAuthProviders) List(ctx context.Context, site string) ([]OIDCProvider, error)
- func (s SQLAuthProviders) Put(ctx context.Context, site string, p OIDCProvider) (OIDCProvider, error)
- type SQLIdentityLinks
- func (s SQLIdentityLinks) Link(ctx context.Context, site, user, issuer, subject, email string, ...) error
- func (s SQLIdentityLinks) Resolve(ctx context.Context, site, issuer, subject string) (string, error)
- func (s SQLIdentityLinks) SubjectFor(ctx context.Context, site, user, issuer string) (string, error)
- type SQLLoginStates
- type SessionCacheBudget
- type SessionCacheBudgetSnapshot
- type SessionCacheSnapshot
- type SessionManager
- func (sm *SessionManager) CacheSnapshot() SessionCacheSnapshot
- func (sm *SessionManager) Close() error
- func (sm *SessionManager) CreateSession(site string, user *User) (string, error)
- func (sm *SessionManager) DeleteSession(sid string)
- func (sm *SessionManager) FindUserByCloudSubject(site, subject string) (*User, error)
- func (sm *SessionManager) FindUserByEmail(site, emailAddr string) (*User, error)
- func (sm *SessionManager) FindUserByEmailContext(parent context.Context, site, emailAddr string) (*User, error)
- func (sm *SessionManager) GetSession(site, sid string) (*User, time.Time, error)
- func (sm *SessionManager) InvalidateSession(sid string)
- func (sm *SessionManager) IsEmailVerified(site, emailAddr string) (bool, error)
- func (sm *SessionManager) ListMagicLinks(site, emailAddr string) ([]MagicLinkRecord, error)
- func (sm *SessionManager) MarkEmailVerified(site, emailAddr string) error
- func (sm *SessionManager) PurgeUserCache(site, user string)
- func (sm *SessionManager) RevokeAllMagicLinks(site, emailAddr string) error
- func (sm *SessionManager) RevokeMagicLink(site, emailAddr, id string) error
- func (sm *SessionManager) RevokeUserSessions(ctx context.Context, site, user string) error
- func (sm *SessionManager) RevokeUserSessionsTx(ctx context.Context, tx *sql.Tx, site, user string) error
- func (sm *SessionManager) SetCacheBudget(budget *SessionCacheBudget)
- func (sm *SessionManager) SetCleanupAdmission(admission interface{ ... })
- func (sm *SessionManager) SetDialect(dialect kdb.Dialect) *SessionManager
- func (sm *SessionManager) StartCleanup()
- type SignInOption
- type SiteGuard
- type SystemCredentials
- type SystemGuard
- func (g *SystemGuard) Close() error
- func (g *SystemGuard) CreateSession(email string) string
- func (g *SystemGuard) CreateSessionBounded(email string) (string, error)
- func (g *SystemGuard) DeleteSession(sid string)
- func (g *SystemGuard) Middleware() gin.HandlerFunc
- func (g *SystemGuard) StartCleanup()
- func (g *SystemGuard) UpdatePassword(newPassword string) error
- func (g *SystemGuard) ValidateSession(sid string) string
- func (g *SystemGuard) ValidateSessionBool(sid string) bool
- func (g *SystemGuard) ValidateWithChangeCheck(email, password string) (valid bool, needsChange bool)
- func (g *SystemGuard) VerifyCredentials(email, password string) error
- type User
Constants ¶
const ( CloudHandoffURLEnv = "KORA_ENGINE_CLOUD_IDENTITY_URL" CloudHandoffTokenEnv = "KORA_ENGINE_CLOUD_IDENTITY_TOKEN" )
Environment variables that configure Cloud handoff; both are required.
const ( DefaultSessionCacheBudgetBytes uint64 = 256 << 20 MaxSessionCacheBudgetBytes uint64 = 4 << 30 )
const DefaultSessionCacheMaxBytes uint64 = 8 << 20
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.
const KoraCloudProviderID = "kora-cloud"
KoraCloudProviderID is the built-in provider for signing in with Kora Cloud.
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.
const MaxConsoleSessions = 8192
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 ¶
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") )
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.
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.
var ErrConsoleSessionCapacity = errors.New("console session capacity exhausted")
var ErrProviderNotFound = errors.New("auth: sign-in provider not found")
ErrProviderNotFound reports an unknown or disabled sign-in provider.
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 ¶
ClientSecretKeyFor is the secret-store key holding a provider's client secret; its reference form is secret://auth/oidc/<id>/client-secret.
func ContextWithSessionCreatedAt ¶
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 ¶
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 ¶
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 ¶
MagicLinkTokenHash returns the persisted token digest, never the token.
func NewAuditID ¶
func NewAuditID() string
func NewMagicLinkToken ¶
NewMagicLinkToken creates a cryptographically random token for a durable management invitation operation. Callers persist only its hash.
func NotifyExtensionTokensChanged ¶
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 ¶
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 SessionCreatedAt ¶
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 ¶
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 TenantMagicLinkURL ¶
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 ¶
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 ¶
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 CloudHandoffConfig ¶
type ConsoleSession ¶
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 ¶
Identity is a canonical, site-scoped principal. It is the target that IdentityLinks resolve to.
type IdentityLink ¶
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 (*IdentityStore) Link ¶
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 (*IdentityStore) Unlink ¶
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 ¶
RegisterAuthRoutes registers authentication endpoints.
type MagicLinkRecord ¶
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 ¶
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 ¶
func (s SQLAuthProviders) Put(ctx context.Context, site string, p OIDCProvider) (OIDCProvider, error)
Put creates or replaces a provider after normalizing and validating it.
type SQLIdentityLinks ¶
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 (SQLIdentityLinks) Link ¶
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.
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 ¶
func (b *SessionCacheBudget) Snapshot() SessionCacheBudgetSnapshot
type SessionCacheSnapshot ¶
type SessionManager ¶
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 ¶
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 (*SessionManager) ListMagicLinks ¶
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 (*SessionManager) RevokeAllMagicLinks ¶
func (sm *SessionManager) RevokeAllMagicLinks(site, emailAddr string) error
func (*SessionManager) RevokeMagicLink ¶
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 ¶
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:
- Cookie: "kora_console_sid" with a server-validated session ID.
- 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.
Source Files
¶
- auth_provider_store.go
- channel.go
- cloud_handoff.go
- csrf.go
- errors.go
- extension_token.go
- identity.go
- identity_sql.go
- kora_cloud_provider.go
- oidc_callback.go
- oidc_jwks.go
- oidc_login.go
- oidc_login_state.go
- password_login.go
- providers.go
- ratelimit.go
- session.go
- session_cache_budget.go
- session_context.go
- sign_in_discovery.go
- site.go
- system.go