auth

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: Apache-2.0 Imports: 9 Imported by: 0

README

Auth - Authentication and Authorization service

Auth service provides authentication features as an API for managing authentication keys as well as administering groups of entities - clients and users.

Authentication

User service is using Auth service gRPC API to obtain login token or password reset token. Authentication key consists of the following fields:

  • ID - key ID
  • Type - one of the three types described below
  • IssuerID - an ID of the SuperMQ User who issued the key
  • Subject - user ID for which the key is issued
  • IssuedAt - the timestamp when the key is issued
  • ExpiresAt - the timestamp after which the key is invalid

There are four types of authentication keys:

  • Access key - keys issued to the user upon login request
  • Refresh key - keys used to generate new access keys
  • Recovery key - password recovery key
  • API key - keys issued upon the user request
  • Invitation key - keys used to invite new users

Authentication keys are represented and distributed by the corresponding JWT.

User keys are issued when user logs in. Each user request (other than registration and login) contains user key that is used to authenticate the user.

API keys are similar to the User keys. The main difference is that API keys have configurable expiration time. If no time is set, the key will never expire. For that reason, API keys are the only key type that can be revoked. This also means that, despite being used as a JWT, it requires a query to the database to validate the API key. The user with API key can perform all the same actions as the user with login key (can act on behalf of the user for Client, Channel, or user profile management), except issuing new API keys.

Recovery key is the password recovery key. It's short-lived token used for password recovery process.

For in-depth explanation of the aforementioned scenarios, as well as thorough understanding of SuperMQ, please check out the official documentation.

The following actions are supported:

  • create (all key types)
  • verify (all key types)
  • obtain (API keys only)
  • revoke (API keys only)

Domains

Domains are used to group users and clients. Each domain has a unique alias that is used to identify the domain. Domains are used to group users and their entities.

Domain consists of the following fields:

  • ID - UUID uniquely representing domain
  • Name - name of the domain
  • Tags - array of tags
  • Metadata - Arbitrary, object-encoded domain's data
  • Alias - unique alias of the domain
  • CreatedAt - timestamp at which the domain is created
  • UpdatedAt - timestamp at which the domain is updated
  • UpdatedBy - user that updated the domain
  • CreatedBy - user that created the domain
  • Status - domain status

Configuration

The service is configured using the environment variables presented in the following table. Note that any unset variables will be replaced with their default values.

Variable Description Default
SMQ_AUTH_LOG_LEVEL Log level for the Auth service (debug, info, warn, error) info
SMQ_AUTH_DB_HOST Database host address localhost
SMQ_AUTH_DB_PORT Database host port 5432
SMQ_AUTH_DB_USER Database user supermq
SMQ_AUTH_DB_PASSWORD Database password supermq
SMQ_AUTH_DB_NAME Name of the database used by the service auth
SMQ_AUTH_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
SMQ_AUTH_DB_SSL_CERT Path to the PEM encoded certificate file ""
SMQ_AUTH_DB_SSL_KEY Path to the PEM encoded key file ""
SMQ_AUTH_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file ""
SMQ_AUTH_HTTP_HOST Auth service HTTP host ""
SMQ_AUTH_HTTP_PORT Auth service HTTP port 8189
SMQ_AUTH_HTTP_SERVER_CERT Path to the PEM encoded HTTP server certificate file ""
SMQ_AUTH_HTTP_SERVER_KEY Path to the PEM encoded HTTP server key file ""
SMQ_AUTH_GRPC_HOST Auth service gRPC host ""
SMQ_AUTH_GRPC_PORT Auth service gRPC port 8181
SMQ_AUTH_GRPC_SERVER_CERT Path to the PEM encoded gRPC server certificate file ""
SMQ_AUTH_GRPC_SERVER_KEY Path to the PEM encoded gRPC server key file ""
SMQ_AUTH_GRPC_SERVER_CA_CERTS Path to the PEM encoded gRPC server CA certificate file ""
SMQ_AUTH_GRPC_CLIENT_CA_CERTS Path to the PEM encoded gRPC client CA certificate file ""
SMQ_AUTH_SECRET_KEY String used for signing tokens secret
SMQ_AUTH_ACCESS_TOKEN_DURATION The access token expiration period 1h
SMQ_AUTH_REFRESH_TOKEN_DURATION The refresh token expiration period 24h
SMQ_AUTH_INVITATION_DURATION The invitation token expiration period 168h
SMQ_SPICEDB_HOST SpiceDB host address localhost
SMQ_SPICEDB_PORT SpiceDB host port 50051
SMQ_SPICEDB_PRE_SHARED_KEY SpiceDB pre-shared key 12345678
SMQ_SPICEDB_SCHEMA_FILE Path to SpiceDB schema file ./docker/spicedb/schema.zed
SMQ_JAEGER_URL Jaeger server URL http://jaeger:4318/v1/traces
SMQ_JAEGER_TRACE_RATIO Jaeger sampling ratio 1.0
SMQ_SEND_TELEMETRY Send telemetry to supermq call home server true
SMQ_AUTH_ADAPTER_INSTANCE_ID Adapter instance ID ""

Deployment

The service itself is distributed as Docker container. Check the auth service section in docker-compose file to see how service is deployed.

