auth

package
v0.0.0-...-101d28d Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: AGPL-3.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OPAQUE_USER_RECORD_LEN         = 256
	OPAQUE_SHARED_SECRETBYTES      = 64
	OPAQUE_REGISTRATION_RECORD_LEN = 192
	OPAQUE_USER_SESSION_PUBLIC_LEN = 96
	OPAQUE_USER_SESSION_SECRET_LEN = 226
	OPAQUE_SERVER_SESSION_LEN      = 320

	// Multi-step registration constants
	OPAQUE_REGISTER_USER_SEC_LEN = 34 // 32 (r) + 2 (pwdU_len)
	OPAQUE_REGISTER_REQUEST_LEN  = 32 // crypto_core_ristretto255_BYTES (blinded element M)
	OPAQUE_REGISTER_PUBLIC_LEN   = 64 // 32 (Z) + 32 (pkS) - server response
	OPAQUE_REGISTER_SECRET_LEN   = 64 // 32 (skS) + 32 (kU)
)

OPAQUE protocol constants from libopaque

View Source
const (
	TOTPIssuer       = "Arkfile"
	TOTPDigits       = 6
	TOTPPeriod       = 30
	TOTPSkew         = 0 // Allow ±0 window (60 seconds total: current + prev/next 30s windows = ±25s tolerance)
	BackupCodeLength = 10
	BackupCodeCount  = 10
)
View Source
const BackupCodeCharset = "ACDEFGHJKLMNPQRTUVWXY34679"

Human-friendly backup code character set (excludes B/8, O/0, I/1, S/5, Z/2)

Variables

View Source
var Echo *echo.Group

Echo is the Echo group with authentication middleware applied

Functions

func CanDecryptTOTPSecret

func CanDecryptTOTPSecret(db *sql.DB, username string) (present bool, decryptable bool, enabled bool, setupCompleted bool, err error)

CanDecryptTOTPSecret checks if a user's TOTP secret can be decrypted (dev diagnostic helper) This is exported for use by dev-only diagnostic endpoints

func CheckAndGenerateBootstrapToken

func CheckAndGenerateBootstrapToken(db *sql.DB) error

CheckAndGenerateBootstrapToken checks if the system needs bootstrapping. Bootstrap mode is enabled when: 1. No ACTIVE admin users exist (users with last_login set), OR 2. ARKFILE_FORCE_ADMIN_BOOTSTRAP environment variable is set to "true"

This function is safe for multi-instance deployments - it checks if a bootstrap token already exists before generating a new one, preventing multiple tokens from being logged to different container stdout streams.

func CleanupExpiredSessions

func CleanupExpiredSessions(db *sql.DB) error

CleanupExpiredSessions removes all expired sessions

func CleanupExpiredTokens

func CleanupExpiredTokens(db *sql.DB) error

CleanupExpiredTokens removes expired tokens from the database This should be called periodically, perhaps daily, to clean up the database

func CleanupTOTPLogs

func CleanupTOTPLogs(db *sql.DB) error

CleanupTOTPLogs removes old TOTP usage logs

func ClientCreateCredentialRequest

func ClientCreateCredentialRequest(password []byte) ([]byte, []byte, error)

