auth

package
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

Auth Service

The Auth service is the central authentication and authorization component of the Mainflux IoT platform. It provides identity verification, role-based access control (RBAC), multi-tenant organization management, and a member invitation system. All other platform services communicate with Auth over its gRPC API to authenticate requests and enforce access policies.

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
MF_AUTH_LOG_LEVEL Service log level (debug, info, warn, error) error
MF_AUTH_DB_HOST Database host address localhost
MF_AUTH_DB_PORT Database host port 5432
MF_AUTH_DB_USER Database user mainflux
MF_AUTH_DB_PASS Database password mainflux
MF_USERS_ADMIN_EMAIL Email of the default root admin user (created on first startup)
MF_AUTH_DB Name of the database used by the service auth
MF_AUTH_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MF_AUTH_DB_SSL_CERT Path to the PEM encoded certificate file
MF_AUTH_DB_SSL_KEY Path to the PEM encoded key file
MF_AUTH_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file
MF_AUTH_HTTP_PORT Auth service HTTP port 8180
MF_AUTH_GRPC_PORT Auth service gRPC port 8181
MF_AUTH_SERVER_CERT Path to server certificate in PEM format
MF_AUTH_SERVER_KEY Path to server key in PEM format
MF_AUTH_SECRET Secret string used for signing tokens auth
MF_AUTH_LOGIN_TOKEN_DURATION Login key expiration period 10h
MF_INVITE_DURATION Validity period for organization invitations 168h
MF_JAEGER_URL Jaeger server URL for distributed tracing. Leave empty to disable tracing.
MF_AUTH_ES_URL Event store (Redis) URL redis://localhost:6379/0
MF_AUTH_GRPC_TIMEOUT Timeout for outgoing gRPC calls (Things and Users services) 1s
MF_THINGS_AUTH_GRPC_URL Things service auth gRPC URL localhost:8183
MF_THINGS_CLIENT_TLS Enable TLS for Things gRPC connection false
MF_THINGS_CA_CERTS Path to trusted CAs in PEM format for Things gRPC TLS
MF_USERS_GRPC_URL Users service gRPC URL localhost:8184
MF_USERS_CLIENT_TLS Enable TLS for Users gRPC connection false
MF_USERS_CA_CERTS Path to trusted CAs in PEM format for Users gRPC TLS
MF_HOST Frontend URL base used in invitation email links http://localhost
MF_EMAIL_HOST Mail server host localhost
MF_EMAIL_PORT Mail server port 25
MF_EMAIL_USERNAME Mail server username
MF_EMAIL_PASSWORD Mail server password
MF_EMAIL_FROM_ADDRESS Sender email address
MF_EMAIL_FROM_NAME Sender display name
MF_EMAIL_TEMPLATES_DIR Path to the directory containing email templates used for invitation emails .

Note: If MF_EMAIL_TEMPLATES_DIR does not point to a valid directory containing the required templates, the service will start normally but invitation emails will not be sent.

Deployment

The service is distributed as a Docker container. Refer to the auth service section in the Docker Compose file for a reference deployment configuration.

To build and run the service manually:

# Download the latest version
go get github.com/MainfluxLabs/mainflux

cd $GOPATH/src/github.com/MainfluxLabs/mainflux

# Compile the service
make auth

# Copy binary to bin
make install

# Run the service
MF_AUTH_LOG_LEVEL=[log level] \
MF_AUTH_DB_HOST=[db host] \
MF_AUTH_DB_PORT=[db port] \
MF_AUTH_DB_USER=[db user] \
MF_AUTH_DB_PASS=[db password] \
MF_AUTH_DB=[db name] \
MF_AUTH_DB_SSL_MODE=[ssl mode] \
MF_AUTH_HTTP_PORT=[http port] \
MF_AUTH_GRPC_PORT=[grpc port] \
MF_AUTH_SECRET=[signing secret] \
MF_AUTH_LOGIN_TOKEN_DURATION=[token duration] \
$GOBIN/mainfluxlabs-auth

Usage

For the full HTTP API reference, see the OpenAPI specification.

For a broader overview of how authentication and authorization fit into the platform, refer to the official documentation.

Documentation

Index

Constants

