Documentation
¶
Index ¶
- Constants
- Variables
- func DecodeDomainUserID(domainUserID string) (string, string)
- func EncodeDomainUserID(domainID, userID string) string
- func IsSymmetricAlgorithm(alg string) (bool, error)
- func IsValidOperationForEntity(entityType EntityType, operation string) bool
- func SwitchToPermission(relation string) string
- type Authn
- type Authz
- type Cache
- type EntityType
- type Hasher
- type Key
- type KeyRepository
- type KeyType
- type Operation
- type PAT
- type PATAuthz
- type PATS
- type PATSPage
- type PATSPageMeta
- type PATSRepository
- type PublicKeyInfo
- type Role
- type Scope
- type ScopesPage
- type ScopesPageMeta
- type Service
- type Status
- type Token
- type TokenInfo
- type Tokenizer
- type UserActiveTokensCache
Constants ¶
const ( AnyIDs = "*" RoleOperationPrefix = "role_" )
const ( OpCreate = "create" OpList = "list" OpCreateClients = "create_clients" OpListClients = "list_clients" OpCreateChannels = "create_channels" OpListChannels = "list_channels" OpCreateGroups = "create_groups" OpListGroups = "list_groups" OpPublish = "publish" OpSubscribe = "subscribe" OpMessagePublish = "message_publish" OpMessageSubscribe = "message_subscribe" )
const ( GroupsScopeStr = "groups" ChannelsScopeStr = "channels" ClientsScopeStr = "clients" DashboardsStr = "dashboards" MessagesStr = "messages" DomainsStr = "domains" UsersStr = "users" )
const ( Active = "active" Revoked = "revoked" Expired = "expired" All = "all" Unknown = "unknown" )
Variables ¶
var ( ErrUnsupportedKeyAlgorithm = errors.New("unsupported key algorithm") ErrInvalidSymmetricKey = errors.New("invalid symmetric key") ErrPublicKeysNotSupported = errors.New("public keys not supported for symmetric algorithm") ErrRevokedToken = errors.NewAuthNError("token is revoked") )
var ( // ErrExpiry indicates that the token is expired. ErrExpiry = errors.New("token is expired") )
var ErrKeyExpired = errors.New("use of expired key")
ErrKeyExpired indicates that the Key is expired.
Functions ¶
func DecodeDomainUserID ¶
func EncodeDomainUserID ¶
func IsSymmetricAlgorithm ¶ added in v0.18.4
IsSymmetricAlgorithm determines if the given algorithm is symmetric (HMAC-based). Returns true for HMAC algorithms (HS256, HS384, HS512). Returns false for asymmetric algorithms (EdDSA). Returns error for unsupported algorithms.
func IsValidOperationForEntity ¶ added in v0.19.0
func IsValidOperationForEntity(entityType EntityType, operation string) bool
func SwitchToPermission ¶
Switch the relative permission for the relation.
Types ¶
type Authn ¶
type Authn interface {
// Issue issues a new Key, returning its token value alongside.
Issue(ctx context.Context, token string, key Key) (Token, error)
// RevokeToken revokes the refresh token by its ID.
RevokeToken(ctx context.Context, userID, tokenID string) error
// Revoke removes the Key with the provided id that is
// issued by the user identified by the provided key.
Revoke(ctx context.Context, token, id string) error
// RetrieveKey retrieves data for the Key identified by the provided
// ID, that is issued by the user identified by the provided key.
RetrieveKey(ctx context.Context, token, id string) (Key, error)
// Identify validates token token. If token is valid, content
// is returned. If token is invalid, or invocation failed for some
// other reason, non-nil error value is returned in response.
Identify(ctx context.Context, token string) (Key, error)
// RetrieveJWKS retrieves public keys to validate issued tokens.
RetrieveJWKS() []PublicKeyInfo
// ListUserRefreshTokens lists all active refresh token sessions for a user.
ListUserRefreshTokens(ctx context.Context, userID string) ([]TokenInfo, error)
}
Authn specifies an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics). Token is a string value of the actual Key and is used to authenticate an Auth service request.
type Authz ¶
type Authz interface {
// Authorize checks authorization of the given `subject`. Basically,
// Authorize verifies that Is `subject` allowed to `relation` on
// `object`. Authorize returns a non-nil error if the subject has
// no relation on the object (which simply means the operation is
// denied).
Authorize(ctx context.Context, pr policies.Policy, patAuthz *PATAuthz) error
}
Authz represents a authorization service. It exposes functionalities through `auth` to perform authorization.
type Cache ¶ added in v0.17.0
type Cache interface {
Save(ctx context.Context, userID string, scopes []Scope) error
CheckScope(ctx context.Context, userID, patID, optionalDomainID string, entityType EntityType, operation string, entityID string) bool
Remove(ctx context.Context, userID string, scopesID []string) error
RemoveUserAllScope(ctx context.Context, userID string) error
RemoveAllScope(ctx context.Context, userID, patID string) error
}
type EntityType ¶ added in v0.17.0
type EntityType uint32
const ( GroupsType EntityType = iota ChannelsType ClientsType DashboardType MessagesType DomainsType UsersType )
func ParseEntityType ¶ added in v0.17.0
func ParseEntityType(et string) (EntityType, error)
func (EntityType) MarshalJSON ¶ added in v0.17.0
func (et EntityType) MarshalJSON() ([]byte, error)
func (EntityType) MarshalText ¶ added in v0.17.0
func (et EntityType) MarshalText() ([]byte, error)
func (EntityType) String ¶ added in v0.17.0
func (et EntityType) String() string
func (*EntityType) UnmarshalJSON ¶ added in v0.17.0
func (et *EntityType) UnmarshalJSON(data []byte) error
func (*EntityType) UnmarshalText ¶ added in v0.17.0
func (et *EntityType) UnmarshalText(data []byte) (err error)
type Hasher ¶ added in v0.17.0
type Hasher interface {
// Hash generates the hashed string from plain-text.
Hash(string) (string, error)
// Compare compares plain-text version to the hashed one. An error should
// indicate failed comparison.
Compare(string, string) error
}
Hasher specifies an API for generating hashes of an arbitrary textual content.
type Key ¶
type Key struct {
ID string `json:"id,omitempty"`
Type KeyType `json:"type,omitempty"`
Issuer string `json:"issuer,omitempty"`
Subject string `json:"subject,omitempty"` // user ID
Role Role `json:"role,omitempty"`
IssuedAt time.Time `json:"issued_at,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
Verified bool `json:"verified,omitempty"`
Description string `json:"description,omitempty"` // Optional description for refresh tokens
}
Key represents API key.
type KeyRepository ¶
type KeyRepository interface {
// Save persists the Key. A non-nil error is returned to indicate
// operation failure
Save(ctx context.Context, key Key) (id string, err error)
// Retrieve retrieves Key by its unique identifier.
Retrieve(ctx context.Context, issuer string, id string) (key Key, err error)
// Remove removes Key with provided ID.
Remove(ctx context.Context, issuer string, id string) error
}
KeyRepository specifies Key persistence API.
type KeyType ¶
type KeyType uint32
const ( // AccessKey is temporary User key received on successful login. AccessKey KeyType = iota // RefreshKey is a temporary User key used to generate a new access key. RefreshKey // RecoveryKey represents a key for resseting password. RecoveryKey // APIKey enables the one to act on behalf of the user. APIKey // PersonalAccessToken represents token generated by user for automation. PersonalAccessToken // InvitationKey is a key for inviting new users. InvitationKey )
type Operation ¶ added in v0.17.0
type Operation = permissions.Operation
const ( )
Dashboard operations.
type PAT ¶ added in v0.17.0
type PAT struct {
ID string `json:"id,omitempty"`
User string `json:"user_id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Secret string `json:"secret,omitempty"`
Role Role `json:"role,omitempty"`
IssuedAt time.Time `json:"issued_at,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
LastUsedAt time.Time `json:"last_used_at,omitempty"`
Revoked bool `json:"revoked,omitempty"`
RevokedAt time.Time `json:"revoked_at,omitempty"`
Status Status `json:"status,omitempty"`
}
PAT represents Personal Access Token.
func (PAT) MarshalBinary ¶ added in v0.17.0
func (PAT) MarshalJSON ¶ added in v0.17.0
func (*PAT) UnmarshalBinary ¶ added in v0.17.0
type PATAuthz ¶ added in v0.19.0
type PATAuthz struct {
PatID string
UserID string
EntityType EntityType
EntityID string
Operation string
Domain string
}
PATAuthz represents the PAT authorization request fields.
type PATS ¶ added in v0.17.0
type PATS interface {
// Create function creates new PAT for given valid inputs.
CreatePAT(ctx context.Context, token, name, description string, duration time.Duration) (PAT, error)
// UpdateName function updates the name for the given PAT ID.
UpdatePATName(ctx context.Context, token, patID, name string) (PAT, error)
// UpdateDescription function updates the description for the given PAT ID.
UpdatePATDescription(ctx context.Context, token, patID, description string) (PAT, error)
// Retrieve function retrieves the PAT for given ID.
RetrievePAT(ctx context.Context, userID string, patID string) (PAT, error)
// RemoveAllPAT function removes all PATs of user.
RemoveAllPAT(ctx context.Context, token string) error
// ListPATS function lists all the PATs for the user.
ListPATS(ctx context.Context, token string, pm PATSPageMeta) (PATSPage, error)
// Delete function deletes the PAT for given ID.
DeletePAT(ctx context.Context, token, patID string) error
// ResetSecret function reset the secret and creates new secret for the given ID.
ResetPATSecret(ctx context.Context, token, patID string, duration time.Duration) (PAT, error)
// RevokeSecret function revokes the secret for the given ID.
RevokePATSecret(ctx context.Context, token, patID string) error
// AddScope function adds a new scope.
AddScope(ctx context.Context, token, patID string, scopes []Scope) error
// RemoveScope function removes a scope.
RemoveScope(ctx context.Context, token string, patID string, scopeIDs ...string) error
// RemovePATAllScope function removes all scope.
RemovePATAllScope(ctx context.Context, token, patID string) error
// List function lists all the Scopes for the patID.
ListScopes(ctx context.Context, token string, pm ScopesPageMeta) (ScopesPage, error)
// IdentifyPAT function will valid the secret.
IdentifyPAT(ctx context.Context, paToken string) (PAT, error)
// AuthorizePAT function will valid the secret and check the given scope exists.
AuthorizePAT(ctx context.Context, userID, patID string, entityType EntityType, domainID string, operation string, entityID string) error
}
PATS specifies function which are required for Personal access Token implementation.
type PATSPageMeta ¶ added in v0.17.0
type PATSRepository ¶ added in v0.17.0
type PATSRepository interface {
// Save persists the PAT
Save(ctx context.Context, pat PAT) (err error)
// Retrieve retrieves users PAT by its unique identifier.
Retrieve(ctx context.Context, userID, patID string) (pat PAT, err error)
// RetrieveScope retrieves PAT scopes by its unique identifier.
RetrieveScope(ctx context.Context, pm ScopesPageMeta) (scopes ScopesPage, err error)
// RetrieveSecretAndRevokeStatus retrieves secret and revoke status of PAT by its unique identifier.
RetrieveSecretAndRevokeStatus(ctx context.Context, userID, patID string) (string, bool, bool, error)
// UpdateName updates the name of a PAT.
UpdateName(ctx context.Context, userID, patID, name string) (PAT, error)
// UpdateDescription updates the description of a PAT.
UpdateDescription(ctx context.Context, userID, patID, description string) (PAT, error)
// UpdateTokenHash updates the token hash of a PAT.
UpdateTokenHash(ctx context.Context, userID, patID, tokenHash string, expiryAt time.Time) (PAT, error)
// RetrieveAll retrieves all PATs belongs to userID.
RetrieveAll(ctx context.Context, userID string, pm PATSPageMeta) (pats PATSPage, err error)
// Revoke PAT with provided ID.
Revoke(ctx context.Context, userID, patID string) error
// Reactivate PAT with provided ID.
Reactivate(ctx context.Context, userID, patID string) error
// Remove removes Key with provided ID.
Remove(ctx context.Context, userID, patID string) error
// RemoveAllPAT removes all PAT for a given user.
RemoveAllPAT(ctx context.Context, userID string) error
AddScope(ctx context.Context, userID string, scopes []Scope) error
RemoveScope(ctx context.Context, userID string, scopesIDs ...string) error
CheckScope(ctx context.Context, userID, patID string, entityType EntityType, domainID string, operation string, entityID string) error
RemoveAllScope(ctx context.Context, patID string) error
}
PATSRepository specifies PATS persistence API.
type PublicKeyInfo ¶ added in v0.18.4
type PublicKeyInfo struct {
KeyID string `json:"kid"`
KeyType string `json:"kty"`
Algorithm string `json:"alg"`
Use string `json:"use,omitempty"`
// EdDSA (Ed25519) fields
Curve string `json:"crv,omitempty"`
X string `json:"x,omitempty"`
}
PublicKeyInfo represents a public key for external distribution via JWKS. This follows RFC 7517 (JSON Web Key) specification.
type Scope ¶ added in v0.17.0
type Scope struct {
ID string `json:"id"`
PatID string `json:"pat_id"`
DomainID string `json:"domain_id"`
EntityType EntityType `json:"entity_type"`
EntityID string `json:"entity_id"`
Operation string `json:"operation"`
}
func (*Scope) Authorized ¶ added in v0.17.0
func (*Scope) UnmarshalJSON ¶ added in v0.19.0
type ScopesPage ¶ added in v0.17.0
type ScopesPageMeta ¶ added in v0.17.0
type Service ¶
Service specifies an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics). Token is a string value of the actual Key and is used to authenticate an Auth service request.
func New ¶
func New(keys KeyRepository, pats PATSRepository, cache Cache, tokensCache UserActiveTokensCache, hasher Hasher, idp supermq.IDProvider, tokenizer Tokenizer, policyEvaluator policies.Evaluator, policyService policies.Service, loginDuration, refreshDuration, invitationDuration time.Duration) Service
New instantiates the auth service implementation.
type Status ¶ added in v0.17.0
type Status uint8
func (Status) MarshalJSON ¶ added in v0.17.0
func (*Status) UnmarshalJSON ¶ added in v0.17.0
type Token ¶
type Token struct {
AccessToken string // AccessToken contains the security credentials for a login session and identifies the client.
RefreshToken string // RefreshToken is a credential artifact that OAuth can use to get a new access token without client interaction.
AccessType string // AccessType is the specific type of access token issued. It can be Bearer, Client or Basic.
}
type Tokenizer ¶
type Tokenizer interface {
// Issue creates a signed token string from the given key claims.
// For RefreshKey types, the token ID is stored as active in the cache.
Issue(key Key) (token string, err error)
// Parse verifies and parses a token string (JWT or PAT), returning the extracted claims.
// For PAT tokens (prefix "pat"), returns a Key with Type set to PersonalAccessToken.
// For JWT tokens, performs cryptographic verification and returns the parsed claims.
Parse(ctx context.Context, token string) (key Key, err error)
// RetrieveJWKS returns public keys for distribution via JWKS endpoint.
// Returns ErrPublicKeysNotSupported for symmetric tokenizers (HMAC).
RetrieveJWKS() ([]PublicKeyInfo, error)
}
Tokenizer handles token creation and verification for authentication. Implementations manage underlying cryptographic operations and key distribution.
type UserActiveTokensCache ¶ added in v0.19.0
type UserActiveTokensCache interface {
// SaveActive saves an active refresh token ID for a user with optional description.
SaveActive(ctx context.Context, userID, tokenID, description string, expiry time.Time) error
// IsActive checks if the token ID is active.
IsActive(ctx context.Context, tokenID string) (bool, error)
// ListUserTokens lists all active token IDs with descriptions for a given user.
ListUserTokens(ctx context.Context, userID string) ([]TokenInfo, error)
// RemoveActive removes an active refresh token ID.
RemoveActive(ctx context.Context, userID, tokenID string) error
}
UserActiveTokensCache represents a cache repository for managing active refresh tokens per user.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package api contains implementation of Auth service HTTP API.
|
Package api contains implementation of Auth service HTTP API. |
|
grpc/auth
Package auth contains implementation of Auth service gRPC API.
|
Package auth contains implementation of Auth service gRPC API. |
|
grpc/token
Package grpc contains implementation of Auth service gRPC API.
|
Package grpc contains implementation of Auth service gRPC API. |
|
Package cache contains the domain concept definitions needed to support SuperMQ auth cache service functionality.
|
Package cache contains the domain concept definitions needed to support SuperMQ auth cache service functionality. |
|
Package hasher contains the domain concept definitions needed to support Supermq users password hasher sub-service functionality.
|
Package hasher contains the domain concept definitions needed to support Supermq users password hasher sub-service functionality. |
|
Package middleware provides logging metrics and tracing middleware for SuperMQ Auth service.
|
Package middleware provides logging metrics and tracing middleware for SuperMQ Auth service. |
|
Package postgres contains Key repository implementations using PostgreSQL as the underlying database.
|
Package postgres contains Key repository implementations using PostgreSQL as the underlying database. |
|
tokenizer
|
|