auth

package
v0.0.0-...-f883f01 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: AGPL-3.0 Imports: 31 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
)

OPAQUE protocol constants from libopaque

View Source
const (
	TOTPIssuer       = "Arkfile"
	TOTPDigits       = 6
	TOTPPeriod       = 30
	TOTPSkew         = 1 // Allow ±1 window (90 seconds total: current + prev/next 30s windows)
	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 AuthenticateUser

func AuthenticateUser(db *sql.DB, username, password string) ([]byte, error)

AuthenticateUser performs the libopaque authentication flow using the one-step method

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 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 CompleteTOTPSetup

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

CompleteTOTPSetup validates a test code and enables TOTP for the user

func DeleteAllRefreshTokensForUser

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

func DisableTOTP

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

DisableTOTP disables TOTP for a user (requires current TOTP code)

func GenerateFullAccessToken

func GenerateFullAccessToken(username string) (string, 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, error)

GenerateTemporaryTOTPToken creates a temporary JWT token that requires TOTP completion

func GenerateToken

func GenerateToken(username string) (string, 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 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 is a convenience function that checks if OPAQUE operations are available through the current provider.

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

func RegisterUser

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

RegisterUser performs the libopaque registration flow using the one-step method

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 RestoreProvider

func RestoreProvider(originalProvider OPAQUEProvider)

RestoreProvider restores a previously saved provider. This should only be used in test code for cleanup.

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 SetTestProvider

func SetTestProvider(testProvider OPAQUEProvider)

SetTestProvider overrides the global provider for testing purposes. This should only be used in test code.

func SetupServerKeys

func SetupServerKeys(db *sql.DB) error

SetupServerKeys generates and stores server key material if it doesn't already exist

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 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 ValidateBackupCode

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

ValidateBackupCode validates and consumes a backup code

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 OPAQUEPasswordManager

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

OPAQUEPasswordManager handles all password authentication via OPAQUE

func NewOPAQUEPasswordManager

func NewOPAQUEPasswordManager() *OPAQUEPasswordManager

NewOPAQUEPasswordManager creates a new password manager instance

func NewOPAQUEPasswordManagerWithDB

func NewOPAQUEPasswordManagerWithDB(db *sql.DB) *OPAQUEPasswordManager

NewOPAQUEPasswordManagerWithDB creates a new password manager instance with a specific database

func (*OPAQUEPasswordManager) AuthenticatePassword

func (opm *OPAQUEPasswordManager) AuthenticatePassword(
	recordIdentifier, password string) ([]byte, error)

AuthenticatePassword authenticates any password via OPAQUE and returns the export key

func (*OPAQUEPasswordManager) DeletePasswordRecord

func (opm *OPAQUEPasswordManager) DeletePasswordRecord(recordIdentifier string) error

DeletePasswordRecord deactivates a password record

func (*OPAQUEPasswordManager) GetFilePasswordRecords

func (opm *OPAQUEPasswordManager) GetFilePasswordRecords(fileID string) ([]*OPAQUEPasswordRecord, error)

GetFilePasswordRecords gets all password records for a specific file

func (*OPAQUEPasswordManager) GetPasswordHint

func (opm *OPAQUEPasswordManager) GetPasswordHint(recordIdentifier string, exportKey []byte) (string, error)

GetPasswordHint decrypts and returns the password hint for a record

func (*OPAQUEPasswordManager) GetPasswordRecord

func (opm *OPAQUEPasswordManager) GetPasswordRecord(recordIdentifier string) (*OPAQUEPasswordRecord, error)

GetPasswordRecord retrieves a password record by identifier

func (*OPAQUEPasswordManager) RegisterCustomFilePassword

func (opm *OPAQUEPasswordManager) RegisterCustomFilePassword(
	username, fileID, password, keyLabel, passwordHint string) error

RegisterCustomFilePassword registers a custom password for a specific file

func (*OPAQUEPasswordManager) RegisterSharePassword

func (opm *OPAQUEPasswordManager) RegisterSharePassword(
	shareID, fileID, ownerUsername, password string) error

RegisterSharePassword registers a password for anonymous share access

type OPAQUEPasswordManagerInterface

type OPAQUEPasswordManagerInterface interface {
	RegisterCustomFilePassword(username, fileID, password, keyLabel, passwordHint string) error
	RegisterSharePassword(shareID, fileID, ownerUsername, password string) error
	AuthenticatePassword(recordIdentifier, password string) ([]byte, error)
	GetPasswordRecord(recordIdentifier string) (*OPAQUEPasswordRecord, error)
	GetFilePasswordRecords(fileID string) ([]*OPAQUEPasswordRecord, error)
	DeletePasswordRecord(recordIdentifier string) error
	GetPasswordHint(recordIdentifier string, exportKey []byte) (string, error)
}

OPAQUEPasswordManagerInterface defines the interface for OPAQUE password management

func GetOPAQUEPasswordManager

func GetOPAQUEPasswordManager() OPAQUEPasswordManagerInterface

GetOPAQUEPasswordManager returns the OPAQUE password manager implementation

func GetOPAQUEPasswordManagerWithDB

func GetOPAQUEPasswordManagerWithDB(db *sql.DB) OPAQUEPasswordManagerInterface

GetOPAQUEPasswordManagerWithDB returns the OPAQUE password manager implementation with database

type OPAQUEPasswordRecord

type OPAQUEPasswordRecord struct {
	ID                    int        `json:"id"`
	RecordType            string     `json:"record_type"`             // 'account', 'file_custom', 'share'
	RecordIdentifier      string     `json:"record_identifier"`       // username, 'user:file:filename', 'share:shareID'
	OPAQUEUserRecord      []byte     `json:"opaque_user_record"`      // OPAQUE registration data
	AssociatedFileID      *string    `json:"associated_file_id"`      // NULL for account, filename for file/share
	AssociatedUsername    *string    `json:"associated_username"`     // User who created this record
	KeyLabel              *string    `json:"key_label"`               // Human-readable label
	PasswordHintEncrypted []byte     `json:"password_hint_encrypted"` // Encrypted with export key
	CreatedAt             time.Time  `json:"created_at"`
	LastUsedAt            *time.Time `json:"last_used_at"`
	IsActive              bool       `json:"is_active"`
}

OPAQUEPasswordRecord represents a unified password record

type OPAQUEProvider

type OPAQUEProvider interface {
	// RegisterUser performs OPAQUE user registration, creating a new user record
	// from a password and server private key. Returns the user record and export key.
	RegisterUser(password []byte, serverPrivateKey []byte) ([]byte, []byte, error)

	// AuthenticateUser performs OPAQUE authentication using a password and stored
	// user record. Returns the export key on successful authentication.
	AuthenticateUser(password []byte, userRecord []byte) ([]byte, error)

	// IsAvailable returns true if the OPAQUE provider is ready for operations.
	IsAvailable() bool

	// GetServerKeys returns the server's public and private keys for OPAQUE operations.
	// These are used for user registration and server-side authentication.
	GetServerKeys() ([]byte, []byte, error)

	// GenerateServerKeys creates new server keys for OPAQUE operations.
	// This is typically called once during initial setup.
	GenerateServerKeys() ([]byte, []byte, error)
}

OPAQUEProvider defines the interface for OPAQUE authentication operations. Static linking eliminates the need for mock implementations.

func GetOPAQUEProvider

func GetOPAQUEProvider() OPAQUEProvider

GetOPAQUEProvider returns the static OPAQUE provider.

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 RealOPAQUEProvider

type RealOPAQUEProvider struct{}

RealOPAQUEProvider wraps the existing OPAQUE implementation to match the interface

func NewRealOPAQUEProvider

func NewRealOPAQUEProvider() *RealOPAQUEProvider

NewRealOPAQUEProvider creates a new real OPAQUE provider

func (*RealOPAQUEProvider) AuthenticateUser

func (r *RealOPAQUEProvider) AuthenticateUser(password []byte, userRecord []byte) ([]byte, error)

AuthenticateUser implements the OPAQUEProvider interface using real OPAQUE

func (*RealOPAQUEProvider) GenerateServerKeys

func (r *RealOPAQUEProvider) GenerateServerKeys() ([]byte, []byte, error)

GenerateServerKeys implements the OPAQUEProvider interface

func (*RealOPAQUEProvider) GetServerKeys

func (r *RealOPAQUEProvider) GetServerKeys() ([]byte, []byte, error)

GetServerKeys implements the OPAQUEProvider interface

func (*RealOPAQUEProvider) IsAvailable

func (r *RealOPAQUEProvider) IsAvailable() bool

IsAvailable implements the OPAQUEProvider interface

func (*RealOPAQUEProvider) RegisterUser

func (r *RealOPAQUEProvider) RegisterUser(password []byte, serverPrivateKey []byte) ([]byte, []byte, error)

RegisterUser implements the OPAQUEProvider interface using real OPAQUE

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:"qrCodeUrl"`
	BackupCodes []string `json:"backupCodes"`
	ManualEntry string   `json:"manualEntry"`
}

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

Jump to

Keyboard shortcuts

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