auth

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const SessionCookie = "dc_session"

SessionCookie is the name of the httpOnly cookie carrying the session JWT.

View Source
const TOTPIssuer = "Docker Commander"

TOTPIssuer is the label shown in authenticator apps (Google Authenticator, Authy, 1Password, …) next to the account.

Variables

View Source
var (
	ErrSetupDone       = errors.New("auth: setup already completed")
	ErrInvalidCreds    = errors.New("auth: invalid credentials")
	ErrRateLimited     = errors.New("auth: too many attempts, try again later")
	ErrMFARequired     = errors.New("auth: 2fa code required")
	ErrInvalidMFACode  = errors.New("auth: invalid 2fa code")
	ErrWeakPassword    = errors.New("auth: password must be at least 10 characters")
	ErrInvalidUsername = errors.New("auth: username must be 3-32 characters")
)

Common authentication errors surfaced to the API layer.

View Source
var ErrInvalidHash = errors.New("auth: invalid password hash format")

ErrInvalidHash is returned when an encoded hash cannot be parsed.

Functions

func HashPassword

func HashPassword(password string) (string, error)

HashPassword derives an Argon2id hash and returns it in the standard PHC encoded string form, e.g. $argon2id$v=19$m=65536,t=3,p=2$<salt>$<hash>.

func LDAPTest

func LDAPTest(cfg store.LDAPConfig) (int, error)

LDAPTest verifies the LDAP settings: dial, optional StartTLS, service bind, and a base search. Returns the number of entries under the user base.

func ValidateTOTP

func ValidateTOTP(code, secret string) bool

ValidateTOTP reports whether code is currently valid for secret. A small skew window is allowed to tolerate clock drift between server and device.

func VerifyPassword

func VerifyPassword(password, encoded string) (bool, error)

VerifyPassword reports whether password matches the encoded hash. The comparison is constant-time to avoid leaking timing information.

Types

type Claims

type Claims struct {
	UserID   int64     `json:"uid"`
	Username string    `json:"usr"`
	Role     string    `json:"role"`
	Kind     TokenKind `json:"knd"`
	jwt.RegisteredClaims
}

Claims is the JWT payload used for both session and MFA-challenge tokens.

func ClaimsFrom

func ClaimsFrom(ctx context.Context) (*Claims, bool)

ClaimsFrom returns the authenticated claims stored in the request context.

type Enrollment

type Enrollment struct {
	Secret     string `json:"secret"`     // base32 secret, also shown for manual entry
	OtpauthURL string `json:"otpauthUrl"` // otpauth:// provisioning URI
	QRDataURI  string `json:"qrDataUri"`  // data:image/png;base64,... for <img src>
}

Enrollment holds the data needed to show a user how to add their 2FA token.

func GenerateTOTP

func GenerateTOTP(accountName string) (*Enrollment, error)

GenerateTOTP creates a new TOTP secret for accountName and renders a QR code as a data URI so the frontend can display it without extra endpoints.

type LDAPResult

type LDAPResult struct {
	Username string
	IsAdmin  bool // member of the configured admin group
}

LDAPResult is the outcome of a successful LDAP authentication.

func LDAPAuthenticate

func LDAPAuthenticate(cfg store.LDAPConfig, username, password string) (*LDAPResult, error)

LDAPAuthenticate verifies a username/password against an LDAP/AD directory: bind with the service account, search for the user, then bind as that user to validate the password. If an admin group is configured, group membership is reported so the account can be provisioned as an admin.

type LoginLimiter

type LoginLimiter struct {
	// contains filtered or unexported fields
}

LoginLimiter is a small in-memory fixed-window rate limiter keyed by client identity (IP or username). It throttles brute-force login attempts without any external dependency. Suitable for a single-instance local tool.

func NewLoginLimiter

func NewLoginLimiter(max int, window time.Duration) *LoginLimiter

NewLoginLimiter allows max failed attempts within the given window.

func (*LoginLimiter) Allow

func (l *LoginLimiter) Allow(key string) bool

Allow reports whether another attempt is permitted for key right now. It does not consume an attempt; call Fail to record a failed attempt.

func (*LoginLimiter) Fail

func (l *LoginLimiter) Fail(key string)

Fail records a failed attempt for key, starting a window if needed.

func (*LoginLimiter) Reset

func (l *LoginLimiter) Reset(key string)

