handlers

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: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Echo *echo.Echo

Echo is the global echo instance used for routing

Functions

func AccessSharedFile

func AccessSharedFile(c echo.Context) error

AccessSharedFile handles anonymous share access with Argon2id password verification

func AdminAdjustCredits

func AdminAdjustCredits(c echo.Context) error

AdminAdjustCredits allows admins to add, subtract, or set user credits (admin only)

func AdminApproveUser

func AdminApproveUser(c echo.Context) error

AdminApproveUser approves a specific user for testing

func AdminCleanupTestUser

func AdminCleanupTestUser(c echo.Context) error

AdminCleanupTestUser performs comprehensive cleanup of test user data

func AdminContactsHandler

func AdminContactsHandler(c echo.Context) error

AdminContactsHandler returns admin contact information for user support

func AdminForceLogout

func AdminForceLogout(c echo.Context) error

AdminForceLogout allows admin to force-logout a specific user (admin-only endpoint)

func AdminGetAllCredits

func AdminGetAllCredits(c echo.Context) error

AdminGetAllCredits returns credit balances for all users (admin only)

func AdminGetUserCredits

func AdminGetUserCredits(c echo.Context) error

AdminGetUserCredits retrieves credit information for a specific user (admin only)

func AdminGetUserStatus

func AdminGetUserStatus(c echo.Context) error

AdminGetUserStatus returns comprehensive user status information

func AdminMiddleware

func AdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc

AdminMiddleware enforces multi-layer security for admin endpoints

func AdminSecurityEvents

func AdminSecurityEvents(c echo.Context) error

AdminSecurityEvents exposes existing security event logs via admin API

func AdminSetCredits

func AdminSetCredits(c echo.Context) error

AdminSetCredits allows admins to set a user's balance to a specific amount (admin only)

func AdminSystemHealth

func AdminSystemHealth(c echo.Context) error

AdminSystemHealth bridges existing monitoring infrastructure to admin API endpoints

func AdminTOTPDecryptCheck

func AdminTOTPDecryptCheck(c echo.Context) error

AdminTOTPDecryptCheck provides TOTP diagnostic information for development

func ApproveUser

func ApproveUser(c echo.Context) error

ApproveUser approves a user

func CSPMiddleware

func CSPMiddleware(next echo.HandlerFunc) echo.HandlerFunc

CSPMiddleware adds Content Security Policy headers with WASM support

func CancelUpload

func CancelUpload(c echo.Context) error

CancelUpload aborts an in-progress upload session

func CompleteUpload

func CompleteUpload(c echo.Context) error

CompleteUpload finalizes a chunked upload

func CreateFileShare

func CreateFileShare(c echo.Context) error

CreateFileShare creates a new Argon2id-based anonymous file share

func CreateUploadSession

func CreateUploadSession(c echo.Context) error

CreateUploadSession initializes a new chunked upload

func DeleteFile

func DeleteFile(c echo.Context) error

DeleteFile handles file deletion

func DeleteKey

func DeleteKey(c echo.Context) error

DeleteKey removes an encryption key from a file

func DeleteShare

func DeleteShare(c echo.Context) error

DeleteShare deletes a share

func DeleteUser

func DeleteUser(c echo.Context) error

DeleteUser deletes a user and all associated data

func DownloadFile

func DownloadFile(c echo.Context) error

DownloadFile handles file downloads with encrypted metadata

func DownloadFileChunk

func DownloadFileChunk(c echo.Context) error

DownloadFileChunk streams a specific chunk of a file to the client

func DownloadSharedFile

func DownloadSharedFile(c echo.Context) error

DownloadSharedFile handles downloading a shared file (after successful password verification)

func ForceRevokeAllTokens

func ForceRevokeAllTokens(c echo.Context) error

ForceRevokeAllTokens implements security-critical revocation for edge cases This function revokes BOTH refresh tokens AND active JWT tokens immediately Used for: password changes, admin force-logout, security breaches

func GetFileDecryptionKey

func GetFileDecryptionKey(c echo.Context) error

GetFileDecryptionKey provides the encryption key for a file given a password

func GetPendingUsers

func GetPendingUsers(c echo.Context) error

GetPendingUsers returns a list of users pending approval

func GetShareInfo

func GetShareInfo(c echo.Context) error

GetShareInfo gets share metadata without password verification for frontend initialization

func GetSharedFile

func GetSharedFile(c echo.Context) error

GetSharedFile renders the share access page

func GetSharedFileByShareID

func GetSharedFileByShareID(c echo.Context) error