View Source
const (
	UserTypeInvitee = "invitee"
	UserTypeInviter = "inviter"

	InviteStatePending  = "pending"
	InviteStateExpired  = "expired"
	InviteStateRevoked  = "revoked"
	InviteStateAccepted = "accepted"
	InviteStateDeclined = "declined"
)
View Source
const (
	LoginKey    = domain.LoginKey
	RecoveryKey = domain.RecoveryKey
	APIKey      = domain.APIKey
)

Key type constants (aliases for domain).

View Source
const (
	RoleRootAdmin = domain.RoleRootAdmin
	RoleAdmin     = domain.RoleAdmin
)

RoleRootAdmin and RoleAdmin are aliases for the shared domain types.

View Source
const (

	// Re-export role constants from domain for backward compatibility.
	Admin   = domain.OrgAdmin
	Owner   = domain.OrgOwner
	Editor  = domain.OrgEditor
	Viewer  = domain.OrgViewer
	RootSub = domain.RootSub
	OrgSub  = domain.OrgSub
)

Variables

View Source
var (
	// ErrInvalidInviteResponse indicates an invalid Invite response action string.
	ErrInvalidInviteResponse = errors.New("invalid invite response action")
	// ErrGroupsDifferingOrgs indicates that groups associated with an Org invite belong to different Orgs
	ErrGroupsDifferingOrgs = errors.New("groups belong to differing organizations")
)
View Source
var (
	// ErrInvalidKeyIssuedAt indicates that the Key is being used before it's issued.
	ErrInvalidKeyIssuedAt = errors.New("invalid issue time")

	// ErrKeyExpired indicates that the Key is expired.
	ErrKeyExpired = errors.New("use of expired key")

	// ErrAPIKeyExpired indicates that the Key is expired
	// and that the key type is API key.
	ErrAPIKeyExpired = errors.New("use of expired API key")
)
View Source
var (
	// ErrCreateOrgMembership indicates failure to create org membership.
	ErrCreateOrgMembership = errors.New("failed to create org membership")

	// ErrRemoveOrgMembership indicates failure to remove org membership.
	ErrRemoveOrgMembership = errors.New("failed to remove org membership")

	// ErrOrgMembershipExists indicates that membership already exists.
	ErrOrgMembershipExists = errors.New("org membership already exists")
)
View Source
var (
	// ErrRetrieveMembershipsByOrg indicates that retrieving memberships by org failed.
	ErrRetrieveMembershipsByOrg = errors.New("failed to retrieve memberships by org")

	// ErrRetrieveOrgsByMembership indicates that retrieving orgs by membership failed.
	ErrRetrieveOrgsByMembership = errors.New("failed to retrieve orgs by membership")
)
View Source
var AllowedOrders = map[string]string{
	"id":         "id",
	"name":       "name",
	"created_at": "created_at",
	"updated_at": "updated_at",
	"invitee_id": "invitee_id",
	"inviter_id": "inviter_id",
	"org_id":     "org_id",
	"state":      "state",
	"issued_at":  "issued_at",
}
View Source
var (
	// ErrOrgNotEmpty indicates org is not empty, can't be deleted.
	ErrOrgNotEmpty = errors.New("org is not empty")
)

Functions

This section is empty.

Types

type Authn

type Authn interface {
	// 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) (Identity, error)
}

Authn specifies an API that must be fullfiled 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(ctx context.Context, ar AuthzReq) error
}

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

type AuthzReq

type AuthzReq = domain.AuthzReq

Domain type aliases

type Backup

type Backup struct {
	Orgs           []Org
	OrgMemberships []OrgMembership
}

type Emailer added in v0.30.0

type Emailer interface {
	// Send the invitee an e-mail notifying them of the Org Invite. `groupNames` represents a mapping of
	// group IDs to group names for groups found in inv.Groups. It may be `nil` if and only if inv.Groups is also nil.
	SendOrgInvite(to []string, inv OrgInvite, orgName, invRedirectPath string, groupNames map[string]string) error
}

type GroupInvite added in v0.34.1

type GroupInvite = domain.GroupInvite

Domain type aliases

type Identity

type Identity = domain.Identity

Domain type aliases

type Invites added in v0.30.0

