authn

package
v0.0.0-...-bab65f3 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: MIT Imports: 6 Imported by: 0

README

Authn - Authentication Module

The authentication module provides the capabilities to manage clients, create login sessions and authenticate tokens.

The module supports the messaging API to manage clients, and offers a http API for password login, logout and token refresh.

Status

This module is in alpha. It is functional but breaking changes can be expected.

Usage

To create an instance of the module a http server can be provided that will serve the http endpoints. The http server is optional and used to make http endpoints available for logging in, logging out and token refresh. The AuthnHttpClient is a simple wrapper to simplify its usage.

In order to login and create auth tokens, an account must be created for the client first. The module api can be used to manage clients. The module TM also describes which actions are available for user management through RRN messages.

HTTP API

This module supports the Things API of the discovery specification.

The TD published by this module provides the actual endpoints for the various operations. The endpoints described below are examples that are based on the defaults.

Login (public route)

Path: /authn/login Input: JSON object

{
  "username": "name",
  "password": "pass"
}

This returns a bearer token that must be placed in the http authorization header:

"authorization": "bearer {token}"

Logout

Logout requires a valid authentication token.

POST /authn/logout

Refresh Token

Token refresh requires an authenticated connection.

POST /authn/refresh

See the test cases for example on how to use this module in the code.

Documentation

Overview

package authn with admin service messaging definitions

package authn with messaging definitions for the authn user service

Index

Constants

View Source
const (
	// Property names
	AdminPropNrClients = "nrClients"

	// Event names
	AdminEventAdded   = "added"
	AdminEventRemoved = "removed"

	// Action names
	AdminActionAddClient   = "addClient"
	AdminActionGetProfile  = "getProfile"
	AdminActionGetProfiles = "getProfiles"
	// AdminActionGetSessions  = "getSessions"
	AdminActionRemoveClient  = "removeClient"
	AdminActionSetPassword   = "setPassword"
	AdminActionSetRole       = "setRole"
	AdminActionUpdateProfile = "updateProfile"
)

property, event and action names

View Source
const (
	DefaultAgentTokenValidityDays    = 90
	DefaultConsumerTokenValidityDays = 30
	DefaultServiceTokenValidityDays  = 365
)

Session token validity for client types

View Source
const (
	PWHASH_ARGON2id = "argon2id"
	PWHASH_BCRYPT   = "bcrypt" // fallback in case argon2id cannot be used
)

supported password hashes

View Source
const (

	// Action names
	UserActionGetProfile    = "getProfile"
	UserActionLogin         = "login"
	UserActionLogout        = "Logout"
	UserActionRefreshToken  = "refreshToken"
	UserActionSetPassword   = "setPassword"
	UserActionUpdateProfile = "updateProfile"
)

RRN Thing property, event and action affordance names

View Source
const (
	// HttpPostLoginPath is the http authentication endpoint of the module
	HttpPostLoginPath   = "/authn/login"
	HttpPostLogoutPath  = "/authn/logout"
	HttpPostRefreshPath = "/authn/refresh"
	HttpGetProfilePath  = "/authn/profile"
)

well-known HTTP API endpoints - these must match the TD

View Source
const (
	AuthnModuleType       = "authn"
	DefaultAdminServiceID = "authnAdmin"
	DefaultUserServiceID  = "authnUser"
)

This module exposes two services, one admin service and one user oriented service. Currently only a single instance of the authn service module is supported.

View Source
const (

	// ClientRoleNone means that the client has no permissions.
	// It can not do anything until the role is upgraded to viewer or better
	ClientRoleNone string = "none"

	// ClientRoleViewer for users that can view information for devices/services
	// they have access to.
	// Viewers cannot invoke actions or change configuration.
	ClientRoleViewer string = "viewer"

	// ClientRoleAgent for devices and services.
	//
	// Agents publish device information for the devices/services it manages and
	// receive request for those devices/services.
	ClientRoleAgent string = "agent"

	// ClientRoleOperator for users that operate devices and services.
	//
	// Operators can view and control devices/services they have access to but
	// not configure them.
	ClientRoleOperator string = "operator"

	// ClientRoleManager for users that manage devices.
	//
	// Managers can view, control and configure devices/services they have access to.
	ClientRoleManager string = "manager"

	// ClientRoleAdmin for users that administer the system.
	//
	// Administrators can view, control and configure all devices and services.
	ClientRoleAdmin string = "admin"

	// ClientRoleService for Service role
	//
	// Services are equivalent to an admin user and agent for devices/services they
	// have access to.
	ClientRoleService string = "service"
)