GetSharedFileByShareID is deprecated - use the new anonymous share system in file_shares.go This function is kept temporarily for backwards compatibility but should not be used

func GetUploadStatus

func GetUploadStatus(c echo.Context) error

GetUploadStatus returns the status of an upload session including which chunks have been uploaded

func GetUserCredits

func GetUserCredits(c echo.Context) error

GetUserCredits returns the current user's credit balance and transaction history

func InitializeRateLimitManager

func InitializeRateLimitManager(rateLimitConfig config.RateLimitConfig) error

InitializeRateLimitManager initializes the global rate limit manager

func ListFiles

func ListFiles(c echo.Context) error

ListFiles returns a list of files owned by the user with encrypted metadata

func ListKeys

func ListKeys(c echo.Context) error

ListKeys lists all encryption keys for a file

func ListShares

func ListShares(c echo.Context) error

ListShares returns all shares created by a user

func ListUsers

func ListUsers(c echo.Context) error

ListUsers returns a list of all users

func LogAdminAction

func LogAdminAction(db interface {
	Exec(string, ...interface{}) (sql.Result, error)
}, adminUsername, action, targetUsername, details string) error

LogAdminAction logs an admin action to the admin_logs table

func LoginRateLimitMiddleware

func LoginRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

LoginRateLimitMiddleware provides rate limiting for login endpoints

func Logout

func Logout(c echo.Context) error

Logout handles user logout

func OpaqueHealthCheck

func OpaqueHealthCheck(c echo.Context) error

OpaqueHealthCheck verifies that the OPAQUE system is functioning properly

func OpaqueLogin

func OpaqueLogin(c echo.Context) error

OpaqueLogin handles OPAQUE user authentication with rock-solid reliability

func OpaqueRegister

func OpaqueRegister(c echo.Context) error

OpaqueRegister handles OPAQUE user registration with rock-solid reliability

func RateLimitMiddleware

func RateLimitMiddleware(endpointConfig config.EndpointConfig) echo.MiddlewareFunc

RateLimitMiddleware creates rate limiting middleware for specific endpoints

func RateLimitShareAccess

func RateLimitShareAccess(shareID string, c echo.Context, accessFunc func() error) error

RateLimitShareAccess wraps share access functions with rate limiting logic

func RefreshToken

func RefreshToken(c echo.Context) error

RefreshToken handles refresh token requests

func RegisterCustomFilePassword

func RegisterCustomFilePassword(c echo.Context) error

RegisterCustomFilePassword registers a custom password with OPAQUE for a file

func RegisterRateLimitMiddleware

func RegisterRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

RegisterRateLimitMiddleware provides rate limiting for registration endpoints

func RegisterRoutes

func RegisterRoutes()

RegisterRoutes initializes all routes for the application

func RequireAdmin

func RequireAdmin(next echo.HandlerFunc) echo.HandlerFunc

RequireAdmin ensures the user has admin privileges before allowing access

func RequireApproved

func RequireApproved(next echo.HandlerFunc) echo.HandlerFunc

RequireApproved ensures the user is approved before allowing access

func RequireTOTP

func RequireTOTP(next echo.HandlerFunc) echo.HandlerFunc

RequireTOTP ensures the user has TOTP enabled before allowing access to protected resources

func RevokeAllRefreshTokens

func RevokeAllRefreshTokens(c echo.Context) error

RevokeAllRefreshTokens revokes all refresh tokens for the current user Note: This does NOT revoke active JWT tokens - they will expire automatically within 30 minutes

func RevokeToken

func RevokeToken(c echo.Context) error

RevokeToken revokes a specific JWT token

func SetPrimaryKey

func SetPrimaryKey(c echo.Context) error

SetPrimaryKey sets a key as the primary key for a file

func ShareRateLimitMiddleware

func ShareRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

ShareRateLimitMiddleware provides rate limiting for share access attempts This middleware is designed to work WITH TimingProtectionMiddleware by not short-circuiting timing

func TLSVersionCheck

func TLSVersionCheck(next echo.HandlerFunc) echo.HandlerFunc

TLSVersionCheck middleware adds TLS version information to response headers and logs TLS version usage for analytics

func TOTPAuth

func TOTPAuth(c echo.Context) error

TOTPAuth validates a TOTP code and completes authentication

func TOTPDisable

func TOTPDisable(c echo.Context) error

TOTPDisable disables TOTP for a user

func TOTPRateLimitMiddleware

func TOTPRateLimitMiddleware(endpointType string) echo.MiddlewareFunc