type Invites interface {
	// CreateOrgInvite creates a pending Invite on behalf of the User authenticated by `token`,
	// towards the user identified by invite.Email, to join the Org identified by invite.OrgID with the invite.Role role.
	// invite.GroupInvites is an optional list of Group memberships. If present, the invitee will additionally
	// be assigned as a member of each of the groups after they accept the Org invite.
	CreateOrgInvite(ctx context.Context, token string, oi OrgInvite, invRedirectPath string) (OrgInvite, error)

	// CreateDormantOrgInvite creates a pending, dormant Org Invite associated with a specific Platform Invite
	// denoted by `platformInviteID`.
	// orgInvite.GroupInvites is an optional list of Group memberships. If present, the invitee will additionally
	// be assigned as a member of each group after they accept the Org invite.
	CreateDormantOrgInvite(ctx context.Context, token string, oi OrgInvite, platformInviteID string) (OrgInvite, error)

	// RevokeOrgInvite revokes a specific pending Invite. An existing pending Invite can only be revoked
	// by its original inviter (creator).
	RevokeOrgInvite(ctx context.Context, token, inviteID string) error

	// RespondOrgInvite responds to a specific invite, either accepting it (after which the invitee
	// is assigned as a member of the appropriate Org), or declining it. An Invite can only be responded
	// to by the invitee that it's directed towards.
	RespondOrgInvite(ctx context.Context, token, inviteID string, accept bool) error

	// ActivateOrgInvite activates all dormant Org Invites associated with the specific Platform Invite.
	// The expiration time of the invites is reset. An e-mail notification is sent to the invitee for each
	// activated invite.
	ActivateOrgInvite(ctx context.Context, platformInviteID, userID, invRedirectPath string) error

	// ViewOrgInvite retrieves a single Invite denoted by its ID.  A specific Org Invite can be retrieved
	// by any user with admin privileges within the Org to which the invite belongs,
	// the Invitee towards who it is directed, or the platform Root Admin.
	ViewOrgInvite(ctx context.Context, token, inviteID string) (OrgInvite, error)

	// ListOrgInvitesByUser retrieves a list of invites either directed towards a specific Invitee,
	// or sent out by a specific Inviter, depending on the value of the `userType` argument, which
	// must be either 'invitee' or 'inviter'.
	ListOrgInvitesByUser(ctx context.Context, token, userType, userID string, pm PageMetadata) (OrgInvitesPage, error)

	// ListOrgInvitesByOrg retrieves a list of invites towards any user(s) to join the org identified
	// by its ID
	ListOrgInvitesByOrg(ctx context.Context, token, orgID string, pm PageMetadata) (OrgInvitesPage, error)

	// GetDormantOrgInviteByPlatformInvite retrieves the dormant Org Invite associated with the specified Platform Invite.
	GetDormantOrgInviteByPlatformInvite(ctx context.Context, platformInviteID string) (OrgInvite, error)

	// SendOrgInviteEmail sends an e-mail notifying the invitee of the corresponding Invite.
	SendOrgInviteEmail(ctx context.Context, invite OrgInvite, email, orgName, invRedirectPath string) error
}

type Key

type Key = domain.Key

Domain type aliases

type KeyRepository

type KeyRepository interface {
	// Save persists the Key. A non-nil error is returned to indicate
	// operation failure
	Save(context.Context, Key) (string, error)

	// Retrieve retrieves Key by its unique identifier.
	Retrieve(context.Context, string, string) (Key, error)

	// Remove removes Key with provided ID.
	Remove(context.Context, string, string) error

	// RetrieveAPIKeys retrieves all API Keys with pagination.
	RetrieveAPIKeys(ctx context.Context, issuerID string, pm PageMetadata) (KeysPage, error)
}

KeyRepository specifies Key persistence API.

type Keys added in v0.24.0

type Keys interface {
	// Issue issues a new Key, returning its token value alongside.
	Issue(ctx context.Context, token string, key Key) (Key, 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)

	// ListAPIKeys retrieves API keys.
	ListAPIKeys(ctx context.Context, token string, pm PageMetadata) (KeysPage, error)
}

Keys specifies an API that must be fullfiled by the domain service implementation, and all of its decorators (e.g. logging & metrics).

type KeysPage added in v0.38.0

type KeysPage = domain.KeysPage

Domain type aliases

type Org

type Org = domain.Org

Domain type aliases

type OrgInvite added in v0.30.0

type OrgInvite = domain.OrgInvite

Domain type aliases

type OrgInvitesPage added in v0.30.0

type OrgInvitesPage = domain.OrgInvitesPage

Domain type aliases

type OrgInvitesRepository added in v0.30.0