ClientCreateCredentialRequest creates the initial authentication request This is Step 1 of the authentication flow (client-side) Input: password (user's password) Output: sec (client secret to store), pub (credential request to send to server)

func ClientCreateRegistrationRequest

func ClientCreateRegistrationRequest(password []byte) ([]byte, []byte, error)

ClientCreateRegistrationRequest creates the initial registration request This is Step 1 of the registration flow (client-side) Input: password (user's password) Output: usrCtx (client context to store), M (registration request to send to server)

func ClientFinalizeRegistration

func ClientFinalizeRegistration(usrCtx []byte, serverResponse []byte, username string) ([]byte, []byte, error)

ClientFinalizeRegistration finalizes the registration process This is Step 3 of the registration flow (client-side) Input: usrCtx (client context from step 1), serverResponse (rpub from server), username Output: rrec (registration record to send to server), exportKey (client export key)

func ClientRecoverCredentials

func ClientRecoverCredentials(sec []byte, serverResponse []byte, username string) ([]byte, []byte, []byte, error)

ClientRecoverCredentials recovers credentials from server response This is Step 3 of the authentication flow (client-side) Input: sec (client secret from step 1), serverResponse (credential response from server), username Output: sk (session key), authU (authentication token to send to server), exportKey (client export key)

func CompleteTOTPSetup

func CompleteTOTPSetup(db *sql.DB, username, testCode string) error

CompleteTOTPSetup validates a test code and enables TOTP for the user

func CreateAuthSession

func CreateAuthSession(db *sql.DB, username string, flowType string, serverPublicKey []byte) (string, error)

CreateAuthSession creates a new authentication session for multi-step protocol

func CreateCredentialResponse

func CreateCredentialResponse(credentialRequest []byte, userRecord []byte, username string) ([]byte, []byte, error)

CreateCredentialResponse handles server-side step of authentication Takes client's credential request (pub), user record (rec), and username, returns server response

func CreateDevAdminWithOPAQUE

func CreateDevAdminWithOPAQUE(db *sql.DB, username, password string) (*models.User, error)

CreateDevAdminWithOPAQUE creates a dev admin user with OPAQUE registration This function simulates the complete client-server OPAQUE registration flow internally to create a dev admin user with known credentials for testing.

CRITICAL SECURITY: This function has triple-layer protection: 1. Production environment check 2. Exact username validation (only "arkfile-dev-admin") 3. ADMIN_USERNAMES environment variable verification

func CreateRegistrationResponse

func CreateRegistrationResponse(requestData []byte) ([]byte, []byte, error)

CreateRegistrationResponse handles server-side step of registration Takes client's registration request (M) and returns server response (rpub) and secret (rsec)

func DeleteAllRefreshTokensForUser

func DeleteAllRefreshTokensForUser(db *sql.DB, username string) error

func DeleteAuthSession

func DeleteAuthSession(db *sql.DB, sessionID string) error

DeleteAuthSession removes a session after use

func GenerateFullAccessToken

func GenerateFullAccessToken(username string) (string, time.Time, error)

GenerateFullAccessToken creates a full access JWT token after TOTP validation

func GenerateRefreshToken

func GenerateRefreshToken() (string, error)

GenerateRefreshToken creates a cryptographically secure random string to be used as a refresh token. It aims for approximately 256 bits of entropy.

func GenerateTemporaryTOTPToken

func GenerateTemporaryTOTPToken(username string) (string, time.Time, error)

GenerateTemporaryTOTPToken creates a temporary JWT token that requires TOTP completion

func GenerateToken

func GenerateToken(username string) (string, time.Time, error)

func GetJWTPrivateKey

func GetJWTPrivateKey() ed25519.PrivateKey

GetJWTPrivateKey returns the loaded Ed25519 private key

func GetJWTPublicKey

func GetJWTPublicKey() ed25519.PublicKey

GetJWTPublicKey returns the loaded Ed25519 public key

func GetOPAQUEServer

func GetOPAQUEServer() (bool, error)

GetOPAQUEServer returns a simple status check for libopaque server readiness

func GetServerKeys

func GetServerKeys() ([]byte, []byte, error)

GetServerKeys returns the server's public and private keys for OPAQUE operations.

func GetUsernameFromToken

func GetUsernameFromToken(c echo.Context) string

func HashToken

func HashToken(token string) (string, error)

HashToken generates a SHA-256 hash of a token string. The raw token should not be stored; only its hash.

func IsOPAQUEAvailable

func IsOPAQUEAvailable() bool

IsOPAQUEAvailable checks if OPAQUE operations are available

func IsRevoked

func IsRevoked(db *sql.DB, tokenID string) (bool, error)

IsRevoked checks if a token has been revoked

func IsUserJWTRevoked

func IsUserJWTRevoked(db *sql.DB, username string, tokenIssuedAt time.Time) (bool, error)

IsUserJWTRevoked checks if all JWTs for a user have been revoked after a specific time This is used during JWT validation to check for user-wide revocations

func IsUserTOTPEnabled

func IsUserTOTPEnabled(db *sql.DB, username string) (bool, error)

IsUserTOTPEnabled checks if TOTP is enabled for a user

func JWTMiddleware

func JWTMiddleware() echo.MiddlewareFunc

func LoadJWTKeys

func LoadJWTKeys() error

LoadJWTKeys loads the Ed25519 private and public keys for JWT signing It uses the KeyManager to retrieve or generate the keys securely.

func RequiresTOTPFromToken

func RequiresTOTPFromToken(c echo.Context) bool

RequiresTOTPFromToken checks if the token requires TOTP completion

func ResetKeysForTest

func ResetKeysForTest()

Testing helper - DO NOT USE IN PRODUCTION ResetKeysForTest resets the sync.Once and key variables for testing purposes

func RevokeAllUserJWTTokens

func RevokeAllUserJWTTokens(db *sql.DB, username, reason string) error

RevokeAllUserJWTTokens creates a user-wide JWT revocation entry This invalidates all JWTs issued to a user before the current timestamp

func RevokeToken

func RevokeToken(db *sql.DB, tokenString, reason string) error

RevokeToken adds a token to the revocation list

func SetupDevAdminTOTP

func SetupDevAdminTOTP(db *sql.DB, user *models.User, totpSecret string) error

SetupDevAdminTOTP sets up TOTP for the dev admin user with a fixed secret This allows predictable TOTP codes for testing purposes.

SECURITY: This function is protected by production environment checks

func SetupServerKeys

func SetupServerKeys(db *sql.DB) error

SetupServerKeys generates and stores server key material if it doesn't already exist. This function is safe for multi-instance deployments - it uses sync.Once to ensure only one goroutine per instance attempts key generation, and handles INSERT conflicts gracefully when multiple instances race to create keys.

func StoreTOTPSetup

func StoreTOTPSetup(db *sql.DB, username string, setup *TOTPSetup) error

StoreTOTPSetup stores the TOTP setup data in the database with server-side encryption

func StoreUserRecord

func StoreUserRecord(rsec []byte, rrec []byte) ([]byte, error)

StoreUserRecord finalizes registration by storing the user record Takes the server secret and client's finalized registration record, returns complete user record

func TOTPJWTMiddleware

func TOTPJWTMiddleware() echo.MiddlewareFunc

TOTPJWTMiddleware creates middleware that only allows TOTP-related operations

func TokenRevocationMiddleware

func TokenRevocationMiddleware(db *sql.DB) echo.MiddlewareFunc

TokenRevocationMiddleware creates a middleware that checks tokens against the revocation list

func UserAuth

func UserAuth(authUServer []byte, authUClient []byte) error

UserAuth validates the client's authentication token Takes server's authU and client's authU, returns true if they match

func ValidateAuthSession

func ValidateAuthSession(db *sql.DB, sessionID string, expectedFlowType string) (username string, serverPk []byte, err error)

ValidateAuthSession validates and retrieves session data

func ValidateBackupCode

func ValidateBackupCode(db *sql.DB, username, code string) error

ValidateBackupCode validates and consumes a backup code

func ValidateBootstrapToken

func ValidateBootstrapToken(tokenHex string) (bool, error)

ValidateBootstrapToken checks if the provided token matches the stored bootstrap token. Uses constant-time comparison to prevent timing attacks.

func ValidateDevAdminAuthentication

func ValidateDevAdminAuthentication(db *sql.DB, username, password, totpSecret string) error

ValidateDevAdminAuthentication performs complete end-to-end validation of dev admin authentication This function simulates the entire OPAQUE authentication flow internally to ensure the dev admin registration was successful and the system is working properly

func ValidateDevAdminTOTPWorkflow

func ValidateDevAdminTOTPWorkflow(db *sql.DB, user *models.User, totpSecret string) error

ValidateDevAdminTOTPWorkflow performs end-to-end TOTP validation for dev admin bootstrap. It verifies that the TOTP secret was stored correctly and can be decrypted, but does NOT generate or validate an actual TOTP code. This avoids "burning" a TOTP window during server startup, which would cause replay-detection failures if an admin login attempt happens within the same 30-second window (e.g., during e2e testing).

func ValidateOPAQUESetup

func ValidateOPAQUESetup(db *sql.DB) error

ValidateOPAQUESetup validates that the libopaque setup is properly configured

func ValidateTOTPCode

func ValidateTOTPCode(db *sql.DB, username, code string) error

ValidateTOTPCode validates a TOTP code with replay protection

Types

type Claims

type Claims struct {
	Username     string `json:"username"`
	RequiresTOTP bool   `json:"requires_totp,omitempty"`
	jwt.RegisteredClaims
}

type OPAQUEServerKeys

type OPAQUEServerKeys struct {
	ServerPrivateKey []byte // 32-byte server private key (crypto_scalarmult_SCALARBYTES)
	ServerPublicKey  []byte // 32-byte server public key (crypto_scalarmult_BYTES)
	OPRFSeed         []byte // 32-byte OPRF seed (crypto_core_ristretto255_SCALARBYTES)
	CreatedAt        time.Time
}

OPAQUEServerKeys represents the server's long-term key material for libopaque

type OPAQUEUserData

type OPAQUEUserData struct {
	Username         string
	SerializedRecord []byte // libopaque user record
	CreatedAt        time.Time
}

OPAQUEUserData represents the server-side storage for libopaque user data

type TOTPData

type TOTPData struct {
	SecretEncrypted      []byte `json:"secret_encrypted"`
	BackupCodesEncrypted []byte `json:"backup_codes_encrypted"`
	Enabled              bool   `json:"enabled"`
	SetupCompleted       bool   `json:"setup_completed"`
	CreatedAt            time.Time
	LastUsed             *time.Time
}

TOTPData represents the stored TOTP data for a user

type TOTPSetup

type TOTPSetup struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	QRCodeImage string   `json:"qr_code_image"` // Base64 data URI for QR code PNG
	BackupCodes []string `json:"backup_codes"`
	ManualEntry string   `json:"manual_entry"`
}

TOTPSetup represents the data needed for TOTP setup

func GenerateTOTPSetup

func GenerateTOTPSetup(username string) (*TOTPSetup, error)

GenerateTOTPSetup creates a new TOTP setup for a user

func GetPendingTOTPSetup

func GetPendingTOTPSetup(db *sql.DB, username string) (*TOTPSetup, error)

GetPendingTOTPSetup retrieves an existing pending (unverified) TOTP setup for a user. Returns the decrypted setup data if a pending setup exists, nil if not. This prevents generating a new secret on every login when setup is incomplete, allowing users to continue with the same secret they may have already saved.

func ResetTOTP

func ResetTOTP(db *sql.DB, username, backupCode string) (*TOTPSetup, error)

ResetTOTP resets TOTP for a user (requires valid backup code) This generates a new TOTP secret and new backup codes while keeping TOTP enabled

Jump to

Keyboard shortcuts

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