TOTPRateLimitMiddleware provides rate limiting for TOTP endpoints

func TOTPSetup

func TOTPSetup(c echo.Context) error

TOTPSetup initializes TOTP setup for a user

func TOTPStatus

func TOTPStatus(c echo.Context) error

TOTPStatus returns the TOTP status for a user

func TOTPVerify

func TOTPVerify(c echo.Context) error

TOTPVerify completes TOTP setup by verifying a test code

func TimingProtectionMiddleware

func TimingProtectionMiddleware(next echo.HandlerFunc) echo.HandlerFunc

TimingProtectionMiddleware enforces 1-second minimum response time for anonymous endpoints

func UpdateEncryption

func UpdateEncryption(c echo.Context) error

UpdateEncryption handles updating a file's encryption with a new or converted format

func UpdateKey

func UpdateKey(c echo.Context) error

UpdateKey updates a key's label or password hint

func UpdateUser

func UpdateUser(c echo.Context) error

UpdateUser updates user properties

func UpdateUserStorageLimit

func UpdateUserStorageLimit(c echo.Context) error

UpdateUserStorageLimit updates a user's storage limit

func UploadChunk

func UploadChunk(c echo.Context) error

UploadChunk handles individual chunk uploads

func UploadFile

func UploadFile(c echo.Context) error

UploadFile handles file uploads with encrypted metadata

Types

type AdminAdjustCreditsRequest

type AdminAdjustCreditsRequest struct {
	AmountUSD     string  `json:"amount_usd" validate:"required"`
	TransactionID *string `json:"transaction_id,omitempty"`
	Reason        string  `json:"reason" validate:"required"`
	Operation     string  `json:"operation" validate:"required"` // "add", "subtract", "set"
}

AdminAdjustCreditsRequest represents the request payload for admin credit adjustments

type AdminApproveRequest

type AdminApproveRequest struct {
	ApprovedBy string `json:"approved_by" validate:"required"`
}

AdminApproveRequest represents the request payload for user approval

type AdminApproveResponse

type AdminApproveResponse struct {
	Success    bool      `json:"success"`
	Username   string    `json:"username"`
	IsApproved bool      `json:"isApproved"`
	ApprovedBy string    `json:"approvedBy"`
	ApprovedAt time.Time `json:"approvedAt"`
}

AdminApproveResponse represents the response from user approval

type AdminCleanupRequest

type AdminCleanupRequest struct {
	Username string `json:"username" validate:"required"`
	Confirm  bool   `json:"confirm" validate:"required"`
}

AdminCleanupRequest represents the request payload for test user cleanup

type AdminCleanupResponse

type AdminCleanupResponse struct {
	Success       bool                   `json:"success"`
	TablesCleared map[string]int         `json:"tables_cleaned"`
	TotalRows     int                    `json:"total_rows_affected"`
	Details       map[string]interface{} `json:"details,omitempty"`
}

AdminCleanupResponse represents the response from test user cleanup

type AdminOPAQUEStatus

type AdminOPAQUEStatus struct {
	HasAccount   bool `json:"has_account"`
	RecordsCount int  `json:"records_count"`
}

AdminOPAQUEStatus represents OPAQUE status information

type AdminSetCreditsRequest

type AdminSetCreditsRequest struct {
	BalanceUSD    string  `json:"balance_usd" validate:"required"`
	TransactionID *string `json:"transaction_id,omitempty"`
	Reason        string  `json:"reason" validate:"required"`
}

AdminSetCreditsRequest represents the request payload for admin balance override

type AdminTOTPStatus

type AdminTOTPStatus struct {
	Present        bool `json:"present"`
	Decryptable    bool `json:"decryptable"`
	Enabled        bool `json:"enabled"`
	SetupCompleted bool `json:"setup_completed"`
}

AdminTOTPStatus represents TOTP status information

type AdminTokenStatus

type AdminTokenStatus struct {
	ActiveRefreshTokens int `json:"active_refresh_tokens"`
	RevokedTokens       int `json:"revoked_tokens"`
}

AdminTokenStatus represents token status information

type AdminUserInfo

type AdminUserInfo struct {
	ID         int64     `json:"id"`
	Username   string    `json:"username"`
	Email      *string   `json:"email,omitempty"`
	IsApproved bool      `json:"isApproved"`
	IsAdmin    bool      `json:"isAdmin"`
	CreatedAt  time.Time `json:"createdAt"`
}

AdminUserInfo represents basic user information

type AdminUserStatusResponse