type OrgInvitesRepository interface {
	// SaveOrgInvite saves one or more pending org invites to the repository.
	SaveOrgInvite(ctx context.Context, invites ...OrgInvite) error

	// SaveDormantInviteRelation saves a relation of a dormant Org Invite with a specific Platform Invite.
	SaveDormantInviteRelation(ctx context.Context, orgInviteID, platformInviteID string) error

	// ActivateOrgInvite activates all dormant Org Invites corresponding to the specified Platform Invite by:
	// - Updating the "invitee_id" and "expires_at" columns of all matching Org Invites to the supplied values
	// - Removing the associated rows from the "dormant_org_invites" table
	// Returns slice of activated Org Invites.
	ActivateOrgInvite(ctx context.Context, platformInviteID, userID string, expirationTime time.Time) ([]OrgInvite, error)

	// RetrieveOrgInviteByID retrieves a specific OrgInvite by its ID.
	RetrieveOrgInviteByID(ctx context.Context, inviteID string) (OrgInvite, error)

	// RemoveOrgInvite removes a specific pending OrgInvite.
	RemoveOrgInvite(ctx context.Context, inviteID string) error

	// RetrieveOrgInviteByUser retrieves a list of invites either directed towards a specific Invitee, or sent out by a
	// specific Inviter, depending on the value of the `userType` argument, which must be either 'invitee' or 'inviter'.
	RetrieveOrgInvitesByUser(ctx context.Context, userType, userID string, pm PageMetadata) (OrgInvitesPage, error)

	// RetrieveOrgInvitesByOrg retrieves a list of invites towards any user(s) to join the Org identified
	// by its ID.
	RetrieveOrgInvitesByOrg(ctx context.Context, orgID string, pm PageMetadata) (OrgInvitesPage, error)

	// UpdateOrgInviteState updates the state of a specific Invite denoted by its ID.
	UpdateOrgInviteState(ctx context.Context, inviteID, state string) error

	// RetrieveDormantOrgInviteByPlatformInvite retrieves the dormant Org Invite associated with the specified Platform Invite.
	RetrieveDormantOrgInviteByPlatformInvite(ctx context.Context, platformInviteID string) (OrgInvite, error)
}

type OrgMembership added in v0.29.0

type OrgMembership = domain.OrgMembership

Domain type aliases

type OrgMemberships added in v0.29.0

type OrgMemberships interface {
	// CreateOrgMemberships adds memberships with member emails into the org identified by orgID.
	CreateOrgMemberships(ctx context.Context, token, orgID string, oms ...OrgMembership) error

	// RemoveOrgMemberships removes memberships with member ids from org identified by orgID.
	RemoveOrgMemberships(ctx context.Context, token string, orgID string, memberIDs ...string) error

	// UpdateOrgMemberships updates membership roles in an org.
	UpdateOrgMemberships(ctx context.Context, token, orgID string, oms ...OrgMembership) error

	// ListOrgMemberships retrieves memberships created for an org identified by orgID.
	ListOrgMemberships(ctx context.Context, token, orgID string, pm PageMetadata) (OrgMembershipsPage, error)

	// ViewOrgMembership retrieves membership identified by memberID and orgID.
	ViewOrgMembership(ctx context.Context, token, orgID, memberID string) (OrgMembership, error)
}

OrgMemberships specify an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics).

type OrgMembershipsPage added in v0.29.0

type OrgMembershipsPage = domain.OrgMembershipsPage

Domain type aliases

type OrgMembershipsRepository added in v0.29.0

type OrgMembershipsRepository interface {
	// Save saves memberships.
	Save(ctx context.Context, oms ...OrgMembership) error

	// Update updates memberships.
	Update(ctx context.Context, oms ...OrgMembership) error

	// Remove removes memberships.
	Remove(ctx context.Context, orgID string, memberIDs ...string) error

	// RetrieveRole retrieves role of membership specified by memberID and orgID.
	RetrieveRole(ctx context.Context, memberID, orgID string) (string, error)

	// RetrieveByOrg retrieves org memberships identified by orgID.
	RetrieveByOrg(ctx context.Context, orgID string, pm PageMetadata) (OrgMembershipsPage, error)

	// BackupAll retrieves all memberships.
	BackupAll(ctx context.Context) ([]OrgMembership, error)

	// BackupByOrg retrieves all memberships by org ID.
	BackupByOrg(ctx context.Context, orgID string) ([]OrgMembership, error)
}

type OrgRepository