Predefined roles of a client The roles are hierarchical in permissions: Authorization using these roles is applied through an authz service. Custom roles can be added if needed but their persmissions need to be managed in the authz service.

View Source
const AuthnAdminServiceID = "authn:admin"

AuthnAdminServiceID is the default thingID of the admin service.

View Source
const AuthnUserServiceID = "authn:user"

AuthnUserThingID is the Thing instance ID of the user facing auth service.

View Source
const DefaultAdminUserID = "admin"

DefaultAdminUserID is the client ID of the default CLI administrator account

View Source
const DefaultPasswordFile = "hub.passwd"

DefaultPasswordFile is the recommended password filename for user storage

Variables

View Source
var AuthnAdminTM []byte

Embed admin service TM

View Source
var AuthnUserTM []byte

Embed user service TM

Functions

This section is empty.

Types

type AdminAddClientArgs

type AdminAddClientArgs struct {

	// ClientID with Client ID
	ClientID string `json:"clientID,omitempty"`

	// DisplayName with Display Name
	DisplayName string `json:"displayName,omitempty"`

	// Role of the client
	Role string `json:"role,omitempty"`
}

AdminAddClientArgs defines the arguments of the addAgent function Add Agent - Create an account for IoT device agents

type AdminGetProfilesResp

type AdminGetProfilesResp []struct {

	// AdminGetProfilesResp with Client Profile
	AdminGetProfilesResp *ClientProfile `json:"AdminGetProfilesResp,omitempty"`
}

AdminGetProfilesResp defines the response of the getProfiles function Get Profiles - Get a list of all client profiles AdminGetProfilesResp defines a Client Profiles data schema.

type AdminSetPasswordArgs

type AdminSetPasswordArgs struct {
	UserName string `json:"username"`
	Password string `json:"password"`
}

args for setting a client's password used in http and rrn messaging

type AdminSetRoleArgs

type AdminSetRoleArgs struct {
	ClientID string `json:"clientID"`
	Role     string `json:"role"`
}

args for setting a client's role used in rrn messaging

type AdminUpdateProfileArgs

type AdminUpdateProfileArgs struct {
	ClientID string        `json:"clientID"`
	Profile  ClientProfile `json:"profile"`
}

args for updating a client's profile used in http and rrn messaging

type AuthnConfig

type AuthnConfig struct {
	// PasswordFile with the file based password store.
	// Use a relative path for using the default $HOME/stores/authn location
	// Use "" for default defined in 'authnstore.DefaultPasswordFile'
	PasswordFile string `yaml:"passwordFile,omitempty"`
	// Encryption of passwords: "argon2id" (default) or "bcrypt"
	Encryption string `yaml:"encryption,omitempty"`

	// predefined accounts
	// Location of client keys and tokens
	KeysDir string `yaml:"certsDir,omitempty"`

	// The default admin account ID to create
	AdminAccountID string `yaml:"adminAccountID,omitempty"`
}

AuthnConfig contains the auth service configuration

func NewAuthnConfig

func NewAuthnConfig(keysDir, storageDir string) AuthnConfig

NewAuthnConfig creates a new AuthnConfig with default values and applies the Setup to ensure the config is valid.

Location of client keys and tokens

storesDir is the authentication data storage directory ($HOME/stores/authn)

func (*AuthnConfig) Setup

func (cfg *AuthnConfig) Setup(keysDir, storageDir string)

Setup ensures config is valid

storesDir is the default storage root directory ($HOME/stores/authn)

type ClientProfile