type AdminUserStatusResponse struct {
	Exists   bool                   `json:"exists"`
	Username string                 `json:"username,omitempty"`
	User     *AdminUserInfo         `json:"user,omitempty"`
	TOTP     *AdminTOTPStatus       `json:"totp,omitempty"`
	OPAQUE   *AdminOPAQUEStatus     `json:"opaque,omitempty"`
	Tokens   *AdminTokenStatus      `json:"tokens,omitempty"`
	Details  map[string]interface{} `json:"details,omitempty"`
}

AdminUserStatusResponse represents the comprehensive user status response

type AuthRateLimitEntry

type AuthRateLimitEntry struct {
	EndpointType       string // "login", "register", "totp_verify", "totp_auth"
	EntityID           string
	FailedCount        int
	LastFailedAttempt  *time.Time
	NextAllowedAttempt *time.Time
}

AuthRateLimitEntry represents a rate limiting entry for authentication endpoints

type FileKeyResponse

type FileKeyResponse struct {
	KeyID        string `json:"keyId"`
	KeyType      string `json:"keyType"`
	KeyLabel     string `json:"keyLabel"`
	PasswordHint string `json:"passwordHint"`
	IsPrimary    bool   `json:"isPrimary"`
	CreatedAt    string `json:"createdAt"`
}

FileKeyResponse represents a file encryption key

type LogoutRequest

type LogoutRequest struct {
	RefreshToken string `json:"refreshToken"`
}

LogoutRequest represents the request structure for logging out

type OpaqueHealthCheckResponse

type OpaqueHealthCheckResponse struct {
	OpaqueReady       bool   `json:"opaqueReady"`
	ServerKeysLoaded  bool   `json:"serverKeysLoaded"`
	DatabaseConnected bool   `json:"databaseConnected"`
	Status            string `json:"status"`
	Message           string `json:"message"`
}

OpaqueHealthCheckResponse represents the health status of OPAQUE system

type OpaqueLoginRequest

type OpaqueLoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

OpaqueLoginRequest represents the request for OPAQUE login

type OpaqueRegisterRequest

type OpaqueRegisterRequest struct {
	Username string `json:"username"`
	Email    string `json:"email,omitempty"` // Optional email
	Password string `json:"password"`
}

OpaqueRegisterRequest represents the request for OPAQUE registration

type RateLimitManager

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

RateLimitManager manages rate limiting state with privacy-preserving entity IDs

var DefaultRateLimitManager *RateLimitManager

Global rate limit manager instance

func NewRateLimitManager

func NewRateLimitManager(db *sql.DB, rateLimitConfig config.RateLimitConfig) *RateLimitManager

NewRateLimitManager creates a new rate limit manager

func (*RateLimitManager) CheckRateLimit

func (rlm *RateLimitManager) CheckRateLimit(entityID, endpoint string, limit int, windowSize time.Duration) (bool, error)

CheckRateLimit checks if a request should be rate limited

type RateLimitState

type RateLimitState struct {
	EntityID       string     `json:"entity_id"`
	TimeWindow     string     `json:"time_window"`
	Endpoint       string     `json:"endpoint"`
	RequestCount   int        `json:"request_count"`
	LastRequest    time.Time  `json:"last_request"`
	ViolationCount int        `json:"violation_count"`
	PenaltyUntil   *time.Time `json:"penalty_until"`
}

RateLimitState represents the current rate limiting state for an entity

type RefreshTokenRequest

type RefreshTokenRequest struct {
	RefreshToken string `json:"refreshToken"`
}

RefreshTokenRequest represents the request structure for refreshing a token

type ShareAccessRequest

type ShareAccessRequest struct {
	Password string `json:"password"` // Share password for client-side Argon2id derivation
}

ShareAccessRequest represents an anonymous share access request

type ShareAccessResponse

type ShareAccessResponse struct {
	Success      bool           `json:"success"`
	Salt         string         `json:"salt,omitempty"`          // Base64-encoded salt for Argon2id
	EncryptedFEK string         `json:"encrypted_fek,omitempty"` // Base64-encoded encrypted FEK
	FileInfo     *ShareFileInfo `json:"file_info,omitempty"`
	Error        string         `json:"error,omitempty"`
	Message      string         `json:"message,omitempty"`
	RetryAfter   int            `json:"retryAfter,omitempty"` // For rate limiting
}

ShareAccessResponse represents the response for anonymous share access

type ShareFileInfo

type ShareFileInfo struct {
	Filename    string `json:"filename"`
	Size        int64  `json:"size"`
	ContentType string `json:"content_type"`
	SHA256Sum   string `json:"sha256sum,omitempty"`
}

