Documentation
¶
Index ¶
- Constants
- Variables
- func CanDecryptTOTPSecret(db *sql.DB, username string) (present bool, decryptable bool, enabled bool, setupCompleted bool, err error)
- func CheckAndGenerateBootstrapToken(db *sql.DB) error
- func CleanupExpiredSessions(db *sql.DB) error
- func CleanupExpiredTokens(db *sql.DB) error
- func CleanupTOTPLogs(db *sql.DB) error
- func ClientCreateCredentialRequest(password []byte) ([]byte, []byte, error)
- func ClientCreateRegistrationRequest(password []byte) ([]byte, []byte, error)
- func ClientFinalizeRegistration(usrCtx []byte, serverResponse []byte, username string) ([]byte, []byte, error)
- func ClientRecoverCredentials(sec []byte, serverResponse []byte, username string) ([]byte, []byte, []byte, error)
- func CompleteTOTPSetup(db *sql.DB, username, testCode string) error
- func CreateAuthSession(db *sql.DB, username string, flowType string, serverPublicKey []byte) (string, error)
- func CreateCredentialResponse(credentialRequest []byte, userRecord []byte, username string) ([]byte, []byte, error)
- func CreateDevAdminWithOPAQUE(db *sql.DB, username, password string) (*models.User, error)
- func CreateRegistrationResponse(requestData []byte) ([]byte, []byte, error)
- func DeleteAllRefreshTokensForUser(db *sql.DB, username string) error
- func DeleteAuthSession(db *sql.DB, sessionID string) error
- func GenerateFullAccessToken(username string) (string, time.Time, error)
- func GenerateRefreshToken() (string, error)
- func GenerateTemporaryTOTPToken(username string) (string, time.Time, error)
- func GenerateToken(username string) (string, time.Time, error)
- func GetJWTPrivateKey() ed25519.PrivateKey
- func GetJWTPublicKey() ed25519.PublicKey
- func GetOPAQUEServer() (bool, error)
- func GetServerKeys() ([]byte, []byte, error)
- func GetUsernameFromToken(c echo.Context) string
- func HashToken(token string) (string, error)
- func IsOPAQUEAvailable() bool
- func IsRevoked(db *sql.DB, tokenID string) (bool, error)
- func IsUserJWTRevoked(db *sql.DB, username string, tokenIssuedAt time.Time) (bool, error)
- func IsUserTOTPEnabled(db *sql.DB, username string) (bool, error)
- func JWTMiddleware() echo.MiddlewareFunc
- func LoadJWTKeys() error
- func RequiresTOTPFromToken(c echo.Context) bool
- func ResetKeysForTest()
- func RevokeAllUserJWTTokens(db *sql.DB, username, reason string) error
- func RevokeToken(db *sql.DB, tokenString, reason string) error
- func SetupDevAdminTOTP(db *sql.DB, user *models.User, totpSecret string) error
- func SetupServerKeys(db *sql.DB) error
- func StoreTOTPSetup(db *sql.DB, username string, setup *TOTPSetup) error
- func StoreUserRecord(rsec []byte, rrec []byte) ([]byte, error)
- func TOTPJWTMiddleware() echo.MiddlewareFunc
- func TokenRevocationMiddleware(db *sql.DB) echo.MiddlewareFunc
- func UserAuth(authUServer []byte, authUClient []byte) error
- func ValidateAuthSession(db *sql.DB, sessionID string, expectedFlowType string) (username string, serverPk []byte, err error)
- func ValidateBackupCode(db *sql.DB, username, code string) error
- func ValidateBootstrapToken(tokenHex string) (bool, error)
- func ValidateDevAdminAuthentication(db *sql.DB, username, password, totpSecret string) error
- func ValidateDevAdminTOTPWorkflow(db *sql.DB, user *models.User, totpSecret string) error
- func ValidateOPAQUESetup(db *sql.DB) error
- func ValidateTOTPCode(db *sql.DB, username, code string) error
- type Claims
- type OPAQUEServerKeys
- type OPAQUEUserData
- type TOTPData
- type TOTPSetup
Constants ¶
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
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 )
const BackupCodeCharset = "ACDEFGHJKLMNPQRTUVWXY34679"
Human-friendly backup code character set (excludes B/8, O/0, I/1, S/5, Z/2)
Variables ¶
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 ¶
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 ¶
CleanupExpiredSessions removes all expired sessions
func CleanupExpiredTokens ¶
CleanupExpiredTokens removes expired tokens from the database This should be called periodically, perhaps daily, to clean up the database
func CleanupTOTPLogs ¶
CleanupTOTPLogs removes old TOTP usage logs
func ClientCreateCredentialRequest ¶
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 ¶
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 ¶
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 ¶
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 ¶
CreateRegistrationResponse handles server-side step of registration Takes client's registration request (M) and returns server response (rpub) and secret (rsec)
func DeleteAuthSession ¶
DeleteAuthSession removes a session after use
func GenerateFullAccessToken ¶
GenerateFullAccessToken creates a full access JWT token after TOTP validation
func GenerateRefreshToken ¶
GenerateRefreshToken creates a cryptographically secure random string to be used as a refresh token. It aims for approximately 256 bits of entropy.
func GenerateTemporaryTOTPToken ¶
GenerateTemporaryTOTPToken creates a temporary JWT token that requires TOTP completion
func GetJWTPrivateKey ¶
func GetJWTPrivateKey() ed25519.PrivateKey
GetJWTPrivateKey returns the loaded Ed25519 private key
func GetJWTPublicKey ¶
GetJWTPublicKey returns the loaded Ed25519 public key
func GetOPAQUEServer ¶
GetOPAQUEServer returns a simple status check for libopaque server readiness
func GetServerKeys ¶
GetServerKeys returns the server's public and private keys for OPAQUE operations.
func GetUsernameFromToken ¶
func HashToken ¶
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 IsUserJWTRevoked ¶
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 ¶
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 ¶
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 ¶
RevokeAllUserJWTTokens creates a user-wide JWT revocation entry This invalidates all JWTs issued to a user before the current timestamp
func RevokeToken ¶
RevokeToken adds a token to the revocation list
func SetupDevAdminTOTP ¶
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 ¶
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 ¶
StoreTOTPSetup stores the TOTP setup data in the database with server-side encryption
func StoreUserRecord ¶
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 ¶
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 ¶
ValidateBackupCode validates and consumes a backup code
func ValidateBootstrapToken ¶
ValidateBootstrapToken checks if the provided token matches the stored bootstrap token. Uses constant-time comparison to prevent timing attacks.
func ValidateDevAdminAuthentication ¶
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 ¶
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 ¶
ValidateOPAQUESetup validates that the libopaque setup is properly configured
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 ¶
GenerateTOTPSetup creates a new TOTP setup for a user
func GetPendingTOTPSetup ¶
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.