type ClientProfile struct {

	// ClientID with the unique client ID
	ClientID string `json:"clientID,omitempty"`

	// Disabled flag to enable/disable the client account
	Disabled bool `json:"disabled,omitempty"`

	// DisplayName of the client
	DisplayName string `json:"displayName,omitempty"`

	// PubKey with public key in PEM format intended for encryption
	PubKeyPem string `json:"pubKey,omitempty"`

	// Role of the client when the account is enabled
	// note that roles can only be updated using UpdateProfile by administrators.
	Role string `json:"role,omitempty"`

	// TimeCreated time the client account was created
	TimeCreated string `json:"created,omitempty"`

	// TimeUpdated time the client was last updated
	TimeUpdated string `json:"updated,omitempty"`
}

ClientProfile defines a Client Profile data schema.

This contains client information of device agents, services and consumers

type IAuthnService

type IAuthnService interface {
	modules.IHiveModule

	// AddClient add a new client account. This fails if the client already exists.
	// Use authenticator's SetPassword or CreateToken to obtain a token to connect.
	AddClient(clientID string, displayName string, role string) error

	// GetProfile Get the client profile
	GetProfile(clientID string) (profile ClientProfile, err error)

	// GetProfiles Get Profiles
	// Get a list of all client profiles
	GetProfiles() (profiles []ClientProfile, err error)

	// obtain the session manager for authentication use by transport modules
	GetSessionManager() ISessionManager

	// RemoveClient removes client account
	RemoveClient(clientID string) error

	// SetPassword sets a client's password for use with Login()
	SetPassword(clientID string, password string) error

	// SetRole sets a client's role.
	// Like passwords only an admin or service can update roles.
	SetRole(clientID string, role string) error

	// UpdateProfile changes a client's profile.
	// Only administrators can update the role. (senderID has role admin or service)
	UpdateProfile(senderID string, profile ClientProfile) error
}

Interface of the authentication server module for managing clients and provide the session manager and authenticator.

type ISessionManager

type ISessionManager interface {
	transports.IAuthenticator

	// CreateToken creates a signed authentication token for a client.
	//
	// The client must be a known client.
	//
	// If no session has started, a new one will be created. This is intended for
	// issuing agent tokens (devices, services) where login is not applicable.
	//
	// Note that accidentally created tokens can be invalidated by invoking Logout.
	// The authenticator tracks a sessionStart time and only tokens created
	// after the sessionStart times are valid.
	//
	//	clientID identifies the client
	//	validity is the duration of the token starting
	//
	// This returns an error if clientID is missing or validity is 0
	CreateToken(clientID string, validity time.Duration) (token string, validUntil time.Time, err error)

	// Login with a password and obtain a new authentication token with limited duration.
	// The token must be refreshed before it expires.
	//
	// Token validation is determined through configuration.
	//
	// This returns the authentication token and the expiration time before it must be refreshed.
	// If the login fails this returns an error
	Login(login string, password string) (token string, validUntil time.Time, err error)

	// Logout invalidates all tokens of this client issued before now.
	Logout(clientID string)

	// RefreshToken issues a new authentication token with an updated expiry time.
	// This extends the life of the session.
	//
	//	clientID Client whose token to refresh
	//	oldToken must be valid
	//
	// This returns the token and the validity time before it must be refreshed,
	// If the clientID is unknown or oldToken is no longer valid this returns an error
	RefreshToken(clientID string, oldToken string) (newToken string, validUntil time.Time, err error)

	// ValidatePassword checks if the given password is valid for the client
	ValidatePassword(clientID string, password string) (err error)
}

Interface of client session management that also support transport authentication

type UserLoginArgs

type UserLoginArgs struct {
	UserName string `json:"username"`
	Password string `json:"password"`
}

Definition of the login request message used in http and rrn messaging

type UserSetPasswordArgs

type UserSetPasswordArgs struct {

	// ClientID with Client ID
	ClientID string `json:"clientID,omitempty"`

	// Password with Password
	Password string `json:"password,omitempty"`
}

UserSetPasswordArgs defines the arguments of the setClientPassword function Set Client Password - Update the password of a consumer

Client ID and password

Directories

Path Synopsis
internal
Package authnclient with administration facing methods
Package authnclient with administration facing methods

Jump to

Keyboard shortcuts

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