ShareFileInfo contains metadata about the shared file

type ShareRateLimitEntry

type ShareRateLimitEntry struct {
	ShareID            string
	EntityID           string
	FailedCount        int
	LastFailedAttempt  *time.Time
	NextAllowedAttempt *time.Time
}

ShareRateLimitEntry represents a rate limiting entry for share access

type ShareRequest

type ShareRequest struct {
	FileID            string `json:"fileId"`
	SharePassword     string `json:"sharePassword"`     // Share password for Argon2id derivation (client-side only)
	Salt              string `json:"salt"`              // Base64-encoded 32-byte salt
	EncryptedFEK      string `json:"encrypted_fek"`     // Base64-encoded FEK encrypted with Argon2id-derived key
	ExpiresAfterHours int    `json:"expiresAfterHours"` // Optional expiration
}

ShareRequest represents a file sharing request (Argon2id-based anonymous shares)

type ShareResponse

type ShareResponse struct {
	ShareID   string     `json:"shareId"`
	ShareURL  string     `json:"shareUrl"`
	CreatedAt time.Time  `json:"createdAt"`
	ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}

ShareResponse represents a file share creation response

type TOTPAuthRequest

type TOTPAuthRequest struct {
	Code       string `json:"code"`
	SessionKey string `json:"sessionKey"`
	IsBackup   bool   `json:"isBackup,omitempty"`
}

TOTPAuthRequest represents the request for TOTP authentication

type TOTPDisableRequest

type TOTPDisableRequest struct {
	CurrentCode string `json:"currentCode"`
	SessionKey  string `json:"sessionKey"`
}

TOTPDisableRequest represents the request for TOTP disabling

type TOTPSetupRequest

type TOTPSetupRequest struct {
	SessionKey string `json:"sessionKey"`
}

TOTPSetupRequest represents the request for TOTP setup

type TOTPSetupResponse

type TOTPSetupResponse struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qrCodeUrl"`
	BackupCodes []string `json:"backupCodes"`
	ManualEntry string   `json:"manualEntry"`
}

TOTPSetupResponse represents the response for TOTP setup

type TOTPStatusResponse

type TOTPStatusResponse struct {
	Enabled       bool       `json:"enabled"`
	SetupRequired bool       `json:"setupRequired"`
	LastUsed      *time.Time `json:"lastUsed,omitempty"`
	CreatedAt     *time.Time `json:"createdAt,omitempty"`
}

TOTPStatusResponse represents the TOTP status response

type TOTPVerifyRequest

type TOTPVerifyRequest struct {
	Code       string `json:"code"`
	SessionKey string `json:"sessionKey"`
	IsBackup   bool   `json:"isBackup,omitempty"`
}

TOTPVerifyRequest represents the request for TOTP verification

type TestOPAQUEProvider

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

TestOPAQUEProvider implements auth.OPAQUEProvider for testing This allows us to test OPAQUE handler logic without requiring CGO libraries

func NewTestOPAQUEProvider

func NewTestOPAQUEProvider() *TestOPAQUEProvider

NewTestOPAQUEProvider creates a new test OPAQUE provider

func (*TestOPAQUEProvider) AuthenticateUser

func (t *TestOPAQUEProvider) AuthenticateUser(password []byte, userRecord []byte) ([]byte, error)

AuthenticateUser implements auth.OPAQUEProvider.AuthenticateUser for testing

func (*TestOPAQUEProvider) GenerateServerKeys

func (t *TestOPAQUEProvider) GenerateServerKeys() ([]byte, []byte, error)

GenerateServerKeys implements auth.OPAQUEProvider.GenerateServerKeys for testing

func (*TestOPAQUEProvider) GetServerKeys

func (t *TestOPAQUEProvider) GetServerKeys() ([]byte, []byte, error)

GetServerKeys implements auth.OPAQUEProvider.GetServerKeys for testing

func (*TestOPAQUEProvider) IsAvailable

func (t *TestOPAQUEProvider) IsAvailable() bool

IsAvailable implements auth.OPAQUEProvider.IsAvailable for testing

func (*TestOPAQUEProvider) RegisterUser

func (t *TestOPAQUEProvider) RegisterUser(password []byte, serverPrivateKey []byte) ([]byte, []byte, error)

RegisterUser implements auth.OPAQUEProvider.RegisterUser for testing

type TestServerKeys

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

TestServerKeys holds mock server key material for testing

Jump to

Keyboard shortcuts

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