Documentation
¶
Index ¶
- Constants
- Variables
- func APIPublishSubjects(service string, methods ...string) []string
- func AllRoles() []string
- func BaselinePublishSubjects() []string
- func HasRole(roles []string, target string) bool
- func IsValidRole(role string) bool
- func NewPrivateKeyFromSeed(s string) (ed25519.PrivateKey, error)
- func NewUser(userConfig *UserConfig, signingKeyPair nkeys.KeyPair) (*User, *UserPassword, error)
- func ParseBundleFromFile(certFile, keyFile string) (*tls.Certificate, *ed25519.PrivateKey, error)
- func ParsePKCS8PrivateKey(der []byte) (*ed25519.PrivateKey, error)
- func PasswordHashAndSalt(password string, hashCost int) string
- func ProviderKeyForIssuer(issuer string) string
- func ValidatePassword(hashedPassword, password string) bool
- type Account
- type AccountConfig
- type Activity
- type Agent
- type AgentConfiguration
- type AgentConfigurationOptions
- type Credentials
- type Invitation
- type InvitationConfig
- type InvitationStatus
- type NATSPermissions
- type OAuthIdentity
- type OAuthProvider
- type OAuthState
- type OAuthUserConfig
- type OIDCConnection
- type Operator
- type OperatorConfig
- type PublicOIDCConnection
- type Service
- type Token
- type User
- type UserBase
- type UserClaims
- type UserConfig
- type UserPassword
Constants ¶
const ( DefaultGroupsClaim = "groups" DefaultOIDCRole = RoleUser )
const ( RoleAdministrator = "administrator" RoleUser = "user" RoleViewer = "viewer" )
Formal role constants (singular form). New code should always use these.
const GoogleIssuerURL = "https://accounts.google.com"
GoogleIssuerURL is the OIDC issuer for Google accounts. Google is modeled as a preconfigured OIDC connection rather than a bespoke provider.
const LegacyGoogleProvider = "google"
LegacyGoogleProvider is the provider key that the deprecated bespoke Google OAuth flow used when storing federated identities ("google:{sub}"). New logins store identities under the issuer-based provider key (see ProviderKeyForIssuer), but lookups fall back to this legacy key so existing Google users keep working.
Variables ¶
var ( ErrUserPasswordNotSupplied = errors.New("no password supplied for user") ErrUsernamePasswordInvalid = errors.New("username and password combination invalid") USER_KINDS = []string{ "user", "service", "agent", } USER_META_KEYS = []string{ "email", "name", "hostId", } )
var ( ErrPrivateKeyNotED25519 = errors.New("tls: private key must by type ed25519") ErrPrivateKeyParsingFailed = errors.New("tls: failed to parse private key") ErrBadSeedLength = errors.New("ed25519: bad seed length") )
var APIMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"}
APIMethods are the HTTP methods a service answers over NATS, in the subject scheme api.{service}.{METHOD}.{resource} of package natsapi. Kept here so the user package stays free of that import.
var DefaultOIDCScopes = []string{"openid", "email", "profile", "groups"}
Default OIDC connection values.
Functions ¶
func APIPublishSubjects ¶
APIPublishSubjects returns the publish subjects that let an identity call the named service's API over NATS with the given methods (all methods when none are given): api.{service}.{METHOD}.>.
func BaselinePublishSubjects ¶
func BaselinePublishSubjects() []string
BaselinePublishSubjects returns the subjects every agent or service must still be allowed to publish once a publish allow list exists: request replies and body pulls (_INBOX.>), service discovery ($SRV.>), and its own logs, store metrics, and AI usage (sys.log.>, sys.metrics.>, sys.ai.>; the prefixes of packages logentry, storemetrics, and ai/usage).
func HasRole ¶
HasRole checks whether the given roles slice contains the target role. It accepts both canonical singular forms and legacy plural forms.
func IsValidRole ¶
IsValidRole returns true if the role is a known canonical role name.
func NewPrivateKeyFromSeed ¶
func NewPrivateKeyFromSeed(s string) (ed25519.PrivateKey, error)
func NewUser ¶
func NewUser(userConfig *UserConfig, signingKeyPair nkeys.KeyPair) (*User, *UserPassword, error)
For roles will use user.Claims.Tags.Add(p ...string)
func ParseBundleFromFile ¶
func ParseBundleFromFile(certFile, keyFile string) (*tls.Certificate, *ed25519.PrivateKey, error)
func ParsePKCS8PrivateKey ¶
func ParsePKCS8PrivateKey(der []byte) (*ed25519.PrivateKey, error)
ParsePKCS8PrivateKey is derived from the Go standard library (crypto/tls).
Copyright 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
func PasswordHashAndSalt ¶
Bcrypt salts the password. Store the cost as well. otherwise: returns salt, passwordHash.
func ProviderKeyForIssuer ¶
ProviderKeyForIssuer returns the federated-identity provider key for an OIDC issuer. The key namespaces every issuer under "oidc:" so identities from different IdPs never collide (e.g. "oidc:https://accounts.google.com").
func ValidatePassword ¶
Passwords should not be sent - will only send bcrypt of password and compared.
Types ¶
type Account ¶
type Account struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
Description string `json:"description"`
Owner string `json:"owner"`
Seed string `json:"seed"`
PublicKey string `json:"public_key"`
Token string `json:"token"`
Claims *jwt.AccountClaims `json:"claims"`
}
func NewAccount ¶
func NewAccount(a AccountConfig, signingKeyPair nkeys.KeyPair) (Account, error)
Operator nkeys.KeyPair passed as argument
func (*Account) GetSigningKeyPair ¶
type AccountConfig ¶
type Activity ¶
type Activity struct {
ID string `json:"id"`
LastIP net.IP `json:"last_ip"`
LastIPv4 string `json:"last_ipv4"`
Active bool `json:"active"`
LoginCount int `json:"login_count"`
FailedLoginCount int `json:"failed_login_count"`
LastFailedLogin time.Time `json:"last_failed_login"`
Locked bool `json:"locked"`
LockedAt time.Time `json:"locked_at"`
LoggedIn bool `json:"loggedin"`
LastLogin time.Time `json:"last_login"`
LastActivity time.Time `json:"last_activity"`
}
For logging activity of admin and user
type AgentConfiguration ¶
type AgentConfiguration struct {
AccountID string `json:"account_id"`
HostID string `json:"host_id"`
// NATS
JWT string `json:"jwt"`
Seed string `json:"seed"`
// TLS
Certificate pki.Certificate `json:"certificate"`
PrivateKey pki.PrivateKey `json:"private_key"`
CA pki.Certificate `json:"ca"`
ControllerURL string `json:"controller_url"`
}
type AgentConfigurationOptions ¶
type AgentConfigurationOptions struct {
AccountID string `json:"account_id"`
HostID string `json:"host_id"`
Hostname string `json:"hostname"`
// Roles grants the agent application roles so its JWT passes the same
// role gates a user with those roles would (none by default).
Roles []string `json:"roles,omitempty"`
// Permissions restricts the NATS subjects the agent may use (nil
// means unrestricted).
Permissions *NATSPermissions `json:"permissions,omitempty"`
}
type Credentials ¶
type Credentials struct {
AccountID string `json:"account_id"`
// NATS
JWT string `json:"jwt"`
Seed string `json:"seed"`
// HTTP API
TrustedAccounts []string `json:"trusted_accounts"`
// TLS
PrivateKey *ed25519.PrivateKey `json:"private_key"`
Certificate *tls.Certificate `json:"certificate"`
CA *tls.Certificate `json:"ca"`
}
func (*Credentials) AddTrustedAccount ¶
func (credentials *Credentials) AddTrustedAccount(accountID string)
type Invitation ¶
type Invitation struct {
ID string `json:"id"` // Unique identifier
Token string `json:"token"` // URL-safe token for invitation link
AccountID string `json:"account_id"` // Account to join
InvitedBy string `json:"invited_by"` // UserID of inviter
Email string `json:"email"` // Email address of invitee
Roles []string `json:"roles"` // Roles to assign on acceptance
Status InvitationStatus `json:"status"` // Current status
CreatedAt time.Time `json:"created_at"` // When invitation was created
ExpiresAt time.Time `json:"expires_at"` // When invitation expires
AcceptedAt *time.Time `json:"accepted_at,omitempty"` // When invitation was accepted
AcceptedBy string `json:"accepted_by,omitempty"` // UserID who accepted
}
Invitation represents an invitation for a user to join an account
func NewInvitation ¶
func NewInvitation(config *InvitationConfig, accountID, invitedBy string) (*Invitation, error)
NewInvitation creates a new invitation
func (*Invitation) Accept ¶
func (i *Invitation) Accept(userID string)
Accept marks the invitation as accepted
func (*Invitation) CanBeAccepted ¶
func (i *Invitation) CanBeAccepted() bool
CanBeAccepted checks if the invitation can be accepted
func (*Invitation) IsExpired ¶
func (i *Invitation) IsExpired() bool
IsExpired checks if the invitation has expired
func (*Invitation) IsPending ¶
func (i *Invitation) IsPending() bool
IsPending checks if the invitation is still pending
type InvitationConfig ¶
type InvitationConfig struct {
Email string `json:"email"` // Email of user to invite
Roles []string `json:"roles"` // Roles to assign
TTLHours int `json:"ttl_hours"` // Time to live in hours
AccountID string `json:"account_id"` // Target account (optional, defaults to caller's account)
}
InvitationConfig contains parameters for creating an invitation
type InvitationStatus ¶
type InvitationStatus string
InvitationStatus represents the current state of an invitation
const ( InvitationPending InvitationStatus = "pending" InvitationAccepted InvitationStatus = "accepted" InvitationExpired InvitationStatus = "expired" InvitationRevoked InvitationStatus = "revoked" )
type NATSPermissions ¶
type NATSPermissions struct {
PublishAllow []string `json:"publish_allow,omitempty"`
PublishDeny []string `json:"publish_deny,omitempty"`
SubscribeAllow []string `json:"subscribe_allow,omitempty"`
SubscribeDeny []string `json:"subscribe_deny,omitempty"`
}
NATSPermissions restricts what a NATS identity (user, agent, or service) may publish and subscribe to. The NATS server enforces them from the user JWT. A nil or empty value leaves the identity unrestricted, as every identity issued before permissions existed is.
Once an allow list is set, everything not listed is denied, so a restricted identity must still be allowed the subjects every agent and service relies on; see BaselinePublishSubjects.
func PermissionsFromClaims ¶
func PermissionsFromClaims(claims *jwt.UserClaims) *NATSPermissions
PermissionsFromClaims reads the permissions back out of a user JWT's claims; nil when the claims restrict nothing.
func ReadOnlyAPIPermissions ¶
func ReadOnlyAPIPermissions(services ...string) *NATSPermissions
ReadOnlyAPIPermissions returns permissions that let an identity read (GET and HEAD) the named services over NATS and nothing else, on top of the baseline subjects.
func (*NATSPermissions) IsEmpty ¶
func (p *NATSPermissions) IsEmpty() bool
IsEmpty reports whether the permissions restrict nothing.
type OAuthIdentity ¶
type OAuthIdentity struct {
ID string `json:"id"` // "google:sub_id"
Provider OAuthProvider `json:"provider"` // OAuth provider name
Subject string `json:"subject"` // Provider's unique identifier (e.g., Google's sub claim)
Email string `json:"email"` // Email from OAuth provider
EmailVerified bool `json:"email_verified"` // Whether email was verified by provider
Name string `json:"name"` // Display name from provider
Picture string `json:"picture"` // Profile picture URL
UserID string `json:"user_id"` // Internal user ID
CreatedAt time.Time `json:"created_at"` // When this identity was linked
LastLoginAt time.Time `json:"last_login_at"` // Last OAuth login time
}
OAuthIdentity stores the mapping between an OAuth provider identity and an internal user
func NewFederatedIdentity ¶
func NewFederatedIdentity(providerKey, subject, email, name, picture, userID string, emailVerified bool) *OAuthIdentity
NewFederatedIdentity creates an OAuthIdentity for a federated (OIDC) login. providerKey is an issuer-based key (see ProviderKeyForIssuer); it is stored on the identity so the same struct serves both the legacy Google flow and generic OIDC.
func NewOAuthIdentity ¶
func NewOAuthIdentity(provider OAuthProvider, subject, email, name, picture, userID string, emailVerified bool) *OAuthIdentity
NewOAuthIdentity creates a new OAuth identity record
func (*OAuthIdentity) UpdateLastLogin ¶
func (o *OAuthIdentity) UpdateLastLogin()
UpdateLastLogin updates the last login timestamp
type OAuthProvider ¶
type OAuthProvider string
OAuthProvider represents supported OAuth providers
const (
OAuthProviderGoogle OAuthProvider = "google"
)
type OAuthState ¶
type OAuthState struct {
State string `json:"state"` // Random state token (also the store key)
RedirectURI string `json:"redirect_uri"` // Where to redirect after login
CreatedAt time.Time `json:"created_at"` // When state was created
InviteToken string `json:"invite_token,omitempty"` // Optional invitation token
AccountID string `json:"account_id,omitempty"` // Account whose connection issued this state
Nonce string `json:"nonce,omitempty"` // OIDC nonce, checked against id_token
}
OAuthState stores temporary state for the OAuth/OIDC flow (CSRF protection). AccountID and Nonce were added for per-tenant OIDC: AccountID binds the state to the connection that issued it, and Nonce is compared against the verified id_token's nonce claim to defend against token replay/injection.
func NewOAuthState ¶
func NewOAuthState(state, redirectURI, inviteToken string) *OAuthState
NewOAuthState creates a new OAuth state record (legacy, no nonce/account).
func NewOIDCState ¶
func NewOIDCState(state, accountID, nonce, redirectURI, inviteToken string) *OAuthState
NewOIDCState creates a new OIDC state record bound to an account and nonce.
type OAuthUserConfig ¶
type OAuthUserConfig struct {
Email string `json:"email"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Roles []string `json:"roles"`
AccountID string `json:"account_id"`
OAuthProvider string `json:"oauth_provider"`
OAuthSubject string `json:"oauth_subject"`
Picture string `json:"picture"`
}
OAuthUserConfig contains configuration for creating an OAuth user
type OIDCConnection ¶
type OIDCConnection struct {
AccountID string `json:"account_id"`
Slug string `json:"slug"` // unique per-tenant login slug
Enabled bool `json:"enabled"` // whether login via this connection is allowed
IssuerURL string `json:"issuer_url"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"` // NEVER returned by any GET handler or logged
RedirectURI string `json:"redirect_uri"`
Scopes []string `json:"scopes"` // default: openid,email,profile,groups
GroupsClaim string `json:"groups_claim"` // id_token claim carrying group membership; default "groups"
// GroupRoleMappings maps an IdP group name to one of user.AllRoles(). The
// IdP is authoritative: roles are re-synced from these mappings on every login.
GroupRoleMappings map[string]string `json:"group_role_mappings"`
AutoProvision bool `json:"auto_provision"` // JIT-create users on first login; default true
DefaultRoles []string `json:"default_roles"` // roles when no group maps; default ["user"]
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
OIDCConnection is a per-tenant OpenID Connect login connection. Exactly one connection may exist per account. The Slug provides a stable, per-tenant login route (/api/v1/oidc/{slug}/authorize).
func NewOIDCConnection ¶
func NewOIDCConnection(accountID, slug, issuerURL, clientID, clientSecret, redirectURI string) *OIDCConnection
NewOIDCConnection builds a connection, applying defaults for any unset optional fields. It does not validate the mutable fields; callers should use Validate before persisting.
func (*OIDCConnection) ApplyDefaults ¶
func (c *OIDCConnection) ApplyDefaults()
ApplyDefaults fills in defaults for optional fields left empty by an API caller. It is idempotent.
func (*OIDCConnection) Public ¶
func (c *OIDCConnection) Public() *PublicOIDCConnection
Public returns the connection without its ClientSecret, safe to serialize to clients.
func (*OIDCConnection) Validate ¶
func (c *OIDCConnection) Validate() error
Validate checks the connection's required fields, transport security, and that every mapped/default role is a known canonical role.
type Operator ¶
type Operator struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Name string `json:"name"`
PublicKey string `json:"public_key"`
Seed string `json:"seed"`
Claims *jwt.OperatorClaims `json:"claims"`
Token string `json:"token"`
}
func NewOperator ¶
func NewOperator(o OperatorConfig) (Operator, error)
func (*Operator) GetSigningKeyPair ¶
type OperatorConfig ¶
type PublicOIDCConnection ¶
type PublicOIDCConnection struct {
AccountID string `json:"account_id"`
Slug string `json:"slug"`
Enabled bool `json:"enabled"`
IssuerURL string `json:"issuer_url"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
Scopes []string `json:"scopes"`
GroupsClaim string `json:"groups_claim"`
GroupRoleMappings map[string]string `json:"group_role_mappings"`
AutoProvision bool `json:"auto_provision"`
DefaultRoles []string `json:"default_roles"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
PublicOIDCConnection is the secret-free projection of a connection returned by GET handlers. It deliberately omits ClientSecret.
type Service ¶
func NewService ¶
func NewService(serviceConfig *UserConfig, signingKeyPair nkeys.KeyPair) (*Service, error)
func (*Service) Credentials ¶
func (service *Service) Credentials() (*Credentials, error)
type Token ¶
type Token struct {
Type jwt.ClaimType `json:"type"`
Subject string `json:"subject"`
Token string `json:"token"`
}
func NewUserToken ¶
privateKey is the issuing account Leaving privateKey as interface{} today for future changes
type User ¶
type User struct {
UserBase
Email string `json:"email"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
OAuthProvider string `json:"oauth_provider,omitempty"` // OAuth provider name (e.g., "google")
OAuthSubject string `json:"oauth_subject,omitempty"` // OAuth provider's unique identifier
Picture string `json:"picture,omitempty"` // Profile picture URL from OAuth
ProfilePhoto string `json:"profile_photo,omitempty"` // Base64-encoded thumbnail photo (max 128x128)
ThemePreference string `json:"theme_preference,omitempty"` // UI theme: "system", "dark", or "light"
Preferences map[string]string `json:"preferences,omitempty"` // Generic key-value user preferences
}
//////////////////////////////////////////////////////////////////////////////////////// User ////////////////////////////////////////////////////////////////////////////////////////
func NewOAuthUser ¶
func NewOAuthUser(config *OAuthUserConfig, signingKeyPair nkeys.KeyPair) (*User, error)
NewOAuthUser creates a new user from OAuth without password OAuth users get NATS nkeys just like local users
func (*User) CreateToken ¶
type UserBase ¶
type UserBase struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Roles []string `json:"roles"`
PublicKey string `json:"publicKey"`
Claims *jwt.UserClaims `json:"claims"`
Token string `json:"token"`
Seed string `json:"seed"`
AccountID string `json:"account_id"`
// Permissions are the NATS subject permissions written into the
// identity's JWT. Nil means unrestricted.
Permissions *NATSPermissions `json:"permissions,omitempty"`
}
Token here is the original token issued when the user is created. Subsequent token requests are not stored in the user object (is up to client).
type UserClaims ¶
type UserClaims struct {
jwt.UserClaims
User string `json:"user"`
Roles []string `json:"roles"`
}
func DecodeUserClaims ¶
func DecodeUserClaims(tokenString string) (*UserClaims, error)
DecodeUserClaims tries to parse a user claims from a JWT string
func ValidateUserToken ¶
func ValidateUserToken(tokenString string, publicKey string) (*UserClaims, error)
func (*UserClaims) Encode ¶
func (u *UserClaims) Encode(pair nkeys.KeyPair) (string, error)
Encode tries to turn the user claims into a JWT string
func (*UserClaims) ExpectedPrefixes ¶
func (u *UserClaims) ExpectedPrefixes() []nkeys.PrefixByte
ExpectedPrefixes defines the types that can encode a user JWT, account
func (*UserClaims) Payload ¶
func (u *UserClaims) Payload() interface{}
Payload returns the user specific data from a user JWT
func (*UserClaims) Validate ¶
func (u *UserClaims) Validate(vr *jwt.ValidationResults)
Validate checks the generic and specific parts of the user jwt
type UserConfig ¶
type UserConfig struct {
Email string `json:"email"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Password string `json:"password"`
Roles []string `json:"roles"`
AccountID string `json:"account_id"`
Name string `json:"name"`
HostID string `json:"host_id"`
Hostname string `json:"hostname"`
// Permissions restricts the NATS subjects the identity may use. Nil
// means unrestricted.
Permissions *NATSPermissions `json:"permissions,omitempty"`
}
//////////////////////////////////////////////////////////////////////////////////////// UserBase ////////////////////////////////////////////////////////////////////////////////////////
type UserPassword ¶
type UserPassword struct {
ID string `json:"id"`
PasswordHash string `json:"passwordhash"`
HashCost int `json:"hashcost"`
}
User password hash and salt.