Reset clears the counter for key after a successful login.

type LoginResult

type LoginResult struct {
	MFARequired bool
	Token       string // session token, or MFA-challenge token if MFARequired
	ExpiresAt   time.Time
	User        *store.User
}

LoginResult is returned from Login: either a finished session, or an MFA challenge the caller must satisfy via VerifyMFA.

type Middleware

type Middleware struct {
	// contains filtered or unexported fields
}

Middleware enforces a valid, fully-authenticated session token. It reads the token from the session cookie first, then falls back to an Authorization Bearer header (useful for API clients and tooling).

func NewMiddleware

func NewMiddleware(tokens *TokenManager) *Middleware

NewMiddleware builds auth middleware backed by the given token manager.

func (*Middleware) ParseSessionToken

func (m *Middleware) ParseSessionToken(raw string) (*Claims, error)

ParseSessionToken validates a raw token and ensures it is a session token. Used by the WebSocket handler which authenticates before upgrading.

func (*Middleware) RequireSession

func (m *Middleware) RequireSession(next http.Handler) http.Handler

RequireSession wraps next, rejecting requests without a valid session token.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service orchestrates the authentication flows on top of the store and the crypto/token primitives in this package.

func NewService

func NewService(s *store.Store, tm *TokenManager) *Service

NewService wires the auth service together.

func (*Service) BeginTOTPEnrollment

func (s *Service) BeginTOTPEnrollment(ctx context.Context, userID int64) (*Enrollment, error)

BeginTOTPEnrollment generates a new secret + QR for the user. The secret is stored but not yet enabled until confirmed via ConfirmTOTPEnrollment.

func (*Service) ConfirmTOTPEnrollment

func (s *Service) ConfirmTOTPEnrollment(ctx context.Context, userID int64, code string) error

ConfirmTOTPEnrollment validates the first code and enables 2FA for the user.

func (*Service) CreateAccount

func (s *Service) CreateAccount(ctx context.Context, username, password, role string, readOnly bool, sections []string) (*store.User, error)

CreateAccount creates a non-setup user account (used by admins). role is "admin" or "user"; for "user", sections and readOnly scope their access.

func (*Service) Login

func (s *Service) Login(ctx context.Context, rlKey, username, password string, exemptMFA bool) (*LoginResult, error)

Login verifies username+password. If the account has TOTP enabled it returns an MFA challenge token; otherwise a full session token. rlKey is the rate limit bucket (typically the client IP). exemptMFA skips the 2FA step (used for localhost when the admin has allowed it).

func (*Service) NeedsSetup

func (s *Service) NeedsSetup(ctx context.Context) (bool, error)

NeedsSetup reports whether no account exists yet (first-run wizard).

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, userID int64, password string) error

SetPassword replaces a user's password (admin reset or self-change).

func (*Service) Setup

func (s *Service) Setup(ctx context.Context, username, password string) (*store.User, error)

Setup creates the first admin account. It fails once any user exists.

func (*Service) VerifyMFA

func (s *Service) VerifyMFA(ctx context.Context, challengeToken, code string) (*LoginResult, error)

VerifyMFA completes login by validating a TOTP code against the MFA-challenge token issued by Login.

type TokenKind

type TokenKind string

TokenKind distinguishes a fully-authenticated session token from the short-lived intermediate token issued between the password and 2FA steps.

const (
	// KindSession is a fully authenticated token (password + 2FA satisfied).
	KindSession TokenKind = "session"
	// KindMFAChallenge is issued after a correct password when TOTP is still
	// required. It only authorises calling the 2FA verification endpoint.
	KindMFAChallenge TokenKind = "mfa"
)

type TokenManager

type TokenManager struct {
	// contains filtered or unexported fields
}

TokenManager mints and verifies HMAC-signed JWTs.

func NewTokenManager

func NewTokenManager(secret []byte, sessionTTL time.Duration) *TokenManager

NewTokenManager returns a manager signing with secret. sessionTTL controls how long a logged-in session stays valid before re-authentication.

func (*TokenManager) Issue

func (m *TokenManager) Issue(userID int64, username, role string, kind TokenKind) (string, time.Time, error)

Issue creates a signed token for the given user and kind.

func (*TokenManager) Parse

func (m *TokenManager) Parse(tokenString string) (*Claims, error)

Parse validates the signature and expiry and returns the claims.

Jump to

Keyboard shortcuts

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