Documentation
¶
Overview ¶
Package auth provides authentication and authorization for NornicDB.
This package implements JWT authentication with role-based access control, designed to meet regulatory compliance requirements:
- GDPR Art.32: Technical and organizational measures to ensure security
- HIPAA §164.312(a): Access Control - Unique User Identification
- FISMA AC-2: Account Management
- SOC 2 CC6.1: Logical access controls
Architecture:
- JWT tokens (HS256 algorithm) for stateless authentication
- Multiple credential sources: Bearer header, cookies, query parameters
- Role-based access control (RBAC) with 4 roles: admin, editor, viewer, none
- Account lockout after failed login attempts
- Password hashing with bcrypt
- Audit logging for compliance
Example Usage:
// Initialize authenticator
config := auth.DefaultAuthConfig()
config.JWTSecret = []byte("your-secret-key-min-32-chars")
config.MinPasswordLength = 12
authenticator, err := auth.NewAuthenticator(config)
if err != nil {
log.Fatal(err)
}
// Set audit logging (required for HIPAA/GDPR)
authenticator.SetAuditLogger(func(event auth.AuditEvent) {
log.Printf("[AUDIT] %s: %s (success=%v)",
event.EventType, event.Username, event.Success)
})
// Create users
admin, _ := authenticator.CreateUser("admin", "SecurePass123!",
[]auth.Role{auth.RoleAdmin})
viewer, _ := authenticator.CreateUser("alice", "AlicePass456!",
[]auth.Role{auth.RoleViewer})
// Authenticate and get JWT token
tokenResp, user, err := authenticator.Authenticate(
"admin", "SecurePass123!", "192.168.1.1", "Mozilla/5.0")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Token: %s\n", tokenResp.AccessToken)
fmt.Printf("Type: %s\n", tokenResp.TokenType) // "Bearer"
// Validate token
claims, err := authenticator.ValidateToken(tokenResp.AccessToken)
if err != nil {
log.Fatal(err)
}
// Check permissions
if user.HasPermission(auth.PermWrite) {
fmt.Println("User can write")
}
OAuth 2.0 Compatibility:
The token endpoint follows RFC 6749 (OAuth 2.0) format:
POST /auth/token Content-Type: application/x-www-form-urlencoded grant_type=password&username=alice&password=secret
Response:
{
"access_token": "eyJhbGc...",
"token_type": "Bearer",
"expires_in": 3600 // omitted if never expires
}
Compliance Features:
GDPR Art.32 (Security):
- Password hashing (bcrypt with configurable cost)
- Token-based authentication (no session storage)
- Account lockout (prevents brute force)
- Audit logging (tracks all authentication events)
HIPAA §164.312(a) (Access Control):
- Unique user identification (User.ID)
- Role-based permissions
- Account disable/enable
- Failed login tracking
FISMA AC-2 (Account Management):
- User creation with roles
- Account lockout
- Audit trail
- Password policy enforcement
Security Best Practices:
- bcrypt for password hashing (adjustable cost)
- HMAC-SHA256 for JWT signatures
- Constant-time string comparison (prevents timing attacks)
- Account lockout after N failed attempts
- No password in logs or responses
ELI12 (Explain Like I'm 12):
Think of this like your school's login system:
1. **Creating an account**: Like signing up for a school portal with username/password 2. **Logging in**: Like entering your credentials at the library computer 3. **JWT token**: Like a hall pass that proves you're allowed to be here 4. **Roles**: Like student vs teacher vs admin - different people can do different things 5. **Account lockout**: If you get your password wrong 5 times, you're locked out for 15 minutes 6. **Audit log**: Like the principal keeping a record of who entered the building and when
The system makes sure only the right people can access the right data!
Plan 04-06-05: auth_attempts_total wiring (D-11 + D-05e + GAP-6 / MET-15).
Design (CONTEXT D-05e + RESEARCH §Q11):
- The pkg/observability.AuthMetrics bag is the single owner of the `nornicdb_auth_attempts_total{result, protocol}` counter family. pkg/auth never imports prometheus directly — it talks to the bag.
- The shared core Authenticator.Authenticate is protocol-agnostic and does NOT increment the counter; the protocol label belongs at the protocol-specific adapter chokepoint (Bolt: handleHello; HTTP: middleware; gRPC: UnaryInterceptor).
- classifyAuthResult is the closed-enum mapper from the Authenticate (..., error) return shape to the result enum.
- RecordAttempt is the SOLE observation entry point — DRY chokepoint used by every protocol adapter. Nil-safe: when the bag is not injected (e.g., test fixtures, embedded usage without a Provider), RecordAttempt is a no-op.
**Audit boundary (T-04-06):** this file ships ZERO changes to pkg/audit/audit.go. The auth_attempts_total counter is a parallel observability signal, not a replacement for the audit log. Operators observe `auth_attempts_total{result="failure"}` rate; compliance auditors read the audit log.
**PII discipline (T-04-01 / ASVS V2):** no `user`, `user_id`, `ip`, or `email` label is exposed. Phase 3 D-03a forbidden-label panic at observability.NewCounterVec catches any attempt to drift.
Package auth: canonical enumeration of RBAC entitlements.
Entitlements are the individual permissions/rights that can be assigned to roles. They include global permissions (read, write, admin, etc.) and per-database entitlements (see database, access database, read, write). Use this list for UI, APIs, and documentation so admins can assign and audit entitlements per role.
Package auth provides OAuth 2.0 authentication support for NornicDB.
This package implements OAuth 2.0 authorization code flow with token validation and refresh capabilities. It integrates with external OAuth providers to authenticate users and issue NornicDB JWT tokens.
OAuth Flow:
- User initiates OAuth login → redirects to OAuth provider
- User authenticates with OAuth provider
- OAuth provider redirects back with authorization code
- Exchange code for access token
- Get user info from OAuth provider
- Create/find NornicDB user account
- Issue NornicDB JWT token
- Validate OAuth tokens on subsequent requests
Security Features:
- CSRF protection via state parameter
- OAuth token validation on each request
- Automatic token refresh when expired
- Short-lived NornicDB tokens (match OAuth token expiry)
Example Usage:
// Configure OAuth
os.Setenv("NORNICDB_AUTH_PROVIDER", "oauth")
os.Setenv("NORNICDB_OAUTH_ISSUER", "http://localhost:8888")
os.Setenv("NORNICDB_OAUTH_CLIENT_ID", "nornicdb-local-test")
os.Setenv("NORNICDB_OAUTH_CLIENT_SECRET", "local-test-secret-123")
os.Setenv("NORNICDB_OAUTH_CALLBACK_URL", "http://localhost:7474/auth/oauth/callback")
// Create OAuth manager
oauthMgr := oauth.NewManager(authenticator)
// Generate authorization URL
state, authURL, err := oauthMgr.GenerateAuthURL("http://localhost:7474")
// Handle callback
user, token, expiry, err := oauthMgr.HandleCallback(r.Context(), code, state)
Package auth: procedure execution privileges (Neo4j's GRANT [IMMUTABLE] EXECUTE [BOOSTED] PROCEDURE … ON DBMS TO role).
A grant names a role, a procedure name or glob (db.cdc.*) and whether it is boosted; a role holds at most one such grant, which is immutable or not. A boosted grant lets the role run a matching procedure that needs administrator rights; a plain EXECUTE grant adds nothing to what the role may already run.
Grants are stored in the system database as _ProcedurePrivilege nodes, kept apart from graph data the way the other system stores keep theirs:
- the system database runs no Cypher graph writes (the cypher package refuses CREATE, MERGE, SET, DELETE, REMOVE and write procedures there, on every route), so grants originate in GRANT and REVOKE through this store; role changes move or remove them through the shared transaction owner;
- as RoleStore and PrivilegesStore key their nodes by an ID only the store chooses (role:…, db_priv:…), a node counts as a grant only when its ID is the one Grant gives that grant, so a node made any other way (a Cypher CREATE gets a generated ID) is never read as a grant.
The store keeps no copy of the grants: it reads them from storage each time it is asked (a label lookup over the few grant nodes, done only when a caller without administrator rights calls a procedure that needs them). So a change is seen as soon as it is committed, by this process and by any other process or server instance over the same storage (a GRANT in an explicit transaction when that transaction commits), and a read that fails denies and returns its error. A version marker that every check compares would also cost a storage read per check, and would add a write to every change that must stay in step with it.
Package auth provides request-scoped RBAC context helpers. When the server mounts authenticated endpoints (Bifrost, GraphQL), it can attach principal roles, DatabaseAccessMode, and ResolvedAccess resolver to the request context so handlers and resolvers can enforce per-database access.
Index ¶
- Constants
- Variables
- func ApplyFineGrainedPrivileges(catalog *FineGrainedCatalog, privileges []FineGrainedPrivilege, verb string, ...) error
- func AuthenticationDisabled(a *Authenticator) bool
- func BindRequestDatabaseRead(ctx context.Context, database string) (string, func() bool)
- func ClassifyAuthResult(err error) string
- func DatabasePopulationAccess(databases []string, allows func(string) bool) (any, all bool)
- func DatabaseReadAllowed(roles []string, database string, privileges *PrivilegesStore, ...) bool
- func EntitlementsAllow(entitlements []string, permission string) bool
- func ExtractToken(authHeader, apiKeyHeader, cookie, queryToken, queryAPIKey string) string
- func FineGrainedDatabaseActionAllowed(ctx context.Context, database string) bool
- func FineGrainedEntityID(localID string, createdAt time.Time) string
- func FineGrainedPrivilegeKey(databaseID string, kind FineGrainedResourceKind, clause string) string
- func GlobalEntitlementIDs() []string
- func HasCredentials(authHeader, apiKeyHeader, cookie, queryToken, queryAPIKey string) bool
- func IsBuiltinRole(name string) bool
- func NormalizeRoleName(role string) string
- func PerDatabaseEntitlementIDs() []string
- func PermissionsForRole(role string, store *RoleEntitlementsStore) []string
- func PermissionsForRoles(roles []string, store *RoleEntitlementsStore) []string
- func PrincipalID(claims *JWTClaims) string
- func ProcedureGlobMatches(glob, name string) bool
- func ReadRelationshipSearchHit(ctx context.Context, engine storage.Engine, id storage.EdgeID) (*storage.Edge, bool, error)
- func RequestAuthenticationDisabledFromContext(ctx context.Context) bool
- func RequestDatabasePermissionAllowed(ctx context.Context, database string, permission Permission) bool
- func RequestPrincipalRolesFromContext(ctx context.Context) []string
- func RequestResolvedAccessResolverFromContext(ctx context.Context) func(string) ResolvedAccess
- func ResolveDatabaseReadAccess(mode DatabaseAccessMode, resolve func(string) ResolvedAccess, database string) (accessible, readable bool)
- func RolePermissionsAsStrings() map[string][]string
- func RolesAllow(roles []string, store *RoleEntitlementsStore, permission string) bool
- func SecureCompare(a, b string) bool
- func UsernamePrincipalID(username string) string
- func ValidRole(r Role) bool
- func WithFineGrainedDatabaseAction(ctx context.Context, action string) context.Context
- func WithFineGrainedRequest(ctx context.Context, request *FineGrainedRequest) context.Context
- func WithReadOnlyDatabaseScope(ctx context.Context, selection string) context.Context
- func WithRequestAuthenticationDisabled(ctx context.Context) context.Context
- func WithRequestDatabaseAccessMode(ctx context.Context, mode DatabaseAccessMode) context.Context
- func WithRequestDatabaseScope(ctx context.Context, scope *RequestDatabaseScope) context.Context
- func WithRequestEntitlementResolver(ctx context.Context, resolver RequestEntitlementResolver) context.Context
- func WithRequestIdentity(ctx context.Context, identity RequestIdentity) context.Context
- func WithRequestPrincipal(ctx context.Context, resolver RequestEntitlementResolver, ...) context.Context
- func WithRequestPrincipalRoles(ctx context.Context, roles []string) context.Context
- func WithRequestResolvedAccessResolver(ctx context.Context, fn func(string) ResolvedAccess) context.Contextdeprecated
- func WithRoleRecords(ctx context.Context, system storage.Engine, roles []string, ...) error
- func WithStoreTransaction(ctx context.Context, engine storage.Engine, mutate func(storage.Engine) error) error
- type AllowlistStore
- func (a *AllowlistStore) Allowlist() map[string][]string
- func (a *AllowlistStore) CanAccessDatabaseForRoles(roles []string, database string) bool
- func (a *AllowlistStore) HasAllowlistData(ctx context.Context) (bool, error)
- func (a *AllowlistStore) Load(ctx context.Context) error
- func (a *AllowlistStore) SaveMappings(ctx context.Context, mappings map[string][]string) error
- func (a *AllowlistStore) SaveRoleDatabases(ctx context.Context, role string, databases []string) error
- func (a *AllowlistStore) SeedIfEmpty(ctx context.Context, databaseNames []string) error
- type AuditEvent
- type AuthConfig
- type AuthMetricsRecorder
- type Authenticator
- func (a *Authenticator) AllowsPasskeyOrigin(origin string) bool
- func (a *Authenticator) AuthMetrics() *observability.AuthMetrics
- func (a *Authenticator) Authenticate(ctx context.Context, username, password, ipAddress, userAgent string) (*TokenResponse, *User, error)
- func (a *Authenticator) BeginPasskeyLogin() (string, *protocol.CredentialAssertion, error)
- func (a *Authenticator) BeginPasskeyLoginForPeer(remoteAddr string) (string, *protocol.CredentialAssertion, error)
- func (a *Authenticator) BeginPasskeyRegistration(ctx context.Context, claims *JWTClaims, password string) (string, *protocol.CredentialCreation, error)
- func (a *Authenticator) ChangePassword(ctx context.Context, username, oldPassword, newPassword string) error
- func (a *Authenticator) ChangeUserState(ctx context.Context, username string, change UserStateChange) error
- func (a *Authenticator) CreateUser(ctx context.Context, username, password string, roles []Role) (*User, error)
- func (a *Authenticator) CreateUserWithJWTKey(ctx context.Context, username, password string, roles []Role, publicKey string) (*User, error)
- func (a *Authenticator) CurrentBasicClaims(claims *JWTClaims, cache *BasicAuthCache, generation uint64) (*JWTClaims, error)
- func (a *Authenticator) CurrentBasicClaimsContext(ctx context.Context, claims *JWTClaims, cache *BasicAuthCache, ...) (*JWTClaims, error)
- func (a *Authenticator) CurrentClaims(claims *JWTClaims) (*JWTClaims, error)
- func (a *Authenticator) CurrentClaimsContext(ctx context.Context, claims *JWTClaims) (*JWTClaims, error)
- func (a *Authenticator) DeleteUser(ctx context.Context, username string) error
- func (a *Authenticator) FinishPasskeyLogin(ctx context.Context, id string, response []byte, ipAddress, userAgent string) (*TokenResponse, error)
- func (a *Authenticator) FinishPasskeyRegistration(ctx context.Context, claims *JWTClaims, id string, response []byte) error
- func (a *Authenticator) GenerateAPIToken(user *User, subject string, expiry time.Duration) (string, error)
- func (a *Authenticator) GenerateAPITokenForClaims(claims *JWTClaims, subject string, expiry time.Duration) (string, error)
- func (a *Authenticator) GenerateClusterToken(nodeID string, role Role) (string, error)
- func (a *Authenticator) GenerateClusterTokenWithExpiry(nodeID string, role Role, expiry time.Duration) (string, error)
- func (a *Authenticator) GetUser(username string) (*User, error)
- func (a *Authenticator) GetUserByID(id string) (*User, error)
- func (a *Authenticator) IsSecurityEnabled() bool
- func (a *Authenticator) ListPasskeys(ctx context.Context, claims *JWTClaims) ([]PasskeyInfo, error)
- func (a *Authenticator) ListUsers() []*User
- func (a *Authenticator) OnPasswordChange(fn func(username string))
- func (a *Authenticator) PasskeysEnabled() bool
- func (a *Authenticator) RecordAttempt(result, protocol string)
- func (a *Authenticator) ReloadUsersAfterRestore(ctx context.Context) error
- func (a *Authenticator) RemovePasskey(ctx context.Context, claims *JWTClaims, id, password string) error
- func (a *Authenticator) RevokeToken(ctx context.Context, token string) (*RevocationReceipt, *JWTClaims, *FineGrainedProviderSession, error)
- func (a *Authenticator) RotateAccountJWT(ctx context.Context, actor *JWTClaims, username, publicKey, password string) (RevocationReceipt, string, error)
- func (a *Authenticator) SetAuditLogger(fn func(AuditEvent))
- func (a *Authenticator) SetAuthMetrics(bag *observability.AuthMetrics)
- func (a *Authenticator) UpdateRoles(ctx context.Context, username string, newRoles []Role) error
- func (a *Authenticator) UpdateRolesAndStatus(ctx context.Context, username string, roles []Role, disabled *bool) error
- func (a *Authenticator) UpdateUser(ctx context.Context, username string, email string, metadata map[string]string) error
- func (a *Authenticator) UserCount() int
- func (a *Authenticator) ValidateToken(token string) (*JWTClaims, error)
- func (a *Authenticator) ValidateTokenWithFineGrainedProvider(ctx context.Context, token string) (*JWTClaims, *FineGrainedProviderSession, error)
- type BasicAuthCache
- func (c *BasicAuthCache) ForgetUser(username string)
- func (c *BasicAuthCache) Generation() uint64
- func (c *BasicAuthCache) Get(username, password string) (*JWTClaims, bool)
- func (c *BasicAuthCache) GetFromHeader(authHeader string) (*JWTClaims, bool)
- func (c *BasicAuthCache) GetFromHeaderWithGeneration(authHeader string) (*JWTClaims, uint64, bool)
- func (c *BasicAuthCache) GetWithGeneration(username, password string) (*JWTClaims, uint64, bool)
- func (c *BasicAuthCache) Set(username, password string, claims *JWTClaims)
- func (c *BasicAuthCache) SetAtGeneration(username, password string, claims *JWTClaims, generation uint64)
- func (c *BasicAuthCache) SetFromHeader(authHeader string, claims *JWTClaims)
- func (c *BasicAuthCache) SetFromHeaderAtGeneration(authHeader string, claims *JWTClaims, generation uint64)
- type CatalogVisibility
- type DatabaseAccessMode
- type DbPrivilege
- type Entitlement
- type EntitlementCategory
- type FineGrainedAccess
- func (a FineGrainedAccess) Allows(actionID string, resource FineGrainedResource) bool
- func (a FineGrainedAccess) AllowsAllDatabases(actionID string) bool
- func (a FineGrainedAccess) AllowsEntireGraphAction(actionID, databaseID, homeDatabaseID string) bool
- func (a FineGrainedAccess) Decision(actionID string, resource FineGrainedResource) (allowed, denied bool)
- func (a FineGrainedAccess) Rules() []FineGrainedEntitlement
- type FineGrainedAccount
- type FineGrainedAction
- type FineGrainedAuthRule
- type FineGrainedAuthRuleCompiler
- type FineGrainedAuthRuleCondition
- type FineGrainedAuthRuleInput
- type FineGrainedCatalog
- type FineGrainedCredentialsExpired
- type FineGrainedDatabaseIdentity
- type FineGrainedEntitlement
- type FineGrainedPermissionError
- type FineGrainedPolicy
- type FineGrainedPredicate
- type FineGrainedPrivilege
- type FineGrainedProviderChange
- type FineGrainedProviderSession
- type FineGrainedRequest
- func (r *FineGrainedRequest) AccessHash() ([32]byte, error)
- func (r *FineGrainedRequest) AllowsAllEntities(action, database string) bool
- func (r *FineGrainedRequest) AllowsDBMS(action string, target string) bool
- func (r *FineGrainedRequest) AllowsDatabase(action, database, property string) bool
- func (r *FineGrainedRequest) AllowsDatabaseIdentity(action, databaseID, property string) bool
- func (r *FineGrainedRequest) AllowsManagedEmbedding(database string, node *storage.Node, input storage.EmbeddingTextPolicy, ...) bool
- func (r *FineGrainedRequest) AllowsNodeIndexPopulation(database, label, property string) bool
- func (r *FineGrainedRequest) CanAccessDatabase(database string) bool
- func (r *FineGrainedRequest) CanSeeDatabase(database string) bool
- func (r *FineGrainedRequest) EffectiveRoles() []string
- func (r *FineGrainedRequest) Graph(engine storage.Engine, database string) storage.Engine
- func (r *FineGrainedRequest) GraphMatches(view, engine storage.Engine, database string) bool
- func (r *FineGrainedRequest) IsImpersonated() bool
- func (r *FineGrainedRequest) Revalidate(ctx context.Context, identity RequestIdentity) error
- func (r *FineGrainedRequest) WithBoostedProcedure(database, procedure string) *FineGrainedRequest
- type FineGrainedResource
- type FineGrainedResourceKind
- type FineGrainedRuntime
- func (runtime *FineGrainedRuntime) Actions() []FineGrainedAction
- func (runtime *FineGrainedRuntime) Admit(ctx context.Context, roles []string) (*FineGrainedRequest, error)
- func (runtime *FineGrainedRuntime) AlterUser(ctx context.Context, username string, change FineGrainedUserAlteration) error
- func (runtime *FineGrainedRuntime) ChangeOwnPassword(ctx context.Context, username, current, replacement string) error
- func (runtime *FineGrainedRuntime) ChangeUserTags(ctx context.Context, names []string, change FineGrainedTagChange, ...) error
- func (runtime *FineGrainedRuntime) CreateRole(ctx context.Context, role string) error
- func (runtime *FineGrainedRuntime) CreateRoleCopy(ctx context.Context, role, source string) error
- func (runtime *FineGrainedRuntime) CreateUser(ctx context.Context, name, password string, passwordChangeRequired bool) error
- func (runtime *FineGrainedRuntime) CreateUserAccount(ctx context.Context, account FineGrainedAccount) error
- func (runtime *FineGrainedRuntime) DeleteUser(ctx context.Context, name string) error
- func (runtime *FineGrainedRuntime) DropRole(ctx context.Context, role string) error
- func (runtime *FineGrainedRuntime) EditCatalog(ctx context.Context, edit func(*FineGrainedCatalog) error) error
- func (runtime *FineGrainedRuntime) Impersonate(ctx context.Context, actor *FineGrainedRequest, username string) (*FineGrainedRequest, *User, error)
- func (runtime *FineGrainedRuntime) ReadCatalog(ctx context.Context) (FineGrainedCatalog, string, error)
- func (runtime *FineGrainedRuntime) RenameRole(ctx context.Context, role, name string) error
- func (runtime *FineGrainedRuntime) RenameUser(ctx context.Context, username, next string) error
- func (runtime *FineGrainedRuntime) ReplaceCatalog(ctx context.Context, revision string, catalog FineGrainedCatalog) error
- func (runtime *FineGrainedRuntime) RoleNames() []string
- func (runtime *FineGrainedRuntime) SetAuthRuleCompiler(compiler FineGrainedAuthRuleCompiler)
- func (runtime *FineGrainedRuntime) SetAuthRuleCompilerContext(compiler func(context.Context, string) (FineGrainedAuthRuleCondition, error))
- func (runtime *FineGrainedRuntime) SetNativeTagAuthorization(enabled bool)
- func (runtime *FineGrainedRuntime) SetPrivateDatabaseOwner(owner func(string) string)
- func (runtime *FineGrainedRuntime) SetRoleMembership(ctx context.Context, users, roles []string, assign bool) error
- func (runtime *FineGrainedRuntime) SetSecurityDirectory(users *Authenticator, stores RoleMutationStores)
- func (runtime *FineGrainedRuntime) SetUserHome(ctx context.Context, username, database string) error
- func (runtime *FineGrainedRuntime) SetUserPassword(ctx context.Context, username string, password *string, changeRequired bool) error
- func (runtime *FineGrainedRuntime) SetUserSuspended(ctx context.Context, username string, suspended bool) error
- func (runtime *FineGrainedRuntime) UserProviders(ctx context.Context) ([]FineGrainedUserProvider, error)
- func (runtime *FineGrainedRuntime) UserTags(username string) []string
- func (runtime *FineGrainedRuntime) Users() []*User
- func (runtime *FineGrainedRuntime) ValidateAdministrator(catalog FineGrainedCatalog) error
- func (runtime *FineGrainedRuntime) ValidateAdministratorContext(ctx context.Context, catalog FineGrainedCatalog) error
- type FineGrainedScope
- type FineGrainedTagChange
- type FineGrainedUserAlteration
- type FineGrainedUserProvider
- type JWTClaims
- type OAuthConfig
- type OAuthManager
- func (m *OAuthManager) ExchangeCode(code string) (_ *OAuthTokenData, err error)
- func (m *OAuthManager) GenerateAuthURL(baseURL string) (string, string, error)
- func (m *OAuthManager) GetUserInfo(accessToken string) (*OAuthUserInfo, error)
- func (m *OAuthManager) HandleCallback(ctx context.Context, code, state string) (*User, string, time.Time, error)
- func (m *OAuthManager) RefreshOAuthToken(user *User, refreshToken string) (err error)
- func (m *OAuthManager) ValidateOAuthToken(user *User) error
- func (m *OAuthManager) ValidateState(state string) error
- type OAuthTokenData
- type OAuthUserInfo
- type PasskeyInfo
- type Permission
- type PrivilegeDatabaseRef
- type PrivilegesStore
- func (p *PrivilegesStore) Granted(roles []string, database string) (ResolvedAccess, bool)
- func (p *PrivilegesStore) Load(ctx context.Context) error
- func (p *PrivilegesStore) Matrix() []struct{ ... }
- func (p *PrivilegesStore) PutMatrix(ctx context.Context, entries []struct{ ... }) error
- func (p *PrivilegesStore) Resolve(principalRoles []string, dbName string) ResolvedAccessdeprecated
- func (p *PrivilegesStore) SavePrivilege(ctx context.Context, role, dbName string, read, write bool) error
- type ProcedurePrivilege
- type ProcedurePrivilegeStore
- func (p *ProcedurePrivilegeStore) AllowsBoosted(roles []string, procedure string) (bool, error)
- func (p *ProcedurePrivilegeStore) Grant(ctx context.Context, role, procedure string, boosted, immutable bool) error
- func (p *ProcedurePrivilegeStore) List(ctx context.Context) ([]ProcedurePrivilege, error)
- func (p *ProcedurePrivilegeStore) Lookup(ctx context.Context, role, procedure string, boosted bool) (ProcedurePrivilege, bool, error)
- func (p *ProcedurePrivilegeStore) Revoke(ctx context.Context, role, procedure string, boosted, immutableOnly bool) (bool, error)
- type RequestDatabaseScope
- func NewRequestDatabaseScope(defaultDatabase string, selections map[string]string) *RequestDatabaseScope
- func NewRequestDatabaseScopeWithSelectionCheck(defaultDatabase string, selections map[string]string, check func(string) bool) *RequestDatabaseScope
- func RequestDatabaseScopeFromContext(ctx context.Context) *RequestDatabaseScope
- type RequestEntitlementResolver
- type RequestIdentity
- type ResolvedAccess
- type RevocationReceipt
- type Role
- type RoleCatalogSnapshot
- type RoleEntitlementsStore
- func (r *RoleEntitlementsStore) Get(role string) []string
- func (r *RoleEntitlementsStore) Load(ctx context.Context) error
- func (r *RoleEntitlementsStore) Set(ctx context.Context, role string, entitlementIDs []string) error
- func (r *RoleEntitlementsStore) SetMappings(ctx context.Context, mappings map[string][]string) error
- type RoleMutationStores
- type RoleNotFoundError
- type RoleStore
- func (r *RoleStore) CreateRole(ctx context.Context, name string) error
- func (r *RoleStore) DeleteRole(ctx context.Context, name string) error
- func (r *RoleStore) DeleteRoleWithStores(ctx context.Context, name string, stores RoleMutationStores) error
- func (r *RoleStore) Exists(name string) bool
- func (r *RoleStore) Load(ctx context.Context) error
- func (r *RoleStore) LockRoleForGrant(ctx context.Context, name string) (bool, error)
- func (r *RoleStore) PrepareFineGrainedCatalog(ctx context.Context) (FineGrainedCatalog, string, error)
- func (r *RoleStore) ReadFineGrainedCatalog(ctx context.Context) (FineGrainedCatalog, string, error)
- func (r *RoleStore) RenameRole(ctx context.Context, oldName, newName string) error
- func (r *RoleStore) RenameRoleWithStores(ctx context.Context, oldName, newName string, stores RoleMutationStores) error
- func (r *RoleStore) RenameRoleWithUsers(ctx context.Context, oldName, newName string, allowlist *AllowlistStore, ...) error
- func (r *RoleStore) ReplaceFineGrainedCatalog(ctx context.Context, expectedRevision string, actions []FineGrainedAction, ...) error
- type TokenResponse
- type User
- type UserStateChange
Constants ¶
const ( // DefaultAuthCacheEntries is the default max size for auth caches. DefaultAuthCacheEntries = 1024 // DefaultAuthCacheTTL is the default TTL for cached auth results. DefaultAuthCacheTTL = 30 * time.Second )
const ( FGACUserJWTRead = "dbms.user.jwt.read" FGACUserJWTSet = "dbms.user.jwt.set" FGACUserJWTRotate = "dbms.user.jwt.rotate" FGACUserRevocationRead = "dbms.user.revocation.read" FGACSelfJWTRead = "dbms.user.self.jwt.read" FGACSelfJWTSet = "dbms.user.self.jwt.set" FGACSelfJWTRotate = "dbms.user.self.jwt.rotate" FGACSelfRevocationRead = "dbms.user.self.revocation.read" FGACSelfPasskeysRead = "dbms.user.self.passkeys.read" FGACSelfPasskeysManage = "dbms.user.self.passkeys.manage" )
Account security actions govern the HTTP account fields and credential operations.
const FineGrainedPublicRole = "public"
FineGrainedPublicRole applies to all authenticated FGAC principals.
Variables ¶
var ( ErrUserNotFound = errors.New("user not found") ErrUserExists = errors.New("user already exists") ErrInvalidCredentials = errors.New("invalid credentials") ErrAccountLocked = errors.New("account locked due to failed login attempts") ErrPasswordTooShort = errors.New("password does not meet minimum length requirement") ErrInvalidToken = errors.New("invalid or expired token") ErrInsufficientRole = errors.New("insufficient role permissions") ErrSessionExpired = errors.New("session expired") ErrNoCredentials = errors.New("no credentials provided") ErrMissingSecret = errors.New("JWT secret not configured") )
Errors for authentication operations.
var ( // ErrInvalidPasskey reports an invalid or expired WebAuthn response. ErrInvalidPasskey = errors.New("invalid or expired passkey response") // ErrPasskeyBusy reports that the bounded challenge store is full. ErrPasskeyBusy = errors.New("too many passkey requests, try again shortly") // ErrPasskeyLimit reports that the account cannot enroll another credential. ErrPasskeyLimit = errors.New("account has reached its passkey limit") )
var ( ErrInvalidRoleName = errors.New("invalid role name") ErrRoleExists = errors.New("role already exists") ErrRoleNotFound = errors.New("role not found") ErrCannotDeleteBuiltinRole = errors.New("cannot delete or rename built-in role") )
Role store errors.
var ErrFineGrainedCatalogChanged = errors.New("fine-grained entitlement catalog changed")
ErrFineGrainedCatalogChanged means the catalog changed since the editor read it. The editor must reload before applying another replacement.
var ErrFineGrainedForbidden = &FineGrainedPermissionError{}
ErrFineGrainedForbidden is returned when the principal lacks a required fine-grained entitlement. Invisible entities use storage.ErrNotFound for graph reads.
var ErrFineGrainedImpersonatedAdministration = &fineGrainedImpersonatedAdministrationError{}
ErrFineGrainedImpersonatedAdministration rejects an administration update made while executing as a different account.
var ErrFineGrainedImpersonationTarget = &fineGrainedImpersonationTargetError{}
ErrFineGrainedImpersonationTarget reports that an authorized actor selected an account that cannot be impersonated. It carries no directory details.
var ErrFineGrainedProviderRequired = errors.New("a user requires at least one auth provider")
ErrFineGrainedProviderRequired reports an account alteration that would leave the account without any authentication provider.
var ErrInvalidFineGrainedPolicy = errors.New("invalid fine-grained policy")
ErrInvalidFineGrainedPolicy is returned for invalid or unresolved policy.
var ( // ErrInvalidJWTKey reports a malformed Ed25519 account public key. ErrInvalidJWTKey = errors.New("JWT public key must be a base64url-encoded 32-byte Ed25519 key") )
var RolePermissions = map[Role][]Permission{ RoleAdmin: {PermRead, PermWrite, PermCreate, PermDelete, PermAdmin, PermSchema, PermUserManage}, RoleEditor: {PermRead, PermWrite, PermCreate, PermDelete}, RoleViewer: {PermRead}, RoleNone: {}, }
RolePermissions maps roles to their allowed permissions. Follows Neo4j's RBAC model.
Functions ¶
func ApplyFineGrainedPrivileges ¶
func ApplyFineGrainedPrivileges(catalog *FineGrainedCatalog, privileges []FineGrainedPrivilege, verb string, allowImmutable bool) error
ApplyFineGrainedPrivileges performs the grant or revoke on an in-memory catalog. The runtime validates roles and writes this catalog transactionally.
func AuthenticationDisabled ¶
func AuthenticationDisabled(a *Authenticator) bool
AuthenticationDisabled is the one definition of "authentication is disabled", which HTTP and Bolt both read: no authenticator, or one with security disabled. Then every request runs with full access, and immutable privileges can be administered, as in Neo4j with authentication disabled.
func BindRequestDatabaseRead ¶
BindRequestDatabaseRead resolves a request selection once and binds its live read checks. It caches no permission result: mode and resolver callbacks run on each invocation, including legacy callbacks without a change generation. Consumers can retain the canonical database and predicate for their lifetime.
func ClassifyAuthResult ¶ added in v1.1.0
ClassifyAuthResult maps the (User, error) return from Authenticate or ValidateToken into the closed result enum {success, failure, denied}.
Mapping per CONTEXT D-05e:
err == nil → "success" errors.Is(err, ErrInvalidCredentials) → "failure" (bad password) errors.Is(err, ErrInvalidToken) → "failure" (bad token) errors.Is(err, ErrSessionExpired) → "failure" (expired) errors.Is(err, ErrAccountLocked) → "denied" (lockout) errors.Is(err, ErrInsufficientRole) → "denied" (RBAC reject) errors.Is(err, ErrNoCredentials) → "denied" (no creds) other (e.g. storage error) → "failure" (defensive)
The mapping is intentional:
- "success" = identity established
- "failure" = credentials presented but rejected
- "denied" = request rejected before / despite credentials (gate)
Operators write per-result-rate alerts:
rate(auth_attempts_total{result="failure"}[5m]) > 1 ⇒ brute force
rate(auth_attempts_total{result="denied"}[5m]) > 0.1 ⇒ misconfig
func DatabasePopulationAccess ¶
DatabasePopulationAccess evaluates an unpartitioned operation's complete database population through its existing live permission predicate. Catalog providers supply every canonical name, including system, empty databases and composites. No database is exempt from admission. Call again at delivery time for long-lived consumers: neither the population nor its verdict is cached.
Any permits a filtered projection; all permits an unpartitioned result. Once both answers are determined, further permission checks cannot change them.
func DatabaseReadAllowed ¶
func DatabaseReadAllowed(roles []string, database string, privileges *PrivilegesStore, entitlements *RoleEntitlementsStore) bool
DatabaseReadAllowed checks only read, without constructing unused write capabilities. It uses the same global entitlement and matrix owners.
func EntitlementsAllow ¶
EntitlementsAllow is the one check of a global entitlement: entitlements (IDs, from PermissionsForRoles) hold permission, or admin, which holds every permission. HTTP, Bolt and the "is admin" checks all decide through it.
func ExtractToken ¶
func FineGrainedDatabaseActionAllowed ¶
FineGrainedDatabaseActionAllowed checks the current feature's scope against a downstream database. Ordinary requests have no additional action scope.
func FineGrainedEntityID ¶
FineGrainedEntityID identifies one stored node or relationship incarnation. For example, a policy editor uses the ID of the resolved node and its persisted creation time to target that node across property updates.
func FineGrainedPrivilegeKey ¶
func FineGrainedPrivilegeKey(databaseID string, kind FineGrainedResourceKind, clause string) string
FineGrainedPrivilegeKey identifies a canonical privilege clause within its stable resource.
func GlobalEntitlementIDs ¶
func GlobalEntitlementIDs() []string
GlobalEntitlementIDs returns the IDs of all global entitlements (same as Permission values for read/write/create/delete/admin/schema/user_manage).
func HasCredentials ¶
HasCredentials checks if a request has any form of authentication credentials. Checks: Authorization header, X-API-Key header, cookie, query params.
func IsBuiltinRole ¶
IsBuiltin returns true if the role name is a built-in (admin, editor, viewer).
func NormalizeRoleName ¶
NormalizeRoleName is the one form of a role's name, for every role store, record and lookup: trimmed, lower case, without the role_ prefix identity providers add (ROLE_ops is the role ops).
func PerDatabaseEntitlementIDs ¶
func PerDatabaseEntitlementIDs() []string
PerDatabaseEntitlementIDs returns the IDs of per-database entitlements.
func PermissionsForRole ¶
func PermissionsForRole(role string, store *RoleEntitlementsStore) []string
PermissionsForRole returns the effective entitlement IDs (permission strings) for a single role. If store is nil or has no override for role, built-in roles use RolePermissions; user-defined return nil.
func PermissionsForRoles ¶
func PermissionsForRoles(roles []string, store *RoleEntitlementsStore) []string
PermissionsForRoles returns the union of effective entitlement IDs for the given roles. Used by server hasPermission and GetEffectivePermissions.
func PrincipalID ¶ added in v1.3.3
PrincipalID returns a stable identity only from validated claims.
func ProcedureGlobMatches ¶
ProcedureGlobMatches reports whether a procedure name matches a grant's name or glob, as Neo4j matches them: * stands for any characters, dots included, and ? for one character; names compare case-insensitively.
func ReadRelationshipSearchHit ¶
func ReadRelationshipSearchHit(ctx context.Context, engine storage.Engine, id storage.EdgeID) (*storage.Edge, bool, error)
ReadRelationshipSearchHit returns the graph-visible relationship and whether its managed embedding may be scored under the caller's source access.
func RequestAuthenticationDisabledFromContext ¶
RequestAuthenticationDisabledFromContext reports whether the server marked the request as served with authentication disabled (WithRequestAuthenticationDisabled).
func RequestDatabasePermissionAllowed ¶
func RequestDatabasePermissionAllowed(ctx context.Context, database string, permission Permission) bool
RequestDatabasePermissionAllowed applies the existing request permission resolver and database selection rules to a direct (non-Cypher) operation. It does not introduce privileges or grant authority to acquire a database.
func RequestPrincipalRolesFromContext ¶
RequestPrincipalRolesFromContext returns the principal's roles from the request context, or nil.
func RequestResolvedAccessResolverFromContext ¶
func RequestResolvedAccessResolverFromContext(ctx context.Context) func(string) ResolvedAccess
RequestResolvedAccessResolverFromContext returns the principal's read and write on a database (dbName -> ResolvedAccess), read from the one entitlement resolver the context carries (WithRequestEntitlementResolver), or nil when it carries none. An explicitly attached legacy adapter takes precedence for this read/write compatibility accessor only.
func ResolveDatabaseReadAccess ¶
func ResolveDatabaseReadAccess(mode DatabaseAccessMode, resolve func(string) ResolvedAccess, database string) (accessible, readable bool)
ResolveDatabaseReadAccess is the shared direct-read decision for protocol routes that read a database without going through Cypher. mode owns whether the principal may select the database; resolve owns its per-database read privilege. A nil mode or resolver preserves configurations where that layer of authorization is disabled.
func RolePermissionsAsStrings ¶
RolePermissionsAsStrings returns role → permission IDs for fallback when role entitlements store has no override. Used by Bolt and other consumers that need the default role→permissions mapping. IDs match GlobalEntitlementIDs().
func RolesAllow ¶
func RolesAllow(roles []string, store *RoleEntitlementsStore, permission string) bool
RolesAllow tests the effective entitlement union without materializing it. Stored overrides and built-in fallback are identical to PermissionsForRoles.
func SecureCompare ¶
SecureCompare performs a constant-time string comparison. Prevents timing attacks on token validation.
func UsernamePrincipalID ¶ added in v1.3.3
UsernamePrincipalID returns the canonical identity for validated basic auth.
func WithFineGrainedDatabaseAction ¶
WithFineGrainedDatabaseAction carries an admitted feature action into downstream database calls. Every downstream target must satisfy its scope.
func WithFineGrainedRequest ¶
func WithFineGrainedRequest(ctx context.Context, request *FineGrainedRequest) context.Context
WithFineGrainedRequest associates an admitted principal with ctx.
func WithReadOnlyDatabaseScope ¶
WithReadOnlyDatabaseScope narrows the caller's live principal to one readable database. Identity and cancellation are preserved; legacy access adapters are narrowed too, so an inherited administrator adapter cannot reintroduce writes.
func WithRequestAuthenticationDisabled ¶
WithRequestAuthenticationDisabled marks a request the server serves with authentication disabled, which therefore carries no principal. Callers that authorize through the request principal (RequestEntitlementResolverFromContext) treat a context with neither a resolver nor this mark as refused.
func WithRequestDatabaseAccessMode ¶
func WithRequestDatabaseAccessMode(ctx context.Context, mode DatabaseAccessMode) context.Context
WithRequestDatabaseAccessMode attaches the principal's per-database access mode to the context.
func WithRequestDatabaseScope ¶ added in v1.3.1
func WithRequestDatabaseScope(ctx context.Context, scope *RequestDatabaseScope) context.Context
WithRequestDatabaseScope attaches the server-derived database scope.
func WithRequestEntitlementResolver ¶ added in v1.3.1
func WithRequestEntitlementResolver(ctx context.Context, resolver RequestEntitlementResolver) context.Context
WithRequestEntitlementResolver attaches the principal's one permission resolver (the server builds it from cypher.PrincipalAccess): whether it holds a permission on a database. RequestResolvedAccessResolverFromContext reads read and write from it.
func WithRequestIdentity ¶
func WithRequestIdentity(ctx context.Context, identity RequestIdentity) context.Context
func WithRequestPrincipal ¶
func WithRequestPrincipal(ctx context.Context, resolver RequestEntitlementResolver, scope *RequestDatabaseScope) context.Context
WithRequestPrincipal attaches a principal as callers that authorize through the request read it: its permission resolver (WithRequestEntitlementResolver) and the databases and aliases it may select (WithRequestDatabaseScope), together. A context with a resolver and no scope is an incomplete principal, which those callers refuse.
func WithRequestPrincipalRoles ¶
WithRequestPrincipalRoles attaches the principal's role names to the context.
func WithRequestResolvedAccessResolver
deprecated
func WithRequestResolvedAccessResolver(ctx context.Context, fn func(string) ResolvedAccess) context.Context
WithRequestResolvedAccessResolver preserves the legacy read/write context adapter. For example, attach a function returning ResolvedAccess{Read: true} to supply a legacy read-only consumer. It leaves any complete entitlement resolver unchanged, including administrator and schema checks; a nil fn clears the legacy adapter without clearing those checks.
Deprecated: production transports should attach the complete permission owner with WithRequestEntitlementResolver instead.
func WithRoleRecords ¶
func WithRoleRecords(ctx context.Context, system storage.Engine, roles []string, mutate func(view storage.Engine) error) error
WithRoleRecords is the one owner of writes to what a role owns besides its role node (procedure grants, entitlement overrides, database allowlists, database privileges) and the one check that the roles they name exist. It runs mutate in one system-store transaction (WithStoreTransaction) after taking each named role's lock (LockRoleForGrant), in one order for every caller, so the write and a concurrent delete or rename of the role can't both commit. A role that doesn't exist is refused with a RoleNotFoundError, and nothing is written. Callers publish their caches only after it returns nil.
func WithStoreTransaction ¶
func WithStoreTransaction(ctx context.Context, engine storage.Engine, mutate func(storage.Engine) error) error
WithStoreTransaction runs system-node mutations in the same BadgerTransaction used by Cypher GRANT/REVOKE. An explicit transaction's engine supplies its existing view; otherwise this function owns begin, commit and rollback. Callers publish their in-memory state only after this function succeeds.
Types ¶
type AllowlistStore ¶
type AllowlistStore struct {
// contains filtered or unexported fields
}
AllowlistStore loads and saves role→databases allowlist in the system database.
func NewAllowlistStore ¶
func NewAllowlistStore(systemStorage storage.Engine) *AllowlistStore
NewAllowlistStore creates a store that reads/writes allowlist to the given system storage.
func (*AllowlistStore) Allowlist ¶
func (a *AllowlistStore) Allowlist() map[string][]string
Allowlist returns a copy of the current allowlist (role → databases). Nil or empty slice means "all databases".
func (*AllowlistStore) CanAccessDatabaseForRoles ¶
func (a *AllowlistStore) CanAccessDatabaseForRoles(roles []string, database string) bool
CanAccessDatabaseForRoles checks the current allowlist under its read lock, without copying the map or constructing a new access-mode adapter.
func (*AllowlistStore) HasAllowlistData ¶
func (a *AllowlistStore) HasAllowlistData(ctx context.Context) (bool, error)
HasAllowlistData returns true if any allowlist entry exists in storage (for seed skip).
func (*AllowlistStore) Load ¶
func (a *AllowlistStore) Load(ctx context.Context) error
Load reads the full allowlist from storage into memory. Call at startup and after PUT.
func (*AllowlistStore) SaveMappings ¶
SaveMappings persists a batch in one transaction through the role-record owner (WithRoleRecords): every role's list is stored, or none when one fails or names a role that doesn't exist. The cache changes only after commit.
func (*AllowlistStore) SaveRoleDatabases ¶
func (a *AllowlistStore) SaveRoleDatabases(ctx context.Context, role string, databases []string) error
SaveRoleDatabases persists one role's database list and refreshes the in-memory allowlist. The role must exist (ErrRoleNotFound).
func (*AllowlistStore) SeedIfEmpty ¶
func (a *AllowlistStore) SeedIfEmpty(ctx context.Context, databaseNames []string) error
SeedIfEmpty creates default allowlist entries for admin, editor, viewer if no allowlist data exists. Built-in roles are seeded with an empty list so they have access to all databases (including dynamically created ones). databaseNames is unused but kept for API compatibility; callers may pass the current db list from dbManager for logging or future use. Call after Load() so in-memory state is correct; or call on fresh DB before any Load().
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time `json:"timestamp"`
EventType string `json:"event_type"`
Username string `json:"username,omitempty"`
UserID string `json:"user_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Success bool `json:"success"`
Details string `json:"details,omitempty"`
RequestPath string `json:"request_path,omitempty"`
}
AuditEvent represents an authentication-related event for compliance logging. Required for GDPR Art.30, HIPAA §164.312(b), FISMA AU controls.
type AuthConfig ¶
type AuthConfig struct {
// Password policy
MinPasswordLength int
BcryptCost int
// Token settings
JWTSecret []byte
TokenExpiry time.Duration // 0 = never expire (default)
// WebAuthnOrigin is the configured browser origin. Empty disables passkeys.
WebAuthnOrigin string
// Lockout settings
MaxFailedLogins int
LockoutDuration time.Duration
// Default admin username (never gets locked out)
// This ensures the root admin account is always accessible
DefaultAdminUsername string
// Feature flags
SecurityEnabled bool
}
AuthConfig holds authentication configuration.
func DefaultAuthConfig ¶
func DefaultAuthConfig() AuthConfig
DefaultAuthConfig returns default authentication configuration. Returns sensible defaults.
type AuthMetricsRecorder ¶ added in v1.1.0
type AuthMetricsRecorder interface {
// RecordAttempt observes a single auth attempt with the given result
// and protocol. Nil-safe — implementations no-op when the bag is nil.
RecordAttempt(result, protocol string)
}
AuthMetricsRecorder is the seam the protocol adapters use to publish the auth_attempts_total counter. The shared Authenticator owns one (set via SetAuthMetrics); protocol adapters can also own their own bag pointer for direct wiring at the chokepoint.
The interface lives in pkg/auth (not pkg/observability) because the caller domain — the protocol adapters — is the one that knows the protocol label value. pkg/observability only knows about the underlying CounterVec.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator manages users and authentication.
func NewAuthenticator ¶
func NewAuthenticator(config AuthConfig, storage storage.Engine) (*Authenticator, error)
NewAuthenticator creates a new Authenticator with the given configuration.
The authenticator manages user accounts, authentication, and authorization. All operations are thread-safe.
Configuration validation:
- If SecurityEnabled=true, JWTSecret is required (min 32 bytes recommended)
- MinPasswordLength defaults to 8 characters
- BcryptCost defaults to bcrypt.DefaultCost (10)
- MaxFailedLogins defaults to 5
- LockoutDuration defaults to 15 minutes
Example:
// Production configuration
config := auth.AuthConfig{
MinPasswordLength: 12,
BcryptCost: 12, // Higher = more secure but slower
JWTSecret: []byte("your-secret-key-at-least-32-chars-long"),
TokenExpiry: 24 * time.Hour, // Tokens expire after 24h
MaxFailedLogins: 5,
LockoutDuration: 30 * time.Minute,
SecurityEnabled: true,
}
auth, err := auth.NewAuthenticator(config)
if err != nil {
log.Fatal(err)
}
// Development configuration (no security)
devConfig := auth.AuthConfig{
SecurityEnabled: false, // All requests allowed
}
auth = auth.NewAuthenticator(devConfig)
Returns error if SecurityEnabled=true but JWTSecret is empty.
Example 1 - Production HIPAA-Compliant Setup:
config := auth.DefaultAuthConfig()
config.SecurityEnabled = true
config.JWTSecret = []byte(os.Getenv("JWT_SECRET")) // Min 32 bytes
config.MinPasswordLength = 12
config.BcryptCost = 12 // High cost for security
config.MaxFailedAttempts = 5
config.LockoutDuration = 30 * time.Minute
config.TokenExpiry = 4 * time.Hour
authenticator, err := auth.NewAuthenticator(config)
if err != nil {
log.Fatal("Failed to initialize auth:", err)
}
// Set up HIPAA-required audit logging
authenticator.SetAuditLogger(func(event auth.AuditEvent) {
auditLogger.Log(audit.Event{
Type: audit.EventLogin,
UserID: event.UserID,
Username: event.Username,
IPAddress: event.IPAddress,
Success: event.Success,
Metadata: map[string]string{"reason": event.Message},
})
})
// Create admin user with strong password
admin, err := authenticator.CreateUser("admin",
"Str0ng!P@ssw0rd#2024", []auth.Role{auth.RoleAdmin})
Example 2 - Multi-Tenant SaaS with Short-Lived Tokens:
config := auth.DefaultAuthConfig()
config.SecurityEnabled = true
config.JWTSecret = loadSecretFromVault()
config.TokenExpiry = 15 * time.Minute // Short-lived tokens
config.MaxFailedAttempts = 3 // Strict lockout
authenticator, err := auth.NewAuthenticator(config)
if err != nil {
return nil, fmt.Errorf("auth init failed: %w", err)
}
// Create per-tenant users
for _, tenant := range tenants {
user, err := authenticator.CreateUser(
fmt.Sprintf("%s-%s", tenant.ID, username),
generateStrongPassword(),
[]auth.Role{auth.RoleEditor},
)
if err != nil {
log.Printf("Failed to create user for tenant %s: %v", tenant.ID, err)
}
}
Example 3 - Development Mode (No Security):
config := auth.DefaultAuthConfig()
config.SecurityEnabled = false // Bypass all auth checks
authenticator, err := auth.NewAuthenticator(config)
if err != nil {
log.Fatal(err)
}
// In dev mode, any token is accepted
// WARNING: Never use in production!
claims, _ := authenticator.ValidateToken("any-token") // Always succeeds
Example 4 - API Integration with Rate Limiting:
config := auth.DefaultAuthConfig()
config.JWTSecret = []byte("secure-secret-32-chars-minimum!!")
config.MaxFailedAttempts = 5
authenticator, err := auth.NewAuthenticator(config)
if err != nil {
return nil, err
}
// Track failed attempts for rate limiting
authenticator.SetAuditLogger(func(event auth.AuditEvent) {
if event.EventType == "login_failed" {
rateLimiter.RecordFailure(event.IPAddress)
if rateLimiter.IsBlocked(event.IPAddress) {
firewall.BlockIP(event.IPAddress, 1*time.Hour)
}
}
})
ELI12:
Think of NewAuthenticator like hiring a bouncer for a club:
- The bouncer checks IDs (validates JWT tokens)
- They remember troublemakers (account lockout after failed attempts)
- They keep a guest list (user database)
- They write down who comes in (audit logging)
- They have different wristbands for VIP, regular, and just-looking (roles)
SecurityEnabled = true means "bouncer is on duty" SecurityEnabled = false means "anyone can walk in" (explicit compatibility mode)
Real-world Analogy:
JWT tokens are like temporary wristbands: - When you log in, you get a wristband (token) - Show the wristband to access stuff (no need to login again) - Wristband expires after a few hours (token expiry) - If you lose it, get a new one by logging in again
Why JWT Instead of Sessions?
Sessions: "I'll remember you" (server stores state) JWT: "Here's a signed badge, prove yourself each time" (stateless) JWT Benefits: - Works across multiple servers (no shared session storage) - Scales better (no memory for sessions) - Mobile-friendly (just store the token)
Security Features:
- Passwords hashed with bcrypt (can't be reversed)
- Account lockout (prevents password guessing)
- Token expiry (stolen tokens eventually die)
- Audit logging (track who did what)
Compliance:
- GDPR Art.32: Security measures ✓
- HIPAA §164.312(a): Access control ✓
- FISMA AC-2: Account management ✓
- SOC 2 CC6.1: Logical access controls ✓
Performance:
- bcrypt hashing: ~50-200ms (intentionally slow for security)
- Token validation: ~1ms (just signature check)
- Thread-safe for concurrent authentication
Thread Safety:
All methods are thread-safe for concurrent use.
Storage Engine (Required):
Users are always persisted to the provided storage engine.
For testing, use a memory storage engine via dependency injection.
// Production: System database storage
systemStorage := dbManager.GetStorage("system")
auth, err := auth.NewAuthenticator(config, systemStorage)
// Testing: Memory storage engine
memoryStorage := storage.NewMemoryEngine()
auth, err := auth.NewAuthenticator(config, memoryStorage)
func (*Authenticator) AllowsPasskeyOrigin ¶
func (a *Authenticator) AllowsPasskeyOrigin(origin string) bool
AllowsPasskeyOrigin checks the configured browser origin for WebAuthn requests.
func (*Authenticator) AuthMetrics ¶ added in v1.1.0
func (a *Authenticator) AuthMetrics() *observability.AuthMetrics
AuthMetrics returns the currently-injected bag (nil if unset). Used by protocol adapters to obtain the bag for direct wiring.
func (*Authenticator) Authenticate ¶
func (a *Authenticator) Authenticate(ctx context.Context, username, password, ipAddress, userAgent string) (*TokenResponse, *User, error)
Authenticate verifies user credentials and returns a JWT token.
This implements the OAuth 2.0 password grant flow (RFC 6749 Section 4.3). On successful authentication:
- Password is verified with bcrypt
- Failed login counter is reset
- LastLogin timestamp is updated
- JWT token is generated
- Audit event is logged
Security features:
- Account lockout after MaxFailedLogins attempts
- Disabled accounts cannot authenticate
- Timing attack resistant (doesn't reveal if user exists)
- Failed attempts are logged for security monitoring
Parameters:
- username: User's username
- password: User's password (plain text)
- ipAddress: Client IP for audit logging
- userAgent: Client User-Agent for audit logging
Returns:
- TokenResponse: OAuth 2.0 token response (access_token, token_type, expires_in)
- User: User object (without password)
- Error: ErrInvalidCredentials, ErrAccountLocked, or ErrUserNotFound
Example:
token, user, err := auth.Authenticate(
"alice",
"AlicePassword123!",
"192.168.1.100",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
)
if err != nil {
if errors.Is(err, auth.ErrAccountLocked) {
http.Error(w, "Account locked. Try again in 15 minutes.", 423)
return
}
http.Error(w, "Invalid credentials", 401)
return
}
// Use token in Authorization header
fmt.Printf("Authorization: Bearer %s\n", token.AccessToken)
// Set cookie for browser sessions
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: token.AccessToken,
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
Compliance:
- HIPAA §164.312(a)(2)(i): Unique User Identification
- HIPAA §164.312(d): Person or Entity Authentication
- GDPR Art.32: Technical measures to ensure security
- FISMA AC-7: Unsuccessful Login Attempts
ctx owns admission only. Credential acceptance and the best-effort login bookkeeping keep their existing distinction: a rejected credential still records its failed-login state and audit event, and a storage refusal of that bookkeeping never turns an accepted credential into a failed login. A canceled caller is refused before any state is read or written, so it reports its own error rather than an uncommitted login outcome, and no credential material is ever included in an error or audit detail.
func (*Authenticator) BeginPasskeyLogin ¶
func (a *Authenticator) BeginPasskeyLogin() (string, *protocol.CredentialAssertion, error)
BeginPasskeyLogin creates a discoverable challenge for platform and roaming keys. Call BeginPasskeyLoginForPeer from an HTTP boundary so one caller cannot exhaust the shared challenge store.
func (*Authenticator) BeginPasskeyLoginForPeer ¶
func (a *Authenticator) BeginPasskeyLoginForPeer(remoteAddr string) (string, *protocol.CredentialAssertion, error)
BeginPasskeyLoginForPeer creates a discoverable challenge for the connection's peer address. Forwarding headers must not be supplied as remoteAddr.
func (*Authenticator) BeginPasskeyRegistration ¶
func (a *Authenticator) BeginPasskeyRegistration(ctx context.Context, claims *JWTClaims, password string) (string, *protocol.CredentialCreation, error)
BeginPasskeyRegistration starts an enrollment after confirming the account password.
func (*Authenticator) ChangePassword ¶
func (a *Authenticator) ChangePassword(ctx context.Context, username, oldPassword, newPassword string) error
ChangePassword updates a user's password and invalidates credential caches only after successful persistence. Audits and listeners run under mu.
func (*Authenticator) ChangeUserState ¶
func (a *Authenticator) ChangeUserState(ctx context.Context, username string, change UserStateChange) error
ChangeUserState applies a typed state transition and its original audit event. Rejection leaves both live and stored state unchanged. It replaces the former EnableUser, DisableUser and UnlockUser Go methods; wire/admin behavior is unchanged.
Example:
err := authenticator.ChangeUserState("alice", auth.UserUnlock)
func (*Authenticator) CreateUser ¶
func (a *Authenticator) CreateUser(ctx context.Context, username, password string, roles []Role) (*User, error)
CreateUser creates a new user account with the given credentials and roles.
The password is immediately hashed with bcrypt and never stored in plain text. If no roles are specified, defaults to RoleViewer.
Parameters:
- username: Unique username (must not already exist)
- password: Plain text password (will be hashed)
- roles: User roles, or empty slice for default (viewer)
Returns:
- User object (without password hash)
- ErrUserExists if username already taken
- ErrPasswordTooShort if password doesn't meet minimum length
Example:
// Create admin user
admin, err := auth.CreateUser(ctx, "admin", "SecurePassword123!",
[]auth.Role{auth.RoleAdmin})
if err != nil {
return err
}
// Create regular user (defaults to viewer)
user, err := auth.CreateUser(ctx, "alice", "AlicePass456!", nil)
// Create user with multiple roles
editor, err := auth.CreateUser(ctx, "bob", "BobPass789!",
[]auth.Role{auth.RoleEditor, auth.RoleViewer})
Audit event: Logs "user_create" with success/failure.
Compliance: HIPAA §164.308(a)(3)(ii)(A) - Unique user IDs
ctx owns admission and the durable user write. A canceled ctx reports its own error: nothing is persisted, no live user is published and no audit event is recorded.
func (*Authenticator) CreateUserWithJWTKey ¶
func (a *Authenticator) CreateUserWithJWTKey(ctx context.Context, username, password string, roles []Role, publicKey string) (*User, error)
CreateUserWithJWTKey creates an account and optionally registers its Ed25519 public signing key.
func (*Authenticator) CurrentBasicClaims ¶
func (a *Authenticator) CurrentBasicClaims(claims *JWTClaims, cache *BasicAuthCache, generation uint64) (*JWTClaims, error)
CurrentBasicClaims validates a cached Basic authentication against the refreshed directory. If refresh invalidated the cache, the caller checks the credentials again through Authenticate.
func (*Authenticator) CurrentBasicClaimsContext ¶
func (a *Authenticator) CurrentBasicClaimsContext(ctx context.Context, claims *JWTClaims, cache *BasicAuthCache, generation uint64) (*JWTClaims, error)
CurrentBasicClaimsContext verifies cached Basic claims with the caller's lifetime.
func (*Authenticator) CurrentClaims ¶
func (a *Authenticator) CurrentClaims(claims *JWTClaims) (*JWTClaims, error)
CurrentClaims is the one owner of a principal's roles on every request: claims with the roles its user account holds now, as the user store records them. Bearer tokens, cached Basic authentication and Bolt sessions all read a principal's roles through it. A role removed from the user, or deleted (which detaches it from every user), stops applying at once, as in Neo4j, where privileges follow the current role membership. A deleted or disabled account, or another account created under the same name, authorizes nothing: ErrInvalidToken. The one identity that is not a user account is a cluster node's token, which keeps its own roles. claims is never changed.
func (*Authenticator) CurrentClaimsContext ¶
func (a *Authenticator) CurrentClaimsContext(ctx context.Context, claims *JWTClaims) (*JWTClaims, error)
CurrentClaimsContext refreshes the principal using the caller's lifetime.
func (*Authenticator) DeleteUser ¶
func (a *Authenticator) DeleteUser(ctx context.Context, username string) error
DeleteUser removes a user under the caller's lifetime. The live user is forgotten, and its success audit recorded, only after the stored delete is accepted; a canceled ctx reports its own error and leaves the user intact.
func (*Authenticator) FinishPasskeyLogin ¶
func (a *Authenticator) FinishPasskeyLogin(ctx context.Context, id string, response []byte, ipAddress, userAgent string) (*TokenResponse, error)
FinishPasskeyLogin checks the account, credential and user verification before issuing the standard NornicDB session.
func (*Authenticator) FinishPasskeyRegistration ¶
func (a *Authenticator) FinishPasskeyRegistration(ctx context.Context, claims *JWTClaims, id string, response []byte) error
FinishPasskeyRegistration verifies and persists the credential under the same account.
func (*Authenticator) GenerateAPIToken ¶
func (a *Authenticator) GenerateAPIToken(user *User, subject string, expiry time.Duration) (string, error)
GenerateAPIToken creates a stateless API token for the given user. These tokens are for MCP servers and other API integrations. The token is not stored; it's generated on-demand and validated by signature.
Parameters:
- user: The authenticated user requesting the token
- subject: A descriptive label for the token (e.g., "my-mcp-server")
- expiry: Token lifetime (0 = never expires)
Returns the raw JWT token string.
func (*Authenticator) GenerateAPITokenForClaims ¶
func (a *Authenticator) GenerateAPITokenForClaims(claims *JWTClaims, subject string, expiry time.Duration) (string, error)
GenerateAPITokenForClaims issues a token using the current account record only while the requesting identity is still authorized.
func (*Authenticator) GenerateClusterToken ¶
func (a *Authenticator) GenerateClusterToken(nodeID string, role Role) (string, error)
GenerateClusterToken creates a JWT token for cluster inter-node authentication. This token can be used by cluster nodes to authenticate with each other using the same shared JWT secret.
The token contains:
- Sub: node identifier (e.g., "cluster-node-2")
- Username: same as nodeID for identification
- Roles: specified role (typically "admin" for cluster nodes)
- Iat: issued at timestamp
- Exp: expiration (if TokenExpiry is configured, otherwise never expires)
Usage:
Generate the secret (must be same on all nodes): openssl rand -base64 48
Configure all cluster nodes with the same secret: NORNICDB_JWT_SECRET=<your-generated-secret>
Generate a cluster token (from admin API or code): token, _ := authenticator.GenerateClusterToken("node-2", auth.RoleAdmin)
Use the token to connect from other nodes: driver = GraphDatabase.driver("bolt://node1:7687", basic_auth("", token)) # Empty principal triggers bearer/JWT auth
Example:
// On cluster setup, generate tokens for each node
token, err := authenticator.GenerateClusterToken("cluster-node-west", auth.RoleAdmin)
if err != nil {
log.Fatal(err)
}
// Distribute token securely to node-west
// Node-west uses it to connect:
driver, _ := neo4j.NewDriverWithContext(
"bolt://node-east:7687",
neo4j.BasicAuth("", token, ""), // Empty username = bearer auth
)
Security considerations:
- Tokens are signed with HMAC-SHA256 using the shared JWT secret
- All cluster nodes MUST use the same JWT secret
- Store the secret securely (e.g., HashiCorp Vault, K8s Secrets)
- Rotate secrets periodically by generating new tokens
func (*Authenticator) GenerateClusterTokenWithExpiry ¶
func (a *Authenticator) GenerateClusterTokenWithExpiry(nodeID string, role Role, expiry time.Duration) (string, error)
GenerateClusterTokenWithExpiry creates a JWT token with a custom expiration time. Useful for short-lived tokens during initial cluster setup or testing.
Parameters:
- nodeID: identifier for the cluster node (e.g., "node-2", "replica-west")
- role: role to assign (typically RoleAdmin for cluster nodes)
- expiry: token lifetime (e.g., 24*time.Hour, 0 for never expires)
Example:
// Generate a token that expires in 7 days
token, _ := auth.GenerateClusterTokenWithExpiry("node-2", auth.RoleAdmin, 7*24*time.Hour)
func (*Authenticator) GetUser ¶
func (a *Authenticator) GetUser(username string) (*User, error)
GetUser returns user info by username without sensitive data.
func (*Authenticator) GetUserByID ¶
func (a *Authenticator) GetUserByID(id string) (*User, error)
GetUserByID retrieves a user by their ID.
func (*Authenticator) IsSecurityEnabled ¶
func (a *Authenticator) IsSecurityEnabled() bool
IsSecurityEnabled returns whether security is enabled.
func (*Authenticator) ListPasskeys ¶
func (a *Authenticator) ListPasskeys(ctx context.Context, claims *JWTClaims) ([]PasskeyInfo, error)
ListPasskeys returns the current account's enrolled credential descriptors.
func (*Authenticator) ListUsers ¶
func (a *Authenticator) ListUsers() []*User
ListUsers returns all users without sensitive data.
func (*Authenticator) OnPasswordChange ¶
func (a *Authenticator) OnPasswordChange(fn func(username string))
OnPasswordChange registers fn, called with a user's name once the user's password has changed. Every cache of Basic credentials registers its ForgetUser (HTTP, Bolt, gRPC), so the old password stops working at once instead of when its cache entry expires. fn runs while the authenticator is locked, so it must not call back into it.
func (*Authenticator) PasskeysEnabled ¶
func (a *Authenticator) PasskeysEnabled() bool
PasskeysEnabled reports whether browser WebAuthn ceremonies are configured.
func (*Authenticator) RecordAttempt ¶ added in v1.1.0
func (a *Authenticator) RecordAttempt(result, protocol string)
RecordAttempt implements AuthMetricsRecorder on the shared Authenticator. Protocol adapters that share a single Authenticator instance can call `auth.RecordAttempt(...)` directly with the appropriate protocol label.
Closed-enum discipline at the call site: callers must pass values from observability.AllowedAuthResults × observability.AllowedAuthProtocols. Any drift is caught by Phase 3 D-03a forbidden-label panic at registration (defense in depth — the call site gate is the actual check).
func (*Authenticator) ReloadUsersAfterRestore ¶
func (a *Authenticator) ReloadUsersAfterRestore(ctx context.Context) error
ReloadUsersAfterRestore replaces the live account directory with the restored system records. The record-order boundary prevents a concurrent account mutation from publishing an older directory after this reload.
func (*Authenticator) RemovePasskey ¶
func (a *Authenticator) RemovePasskey(ctx context.Context, claims *JWTClaims, id, password string) error
RemovePasskey deletes one enrolled credential after confirming the account password.
func (*Authenticator) RevokeToken ¶
func (a *Authenticator) RevokeToken(ctx context.Context, token string) (*RevocationReceipt, *JWTClaims, *FineGrainedProviderSession, error)
RevokeToken invalidates one presented account JWT. Repeating a successful request returns the original receipt while the record is retained. The returned claims and optional provider binding identify the subject for authorization of the receipt only. The caller must not use them to authorize a session.
func (*Authenticator) RotateAccountJWT ¶
func (a *Authenticator) RotateAccountJWT(ctx context.Context, actor *JWTClaims, username, publicKey, password string) (RevocationReceipt, string, error)
RotateAccountJWT changes one account's signing key and invalidates its old JWTs. The caller authorizes access to the target account; actor must still be valid when the change is staged.
func (*Authenticator) SetAuditLogger ¶
func (a *Authenticator) SetAuditLogger(fn func(AuditEvent))
SetAuditLogger sets the audit logging callback.
func (*Authenticator) SetAuthMetrics ¶ added in v1.1.0
func (a *Authenticator) SetAuthMetrics(bag *observability.AuthMetrics)
SetAuthMetrics injects the observability AuthMetrics bag for the auth_attempts_total counter (D-11 / D-05e / MET-15).
Idempotent. Calling with nil disables observation.
IMPORTANT: this is a parallel observability signal — the audit log (pkg/audit/audit.go) is the compliance source of truth and remains unchanged.
func (*Authenticator) UpdateRoles ¶
UpdateRoles changes a user's roles, persisting before live publication.
func (*Authenticator) UpdateRolesAndStatus ¶
func (a *Authenticator) UpdateRolesAndStatus(ctx context.Context, username string, roles []Role, disabled *bool) error
UpdateRolesAndStatus applies the requested roles and account status together. A nil argument leaves that field unchanged. Existing user mutations stage their writes in the shared transaction; caches and audit events publish only after the whole request commits.
func (*Authenticator) UpdateUser ¶
func (a *Authenticator) UpdateUser(ctx context.Context, username string, email string, metadata map[string]string) error
UpdateUser updates profile information. Empty email preserves the current value; a nonnil metadata map merges its entries into the existing metadata.
func (*Authenticator) UserCount ¶
func (a *Authenticator) UserCount() int
UserCount returns the number of registered users.
func (*Authenticator) ValidateToken ¶
func (a *Authenticator) ValidateToken(token string) (*JWTClaims, error)
ValidateToken validates a JWT token and returns the claims.
The token is verified using HMAC-SHA256. If valid, returns the decoded claims including user ID, username, roles, and expiration.
Validation checks:
- Token format (header.payload.signature)
- Signature verification (HMAC-SHA256)
- Expiration (if Exp > 0)
- Not before (if configured)
If SecurityEnabled=false, returns dummy claims allowing all access.
The token can include "Bearer " prefix (will be stripped).
Parameters:
- token: JWT token string (with or without "Bearer " prefix)
Returns:
- JWTClaims: Decoded claims with user info and roles
- Error: ErrInvalidToken, ErrSessionExpired, or ErrNoCredentials
Example:
// From Authorization header
authHeader := r.Header.Get("Authorization") // "Bearer eyJhbGc..."
claims, err := auth.ValidateToken(authHeader)
if err != nil {
http.Error(w, "Unauthorized", 401)
return
}
fmt.Printf("User: %s\n", claims.Username)
fmt.Printf("Roles: %v\n", claims.Roles)
// Check if user has admin role
hasAdmin := false
for _, role := range claims.Roles {
if role == string(auth.RoleAdmin) {
hasAdmin = true
break
}
}
Security:
- Uses constant-time comparison to prevent timing attacks
- Validates expiration to prevent replay attacks
- Checks signature to prevent tampering
func (*Authenticator) ValidateTokenWithFineGrainedProvider ¶
func (a *Authenticator) ValidateTokenWithFineGrainedProvider(ctx context.Context, token string) (*JWTClaims, *FineGrainedProviderSession, error)
ValidateTokenWithFineGrainedProvider validates the token and returns any verified external-provider context for FGAC-aware protocols.
type BasicAuthCache ¶
type BasicAuthCache struct {
// contains filtered or unexported fields
}
BasicAuthCache caches successful Basic authentication results to avoid repeated bcrypt work on high-volume request paths. It spares the password check only: every caller passes a cached result through Authenticator.CurrentClaims, so the roles are the account's current ones, and every owner registers ForgetUser with Authenticator.OnPasswordChange, so a changed password stops working at once.
func NewBasicAuthCache ¶
func NewBasicAuthCache(maxEntries int, ttl time.Duration) *BasicAuthCache
NewBasicAuthCache creates a new cache for Basic auth results.
func (*BasicAuthCache) ForgetUser ¶
func (c *BasicAuthCache) ForgetUser(username string)
ForgetUser drops every cached result of username, so a password that was just changed authenticates no more (Authenticator.OnPasswordChange calls it): the next request with it is checked in full.
func (*BasicAuthCache) Generation ¶
func (c *BasicAuthCache) Generation() uint64
Generation captures the cache publication generation before credentials are authenticated. SetAtGeneration and SetFromHeaderAtGeneration publish only within that generation.
func (*BasicAuthCache) Get ¶
func (c *BasicAuthCache) Get(username, password string) (*JWTClaims, bool)
Get retrieves cached claims using username/password (when header isn't available).
func (*BasicAuthCache) GetFromHeader ¶
func (c *BasicAuthCache) GetFromHeader(authHeader string) (*JWTClaims, bool)
GetFromHeader retrieves cached claims using the full Basic auth header.
func (*BasicAuthCache) GetFromHeaderWithGeneration ¶
func (c *BasicAuthCache) GetFromHeaderWithGeneration(authHeader string) (*JWTClaims, uint64, bool)
GetFromHeaderWithGeneration returns the cache generation observed with the claims.
func (*BasicAuthCache) GetWithGeneration ¶
func (c *BasicAuthCache) GetWithGeneration(username, password string) (*JWTClaims, uint64, bool)
GetWithGeneration returns the cache generation observed with the claims.
func (*BasicAuthCache) Set ¶
func (c *BasicAuthCache) Set(username, password string, claims *JWTClaims)
Set caches claims using username/password at the current generation. It preserves the original setter contract; authentication paths must instead use SetAtGeneration with a generation captured before checking credentials.
func (*BasicAuthCache) SetAtGeneration ¶
func (c *BasicAuthCache) SetAtGeneration(username, password string, claims *JWTClaims, generation uint64)
SetAtGeneration caches claims only if generation, captured before checking credentials, still matches. For example, capture cache.Generation() before authenticating and pass it here to prevent a password change from racing publication of a successful check of the old password.
func (*BasicAuthCache) SetFromHeader ¶
func (c *BasicAuthCache) SetFromHeader(authHeader string, claims *JWTClaims)
SetFromHeader caches claims using the full Basic auth header at the current generation. It preserves the original setter contract; authentication paths must use SetFromHeaderAtGeneration with a generation captured before checking credentials to reject publication racing a password change.
func (*BasicAuthCache) SetFromHeaderAtGeneration ¶
func (c *BasicAuthCache) SetFromHeaderAtGeneration(authHeader string, claims *JWTClaims, generation uint64)
SetFromHeaderAtGeneration caches claims only if generation, captured before authentication, still matches. For example, capture cache.Generation(), check credentials, then publish with the captured value so ForgetUser wins a race.
type CatalogVisibility ¶
type CatalogVisibility struct {
// contains filtered or unexported fields
}
CatalogVisibility is the principal's live metadata view. It binds permission metadata rather than an execution context, so it can travel with row values without acquiring cancellation ownership. Its zero value is trusted embedded use with no configured authorization policy.
func NewCatalogVisibility ¶
func NewCatalogVisibility(mode DatabaseAccessMode, scope *RequestDatabaseScope, selection func(database, permission string) bool) CatalogVisibility
NewCatalogVisibility binds the existing visibility mode, request selection scope and permission resolver. No decision is cached: retained store-backed modes and resolvers remain live. For example, bind once for a statement row, then call view.CanSeeDatabase("reports") before publishing catalog metadata. A nil component leaves that component unconfigured.
func (CatalogVisibility) CanSeeDatabase ¶
func (v CatalogVisibility) CanSeeDatabase(database string) bool
CanSeeDatabase reports whether database may be named in catalog output. Explicit metadata visibility does not require data-read privileges. A request scope remains a selection boundary; absent an explicit mode, the existing access resolver decides, preserving trusted callers without a resolver.
type DatabaseAccessMode ¶
type DatabaseAccessMode interface {
CanSeeDatabase(dbName string) bool
CanAccessDatabase(dbName string) bool
}
DatabaseAccessMode answers whether a principal may see and access databases. Equivalent to Neo4j DatabaseAccessMode. Used before executing Cypher: CanAccessDatabase(dbName) must be true or the request is denied with 403.
var DenyAllDatabaseAccessMode DatabaseAccessMode = denyAllDBAccessMode{}
DenyAllDatabaseAccessMode is the singleton that denies all databases. Use when auth is enabled and no allowlist is configured (secure default).
var FullDatabaseAccessMode DatabaseAccessMode = fullDBAccessMode{}
FullDatabaseAccessMode is the singleton that allows all databases. Use when auth is disabled so dev/local usage works without RBAC.
func NewAllowlistDatabaseAccessMode ¶
func NewAllowlistDatabaseAccessMode(allowlist map[string][]string, principalRoles []string) DatabaseAccessMode
NewAllowlistDatabaseAccessMode returns a DatabaseAccessMode for the given allowlist and principal roles. For each role: if the role has no allowlist (or empty), treat as "all databases"; else allow only listed DBs. CanAccessDatabase(dbName) is true iff at least one of the principal's roles allows the database.
func RequestDatabaseAccessModeFromContext ¶
func RequestDatabaseAccessModeFromContext(ctx context.Context) DatabaseAccessMode
RequestDatabaseAccessModeFromContext returns the principal's DatabaseAccessMode from context, or nil.
type DbPrivilege ¶
DbPrivilege holds read/write for one (role, database).
type Entitlement ¶
type Entitlement struct {
ID string `json:"id"` // Stable ID (e.g. "read", "database_write")
Name string `json:"name"` // Display name
Description string `json:"description"` // What this entitlement gates
Category EntitlementCategory `json:"category"` // global or per_database
}
Entitlement describes a single assignable permission or right.
func AllEntitlements ¶
func AllEntitlements() []Entitlement
AllEntitlements returns the full list of entitlements with descriptions. Use this for UI (assign entitlements to roles), APIs (GET /auth/entitlements), and documentation. Global entitlements map to Permission; per-database entitlements map to allowlist (see/access) and privileges matrix (read/write).
type EntitlementCategory ¶
type EntitlementCategory string
EntitlementCategory indicates whether an entitlement is global or per-database.
const ( EntitlementCategoryGlobal EntitlementCategory = "global" EntitlementCategoryPerDatabase EntitlementCategory = "per_database" )
type FineGrainedAccess ¶
type FineGrainedAccess struct {
// contains filtered or unexported fields
}
FineGrainedAccess holds the compiled policy for one executing principal.
func (FineGrainedAccess) Allows ¶
func (a FineGrainedAccess) Allows(actionID string, resource FineGrainedResource) bool
Allows checks one action on a fully resolved resource. An applicable deny overrides a grant. Unknown actions and incomplete targets are denied.
func (FineGrainedAccess) AllowsAllDatabases ¶
func (a FineGrainedAccess) AllowsAllDatabases(actionID string) bool
AllowsAllDatabases requires a wildcard database grant and rejects every applicable denial. It is used for operations whose target is the full database population, including databases added while background work runs.
func (FineGrainedAccess) AllowsEntireGraphAction ¶
func (a FineGrainedAccess) AllowsEntireGraphAction(actionID, databaseID, homeDatabaseID string) bool
AllowsEntireGraphAction reports whether a grant covers every entity and property in a database for this action, with no applicable denials.
func (FineGrainedAccess) Decision ¶
func (a FineGrainedAccess) Decision(actionID string, resource FineGrainedResource) (allowed, denied bool)
Decision distinguishes an explicit deny from the absence of a grant. A compound operation may combine grants but must apply explicit denials.
func (FineGrainedAccess) Rules ¶
func (a FineGrainedAccess) Rules() []FineGrainedEntitlement
Rules returns a detached list of the effective principal's assigned rules, including applicable denials. A decision still requires a concrete target.
type FineGrainedAccount ¶
type FineGrainedAccount struct {
Name string
Password string
PasswordChangeRequired bool
Suspended bool
HomeDatabase string
Providers map[string]string
}
FineGrainedAccount is the account state one CREATE USER statement declares.
type FineGrainedAction ¶
type FineGrainedAction struct {
ID string `json:"id"`
ResourceKind FineGrainedResourceKind `json:"resourceKind"`
Property bool `json:"property,omitempty"`
Creates bool `json:"creates,omitempty"`
}
FineGrainedAction is the scope contract registered by an operation owner. Property actions must receive one concrete property key per decision.
func FineGrainedAdministrationActions ¶
func FineGrainedAdministrationActions() []FineGrainedAction
FineGrainedAdministrationActions is the operation inventory for database schema, name tokens, security administration and database administration.
func FineGrainedCoreActions ¶
func FineGrainedCoreActions() []FineGrainedAction
FineGrainedCoreActions returns the storage and administration contracts.
func GraphFineGrainedActions ¶
func GraphFineGrainedActions() []FineGrainedAction
GraphFineGrainedActions returns the action contracts used to define graph entitlements. A node and a relationship use separate action IDs so that an operator can delegate either kind without granting the other.
type FineGrainedAuthRule ¶
type FineGrainedAuthRule struct {
Name string `json:"name"`
Condition string `json:"condition"`
Enabled bool `json:"enabled"`
Roles []string `json:"roles,omitempty"`
}
FineGrainedAuthRule grants its roles to authenticated users for whom an enabled condition evaluates to true.
type FineGrainedAuthRuleCompiler ¶
type FineGrainedAuthRuleCompiler func(string) (FineGrainedAuthRuleCondition, error)
FineGrainedAuthRuleCompiler validates and compiles an authorization condition.
type FineGrainedAuthRuleCondition ¶
type FineGrainedAuthRuleCondition func(FineGrainedAuthRuleInput) bool
FineGrainedAuthRuleCondition evaluates a compiled, graph-independent rule.
type FineGrainedAuthRuleInput ¶
type FineGrainedAuthRuleInput struct {
Context context.Context
NativeTags []string
Claims map[string]any
Now time.Time
}
FineGrainedAuthRuleInput is the identity information visible to a rule condition. Claims come from a verified identity provider at admission. Nil collections denote unavailable providers; empty collections denote available providers that supplied no tags or claims.
type FineGrainedCatalog ¶
type FineGrainedCatalog struct {
Definitions []FineGrainedEntitlement `json:"definitions"`
Assignments map[string][]string `json:"assignments"`
Privileges []FineGrainedPrivilege `json:"privileges,omitempty"`
AuthRules []FineGrainedAuthRule `json:"authRules,omitempty"`
}
FineGrainedCatalog is persisted independently of legacy coarse grants. Role names refer to the existing RBAC role records.
func DefaultFineGrainedCatalog ¶
func DefaultFineGrainedCatalog(actions []FineGrainedAction) FineGrainedCatalog
DefaultFineGrainedCatalog explicitly grants the registered actions to the installation administrator on first activation.
type FineGrainedCredentialsExpired ¶
type FineGrainedCredentialsExpired struct{}
FineGrainedCredentialsExpired signals an authenticated native account that must change its password before entering ordinary execution.
func (*FineGrainedCredentialsExpired) BoltErrorCode ¶
func (*FineGrainedCredentialsExpired) BoltErrorCode() string
func (*FineGrainedCredentialsExpired) Error ¶
func (*FineGrainedCredentialsExpired) Error() string
type FineGrainedDatabaseIdentity ¶
FineGrainedDatabaseIdentity resolves a canonical database name to its stable database identifier. An empty result means that the target cannot be resolved.
type FineGrainedEntitlement ¶
type FineGrainedEntitlement struct {
ID string `json:"id"`
Action string `json:"action"`
Scope FineGrainedScope `json:"scope"`
Deny bool `json:"deny,omitempty"`
}
FineGrainedEntitlement is a named, reusable binding of an action and scope. Separate definitions let a role grant traversal and only selected properties.
type FineGrainedPermissionError ¶
type FineGrainedPermissionError struct{}
FineGrainedPermissionError maps operation denials to the normal transport status without including hidden data or the entire policy in the error.
func (*FineGrainedPermissionError) BoltErrorCode ¶
func (*FineGrainedPermissionError) BoltErrorCode() string
func (*FineGrainedPermissionError) Error ¶
func (*FineGrainedPermissionError) Error() string
type FineGrainedPolicy ¶
type FineGrainedPolicy struct {
// contains filtered or unexported fields
}
FineGrainedPolicy is an immutable, compiled catalog. Bind it to the previously resolved roles of the executing principal before evaluation.
func CompileFineGrainedPolicy ¶
func CompileFineGrainedPolicy(actions []FineGrainedAction, catalog FineGrainedCatalog) (*FineGrainedPolicy, error)
CompileFineGrainedPolicy validates the full catalog against the registered operation contracts. A role referring to an unknown definition is invalid.
For example, register graph.node.property.read as a node property action and give the reviewers role a definition scoped to the title property.
func (*FineGrainedPolicy) ForRoles ¶
func (p *FineGrainedPolicy) ForRoles(roles []string) FineGrainedAccess
ForRoles resolves the union of the given roles once for a request or other admitted work. Built-in names confer only their explicit assignments.
type FineGrainedPredicate ¶
type FineGrainedPredicate struct {
Property string `json:"property"`
Operator string `json:"operator"`
Value any `json:"value,omitempty"`
}
FineGrainedPredicate compares one stored property to literal values. For example, use Property "status", Operator "=", and Value "published". A read action can have a predicate even when it does not expose the property being tested to the caller.
type FineGrainedPrivilege ¶
type FineGrainedPrivilege struct {
Key string `json:"key"`
Role string `json:"role"`
Name string `json:"name"`
Graph string `json:"graph"`
Segment string `json:"segment"`
Resource string `json:"resource"`
Clause string `json:"clause"`
Deny bool `json:"deny,omitempty"`
Immutable bool `json:"immutable,omitempty"`
Entitlements []FineGrainedEntitlement `json:"entitlements"`
}
FineGrainedPrivilege is a Cypher-administered, role-owned security record. Entitlements are its evaluated constituents. The declarative fields retain enough information for SHOW PRIVILEGES and restore through Cypher commands.
type FineGrainedProviderChange ¶
FineGrainedProviderChange is a single ALTER USER provider transition. Removal is applied before new bindings are assigned.
type FineGrainedProviderSession ¶
type FineGrainedProviderSession struct {
// contains filtered or unexported fields
}
FineGrainedProviderSession is a verified, principal-bound provider session. Its attributes are available to authorization rules in the same session.
func (*FineGrainedProviderSession) WithContext ¶
func (session *FineGrainedProviderSession) WithContext(ctx context.Context) context.Context
WithContext carries a verified external identity to FGAC admission. A nil session leaves the context untouched.
type FineGrainedRequest ¶
type FineGrainedRequest struct {
Access FineGrainedAccess
DatabaseID FineGrainedDatabaseIdentity
HomeDatabaseID string
HomeDatabaseName string
PasswordChangeRequired bool
Runtime *FineGrainedRuntime
Fingerprint string
// contains filtered or unexported fields
}
FineGrainedRequest binds a catalog snapshot to a principal and a catalog identity resolver for a request.
func FineGrainedRequestFromContext ¶
func FineGrainedRequestFromContext(ctx context.Context) *FineGrainedRequest
FineGrainedRequestFromContext returns the request's fine-grained principal, when enabled by the request owner.
func (*FineGrainedRequest) AccessHash ¶
func (r *FineGrainedRequest) AccessHash() ([32]byte, error)
AccessHash identifies the effective grant rules for a retained read view. It keeps two requests with a reused revision string but different grants from sharing cached rows or admission decisions.
func (*FineGrainedRequest) AllowsAllEntities ¶
func (r *FineGrainedRequest) AllowsAllEntities(action, database string) bool
AllowsAllEntities checks for complete access to one kind of entity in the database. Feeds with IDs only require this proof because a deleted record cannot be evaluated against its former labels and properties.
func (*FineGrainedRequest) AllowsDBMS ¶
func (r *FineGrainedRequest) AllowsDBMS(action string, target string) bool
AllowsDBMS checks an operation that affects the server rather than a database.
func (*FineGrainedRequest) AllowsDatabase ¶
func (r *FineGrainedRequest) AllowsDatabase(action, database, property string) bool
AllowsDatabase checks a capability on a canonical database target.
func (*FineGrainedRequest) AllowsDatabaseIdentity ¶
func (r *FineGrainedRequest) AllowsDatabaseIdentity(action, databaseID, property string) bool
AllowsDatabaseIdentity checks a capability against a captured database ID.
func (*FineGrainedRequest) AllowsManagedEmbedding ¶
func (r *FineGrainedRequest) AllowsManagedEmbedding(database string, node *storage.Node, input storage.EmbeddingTextPolicy, allProperties bool) bool
AllowsManagedEmbedding checks the actual labels and fields a provider consumes, plus the target's managed-vector write privilege.
func (*FineGrainedRequest) AllowsNodeIndexPopulation ¶
func (r *FineGrainedRequest) AllowsNodeIndexPopulation(database, label, property string) bool
AllowsNodeIndexPopulation proves that a stored property posting cannot expose a node or value hidden from this principal. An index seek may inspect posting counts before it hydrates any node, so checking only the returned node's permission would disclose hidden matches through plan and timing. Conditional, entity-specific, and denied grants retain the scoped scan.
func (*FineGrainedRequest) CanAccessDatabase ¶
func (r *FineGrainedRequest) CanAccessDatabase(database string) bool
GraphAccessMode is the coarse database-selection adapter. Entity and operation decisions still use the same fine-grained request in execution.
func (*FineGrainedRequest) CanSeeDatabase ¶
func (r *FineGrainedRequest) CanSeeDatabase(database string) bool
CanSeeDatabase limits database discovery to the principal's accessible databases. The metadata database remains available for SHOW CURRENT USER.
func (*FineGrainedRequest) EffectiveRoles ¶
func (r *FineGrainedRequest) EffectiveRoles() []string
EffectiveRoles returns the direct and rule-assigned roles in this admission.
func (*FineGrainedRequest) Graph ¶
Graph binds graph operations to the same policy for both point and population reads. The supplied engine determines the transaction snapshot.
func (*FineGrainedRequest) GraphMatches ¶
func (r *FineGrainedRequest) GraphMatches(view, engine storage.Engine, database string) bool
GraphMatches reports whether view already protects the given graph engine under this request. The execution owner reuses that view for one statement.
func (*FineGrainedRequest) IsImpersonated ¶
func (r *FineGrainedRequest) IsImpersonated() bool
IsImpersonated reports that the request executes as another account.
func (*FineGrainedRequest) Revalidate ¶
func (r *FineGrainedRequest) Revalidate(ctx context.Context, identity RequestIdentity) error
Revalidate checks that a retained operation still has its original policy and role membership before publishing further results.
func (*FineGrainedRequest) WithBoostedProcedure ¶
func (r *FineGrainedRequest) WithBoostedProcedure(database, procedure string) *FineGrainedRequest
WithBoostedProcedure binds the graph privileges of one explicitly authorized procedure invocation to its selected database. Database and feature grants outside the Neo4j graph and token actions continue to use the caller's roles.
type FineGrainedResource ¶
type FineGrainedResource struct {
Kind FineGrainedResourceKind
DatabaseID string
HomeDatabaseID string
Types []string
EntityID string
CreatingEntity bool
Property string
// EntityProperties is the authoritative image used by property predicates.
EntityProperties map[string]any
}
FineGrainedResource is the resolved target of one operation. The operation owner supplies stable IDs and actual labels/types, not caller assertions.
type FineGrainedResourceKind ¶
type FineGrainedResourceKind string
FineGrainedResourceKind identifies the namespace of an authorized target.
const ( FineGrainedDBMS FineGrainedResourceKind = "dbms" FineGrainedDatabase FineGrainedResourceKind = "database" FineGrainedNode FineGrainedResourceKind = "node" FineGrainedRelationship FineGrainedResourceKind = "relationship" )
type FineGrainedRuntime ¶
type FineGrainedRuntime struct {
// contains filtered or unexported fields
}
FineGrainedRuntime admits authenticated principals against the same committed policy store used by the catalog editor and role administration.
func NewFineGrainedRuntime ¶
func NewFineGrainedRuntime(roles *RoleStore, actions []FineGrainedAction, databaseID FineGrainedDatabaseIdentity, home func() string) *FineGrainedRuntime
NewFineGrainedRuntime binds the policy store to the set of operations implemented by the server and its database manager.
func (*FineGrainedRuntime) Actions ¶
func (runtime *FineGrainedRuntime) Actions() []FineGrainedAction
Actions returns the operations registered by this FGAC runtime.
func (*FineGrainedRuntime) Admit ¶
func (runtime *FineGrainedRuntime) Admit(ctx context.Context, roles []string) (*FineGrainedRequest, error)
Admit reads the committed revision and captures its immutable policy for the authenticated roles. Unknown or unreadable policy prevents admission.
func (*FineGrainedRuntime) AlterUser ¶
func (runtime *FineGrainedRuntime) AlterUser(ctx context.Context, username string, change FineGrainedUserAlteration) error
AlterUser applies every declared ALTER USER clause in one user-record transaction, so no reader observes a partly altered account.
func (*FineGrainedRuntime) ChangeOwnPassword ¶
func (runtime *FineGrainedRuntime) ChangeOwnPassword(ctx context.Context, username, current, replacement string) error
ChangeOwnPassword uses the same verified current-password mutation as HTTP.
func (*FineGrainedRuntime) ChangeUserTags ¶
func (runtime *FineGrainedRuntime) ChangeUserTags(ctx context.Context, names []string, change FineGrainedTagChange, tags []string, ifExists bool) error
ChangeUserTags writes all selected native users in one system transaction. Tags are security metadata and use the same publication order as roles.
func (*FineGrainedRuntime) CreateRole ¶
func (runtime *FineGrainedRuntime) CreateRole(ctx context.Context, role string) error
CreateRole creates a role in the shared security directory.
func (*FineGrainedRuntime) CreateRoleCopy ¶
func (runtime *FineGrainedRuntime) CreateRoleCopy(ctx context.Context, role, source string) error
CreateRoleCopy creates a role that starts with the persisted privileges and assignments of another role. The role record and every copied catalog record commit in one transaction through the role-record owners, so a concurrent delete or rename of the source cannot leave a half-copied role. A source role that does not exist refuses the statement.
func (*FineGrainedRuntime) CreateUser ¶
func (runtime *FineGrainedRuntime) CreateUser(ctx context.Context, name, password string, passwordChangeRequired bool) error
CreateUser creates a native user in the directory used by authentication.
func (*FineGrainedRuntime) CreateUserAccount ¶
func (runtime *FineGrainedRuntime) CreateUserAccount(ctx context.Context, account FineGrainedAccount) error
CreateUserAccount creates one native account with every declared clause applied by the single user-record write: the password, its change requirement, the login state and the home database publish together.
func (*FineGrainedRuntime) DeleteUser ¶
func (runtime *FineGrainedRuntime) DeleteUser(ctx context.Context, name string) error
DeleteUser deletes a native user and invalidates their authenticated state.
func (*FineGrainedRuntime) DropRole ¶
func (runtime *FineGrainedRuntime) DropRole(ctx context.Context, role string) error
DropRole removes a role, its privileges and its user memberships.
func (*FineGrainedRuntime) EditCatalog ¶
func (runtime *FineGrainedRuntime) EditCatalog(ctx context.Context, edit func(*FineGrainedCatalog) error) error
EditCatalog applies a security administration command to the current catalog. An edit racing a different editor reports a conflict.
func (*FineGrainedRuntime) Impersonate ¶
func (runtime *FineGrainedRuntime) Impersonate(ctx context.Context, actor *FineGrainedRequest, username string) (*FineGrainedRequest, *User, error)
Impersonate resolves an authorized, active native account and admits its roles. The actor's grants never enter the impersonated request.
func (*FineGrainedRuntime) ReadCatalog ¶
func (runtime *FineGrainedRuntime) ReadCatalog(ctx context.Context) (FineGrainedCatalog, string, error)
ReadCatalog returns the committed catalog and the revision used to edit it.
func (*FineGrainedRuntime) RenameRole ¶
func (runtime *FineGrainedRuntime) RenameRole(ctx context.Context, role, name string) error
RenameRole renames a role and all security records that reference it.
func (*FineGrainedRuntime) RenameUser ¶
func (runtime *FineGrainedRuntime) RenameUser(ctx context.Context, username, next string) error
RenameUser changes the stored login name and removes the old key atomically. The stable account ID and its role assignments stay with the account.
func (*FineGrainedRuntime) ReplaceCatalog ¶
func (runtime *FineGrainedRuntime) ReplaceCatalog(ctx context.Context, revision string, catalog FineGrainedCatalog) error
ReplaceCatalog persists an authorized edit while preserving the built-in administrator's ability to manage the policy.
func (*FineGrainedRuntime) RoleNames ¶
func (runtime *FineGrainedRuntime) RoleNames() []string
RoleNames returns the same role catalog used by HTTP administration.
func (*FineGrainedRuntime) SetAuthRuleCompiler ¶
func (runtime *FineGrainedRuntime) SetAuthRuleCompiler(compiler FineGrainedAuthRuleCompiler)
SetAuthRuleCompiler binds the Cypher condition compiler before serving.
func (*FineGrainedRuntime) SetAuthRuleCompilerContext ¶
func (runtime *FineGrainedRuntime) SetAuthRuleCompilerContext(compiler func(context.Context, string) (FineGrainedAuthRuleCondition, error))
SetAuthRuleCompilerContext binds a compiler that uses the caller's context.
func (*FineGrainedRuntime) SetNativeTagAuthorization ¶
func (runtime *FineGrainedRuntime) SetNativeTagAuthorization(enabled bool)
SetNativeTagAuthorization enables policy evaluation of native user tags.
func (*FineGrainedRuntime) SetPrivateDatabaseOwner ¶
func (runtime *FineGrainedRuntime) SetPrivateDatabaseOwner(owner func(string) string)
SetPrivateDatabaseOwner binds the directory's private-database lookup before requests can be admitted.
func (*FineGrainedRuntime) SetRoleMembership ¶
func (runtime *FineGrainedRuntime) SetRoleMembership(ctx context.Context, users, roles []string, assign bool) error
SetRoleMembership changes every cited user in the same system transaction. The role and user write owners serialize it with other directory mutations.
func (*FineGrainedRuntime) SetSecurityDirectory ¶
func (runtime *FineGrainedRuntime) SetSecurityDirectory(users *Authenticator, stores RoleMutationStores)
SetSecurityDirectory attaches the server's authoritative role and user stores before the runtime is published to request handlers.
func (*FineGrainedRuntime) SetUserHome ¶
func (runtime *FineGrainedRuntime) SetUserHome(ctx context.Context, username, database string) error
SetUserHome changes the account-specific database selected when no database is named. An empty name restores selection of the installation default.
func (*FineGrainedRuntime) SetUserPassword ¶
func (runtime *FineGrainedRuntime) SetUserPassword(ctx context.Context, username string, password *string, changeRequired bool) error
SetUserPassword updates a native secret or its change-required state.
func (*FineGrainedRuntime) SetUserSuspended ¶
func (runtime *FineGrainedRuntime) SetUserSuspended(ctx context.Context, username string, suspended bool) error
SetUserSuspended applies the security directory's normal login state change.
func (*FineGrainedRuntime) UserProviders ¶
func (runtime *FineGrainedRuntime) UserProviders(ctx context.Context) ([]FineGrainedUserProvider, error)
UserProviders returns the configured providers of the current user directory for an administrator authorized to list users.
func (*FineGrainedRuntime) UserTags ¶
func (runtime *FineGrainedRuntime) UserTags(username string) []string
UserTags returns the native directory's security metadata for an authorized SHOW USERS projection. Disabled users still have tags.
func (*FineGrainedRuntime) Users ¶
func (runtime *FineGrainedRuntime) Users() []*User
Users returns the directory's public user records for SHOW ROLE WITH USERS.
func (*FineGrainedRuntime) ValidateAdministrator ¶
func (runtime *FineGrainedRuntime) ValidateAdministrator(catalog FineGrainedCatalog) error
ValidateAdministrator checks the policy-management grant on deployments where the policy-management action is registered.
func (*FineGrainedRuntime) ValidateAdministratorContext ¶
func (runtime *FineGrainedRuntime) ValidateAdministratorContext(ctx context.Context, catalog FineGrainedCatalog) error
ValidateAdministratorContext validates the administrator policy using ctx.
type FineGrainedScope ¶
type FineGrainedScope struct {
Kind FineGrainedResourceKind `json:"kind"`
DatabaseID string `json:"databaseId,omitempty"`
HomeDatabase bool `json:"homeDatabase,omitempty"`
Types []string `json:"types,omitempty"`
EntityIDs []string `json:"entityIds,omitempty"`
Properties []string `json:"properties,omitempty"`
Predicate *FineGrainedPredicate `json:"predicate,omitempty"`
PropertyPatterns []string `json:"propertyPatterns,omitempty"`
}
FineGrainedScope selects resources of one kind. An empty database ID selects all databases and is inherent for DBMS actions. Empty selector lists select all values in that dimension. Populated dimensions intersect. Types are node labels or relationship types, matched exactly.
type FineGrainedTagChange ¶
type FineGrainedTagChange uint8
FineGrainedTagChange selects one documented native user tag operation.
const ( ReplaceFineGrainedTags FineGrainedTagChange = iota + 1 AddFineGrainedTags RemoveFineGrainedTags )
type FineGrainedUserAlteration ¶
type FineGrainedUserAlteration struct {
Password *string
PasswordChangeRequired *bool
Suspended *bool
HomeDatabase *string
Providers *FineGrainedProviderChange
}
FineGrainedUserAlteration is one ALTER USER statement's clauses. A nil field is a clause the statement did not write, so that part of the account keeps its stored value.
type FineGrainedUserProvider ¶
type FineGrainedUserProvider struct {
User *User
Name string
Subject string
HasNative bool
PasswordChangeRequired bool
}
FineGrainedUserProvider is the authorized SHOW USERS WITH AUTH row. The native row describes account state without including credential material.
type JWTClaims ¶
type JWTClaims struct {
Sub string `json:"sub"` // Subject (user ID)
Email string `json:"email,omitempty"` // User email
Username string `json:"username,omitempty"` // Username
Roles []string `json:"roles"` // User roles
Iat int64 `json:"iat"` // Issued at (Unix timestamp)
Exp int64 `json:"exp,omitempty"` // Expiration (Unix timestamp, 0 = never)
JTI string `json:"jti,omitempty"`
// contains filtered or unexported fields
}
JWTClaims represents the claims in a JWT token. Standard JWT claims structure.
type OAuthConfig ¶
type OAuthConfig struct {
Provider string // "oauth" to enable
Issuer string // OAuth provider base URL
ClientID string // OAuth client ID
ClientSecret string // OAuth client secret
CallbackURL string // OAuth callback URL
}
OAuthConfig holds OAuth provider configuration.
func GetOAuthConfig ¶
func GetOAuthConfig() *OAuthConfig
GetConfig returns the current OAuth configuration from environment variables.
func (*OAuthConfig) IsConfigured ¶
func (c *OAuthConfig) IsConfigured() bool
IsConfigured checks if OAuth is properly configured.
type OAuthManager ¶
type OAuthManager struct {
// contains filtered or unexported fields
}
OAuthManager manages OAuth 2.0 authentication flow and token validation.
func NewOAuthManager ¶
func NewOAuthManager(authenticator *Authenticator) *OAuthManager
NewOAuthManager creates a new OAuth manager.
func (*OAuthManager) ExchangeCode ¶
func (m *OAuthManager) ExchangeCode(code string) (_ *OAuthTokenData, err error)
ExchangeCode exchanges an authorization code for an access token.
func (*OAuthManager) GenerateAuthURL ¶
func (m *OAuthManager) GenerateAuthURL(baseURL string) (string, string, error)
GenerateAuthURL generates an OAuth authorization URL and stores state for CSRF protection. Returns the state parameter and the authorization URL.
func (*OAuthManager) GetUserInfo ¶
func (m *OAuthManager) GetUserInfo(accessToken string) (*OAuthUserInfo, error)
GetUserInfo retrieves user information from the OAuth provider.
func (*OAuthManager) HandleCallback ¶
func (m *OAuthManager) HandleCallback(ctx context.Context, code, state string) (*User, string, time.Time, error)
HandleCallback handles the OAuth callback, exchanges code for token, gets user info, and creates/updates the NornicDB user account. Returns the user, NornicDB JWT token, and OAuth token expiry time.
ctx is the callback request's lifetime and reaches the account write it owns: a canceled callback does not create an account or persist OAuth token metadata. The metadata refresh after a successful account create stays best-effort; the callback reports the account outcome, not that refresh.
func (*OAuthManager) RefreshOAuthToken ¶
func (m *OAuthManager) RefreshOAuthToken(user *User, refreshToken string) (err error)
RefreshOAuthToken attempts to refresh an expired OAuth access token using a refresh token.
func (*OAuthManager) ValidateOAuthToken ¶
func (m *OAuthManager) ValidateOAuthToken(user *User) error
ValidateOAuthToken validates that an OAuth user's OAuth access token is still valid by calling the OAuth provider's userinfo endpoint.
func (*OAuthManager) ValidateState ¶
func (m *OAuthManager) ValidateState(state string) error
ValidateState validates an OAuth state parameter and removes it (one-time use).
type OAuthTokenData ¶
type OAuthTokenData struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
Scope string `json:"scope"`
RefreshToken string `json:"refresh_token,omitempty"`
}
OAuthTokenData represents an OAuth access token response.
type OAuthUserInfo ¶
type OAuthUserInfo struct {
Sub string `json:"sub"`
Email string `json:"email"`
PreferredUsername string `json:"preferred_username"`
Roles []string `json:"roles"`
// contains filtered or unexported fields
}
OAuthUserInfo represents user information from OAuth provider.
type PasskeyInfo ¶
PasskeyInfo is safe to return to the account owner for credential management.
type Permission ¶
type Permission string
Permission represents an action that can be performed.
const ( PermRead Permission = "read" PermWrite Permission = "write" PermCreate Permission = "create" PermDelete Permission = "delete" PermAdmin Permission = "admin" PermSchema Permission = "schema" PermUserManage Permission = "user_manage" )
Permissions map to Neo4j-compatible actions.
type PrivilegeDatabaseRef ¶
type PrivilegeDatabaseRef struct {
Name string // Normalized database name, e.g. "nornic", "system"
OwningDatabaseName string // For composite/sharded; empty or Name for normal DBs
}
PrivilegeDatabaseRef identifies the database for privilege checks. Equivalent to Neo4j PrivilegeDatabaseReference (name, owningDatabaseName). For normal (non-composite) databases, Name and OwningDatabaseName are the same.
type PrivilegesStore ¶
type PrivilegesStore struct {
// contains filtered or unexported fields
}
PrivilegesStore persists and resolves per (role, database) read/write.
func NewPrivilegesStore ¶
func NewPrivilegesStore(systemStorage storage.Engine) *PrivilegesStore
NewPrivilegesStore creates a store that reads/writes _DbPrivilege nodes.
func (*PrivilegesStore) Granted ¶
func (p *PrivilegesStore) Granted(roles []string, database string) (ResolvedAccess, bool)
Granted is the read and write the privileges matrix records for roles on database, the union of their entries, and whether any of the roles has an entry there. A nil store records none.
func (*PrivilegesStore) Load ¶
func (p *PrivilegesStore) Load(ctx context.Context) error
Load reads all _DbPrivilege nodes from storage into memory.
func (*PrivilegesStore) Matrix ¶
func (p *PrivilegesStore) Matrix() []struct { Role string `json:"role"` Database string `json:"database"` Read bool `json:"read"` Write bool `json:"write"` }
Matrix returns a copy of the full matrix for GET API.
func (*PrivilegesStore) PutMatrix ¶
func (p *PrivilegesStore) PutMatrix(ctx context.Context, entries []struct { Role string `json:"role"` Database string `json:"database"` Read bool `json:"read"` Write bool `json:"write"` }) error
PutMatrix replaces the stored matrix with the given list (for PUT /auth/access/privileges): it deletes every _DbPrivilege node and creates one per entry, in one transaction through the role-record owner, so the matrix changes entirely or not at all, and every entry's role must exist.
func (*PrivilegesStore) Resolve
deprecated
func (p *PrivilegesStore) Resolve(principalRoles []string, dbName string) ResolvedAccess
Resolve preserves the legacy database-access contract: explicit matrix grants win, otherwise built-in role permissions supply the defaults. For example, store.Resolve([]string{"viewer"}, "reports") returns that role's matrix grant when present, even if it differs from the role's global entitlements.
Deprecated: production authorization should use ResolveDatabaseAccess with the stored entitlement policy; Resolve intentionally retains legacy semantics.
func (*PrivilegesStore) SavePrivilege ¶
func (p *PrivilegesStore) SavePrivilege(ctx context.Context, role, dbName string, read, write bool) error
SavePrivilege persists one (role, database, read, write) and refreshes in-memory, through the role-record owner (WithRoleRecords). The role must exist (ErrRoleNotFound).
type ProcedurePrivilege ¶
ProcedurePrivilege is one EXECUTE grant: Role may run the procedures Procedure (a name or glob) names; Boosted lifts their administrator requirement; Immutable marks a grant made with GRANT IMMUTABLE.
type ProcedurePrivilegeStore ¶
type ProcedurePrivilegeStore struct {
// contains filtered or unexported fields
}
ProcedurePrivilegeStore reads and writes procedure grants in the system database (or in an explicit transaction's view of it).
func NewProcedurePrivilegeStore ¶
func NewProcedurePrivilegeStore(systemStorage storage.Engine) *ProcedurePrivilegeStore
NewProcedurePrivilegeStore creates a store over the system database.
func (*ProcedurePrivilegeStore) AllowsBoosted ¶
func (p *ProcedurePrivilegeStore) AllowsBoosted(roles []string, procedure string) (bool, error)
AllowsBoosted reports whether any of roles holds a boosted grant whose name or glob matches procedure: a principal's privileges are the union of its roles'. When the grants can't be read it denies, and returns the error.
func (*ProcedurePrivilegeStore) Grant ¶
func (p *ProcedurePrivilegeStore) Grant(ctx context.Context, role, procedure string, boosted, immutable bool) error
Grant records that role may execute the procedures procedure names (boosted or not). As in Neo4j, a role holds one such grant: granting it again changes nothing, except that GRANT IMMUTABLE makes a regular grant immutable.
func (*ProcedurePrivilegeStore) List ¶
func (p *ProcedurePrivilegeStore) List(ctx context.Context) ([]ProcedurePrivilege, error)
List returns every grant, in role, procedure order. Both the read and its own work over the read's rows run on ctx, the caller's lifetime: a canceled caller gets its cancellation and no grants, never the part it had converted or sorted.
func (*ProcedurePrivilegeStore) Lookup ¶
func (p *ProcedurePrivilegeStore) Lookup(ctx context.Context, role, procedure string, boosted bool) (ProcedurePrivilege, bool, error)
Lookup returns role's grant for procedure (boosted or not), if it holds one. A read that fails is an error, never "no grant".
func (*ProcedurePrivilegeStore) Revoke ¶
func (p *ProcedurePrivilegeStore) Revoke(ctx context.Context, role, procedure string, boosted, immutableOnly bool) (bool, error)
Revoke removes role's grant for procedure (boosted or not), and reports whether there was one. With immutableOnly (REVOKE IMMUTABLE) it removes only an immutable grant, as Neo4j does; without, either.
type RequestDatabaseScope ¶ added in v1.3.1
type RequestDatabaseScope struct {
// contains filtered or unexported fields
}
RequestDatabaseScope is the server-derived set of database names and aliases available to a request. A live selection check can restrict these catalog names.
func NewRequestDatabaseScope ¶ added in v1.3.1
func NewRequestDatabaseScope(defaultDatabase string, selections map[string]string) *RequestDatabaseScope
NewRequestDatabaseScope constructs an immutable request scope. Selection keys are normalized for lookup and the supplied map is defensively copied.
func NewRequestDatabaseScopeWithSelectionCheck ¶
func NewRequestDatabaseScopeWithSelectionCheck(defaultDatabase string, selections map[string]string, check func(string) bool) *RequestDatabaseScope
NewRequestDatabaseScopeWithSelectionCheck binds the existing live graph-selection owner. Catalog aliases do not confer authority, and later grants/revocations are observed without rebuilding the request context.
func RequestDatabaseScopeFromContext ¶ added in v1.3.1
func RequestDatabaseScopeFromContext(ctx context.Context) *RequestDatabaseScope
RequestDatabaseScopeFromContext returns the server-derived database scope.
type RequestEntitlementResolver ¶ added in v1.3.1
type RequestEntitlementResolver func(database string, permission Permission) bool
RequestEntitlementResolver checks an effective permission for a database.
func RequestEntitlementResolverFromContext ¶ added in v1.3.1
func RequestEntitlementResolverFromContext(ctx context.Context) RequestEntitlementResolver
RequestEntitlementResolverFromContext returns the effective entitlement resolver.
type RequestIdentity ¶
RequestIdentity is projected only from verified authentication by the host. It carries identity, not a second permission decision.
func RequestIdentityFromContext ¶
func RequestIdentityFromContext(ctx context.Context) RequestIdentity
type ResolvedAccess ¶
type ResolvedAccess struct {
Read bool // Allow MATCH, read properties, etc.
Write bool // Allow CREATE, DELETE, SET, MERGE, etc.
}
ResolvedAccess is the resolved read/write capability for a (principal, database). Equivalent to Neo4j AccessMode for a single DB. Used for execution-time mutation checks: Write must be true to allow CREATE, DELETE, SET, MERGE, etc.
func ResolveDatabaseAccess ¶
func ResolveDatabaseAccess(roles []string, database string, privileges *PrivilegesStore, entitlements *RoleEntitlementsStore) ResolvedAccess
ResolveDatabaseAccess is the one resolver of a principal's read and write on a database, which HTTP, Bolt, gRPC, GraphQL, MCP and plugins all use (through cypher.PrincipalAccess or the server's resolved-access resolver). The roles' global entitlements (PermissionsForRoles: stored overrides, else the built-in roles' defaults) gate it: the read entitlement is what lets a principal use a database at all, and write needs the write entitlement too. Within that, the privileges matrix decides when any of the roles has an entry for the database; otherwise the entitlements decide alone. So removing a role's write entitlement stops its writes on every database at once.
type RevocationReceipt ¶
type RevocationReceipt struct {
ID string `json:"id"`
Scope string `json:"scope"`
RevokedAt time.Time `json:"revoked_at"`
TokenExpiresAt int64 `json:"token_expires_at,omitempty"`
}
RevocationReceipt identifies a committed revocation without carrying a credential.
type Role ¶
type Role string
Role represents a user role with associated permissions.
const ( RoleAdmin Role = "admin" // Full access including user management RoleEditor Role = "editor" // Read/write data RoleViewer Role = "viewer" // Read only (default) RoleNone Role = "none" // No access )
Predefined roles following Neo4j conventions.
func ConvertOAuthRoles ¶
ConvertOAuthRoles converts OAuth role strings to auth.Role enum.
func RoleFromString ¶
RoleFromString converts a string to a Role.
type RoleCatalogSnapshot ¶
RoleCatalogSnapshot contains independently owned role metadata. Overrides contain stored entitlement IDs; PermissionsForRole resolves effective grants.
func ReadRoleCatalog ¶
func ReadRoleCatalog(roles *RoleStore, entitlements *RoleEntitlementsStore) RoleCatalogSnapshot
ReadRoleCatalog reads each supplied store under its own read lock. Pass nil for a view that is not needed; its result field remains nil. Role names keep built-ins first and sort user-defined names. Maps and slices belong to the caller.
Example:
catalog := auth.ReadRoleCatalog(roleStore, entitlementStore)
for _, name := range catalog.RoleNames {
fmt.Println(name, catalog.EntitlementOverrides[name])
}
type RoleEntitlementsStore ¶
type RoleEntitlementsStore struct {
// contains filtered or unexported fields
}
RoleEntitlementsStore loads and saves role→entitlement IDs (global permissions) in the system database.
func NewRoleEntitlementsStore ¶
func NewRoleEntitlementsStore(systemStorage storage.Engine) *RoleEntitlementsStore
NewRoleEntitlementsStore creates a store that reads/writes role entitlements to the given system storage.
func (*RoleEntitlementsStore) Get ¶
func (r *RoleEntitlementsStore) Get(role string) []string
Get returns the stored entitlement IDs for a role. Returns nil if no override is stored. For permission resolution use PermissionsForRole so built-in roles use RolePermissions when not overridden.
func (*RoleEntitlementsStore) Load ¶
func (r *RoleEntitlementsStore) Load(ctx context.Context) error
Load reads all _RoleEntitlement nodes from storage into memory. Call at startup and after PUT.
func (*RoleEntitlementsStore) Set ¶
func (r *RoleEntitlementsStore) Set(ctx context.Context, role string, entitlementIDs []string) error
Set persists one role's entitlement IDs and refreshes in-memory. Empty list removes the override (a built-in role then uses RolePermissions). The role must exist (ErrRoleNotFound).
func (*RoleEntitlementsStore) SetMappings ¶
func (r *RoleEntitlementsStore) SetMappings(ctx context.Context, mappings map[string][]string) error
SetMappings persists every role's entitlement IDs in one transaction through the role-record owner (WithRoleRecords): all of them are stored, or, when one fails or names a role that doesn't exist, none. The cache changes only after commit.
type RoleMutationStores ¶
type RoleMutationStores struct {
Allowlist *AllowlistStore
Privileges *PrivilegesStore
Entitlements *RoleEntitlementsStore
Users *Authenticator
// contains filtered or unexported fields
}
RoleMutationStores are the loaded caches that must follow a role change. All supplied stores must use the role store's system database.
type RoleNotFoundError ¶
type RoleNotFoundError struct{ Role string }
RoleNotFoundError is ErrRoleNotFound for one role, by the name its caller gave.
func (*RoleNotFoundError) Error ¶
func (e *RoleNotFoundError) Error() string
func (*RoleNotFoundError) Unwrap ¶
func (e *RoleNotFoundError) Unwrap() error
type RoleStore ¶
type RoleStore struct {
// contains filtered or unexported fields
}
RoleStore persists user-defined role names in the system database.
func NewRoleStore ¶
NewRoleStore creates a store that reads/writes _Role nodes in the given system storage.
func (*RoleStore) CreateRole ¶
CreateRole creates a user-defined role. Fails if name is built-in or already exists.
func (*RoleStore) DeleteRole ¶
DeleteRole removes the role, its grants and stored user assignments atomically. Servers use DeleteRoleWithStores to publish their loaded caches after commit.
func (*RoleStore) DeleteRoleWithStores ¶
func (r *RoleStore) DeleteRoleWithStores(ctx context.Context, name string, stores RoleMutationStores) error
DeleteRoleWithStores removes every role-owned record and user assignment in the same transaction owner as rename, publishing loaded caches after commit.
func (*RoleStore) LockRoleForGrant ¶
LockRoleForGrant reads and writes the role record in the grant transaction. Role deletion writes that same record, so their commits serialize: neither can commit from a snapshot that missed the other's role or grant changes.
func (*RoleStore) PrepareFineGrainedCatalog ¶
func (r *RoleStore) PrepareFineGrainedCatalog(ctx context.Context) (FineGrainedCatalog, string, error)
PrepareFineGrainedCatalog reads policy on activation and removes references to roles that no longer have the identity recorded with their assignments.
func (*RoleStore) ReadFineGrainedCatalog ¶
ReadFineGrainedCatalog reads a committed policy document and its revision. An empty revision means that no catalog has been created.
func (*RoleStore) RenameRole ¶
RenameRole moves the role and all its stored grants and assignments atomically. Servers use RenameRoleWithStores to publish their loaded caches after commit.
func (*RoleStore) RenameRoleWithStores ¶
func (r *RoleStore) RenameRoleWithStores(ctx context.Context, oldName, newName string, stores RoleMutationStores) error
RenameRoleWithStores moves every persisted role record and user assignment in one system-store transaction. Loaded caches change only after commit.
func (*RoleStore) RenameRoleWithUsers ¶
func (r *RoleStore) RenameRoleWithUsers(ctx context.Context, oldName, newName string, allowlist *AllowlistStore, users *Authenticator) error
RenameRoleWithUsers retains the caller's loaded allowlist and user caches.
func (*RoleStore) ReplaceFineGrainedCatalog ¶
func (r *RoleStore) ReplaceFineGrainedCatalog(ctx context.Context, expectedRevision string, actions []FineGrainedAction, catalog FineGrainedCatalog) error
ReplaceFineGrainedCatalog validates definitions and role references and persists them as one system transaction if expectedRevision still matches. This is a storage operation. Its caller must authorize policy administration.
Read the current revision before editing. Use an empty expected revision to create the initial catalog.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"` // Always "Bearer"
ExpiresIn int64 `json:"expires_in,omitempty"` // Seconds until expiration (omitted if never expires)
Scope string `json:"scope,omitempty"`
}
TokenResponse follows OAuth 2.0 RFC 6749 token response format. Compatible with standard OAuth 2.0 token endpoints.
type User ¶
type User struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email,omitempty"`
PasswordHash string `json:"-"` // Never serialize
Roles []Role `json:"roles"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastLogin time.Time `json:"last_login,omitempty"`
FailedLogins int `json:"-"` // Internal tracking
LockedUntil time.Time `json:"-"` // Internal tracking
Disabled bool `json:"disabled,omitempty"`
HomeDatabase string `json:"home_database,omitempty"`
PasswordChangeRequired bool `json:"password_change_required,omitempty"`
SecurityTags []string `json:"-"`
Metadata map[string]string `json:"metadata,omitempty"`
// contains filtered or unexported fields
}
User represents an authenticated user account.
Users have:
- Unique ID and username
- Password (hashed with bcrypt, never exposed)
- One or more roles (admin, editor, viewer, none)
- Timestamps for auditing
- Metadata for custom properties
Security features:
- PasswordHash is never serialized (json:"-" tag)
- FailedLogins and LockedUntil track brute force attempts
- Disabled flag allows account suspension
Example:
user := &auth.User{
ID: "usr-abc123",
Username: "alice",
Email: "alice@example.com",
Roles: []auth.Role{auth.RoleEditor},
Metadata: map[string]string{
"department": "Engineering",
"team": "Backend",
},
}
// Check permissions
if user.HasRole(auth.RoleAdmin) {
fmt.Println("User is admin")
}
if user.HasPermission(auth.PermWrite) {
fmt.Println("User can write data")
}
func (*User) HasPermission ¶
func (u *User) HasPermission(perm Permission) bool
HasPermission checks if the user has a specific permission through any of their roles.
Permissions are granted by roles. This method checks all the user's roles and returns true if any role grants the requested permission.
Permission hierarchy:
- RoleAdmin: read, write, create, delete, admin, schema, user_manage
- RoleEditor: read, write, create, delete
- RoleViewer: read
- RoleNone: (no permissions)
Example:
user := &auth.User{
Roles: []auth.Role{auth.RoleEditor},
}
if user.HasPermission(auth.PermRead) {
fmt.Println("Can read") // Printed
}
if user.HasPermission(auth.PermWrite) {
fmt.Println("Can write") // Printed
}
if user.HasPermission(auth.PermUserManage) {
fmt.Println("Can manage users") // NOT printed (needs RoleAdmin)
}
func (*User) HasRole ¶
HasRole checks if the user has a specific role.
A user can have multiple roles. This method returns true if any of the user's roles match the specified role.
Example:
user := &auth.User{
Roles: []auth.Role{auth.RoleEditor, auth.RoleViewer},
}
if user.HasRole(auth.RoleAdmin) {
fmt.Println("Is admin") // Not printed
}
if user.HasRole(auth.RoleEditor) {
fmt.Println("Is editor") // Printed
}
type UserStateChange ¶
type UserStateChange uint8
UserStateChange identifies one account state transition. The zero value is invalid; no action implicitly enables an account.
const ( // UserEnable clears Disabled, FailedLogins and LockedUntil. UserEnable UserStateChange = iota + 1 // UserDisable sets Disabled and preserves the lockout counters/deadline. UserDisable // UserUnlock clears FailedLogins and LockedUntil, preserving Disabled. UserUnlock )
Source Files
¶
- account_jwt.go
- allowlist.go
- auth.go
- auth_cache.go
- auth_metrics.go
- catalog_visibility.go
- cluster_token.go
- database_access.go
- database_population.go
- entitlements.go
- fine_grained_actions.go
- fine_grained_auth_rules.go
- fine_grained_catalog_store.go
- fine_grained_directory.go
- fine_grained_directory_refresh.go
- fine_grained_graph.go
- fine_grained_graph_counts.go
- fine_grained_graph_writes.go
- fine_grained_policy.go
- fine_grained_predicate.go
- fine_grained_privileges.go
- fine_grained_provider_bindings.go
- fine_grained_provider_directory.go
- fine_grained_provider_session.go
- fine_grained_runtime.go
- fine_grained_tags.go
- oauth.go
- passkeys.go
- privileges.go
- procedure_privileges.go
- request_identity.go
- request_rbac_context.go
- request_read_only.go
- role_catalog_snapshot.go
- role_entitlements.go
- role_mutation.go
- role_records.go
- roles.go
- store_transaction.go
- user_mutation.go
- user_record.go
- user_record_write.go