Running this service outside of container requires working instance of the postgres database, SpiceDB, and Jaeger server. To start the service outside of the container, execute the following shell script:

# download the latest version of the service
git clone https://github.com/absmach/supermq

cd supermq

# compile the service
make auth

# copy binary to bin
make install

# set the environment variables and run the service
SMQ_AUTH_LOG_LEVEL=info \
SMQ_AUTH_DB_HOST=localhost \
SMQ_AUTH_DB_PORT=5432 \
SMQ_AUTH_DB_USER=supermq \
SMQ_AUTH_DB_PASSWORD=supermq \
SMQ_AUTH_DB_NAME=auth \
SMQ_AUTH_DB_SSL_MODE=disable \
SMQ_AUTH_DB_SSL_CERT="" \
SMQ_AUTH_DB_SSL_KEY="" \
SMQ_AUTH_DB_SSL_ROOT_CERT="" \
SMQ_AUTH_HTTP_HOST=localhost \
SMQ_AUTH_HTTP_PORT=8189 \
SMQ_AUTH_HTTP_SERVER_CERT="" \
SMQ_AUTH_HTTP_SERVER_KEY="" \
SMQ_AUTH_GRPC_HOST=localhost \
SMQ_AUTH_GRPC_PORT=8181 \
SMQ_AUTH_GRPC_SERVER_CERT="" \
SMQ_AUTH_GRPC_SERVER_KEY="" \
SMQ_AUTH_GRPC_SERVER_CA_CERTS="" \
SMQ_AUTH_GRPC_CLIENT_CA_CERTS="" \
SMQ_AUTH_SECRET_KEY=secret \
SMQ_AUTH_ACCESS_TOKEN_DURATION=1h \
SMQ_AUTH_REFRESH_TOKEN_DURATION=24h \
SMQ_AUTH_INVITATION_DURATION=168h \
SMQ_SPICEDB_HOST=localhost \
SMQ_SPICEDB_PORT=50051 \
SMQ_SPICEDB_PRE_SHARED_KEY=12345678 \
SMQ_SPICEDB_SCHEMA_FILE=./docker/spicedb/schema.zed \
SMQ_JAEGER_URL=http://localhost:14268/api/traces \
SMQ_JAEGER_TRACE_RATIO=1.0 \
SMQ_SEND_TELEMETRY=true \
SMQ_AUTH_ADAPTER_INSTANCE_ID="" \
$GOBIN/supermq-auth

Setting SMQ_AUTH_HTTP_SERVER_CERT and SMQ_AUTH_HTTP_SERVER_KEY will enable TLS against the service. The service expects a file in PEM format for both the certificate and the key. Setting SMQ_AUTH_GRPC_SERVER_CERT and SMQ_AUTH_GRPC_SERVER_KEY will enable TLS against the service. The service expects a file in PEM format for both the certificate and the key. Setting SMQ_AUTH_GRPC_SERVER_CA_CERTS will enable TLS against the service trusting only those CAs that are provided. The service expects a file in PEM format of trusted CAs. Setting SMQ_AUTH_GRPC_CLIENT_CA_CERTS will enable TLS against the service trusting only those CAs that are provided. The service expects a file in PEM format of trusted CAs.

Usage

For more information about service capabilities and its usage, please check out the API documentation.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrExpiry indicates that the token is expired.
	ErrExpiry = errors.New("token is expired")
)
View Source
var ErrKeyExpired = errors.New("use of expired key")

ErrKeyExpired indicates that the Key is expired.

Functions

func DecodeDomainUserID

func DecodeDomainUserID(domainUserID string) (string, string)

func EncodeDomainUserID

func EncodeDomainUserID(domainID, userID string) string

func SwitchToPermission

func SwitchToPermission(relation string) string

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)

	// 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)
}

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) error
}

Authz represents a authorization service. It exposes functionalities through `auth` to perform authorization.

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
	User      string    `json:"user,omitempty"`
	Domain    string    `json:"domain,omitempty"` // domain user ID
	IssuedAt  time.Time `json:"issued_at,omitempty"`
	ExpiresAt time.Time `json:"expires_at,omitempty"`
}

Key represents API key.

func (Key) Expired

func (key Key) Expired() bool

Expired verifies if the key is expired.

func (Key) String

func (key Key) String() string

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
	// InvitationKey is a key for inviting new users.
	InvitationKey
)

func (KeyType) String

func (kt KeyType) String() string

type Service

type Service interface {
	Authn
	Authz
}

func New

func New(keys KeyRepository, idp supermq.IDProvider, tokenizer Tokenizer, policyEvaluator policies.Evaluator, policyService policies.Service, loginDuration, refreshDuration, invitationDuration time.Duration) Service

New instantiates the auth service implementation.

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 converts API Key to its string representation.
	Issue(key Key) (token string, err error)

	// Parse extracts API Key data from string token.
	Parse(token string) (key Key, err error)
}

Tokenizer specifies API for encoding and decoding between string and Key.

Directories

Path Synopsis
api
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 postgres contains Key repository implementations using PostgreSQL as the underlying database.
Package postgres contains Key repository implementations using PostgreSQL as the underlying database.
Package tracing provides tracing instrumentation for SuperMQ Users service.
Package tracing provides tracing instrumentation for SuperMQ Users service.

Jump to

Keyboard shortcuts

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