type OrgRepository interface {
	// Save orgs
	Save(ctx context.Context, orgs ...Org) error

	// Update an org
	Update(ctx context.Context, org Org) error

	// Remove orgs
	Remove(ctx context.Context, ownerID string, orgIDs ...string) error

	// RetrieveByID retrieves org by its id
	RetrieveByID(ctx context.Context, id string) (Org, error)

	// BackupAll retrieves all orgs.
	BackupAll(ctx context.Context) ([]Org, error)

	// RetrieveAll retrieves all orgs with pagination.
	RetrieveAll(ctx context.Context, pm PageMetadata) (OrgsPage, error)

	// RetrieveByMember list of orgs that member belongs to
	RetrieveByMember(ctx context.Context, memberID string, pm PageMetadata) (OrgsPage, error)
}

OrgRepository specifies an org persistence API.

type Orgs

type Orgs interface {
	// CreateOrg creates new org.
	CreateOrg(ctx context.Context, token string, org Org) (Org, error)

	// UpdateOrg updates the org identified by the provided ID.
	UpdateOrg(ctx context.Context, token string, org Org) (Org, error)

	// ViewOrg retrieves data about the org identified by ID.
	ViewOrg(ctx context.Context, token, id string) (Org, error)

	// ListOrgs retrieves orgs.
	ListOrgs(ctx context.Context, token string, pm PageMetadata) (OrgsPage, error)

	// RemoveOrgs removes the orgs identified with the provided IDs.
	RemoveOrgs(ctx context.Context, token string, ids ...string) error

	// GetOwnerIDByOrg returns an owner ID for a given org ID.
	GetOwnerIDByOrg(ctx context.Context, orgID string) (string, error)

	// Backup retrieves all orgs and org memberships. Only accessible by admin.
	Backup(ctx context.Context, token string) (Backup, error)

	// Restore adds orgs and org memberships from a backup. Only accessible by admin.
	Restore(ctx context.Context, token string, backup Backup) error
}

Orgs specifies an API that must be fullfiled by the domain service implementation, and all of its decorators (e.g. logging & metrics).

type OrgsPage

type OrgsPage = domain.OrgsPage

Domain type aliases

type PageMetadata

type PageMetadata struct {
	Total    uint64         `json:"total,omitempty"`
	Offset   uint64         `json:"offset,omitempty"`
	Limit    uint64         `json:"limit,omitempty"`
	Order    string         `json:"order,omitempty"`
	Dir      string         `json:"dir,omitempty"`
	State    string         `json:"state,omitempty"`
	Name     string         `json:"name,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
	Email    string         `json:"email,omitempty"`
}

func (PageMetadata) Validate added in v0.39.0

func (pm PageMetadata) Validate(maxLimitSize, maxNameSize int) error

Validate validates the page metadata.

type Roles

type Roles interface {
	// AssignRole assigns a role to a user.
	AssignRole(ctx context.Context, id, role string) error

	// RetrieveRole retrieves a role for a user.
	RetrieveRole(ctx context.Context, id string) (string, error)
}

type RolesRepository

type RolesRepository interface {
	// SaveRole saves the user role.
	SaveRole(ctx context.Context, id, role string) error
	// RetrieveRole retrieves the user role.
	RetrieveRole(ctx context.Context, id string) (string, error)
	// UpdateRole updates the user role.
	UpdateRole(ctx context.Context, id, role string) error
	// RemoveRole removes the user role.
	RemoveRole(ctx context.Context, id string) error
}

type Service

type Service interface {
	Authn
	Authz
	Roles
	Orgs
	OrgMemberships
	Invites
	Keys
}

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(orgs OrgRepository, tc protomfx.ThingsServiceClient, uc protomfx.UsersServiceClient, keys KeyRepository, roles RolesRepository,
	memberships OrgMembershipsRepository, invites OrgInvitesRepository, emailer Emailer, idp uuid.IDProvider, tokenizer Tokenizer, loginDuration time.Duration, inviteDuration time.Duration) Service

New instantiates the auth service implementation.

type Tokenizer

type Tokenizer interface {
	// Issue converts API Key to its string representation.
	Issue(Key) (string, error)

	// Parse extracts API Key data from string token.
	Parse(string) (Key, 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
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 redis contains cache implementations using Redis as the underlying database.
Package redis contains cache implementations using Redis as the underlying database.
Package tracing contains middlewares that will add spans to existing traces.
Package tracing contains middlewares that will add spans to existing traces.

Jump to

Keyboard shortcuts

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