Documentation ¶
Overview ¶
Package dataprovider provides data access. It abstracts different data providers and exposes a common API.
Index ¶
- Constants
- Variables
- func AddAPIKey(apiKey *APIKey, executor, ipAddress string) error
- func AddActiveTransfer(transfer ActiveTransfer)
- func AddAdmin(admin *Admin, executor, ipAddress string) error
- func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress string) error
- func AddGroup(group *Group, executor, ipAddress string) error
- func AddShare(share *Share, executor, ipAddress string) error
- func AddSharedSession(session Session) error
- func AddUser(user *User, executor, ipAddress string) error
- func CacheWebDAVUser(cachedUser *CachedUser)
- func CheckCachedPassword(username, password string) (bool, bool)
- func CheckCachedUserCredentials(user *CachedUser, password, loginMethod, protocol string, ...) error
- func CleanupActiveTransfers(before time.Time) error
- func CleanupDefender(from int64) error
- func CleanupSharedSessions(sessionType SessionType, before time.Time) error
- func Close() error
- func ConvertName(name string) string
- func DeleteAPIKey(keyID string, executor, ipAddress string) error
- func DeleteAdmin(username, executor, ipAddress string) error
- func DeleteDefenderHost(ip string) error
- func DeleteFolder(folderName, executor, ipAddress string) error
- func DeleteGroup(name string, executor, ipAddress string) error
- func DeleteShare(shareID string, executor, ipAddress string) error
- func DeleteSharedSession(key string) error
- func DeleteUser(username, executor, ipAddress string) error
- func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error)
- func GetBackupsPath() string
- func GetFolderByName(name string) (vfs.BaseVirtualFolder, error)
- func GetFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error)
- func GetQuotaTracking() int
- func GetUsedQuota(username string) (int, int64, int64, int64, error)
- func GetUsedVirtualFolderQuota(name string) (int, int64, error)
- func GetUserVariants(username string) (User, User, error)
- func HasAdmin() bool
- func HasUsersBaseDir() bool
- func Initialize(cnf Config, basePath string, checkAdmins bool) error
- func InitializeDatabase(cnf Config, basePath string) error
- func InitializeWebDAVUserCache(maxSize int)
- func ReloadConfig() error
- func RemoveActiveTransfer(transferID int64, connectionID string)
- func RemoveCachedWebDAVUser(username string)
- func ResetDatabase(cnf Config, basePath string) error
- func RevertDatabase(cnf Config, basePath string, targetVersion int) error
- func SetDefenderBanTime(ip string, banTime int64) error
- func SetTempPath(fsPath string)
- func UpdateAPIKey(apiKey *APIKey, executor, ipAddress string) error
- func UpdateAPIKeyLastUse(apiKey *APIKey) error
- func UpdateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string)
- func UpdateAdmin(admin *Admin, executor, ipAddress string) error
- func UpdateAdminLastLogin(admin *Admin)
- func UpdateDefenderBanTime(ip string, minutes int) error
- func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, ...) error
- func UpdateGroup(group *Group, users []string, executor, ipAddress string) error
- func UpdateLastLogin(user *User)
- func UpdateShare(share *Share, executor, ipAddress string) error
- func UpdateShareLastUse(share *Share, numTokens int) error
- func UpdateUser(user *User, executor, ipAddress string) error
- func UpdateUserPassword(username, plainPwd, executor, ipAddress string) error
- func UpdateUserQuota(user *User, filesAdd int, sizeAdd int64, reset bool) error
- func UpdateUserTransferQuota(user *User, uploadSize, downloadSize int64, reset bool) error
- func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error
- func ValidateFolder(folder *vfs.BaseVirtualFolder) error
- func ValidateUser(user *User) error
- type APIKey
- type APIKeyScope
- type ActiveTransfer
- type Admin
- func (a *Admin) CanLogin(ip string) error
- func (a *Admin) CanLoginFromIP(ip string) bool
- func (a *Admin) CanManageMFA() bool
- func (a *Admin) CheckPassword(password string) (bool, error)
- func (a *Admin) CountUnusedRecoveryCodes() int
- func (a *Admin) GetAllowedIPAsString() string
- func (a *Admin) GetLastLoginAsString() string
- func (a *Admin) GetPermissionsAsString() string
- func (a *Admin) GetSignature() string
- func (a *Admin) GetValidPerms() []string
- func (a *Admin) HasPermission(perm string) bool
- func (a *Admin) HideConfidentialData()
- func (a *Admin) RenderAsJSON(reload bool) ([]byte, error)
- func (a *Admin) SetEmptySecretsIfNil()
- func (a *Admin) SetNilSecretsIfEmpty()
- type AdminFilters
- type AdminTOTPConfig
- type Argon2Options
- type AutoBackup
- type BackupData
- type BcryptOptions
- type BoltProvider
- type CachedUser
- type Config
- type DefenderEntry
- type Group
- func (g *Group) GetAllowedIPAsString() string
- func (g *Group) GetDeniedIPAsString() string
- func (g *Group) GetEncryptionAdditionalData() string
- func (g *Group) GetPermissions() []sdk.DirectoryPermissions
- func (g *Group) GetUsersAsString() string
- func (g *Group) HasExternalAuth() bool
- func (g *Group) PrepareForRendering()
- func (g *Group) RenderAsJSON(reload bool) ([]byte, error)
- func (g *Group) SetEmptySecretsIfNil()
- type GroupUserSettings
- type MemoryProvider
- type MySQLProvider
- type ObjectsActions
- type PGSQLProvider
- type PasswordHashing
- type PasswordValidation
- type PasswordValidationRules
- type Provider
- type ProviderStatus
- type RecoveryCode
- type SQLiteProvider
- type Session
- type SessionType
- type Share
- func (s *Share) CheckCredentials(username, password string) (bool, error)
- func (s *Share) GetAllowedFromAsString() string
- func (s *Share) GetInfoString() string
- func (s *Share) GetRelativePath(name string) string
- func (s *Share) GetScopeAsString() string
- func (s *Share) HasRedactedPassword() bool
- func (s *Share) HideConfidentialData()
- func (s *Share) IsExpired() bool
- func (s *Share) IsUsable(ip string) (bool, error)
- func (s *Share) RenderAsJSON(reload bool) ([]byte, error)
- type ShareScope
- type TransferQuota
- type User
- func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, ...) (User, string, error)
- func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge, ...) (User, error)
- func CheckUserAndPass(username, password, ip, protocol string) (User, error)
- func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string, isSSHCert bool) (User, string, error)
- func CheckUserAndTLSCert(username, ip, protocol string, tlsCert *x509.Certificate) (User, error)
- func CheckUserBeforeTLSAuth(username, ip, protocol string, tlsCert *x509.Certificate) (User, error)
- func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error)
- func GetUserWithGroupSettings(username string) (User, error)
- func GetUsers(limit, offset int, order string) ([]User, error)
- func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error)
- func UserExists(username string) (User, error)
- func (u *User) CanAddDirsFromWeb(target string) bool
- func (u *User) CanAddFilesFromWeb(target string) bool
- func (u *User) CanChangeAPIKeyAuth() bool
- func (u *User) CanChangeInfo() bool
- func (u *User) CanChangePassword() bool
- func (u *User) CanDeleteFromWeb(target string) bool
- func (u *User) CanManageMFA() bool
- func (u *User) CanManagePublicKeys() bool
- func (u *User) CanManageShares() bool
- func (u *User) CanRenameFromWeb(src, dest string) bool
- func (u *User) CanResetPassword() bool
- func (u *User) CheckFsRoot(connectionID string) error
- func (u *User) CheckLoginConditions() error
- func (u *User) CheckMetadataConsistency() error
- func (u *User) CloseFs() error
- func (u *User) CountUnusedRecoveryCodes() int
- func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo
- func (u *User) GetAllowedIPAsString() string
- func (u *User) GetAllowedLoginMethods() []string
- func (u *User) GetBandwidthAsString() string
- func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64)
- func (u *User) GetCleanedPath(rawVirtualPath string) string
- func (u *User) GetDataTransferLimits(clientIP string) (int64, int64, int64)
- func (u *User) GetDeniedIPAsString() string
- func (u *User) GetEncryptionAdditionalData() string
- func (u *User) GetExpirationDateAsString() string
- func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error)
- func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error)
- func (u *User) GetFiltersAsJSON() ([]byte, error)
- func (u *User) GetFsConfigAsJSON() ([]byte, error)
- func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem
- func (u *User) GetGCSCredentialsFilePath() string
- func (u *User) GetGID() int
- func (u *User) GetGroupsAsString() string
- func (u *User) GetHomeDir() string
- func (u *User) GetInfoString() string
- func (u *User) GetLastLoginAsString() string
- func (u *User) GetLastQuotaUpdateAsString() string
- func (u *User) GetMFAStatusAsString() string
- func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string
- func (u *User) GetPermissionsAsJSON() ([]byte, error)
- func (u *User) GetPermissionsAsString() string
- func (u *User) GetPermissionsForPath(p string) []string
- func (u *User) GetPublicKeysAsJSON() ([]byte, error)
- func (u *User) GetQuotaSummary() string
- func (u *User) GetSignature() string
- func (u *User) GetStatusAsString() string
- func (u *User) GetStorageDescrition() string
- func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions
- func (u *User) GetUID() int
- func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error)
- func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool
- func (u *User) HasAnyPerm(permissions []string, path string) bool
- func (u *User) HasBufferedSFTP(name string) bool
- func (u *User) HasExternalAuth() bool
- func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool
- func (u *User) HasPerm(permission, path string) bool
- func (u *User) HasPermissionsInside(virtualPath string) bool
- func (u *User) HasPerms(permissions []string, path string) bool
- func (u *User) HasPermsDeleteAll(path string) bool
- func (u *User) HasPermsRenameAll(path string) bool
- func (u *User) HasPrimaryGroup(name string) bool
- func (u *User) HasQuotaRestrictions() bool
- func (u *User) HasRecentActivity() bool
- func (u *User) HasSecondaryGroup(name string) bool
- func (u *User) HasTransferQuotaRestrictions() bool
- func (u *User) HasVirtualFoldersInside(virtualPath string) bool
- func (u *User) IsFileAllowed(virtualPath string) (bool, int)
- func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool
- func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool
- func (u *User) IsMappedPath(fsPath string) bool
- func (u *User) IsPartialAuth(loginMethod string) bool
- func (u *User) IsPasswordHashed() bool
- func (u *User) IsTLSUsernameVerificationEnabled() bool
- func (u *User) IsVirtualFolder(virtualPath string) bool
- func (u *User) LoadAndApplyGroupSettings() error
- func (u *User) MustSetSecondFactor() bool
- func (u *User) MustSetSecondFactorForProtocol(protocol string) bool
- func (u *User) PrepareForRendering()
- func (u *User) RenderAsJSON(reload bool) ([]byte, error)
- func (u *User) ScanQuota() (int, int64, error)
- func (u *User) SetEmptySecrets()
- func (u *User) SetEmptySecretsIfNil()
- type UserFilters
- type UserTOTPConfig
Constants ¶
const ( // ActionExecutorSelf is used as username for self action, for example a user/admin that updates itself ActionExecutorSelf = "__self__" // ActionExecutorSystem is used as username for actions with no explicit executor associated, for example // adding/updating a user/admin by loading initial data ActionExecutorSystem = "__system__" )
const ( PermAdminAny = "*" PermAdminAddUsers = "add_users" PermAdminChangeUsers = "edit_users" PermAdminDeleteUsers = "del_users" PermAdminViewUsers = "view_users" PermAdminViewConnections = "view_conns" PermAdminCloseConnections = "close_conns" PermAdminViewServerStatus = "view_status" PermAdminManageAdmins = "manage_admins" PermAdminManageGroups = "manage_groups" PermAdminManageAPIKeys = "manage_apikeys" PermAdminQuotaScans = "quota_scans" PermAdminManageSystem = "manage_system" PermAdminManageDefender = "manage_defender" PermAdminViewDefender = "view_defender" PermAdminRetentionChecks = "retention_checks" PermAdminMetadataChecks = "metadata_checks" PermAdminViewEvents = "view_events" )
Available permissions for SFTPGo admins
const ( // SQLiteDataProviderName defines the name for SQLite database provider SQLiteDataProviderName = "sqlite" // PGSQLDataProviderName defines the name for PostgreSQL database provider PGSQLDataProviderName = "postgresql" // MySQLDataProviderName defines the name for MySQL database provider MySQLDataProviderName = "mysql" // BoltDataProviderName defines the name for bbolt key/value store provider BoltDataProviderName = "bolt" // MemoryDataProviderName defines the name for memory provider MemoryDataProviderName = "memory" // CockroachDataProviderName defines the for CockroachDB provider CockroachDataProviderName = "cockroachdb" // DumpVersion defines the version for the dump. // For restore/load we support the current version and the previous one DumpVersion = 12 )
const ( HashingAlgoBcrypt = "bcrypt" HashingAlgoArgon2ID = "argon2id" )
Supported algorithms for hashing passwords. These algorithms can be used when SFTPGo hashes a plain text password
const ( OrderASC = "ASC" OrderDESC = "DESC" )
ordering constants
const ( // All permissions are granted PermAny = "*" // List items such as files and directories is allowed PermListItems = "list" // download files is allowed PermDownload = "download" // upload files is allowed PermUpload = "upload" // overwrite an existing file, while uploading, is allowed // upload permission is required to allow file overwrite PermOverwrite = "overwrite" // delete files or directories is allowed PermDelete = "delete" // delete files is allowed PermDeleteFiles = "delete_files" // delete directories is allowed PermDeleteDirs = "delete_dirs" // rename files or directories is allowed PermRename = "rename" // rename files is allowed PermRenameFiles = "rename_files" // rename directories is allowed PermRenameDirs = "rename_dirs" // create directories is allowed PermCreateDirs = "create_dirs" // create symbolic links is allowed PermCreateSymlinks = "create_symlinks" // changing file or directory permissions is allowed PermChmod = "chmod" // changing file or directory owner and group is allowed PermChown = "chown" // changing file or directory access and modification time is allowed PermChtimes = "chtimes" )
Available permissions for SFTPGo users
const ( LoginMethodNoAuthTryed = "no_auth_tryed" LoginMethodPassword = "password" SSHLoginMethodPassword = "password-over-SSH" SSHLoginMethodPublicKey = "publickey" SSHLoginMethodKeyboardInteractive = "keyboard-interactive" SSHLoginMethodKeyAndPassword = "publickey+password" SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive" LoginMethodTLSCertificate = "TLSCertificate" LoginMethodTLSCertificateAndPwd = "TLSCertificate+password" LoginMethodIDP = "IDP" )
Available login methods
Variables ¶
var ( // SupportedProviders defines the supported data providers SupportedProviders = []string{SQLiteDataProviderName, PGSQLDataProviderName, MySQLDataProviderName, BoltDataProviderName, MemoryDataProviderName, CockroachDataProviderName} // ValidPerms defines all the valid permissions for a user ValidPerms = []string{PermAny, PermListItems, PermDownload, PermUpload, PermOverwrite, PermCreateDirs, PermRename, PermRenameFiles, PermRenameDirs, PermDelete, PermDeleteFiles, PermDeleteDirs, PermCreateSymlinks, PermChmod, PermChown, PermChtimes} // ValidLoginMethods defines all the valid login methods ValidLoginMethods = []string{SSHLoginMethodPublicKey, LoginMethodPassword, SSHLoginMethodPassword, SSHLoginMethodKeyboardInteractive, SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt, LoginMethodTLSCertificate, LoginMethodTLSCertificateAndPwd} // SSHMultiStepsLoginMethods defines the supported Multi-Step Authentications SSHMultiStepsLoginMethods = []string{SSHLoginMethodKeyAndPassword, SSHLoginMethodKeyAndKeyboardInt} // ErrNoAuthTryed defines the error for connection closed before authentication ErrNoAuthTryed = errors.New("no auth tryed") // ErrNotImplemented defines the error for features not supported for a particular data provider ErrNotImplemented = errors.New("feature not supported with the configured data provider") // ValidProtocols defines all the valid protcols ValidProtocols = []string{protocolSSH, protocolFTP, protocolWebDAV, protocolHTTP} // MFAProtocols defines the supported protocols for multi-factor authentication MFAProtocols = []string{protocolHTTP, protocolSSH, protocolFTP} // ErrNoInitRequired defines the error returned by InitProvider if no inizialization/update is required ErrNoInitRequired = errors.New("the data provider is up to date") // ErrInvalidCredentials defines the error to return if the supplied credentials are invalid ErrInvalidCredentials = errors.New("invalid credentials") // ErrLoginNotAllowedFromIP defines the error to return if login is denied from the current IP ErrLoginNotAllowedFromIP = errors.New("login is not allowed from this IP") )
Functions ¶
func AddActiveTransfer ¶ added in v2.3.0
func AddActiveTransfer(transfer ActiveTransfer)
AddActiveTransfer stores the specified transfer
func AddFolder ¶
func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress string) error
AddFolder adds a new virtual folder.
func AddSharedSession ¶ added in v2.3.0
AddSharedSession stores a new session within the data provider
func CacheWebDAVUser ¶
func CacheWebDAVUser(cachedUser *CachedUser)
CacheWebDAVUser add a user to the WebDAV cache
func CheckCachedPassword ¶
CheckCachedPassword is an utility method used only in test cases
func CheckCachedUserCredentials ¶
func CheckCachedUserCredentials(user *CachedUser, password, loginMethod, protocol string, tlsCert *x509.Certificate) error
CheckCachedUserCredentials checks the credentials for a cached user
func CleanupActiveTransfers ¶ added in v2.3.0
CleanupActiveTransfers removes the transfer before the specified time
func CleanupDefender ¶ added in v2.2.1
CleanupDefender removes events and hosts older than "from" from the data provider
func CleanupSharedSessions ¶ added in v2.3.0
func CleanupSharedSessions(sessionType SessionType, before time.Time) error
CleanupSharedSessions removes the shared session with the specified type and before the specified time
func Close ¶
func Close() error
Close releases all provider resources. This method is used in test cases. Closing an uninitialized provider is not supported
func ConvertName ¶ added in v2.3.0
ConvertName converts the given name based on the configured rules
func DeleteAPIKey ¶
DeleteAPIKey deletes an existing API key
func DeleteAdmin ¶
DeleteAdmin deletes an existing SFTPGo admin
func DeleteDefenderHost ¶ added in v2.2.1
DeleteDefenderHost removes the specified IP from the defender lists
func DeleteFolder ¶
DeleteFolder deletes an existing folder.
func DeleteGroup ¶ added in v2.3.0
DeleteGroup deletes an existing Group
func DeleteShare ¶
DeleteShare deletes an existing share
func DeleteSharedSession ¶ added in v2.3.0
DeleteSharedSession deletes the session with the specified key
func DeleteUser ¶
DeleteUser deletes an existing SFTPGo user.
func ExecutePostLoginHook ¶
ExecutePostLoginHook executes the post login hook if defined
func GetBackupsPath ¶ added in v2.3.0
func GetBackupsPath() string
GetBackupsPath returns the normalized backups path
func GetFolderByName ¶
func GetFolderByName(name string) (vfs.BaseVirtualFolder, error)
GetFolderByName returns the folder with the specified name if any
func GetFolders ¶
GetFolders returns an array of folders respecting limit and offset
func GetQuotaTracking ¶
func GetQuotaTracking() int
GetQuotaTracking returns the configured mode for user's quota tracking
func GetUsedQuota ¶
GetUsedQuota returns the used quota for the given SFTPGo user.
func GetUsedVirtualFolderQuota ¶
GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.
func GetUserVariants ¶ added in v2.3.0
GetUserVariants tries to return the user with the specified username with and without group settings applied
func HasAdmin ¶
func HasAdmin() bool
HasAdmin returns true if the first admin has been created and so SFTPGo is ready to be used
func HasUsersBaseDir ¶ added in v2.2.2
func HasUsersBaseDir() bool
HasUsersBaseDir returns true if users base dir is set
func Initialize ¶
Initialize the data provider. An error is returned if the configured driver is invalid or if the data provider cannot be initialized
func InitializeDatabase ¶
InitializeDatabase creates the initial database structure
func InitializeWebDAVUserCache ¶
func InitializeWebDAVUserCache(maxSize int)
InitializeWebDAVUserCache initializes the cache for webdav users
func ReloadConfig ¶
func ReloadConfig() error
ReloadConfig reloads provider configuration. Currently only implemented for memory provider, allows to reload the users from the configured file, if defined
func RemoveActiveTransfer ¶ added in v2.3.0
RemoveActiveTransfer removes the specified transfer
func RemoveCachedWebDAVUser ¶
func RemoveCachedWebDAVUser(username string)
RemoveCachedWebDAVUser removes a cached WebDAV user
func ResetDatabase ¶
ResetDatabase restores schema and/or data to a previous version
func RevertDatabase ¶
RevertDatabase restores schema and/or data to a previous version
func SetDefenderBanTime ¶ added in v2.2.1
SetDefenderBanTime sets the ban time for the specified IP
func UpdateAPIKey ¶
UpdateAPIKey updates an existing API key
func UpdateAPIKeyLastUse ¶
UpdateAPIKeyLastUse updates the LastUseAt field for the given API key
func UpdateActiveTransferSizes ¶ added in v2.3.0
UpdateActiveTransferSizes updates the current upload and download sizes for the specified transfer
func UpdateAdmin ¶
UpdateAdmin updates an existing SFTPGo admin
func UpdateAdminLastLogin ¶
func UpdateAdminLastLogin(admin *Admin)
UpdateAdminLastLogin updates the last login field for the given SFTPGo admin
func UpdateDefenderBanTime ¶ added in v2.2.1
UpdateDefenderBanTime increments ban time for the specified ip
func UpdateFolder ¶
func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress string) error
UpdateFolder updates the specified virtual folder
func UpdateGroup ¶ added in v2.3.0
UpdateGroup updates an existing Group
func UpdateLastLogin ¶
func UpdateLastLogin(user *User)
UpdateLastLogin updates the last login field for the given SFTPGo user
func UpdateShare ¶
UpdateShare updates an existing share
func UpdateShareLastUse ¶
UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share
func UpdateUser ¶
UpdateUser updates an existing SFTPGo user.
func UpdateUserPassword ¶ added in v2.3.0
UpdateUserPassword updates the user password
func UpdateUserQuota ¶
UpdateUserQuota updates the quota for the given SFTPGo user adding filesAdd and sizeAdd. If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
func UpdateUserTransferQuota ¶ added in v2.3.0
UpdateUserTransferQuota updates the transfer quota for the given SFTPGo user. If reset is true uploadSize and downloadSize indicates the actual sizes instead of the difference.
func UpdateVirtualFolderQuota ¶
func UpdateVirtualFolderQuota(vfolder *vfs.BaseVirtualFolder, filesAdd int, sizeAdd int64, reset bool) error
UpdateVirtualFolderQuota updates the quota for the given virtual folder adding filesAdd and sizeAdd. If reset is true filesAdd and sizeAdd indicates the total files and the total size instead of the difference.
func ValidateFolder ¶
func ValidateFolder(folder *vfs.BaseVirtualFolder) error
ValidateFolder returns an error if the folder is not valid FIXME: this should be defined as Folder struct method
func ValidateUser ¶
ValidateUser returns an error if the user is not valid FIXME: this should be defined as User struct method
Types ¶
type APIKey ¶
type APIKey struct { // Database unique identifier ID int64 `json:"-"` // Unique key identifier, used for key lookups. // The generated key is in the format `KeyID.hash(Key)` so we can split // and lookup by KeyID and then verify if the key matches the recorded hash KeyID string `json:"id"` // User friendly key name Name string `json:"name"` // we store the hash of the key, this is just like a password Key string `json:"key,omitempty"` Scope APIKeyScope `json:"scope"` CreatedAt int64 `json:"created_at"` UpdatedAt int64 `json:"updated_at"` // 0 means never used LastUseAt int64 `json:"last_use_at,omitempty"` // 0 means never expire ExpiresAt int64 `json:"expires_at,omitempty"` Description string `json:"description,omitempty"` // Username associated with this API key. // If empty and the scope is APIKeyScopeUser the key is valid for any user User string `json:"user,omitempty"` // Admin username associated with this API key. // If empty and the scope is APIKeyScopeAdmin the key is valid for any admin Admin string `json:"admin,omitempty"` // contains filtered or unexported fields }
APIKey defines a SFTPGo API key. API keys can be used as authentication alternative to short lived tokens for REST API
func APIKeyExists ¶
APIKeyExists returns the API key with the given ID if it exists
func GetAPIKeys ¶
GetAPIKeys returns an array of API keys respecting limit and offset
func (*APIKey) Authenticate ¶
Authenticate tries to authenticate the provided plain key
func (*APIKey) DisplayKey ¶
DisplayKey returns the key to show to the user
func (*APIKey) HideConfidentialData ¶
func (k *APIKey) HideConfidentialData()
HideConfidentialData hides API key confidential data
type APIKeyScope ¶
type APIKeyScope int
APIKeyScope defines the supported API key scopes
const ( // the API key will be used for an admin APIKeyScopeAdmin APIKeyScope = iota + 1 // the API key will be used for a user APIKeyScopeUser )
Supported API key scopes
type ActiveTransfer ¶ added in v2.3.0
type ActiveTransfer struct { ID int64 Type int ConnID string Username string FolderName string IP string TruncatedSize int64 CurrentULSize int64 CurrentDLSize int64 CreatedAt int64 UpdatedAt int64 }
ActiveTransfer defines an active protocol transfer
func GetActiveTransfers ¶ added in v2.3.0
func GetActiveTransfers(from time.Time) ([]ActiveTransfer, error)
GetActiveTransfers retrieves the active transfers with an update time after the specified value
type Admin ¶
type Admin struct { // Database unique identifier ID int64 `json:"id"` // 1 enabled, 0 disabled (login is not allowed) Status int `json:"status"` // Username Username string `json:"username"` Password string `json:"password,omitempty"` Email string `json:"email,omitempty"` Permissions []string `json:"permissions"` Filters AdminFilters `json:"filters,omitempty"` Description string `json:"description,omitempty"` AdditionalInfo string `json:"additional_info,omitempty"` // Creation time as unix timestamp in milliseconds. It will be 0 for admins created before v2.2.0 CreatedAt int64 `json:"created_at"` // last update time as unix timestamp in milliseconds UpdatedAt int64 `json:"updated_at"` // Last login as unix timestamp in milliseconds LastLogin int64 `json:"last_login"` }
Admin defines a SFTPGo admin
func AdminExists ¶
AdminExists returns the admin with the given username if it exists
func CheckAdminAndPass ¶
CheckAdminAndPass validates the given admin and password connecting from ip
func (*Admin) CanLoginFromIP ¶
CanLoginFromIP returns true if login from the given IP is allowed
func (*Admin) CanManageMFA ¶
CanManageMFA returns true if the admin can add a multi-factor authentication configuration
func (*Admin) CheckPassword ¶
CheckPassword verifies the admin password
func (*Admin) CountUnusedRecoveryCodes ¶
CountUnusedRecoveryCodes returns the number of unused recovery codes
func (*Admin) GetAllowedIPAsString ¶
GetAllowedIPAsString returns the allowed IP as comma separated string
func (*Admin) GetLastLoginAsString ¶ added in v2.3.0
GetLastLoginAsString returns the last login as string
func (*Admin) GetPermissionsAsString ¶
GetPermissionsAsString returns permission as string
func (*Admin) GetSignature ¶
GetSignature returns a signature for this admin. It could change after an update
func (*Admin) GetValidPerms ¶
GetValidPerms returns the allowed admin permissions
func (*Admin) HasPermission ¶
HasPermission returns true if the admin has the specified permission
func (*Admin) HideConfidentialData ¶
func (a *Admin) HideConfidentialData()
HideConfidentialData hides admin confidential data
func (*Admin) RenderAsJSON ¶
RenderAsJSON implements the renderer interface used within plugins
func (*Admin) SetEmptySecretsIfNil ¶
func (a *Admin) SetEmptySecretsIfNil()
SetEmptySecretsIfNil sets the secrets to empty if nil
func (*Admin) SetNilSecretsIfEmpty ¶
func (a *Admin) SetNilSecretsIfEmpty()
SetNilSecretsIfEmpty set the secrets to nil if empty. This is useful before rendering as JSON so the empty fields will not be serialized.
type AdminFilters ¶
type AdminFilters struct { // only clients connecting from these IP/Mask are allowed. // IP/Mask must be in CIDR notation as defined in RFC 4632 and RFC 4291 // for example "192.0.2.0/24" or "2001:db8::/32" AllowList []string `json:"allow_list,omitempty"` // API key auth allows to impersonate this administrator with an API key AllowAPIKeyAuth bool `json:"allow_api_key_auth,omitempty"` // Time-based one time passwords configuration TOTPConfig AdminTOTPConfig `json:"totp_config,omitempty"` // Recovery codes to use if the user loses access to their second factor auth device. // Each code can only be used once, you should use these codes to login and disable or // reset 2FA for your account RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"` }
AdminFilters defines additional restrictions for SFTPGo admins TODO: rename to AdminOptions in v3
type AdminTOTPConfig ¶ added in v2.2.2
type AdminTOTPConfig struct { Enabled bool `json:"enabled,omitempty"` ConfigName string `json:"config_name,omitempty"` Secret *kms.Secret `json:"secret,omitempty"` }
AdminTOTPConfig defines the time-based one time password configuration
type Argon2Options ¶
type Argon2Options struct { Memory uint32 `json:"memory" mapstructure:"memory"` Iterations uint32 `json:"iterations" mapstructure:"iterations"` Parallelism uint8 `json:"parallelism" mapstructure:"parallelism"` }
Argon2Options defines the options for argon2 password hashing
type AutoBackup ¶ added in v2.3.0
type AutoBackup struct { Enabled bool `json:"enabled" mapstructure:"enabled"` // hour as standard cron expression. Allowed values: 0-23. // Allowed special characters: asterisk (*), slash (/), comma (,), hyphen (-). // More info about special characters here: // https://pkg.go.dev/github.com/robfig/cron#hdr-Special_Characters Hour string `json:"hour" mapstructure:"hour"` // Day of the week as cron expression. Allowed values: 0-6 (Sunday to Saturday). // Allowed special characters: asterisk (*), slash (/), comma (,), hyphen (-), question mark (?). // More info about special characters here: // https://pkg.go.dev/github.com/robfig/cron#hdr-Special_Characters DayOfWeek string `json:"day_of_week" mapstructure:"day_of_week"` }
AutoBackup defines the settings for automatic provider backups. Example: hour "0" and day_of_week "*" means a backup every day at midnight. The backup file name is in the format backup_<day_of_week>_<hour>.json files with the same name will be overwritten
type BackupData ¶
type BackupData struct { Users []User `json:"users"` Groups []Group `json:"groups"` Folders []vfs.BaseVirtualFolder `json:"folders"` Admins []Admin `json:"admins"` APIKeys []APIKey `json:"api_keys"` Version int `json:"version"` }
BackupData defines the structure for the backup/restore files
func DumpData ¶
func DumpData() (BackupData, error)
DumpData returns all users, folders, admins, api keys, shares
func ParseDumpData ¶
func ParseDumpData(data []byte) (BackupData, error)
ParseDumpData tries to parse data as BackupData
func (*BackupData) HasFolder ¶
func (d *BackupData) HasFolder(name string) bool
HasFolder returns true if the folder with the given name is included
type BcryptOptions ¶
type BcryptOptions struct {
Cost int `json:"cost" mapstructure:"cost"`
}
BcryptOptions defines the options for bcrypt password hashing
type BoltProvider ¶
type BoltProvider struct {
// contains filtered or unexported fields
}
BoltProvider defines the auth provider for bolt key/value store
type CachedUser ¶
type CachedUser struct { User User Expiration time.Time Password string LockSystem webdav.LockSystem }
CachedUser adds fields useful for caching to a SFTPGo user
func GetCachedWebDAVUser ¶
func GetCachedWebDAVUser(username string) (*CachedUser, bool)
GetCachedWebDAVUser returns a previously cached WebDAV user
func (*CachedUser) IsExpired ¶
func (c *CachedUser) IsExpired() bool
IsExpired returns true if the cached user is expired
type Config ¶
type Config struct { // Driver name, must be one of the SupportedProviders Driver string `json:"driver" mapstructure:"driver"` // Database name. For driver sqlite this can be the database name relative to the config dir // or the absolute path to the SQLite database. Name string `json:"name" mapstructure:"name"` // Database host Host string `json:"host" mapstructure:"host"` // Database port Port int `json:"port" mapstructure:"port"` // Database username Username string `json:"username" mapstructure:"username"` // Database password Password string `json:"password" mapstructure:"password"` // Used for drivers mysql and postgresql. // 0 disable SSL/TLS connections. // 1 require ssl. // 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql. // 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql. SSLMode int `json:"sslmode" mapstructure:"sslmode"` // Path to the root certificate authority used to verify that the server certificate was signed by a trusted CA RootCert string `json:"root_cert" mapstructure:"root_cert"` // Path to the client certificate for two-way TLS authentication ClientCert string `json:"client_cert" mapstructure:"client_cert"` // Path to the client key for two-way TLS authentication ClientKey string `json:"client_key" mapstructure:"client_key"` // Custom database connection string. // If not empty this connection string will be used instead of build one using the previous parameters ConnectionString string `json:"connection_string" mapstructure:"connection_string"` // prefix for SQL tables SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"` // Set the preferred way to track users quota between the following choices: // 0, disable quota tracking. REST API to scan user dir and update quota will do nothing // 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions // 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions // and for virtual folders. // With this configuration the "quota scan" REST API can still be used to periodically update space usage // for users without quota restrictions TrackQuota int `json:"track_quota" mapstructure:"track_quota"` // Sets the maximum number of open connections for mysql and postgresql driver. // Default 0 (unlimited) PoolSize int `json:"pool_size" mapstructure:"pool_size"` // Users default base directory. // If no home dir is defined while adding a new user, and this value is // a valid absolute path, then the user home dir will be automatically // defined as the path obtained joining the base dir and the username UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"` // Actions to execute on objects add, update, delete. // The supported objects are user, admin, api_key. // Update action will not be fired for internal updates such as the last login or the user quota fields. Actions ObjectsActions `json:"actions" mapstructure:"actions"` // Absolute path to an external program or an HTTP URL to invoke for users authentication. // Leave empty to use builtin authentication. // If the authentication succeed the user will be automatically added/updated inside the defined data provider. // Actions defined for user added/updated will not be executed in this case. // This method is slower than built-in authentication methods, but it's very flexible as anyone can // easily write his own authentication hooks. ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"` // ExternalAuthScope defines the scope for the external authentication hook. // - 0 means all supported authentication scopes, the external hook will be executed for password, // public key, keyboard interactive authentication and TLS certificates // - 1 means passwords only // - 2 means public keys only // - 4 means keyboard interactive only // - 8 means TLS certificates only // you can combine the scopes, for example 3 means password and public key, 5 password and keyboard // interactive and so on ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"` // CredentialsPath defines the directory for storing user provided credential files such as // Google Cloud Storage credentials. It can be a path relative to the config dir or an // absolute path CredentialsPath string `json:"credentials_path" mapstructure:"credentials_path"` // Absolute path to an external program or an HTTP URL to invoke just before the user login. // This program/URL allows to modify or create the user trying to login. // It is useful if you have users with dynamic fields to update just before the login. // Please note that if you want to create a new user, the pre-login hook response must // include all the mandatory user fields. // // The pre-login hook must finish within 30 seconds. // // If an error happens while executing the "PreLoginHook" then login will be denied. // PreLoginHook and ExternalAuthHook are mutally exclusive. // Leave empty to disable. PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"` // Absolute path to an external program or an HTTP URL to invoke after the user login. // Based on the configured scope you can choose if notify failed or successful logins // or both PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"` // PostLoginScope defines the scope for the post-login hook. // - 0 means notify both failed and successful logins // - 1 means notify failed logins // - 2 means notify successful logins PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"` // Absolute path to an external program or an HTTP URL to invoke just before password // authentication. This hook allows you to externally check the provided password, // its main use case is to allow to easily support things like password+OTP for protocols // without keyboard interactive support such as FTP and WebDAV. You can ask your users // to login using a string consisting of a fixed password and a One Time Token, you // can verify the token inside the hook and ask to SFTPGo to verify the fixed part. CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"` // CheckPasswordScope defines the scope for the check password hook. // - 0 means all protocols // - 1 means SSH // - 2 means FTP // - 4 means WebDAV // you can combine the scopes, for example 6 means FTP and WebDAV CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"` // Defines how the database will be initialized/updated: // - 0 means automatically // - 1 means manually using the initprovider sub-command UpdateMode int `json:"update_mode" mapstructure:"update_mode"` // PasswordHashing defines the configuration for password hashing PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"` // PasswordValidation defines the password validation rules PasswordValidation PasswordValidation `json:"password_validation" mapstructure:"password_validation"` // Verifying argon2 passwords has a high memory and computational cost, // by enabling, in memory, password caching you reduce this cost. PasswordCaching bool `json:"password_caching" mapstructure:"password_caching"` // DelayedQuotaUpdate defines the number of seconds to accumulate quota updates. // If there are a lot of close uploads, accumulating quota updates can save you many // queries to the data provider. // If you want to track quotas, a scheduled quota update is recommended in any case, the stored // quota size may be incorrect for several reasons, such as an unexpected shutdown, temporary provider // failures, file copied outside of SFTPGo, and so on. // 0 means immediate quota update. DelayedQuotaUpdate int `json:"delayed_quota_update" mapstructure:"delayed_quota_update"` // If enabled, a default admin user with username "admin" and password "password" will be created // on first start. // You can also create the first admin user by using the web interface or by loading initial data. CreateDefaultAdmin bool `json:"create_default_admin" mapstructure:"create_default_admin"` // Rules for usernames and folder names: // - 0 means no rules // - 1 means you can use any UTF-8 character. The names are used in URIs for REST API and Web admin. // By default only unreserved URI characters are allowed: ALPHA / DIGIT / "-" / "." / "_" / "~". // - 2 means names are converted to lowercase before saving/matching and so case // insensitive matching is possible // - 4 means trimming trailing and leading white spaces before saving/matching // Rules can be combined, for example 3 means both converting to lowercase and allowing any UTF-8 character. // Enabling these options for existing installations could be backward incompatible, some users // could be unable to login, for example existing users with mixed cases in their usernames. // You have to ensure that all existing users respect the defined rules. NamingRules int `json:"naming_rules" mapstructure:"naming_rules"` // MySQL, PostgreSQL and CockroachDB can be shared, this setting is ignored for other data // providers. For shared data providers, SFTPGo periodically reloads the latest updated users, // based on the "updated_at" field, and updates its internal caches if users are updated from // a different instance. This check, if enabled, is executed every 10 minutes. // For shared data providers, active transfers are persisted in the database and thus // quota checks between ongoing transfers will work cross multiple instances IsShared int `json:"is_shared" mapstructure:"is_shared"` // Path to the backup directory. This can be an absolute path or a path relative to the config dir BackupsPath string `json:"backups_path" mapstructure:"backups_path"` // Settings for automatic backups AutoBackup AutoBackup `json:"auto_backup" mapstructure:"auto_backup"` }
Config provider configuration
func GetProviderConfig ¶ added in v2.2.1
func GetProviderConfig() Config
GetProviderConfig returns the current provider configuration
func (*Config) IsDefenderSupported ¶ added in v2.2.1
IsDefenderSupported returns true if the configured provider supports the defender
type DefenderEntry ¶ added in v2.2.1
type DefenderEntry struct { ID int64 `json:"-"` IP string `json:"ip"` Score int `json:"score,omitempty"` BanTime time.Time `json:"ban_time,omitempty"` }
DefenderEntry defines a defender entry
func AddDefenderEvent ¶ added in v2.2.1
func AddDefenderEvent(ip string, score int, from int64) (DefenderEntry, error)
AddDefenderEvent adds an event for the given IP with the given score and returns the host with the updated score
func GetDefenderHostByIP ¶ added in v2.2.1
func GetDefenderHostByIP(ip string, from int64) (DefenderEntry, error)
GetDefenderHostByIP returns a defender host by ip, if any
func GetDefenderHosts ¶ added in v2.2.1
func GetDefenderHosts(from int64, limit int) ([]DefenderEntry, error)
GetDefenderHosts returns hosts that are banned or for which some violations have been detected
func IsDefenderHostBanned ¶ added in v2.2.1
func IsDefenderHostBanned(ip string) (DefenderEntry, error)
IsDefenderHostBanned returns a defender entry and no error if the specified host is banned
func (*DefenderEntry) GetBanTime ¶ added in v2.2.1
func (d *DefenderEntry) GetBanTime() string
GetBanTime returns the ban time for a defender entry as string
func (*DefenderEntry) GetID ¶ added in v2.2.1
func (d *DefenderEntry) GetID() string
GetID returns an unique ID for a defender entry
func (*DefenderEntry) MarshalJSON ¶ added in v2.2.1
func (d *DefenderEntry) MarshalJSON() ([]byte, error)
MarshalJSON returns the JSON encoding of a DefenderEntry.
type Group ¶ added in v2.3.0
type Group struct { sdk.BaseGroup // settings to apply to users for whom this is a primary group UserSettings GroupUserSettings `json:"user_settings,omitempty"` // Mapping between virtual paths and virtual folders VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"` }
Group defines an SFTPGo group. Groups are used to easily configure similar users
func GroupExists ¶ added in v2.3.0
GroupExists returns the Group with the given name if it exists
func (*Group) GetAllowedIPAsString ¶ added in v2.3.0
GetAllowedIPAsString returns the allowed IP as comma separated string
func (*Group) GetDeniedIPAsString ¶ added in v2.3.0
GetDeniedIPAsString returns the denied IP as comma separated string
func (*Group) GetEncryptionAdditionalData ¶ added in v2.3.0
GetEncryptionAdditionalData returns the additional data to use for AEAD
func (*Group) GetPermissions ¶ added in v2.3.0
func (g *Group) GetPermissions() []sdk.DirectoryPermissions
GetPermissions returns the permissions as list
func (*Group) GetUsersAsString ¶ added in v2.3.0
GetUsersAsString returns the list of users as comma separated string
func (*Group) HasExternalAuth ¶ added in v2.3.0
HasExternalAuth returns true if the external authentication is globally enabled and it is not disabled for this group
func (*Group) PrepareForRendering ¶ added in v2.3.0
func (g *Group) PrepareForRendering()
PrepareForRendering prepares a group for rendering. It hides confidential data and set to nil the empty secrets so they are not serialized
func (*Group) RenderAsJSON ¶ added in v2.3.0
RenderAsJSON implements the renderer interface used within plugins
func (*Group) SetEmptySecretsIfNil ¶ added in v2.3.0
func (g *Group) SetEmptySecretsIfNil()
SetEmptySecretsIfNil sets the secrets to empty if nil
type GroupUserSettings ¶ added in v2.3.0
type GroupUserSettings struct { sdk.BaseGroupUserSettings // Filesystem configuration details FsConfig vfs.Filesystem `json:"filesystem"` }
GroupUserSettings defines the settings to apply to users
type MemoryProvider ¶
type MemoryProvider struct {
// contains filtered or unexported fields
}
MemoryProvider defines the auth provider for a memory store
type MySQLProvider ¶
type MySQLProvider struct {
// contains filtered or unexported fields
}
MySQLProvider defines the auth provider for MySQL/MariaDB database
type ObjectsActions ¶
type ObjectsActions struct { // Valid values are add, update, delete. Empty slice to disable ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"` // Valid values are user, admin, api_key ExecuteFor []string `json:"execute_for" mapstructure:"execute_for"` // Absolute path to an external program or an HTTP URL Hook string `json:"hook" mapstructure:"hook"` }
ObjectsActions defines the action to execute on user create, update, delete for the specified objects
type PGSQLProvider ¶
type PGSQLProvider struct {
// contains filtered or unexported fields
}
PGSQLProvider defines the auth provider for PostgreSQL database
type PasswordHashing ¶
type PasswordHashing struct { BcryptOptions BcryptOptions `json:"bcrypt_options" mapstructure:"bcrypt_options"` Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"` // Algorithm to use for hashing passwords. Available algorithms: argon2id, bcrypt. Default: bcrypt Algo string `json:"algo" mapstructure:"algo"` }
PasswordHashing defines the configuration for password hashing
type PasswordValidation ¶
type PasswordValidation struct { // Password validation rules for SFTPGo admin users Admins PasswordValidationRules `json:"admins" mapstructure:"admins"` // Password validation rules for SFTPGo protocol users Users PasswordValidationRules `json:"users" mapstructure:"users"` }
PasswordValidation defines the password validation rules for admins and protocol users
type PasswordValidationRules ¶
type PasswordValidationRules struct { // MinEntropy defines the minimum password entropy. // 0 means disabled, any password will be accepted. // Take a look at the following link for more details // https://github.com/wagslane/go-password-validator#what-entropy-value-should-i-use MinEntropy float64 `json:"min_entropy" mapstructure:"min_entropy"` }
PasswordValidationRules defines the password validation rules
type Provider ¶
type Provider interface {
// contains filtered or unexported methods
}
Provider defines the interface that data providers must implement.
type ProviderStatus ¶
type ProviderStatus struct { Driver string `json:"driver"` IsActive bool `json:"is_active"` Error string `json:"error"` }
ProviderStatus defines the provider status
func GetProviderStatus ¶
func GetProviderStatus() ProviderStatus
GetProviderStatus returns an error if the provider is not available
type RecoveryCode ¶ added in v2.2.2
RecoveryCode defines a 2FA recovery code
type SQLiteProvider ¶
type SQLiteProvider struct {
// contains filtered or unexported fields
}
SQLiteProvider defines the auth provider for SQLite database
type Session ¶ added in v2.3.0
type Session struct { Key string Data any Type SessionType Timestamp int64 }
Session defines a shared session persisted in the data provider
func GetSharedSession ¶ added in v2.3.0
GetSharedSession retrieves the session with the specified key
type SessionType ¶ added in v2.3.0
type SessionType int
SessionType defines the supported session types
const ( SessionTypeOIDCAuth SessionType = iota + 1 SessionTypeOIDCToken SessionTypeResetCode )
Supported session types
type Share ¶
type Share struct { int64 `json:"-"` // Unique ID used to access this object Paths []string `json:"paths"` // Username who shared this object LastUseAt int64 `json:"last_use_at,omitempty"` ExpiresAt int64 `json:"expires_at,omitempty"` Password string `json:"password"` MaxTokens int `json:"max_tokens,omitempty"` UsedTokens int `json:"used_tokens,omitempty"` AllowFrom []string `json:"allow_from,omitempty"` // otherwise we fail to restore existing shares and we have to insert // all the previous values with no modifications IsRestore bool `json:"-"` }ID
Share defines files and or directories shared with external users
func ShareExists ¶
ShareExists returns the share with the given ID if it exists
func (*Share) CheckCredentials ¶ added in v2.3.0
CheckCredentials verifies the share credentials if a password if set
func (*Share) GetAllowedFromAsString ¶
GetAllowedFromAsString returns the allowed IP as comma separated string
func (*Share) GetInfoString ¶
GetInfoString returns share's info as string.
func (*Share) GetRelativePath ¶ added in v2.3.0
GetRelativePath returns the specified absolute path as relative to the share base path
func (*Share) GetScopeAsString ¶
GetScopeAsString returns the share's scope as string. Used in web pages
func (*Share) HasRedactedPassword ¶
HasRedactedPassword returns true if this share has a redacted password
func (*Share) HideConfidentialData ¶
func (s *Share) HideConfidentialData()
HideConfidentialData hides share confidential data
type ShareScope ¶
type ShareScope int
ShareScope defines the supported share scopes
const ()
Supported share scopes
type TransferQuota ¶ added in v2.3.0
type TransferQuota struct { ULSize int64 DLSize int64 TotalSize int64 AllowedULSize int64 AllowedDLSize int64 AllowedTotalSize int64 }
TransferQuota stores the allowed transfer quota fields
func (*TransferQuota) HasDownloadSpace ¶ added in v2.3.0
func (q *TransferQuota) HasDownloadSpace() bool
HasDownloadSpace returns true if there is transfer download space available
func (*TransferQuota) HasSizeLimits ¶ added in v2.3.0
func (q *TransferQuota) HasSizeLimits() bool
HasSizeLimits returns true if any size limit is set
func (*TransferQuota) HasUploadSpace ¶ added in v2.3.0
func (q *TransferQuota) HasUploadSpace() bool
HasUploadSpace returns true if there is transfer upload space available
type User ¶
type User struct { sdk.BaseUser // Additional restrictions Filters UserFilters `json:"filters"` // Mapping between virtual paths and virtual folders VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"` // Filesystem configuration details FsConfig vfs.Filesystem `json:"filesystem"` // groups associated with this user Groups []sdk.GroupMapping `json:"groups,omitempty"` // contains filtered or unexported fields }
User defines a SFTPGo user
func CheckCompositeCredentials ¶
func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (User, string, error)
CheckCompositeCredentials checks multiple credentials. WebDAV users can send both a password and a TLS certificate within the same request
func CheckKeyboardInteractiveAuth ¶
func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (User, error)
CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns the authenticated user or an error
func CheckUserAndPass ¶
CheckUserAndPass retrieves the SFTPGo user with the given username and password if a match is found or an error
func CheckUserAndPubKey ¶
func CheckUserAndPubKey(username string, pubKey []byte, ip, protocol string, isSSHCert bool) (User, string, error)
CheckUserAndPubKey retrieves the SFTP user with the given username and public key if a match is found or an error
func CheckUserAndTLSCert ¶
func CheckUserAndTLSCert(username, ip, protocol string, tlsCert *x509.Certificate) (User, error)
CheckUserAndTLSCert returns the SFTPGo user with the given username and check if the given TLS certificate allow authentication without password
func CheckUserBeforeTLSAuth ¶
func CheckUserBeforeTLSAuth(username, ip, protocol string, tlsCert *x509.Certificate) (User, error)
CheckUserBeforeTLSAuth checks if a user exits before trying mutual TLS
func GetUserAfterIDPAuth ¶ added in v2.3.0
func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error)
GetUserAfterIDPAuth returns the SFTPGo user with the specified username after a successful authentication with an external identity provider. If a pre-login hook is defined it will be executed so the SFTPGo user can be created if it does not exist
func GetUserWithGroupSettings ¶ added in v2.3.0
GetUserWithGroupSettings tries to return the user with the specified username loading also the group settings
func GetUsersForQuotaCheck ¶ added in v2.3.0
GetUsersForQuotaCheck returns the users with the fields required for a quota check
func UserExists ¶
UserExists checks if the given SFTPGo username exists, returns an error if no match is found
func (*User) CanAddDirsFromWeb ¶
CanAddDirsFromWeb returns true if the client can add directories from the web UI. The specified target is the directory where the new directory must be created
func (*User) CanAddFilesFromWeb ¶
CanAddFilesFromWeb returns true if the client can add files from the web UI. The specified target is the directory where the files must be uploaded
func (*User) CanChangeAPIKeyAuth ¶
CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
func (*User) CanChangeInfo ¶
CanChangeInfo returns true if this user is allowed to change its info such as email and description
func (*User) CanChangePassword ¶
CanChangePassword returns true if this user is allowed to change its password
func (*User) CanDeleteFromWeb ¶
CanDeleteFromWeb returns true if the client can delete objects from the web UI. The specified target is the parent directory for the object to delete
func (*User) CanManageMFA ¶
CanManageMFA returns true if the user can add a multi-factor authentication configuration
func (*User) CanManagePublicKeys ¶
CanManagePublicKeys returns true if this user is allowed to manage public keys from the web client. Used in web client UI
func (*User) CanManageShares ¶
CanManageShares returns true if the user can add, update and list shares
func (*User) CanRenameFromWeb ¶
CanRenameFromWeb returns true if the client can rename objects from the web UI. The specified src and dest are the source and target directories for the rename.
func (*User) CanResetPassword ¶
CanResetPassword returns true if this user is allowed to reset its password
func (*User) CheckFsRoot ¶
CheckFsRoot check the root directory for the main fs and the virtual folders. It returns an error if the main filesystem cannot be created
func (*User) CheckLoginConditions ¶
CheckLoginConditions checks if the user is active and not expired
func (*User) CheckMetadataConsistency ¶ added in v2.2.1
CheckMetadataConsistency checks the consistency between the metadata stored in the configured metadata plugin and the filesystem
func (*User) CountUnusedRecoveryCodes ¶
CountUnusedRecoveryCodes returns the number of unused recovery codes
func (*User) FilterListDir ¶ added in v2.3.0
FilterListDir adds virtual folders and remove hidden items from the given files list
func (*User) GetAllowedIPAsString ¶
GetAllowedIPAsString returns the allowed IP as comma separated string
func (*User) GetAllowedLoginMethods ¶
GetAllowedLoginMethods returns the allowed login methods
func (*User) GetBandwidthAsString ¶
GetBandwidthAsString returns bandwidth limits if defines
func (*User) GetBandwidthForIP ¶ added in v2.2.1
GetBandwidthForIP returns the upload and download bandwidth for the specified IP
func (*User) GetCleanedPath ¶ added in v2.3.0
GetCleanedPath returns a clean POSIX absolute path using the user start directory as base if the provided rawVirtualPath is relative
func (*User) GetDataTransferLimits ¶ added in v2.3.0
GetDataTransferLimits returns upload, download and total data transfer limits
func (*User) GetDeniedIPAsString ¶
GetDeniedIPAsString returns the denied IP as comma separated string
func (*User) GetEncryptionAdditionalData ¶
GetEncryptionAdditionalData returns the additional data to use for AEAD
func (*User) GetExpirationDateAsString ¶
GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
func (*User) GetFilesystem ¶
GetFilesystem returns the base filesystem for this user
func (*User) GetFilesystemForPath ¶
GetFilesystemForPath returns the filesystem for the given path
func (*User) GetFiltersAsJSON ¶
GetFiltersAsJSON returns the filters as json byte array
func (*User) GetFsConfigAsJSON ¶
GetFsConfigAsJSON returns the filesystem config as json byte array
func (*User) GetFsConfigForPath ¶
func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem
GetFsConfigForPath returns the file system configuration for the specified virtual path
func (*User) GetGCSCredentialsFilePath ¶
GetGCSCredentialsFilePath returns the path for GCS credentials
func (*User) GetGroupsAsString ¶ added in v2.3.0
GetGroupsAsString returns the user's groups as a string
func (*User) GetHomeDir ¶
GetHomeDir returns the shortest path name equivalent to the user's home directory
func (*User) GetInfoString ¶
GetInfoString returns user's info as string. Storage provider, number of public keys, max sessions, uid, gid, denied and allowed IP/Mask are returned
func (*User) GetLastLoginAsString ¶ added in v2.3.0
GetLastLoginAsString returns the last login as string
func (*User) GetLastQuotaUpdateAsString ¶ added in v2.3.0
GetLastQuotaUpdateAsString returns the last quota update as string
func (*User) GetMFAStatusAsString ¶ added in v2.3.0
GetMFAStatusAsString returns MFA status
func (*User) GetNextAuthMethods ¶
func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string
GetNextAuthMethods returns the list of authentications methods that can continue for multi-step authentication
func (*User) GetPermissionsAsJSON ¶
GetPermissionsAsJSON returns the permissions as json byte array
func (*User) GetPermissionsAsString ¶
GetPermissionsAsString returns the user's permissions as comma separated string
func (*User) GetPermissionsForPath ¶
GetPermissionsForPath returns the permissions for the given path. The path must be a SFTPGo exposed path
func (*User) GetPublicKeysAsJSON ¶
GetPublicKeysAsJSON returns the public keys as json byte array
func (*User) GetQuotaSummary ¶
GetQuotaSummary returns used quota and limits if defined
func (*User) GetSignature ¶
GetSignature returns a signature for this admin. It could change after an update
func (*User) GetStatusAsString ¶
GetStatusAsString returns the user status as a string
func (*User) GetStorageDescrition ¶ added in v2.3.0
GetStorageDescrition returns the storage description
func (*User) GetSubDirPermissions ¶
func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions
GetSubDirPermissions returns permissions for sub directories
func (*User) GetVirtualFolderForPath ¶
func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error)
GetVirtualFolderForPath returns the virtual folder containing the specified virtual path. If the path is not inside a virtual folder an error is returned
func (*User) GetVirtualFoldersInPath ¶
GetVirtualFoldersInPath returns the virtual folders inside virtualPath including any parents
func (*User) HasAnyPerm ¶
HasAnyPerm returns true if the user has at least one of the given permissions
func (*User) HasBufferedSFTP ¶ added in v2.2.1
HasBufferedSFTP returns true if the user has a SFTP filesystem with buffering enabled
func (*User) HasExternalAuth ¶ added in v2.3.0
HasExternalAuth returns true if the external authentication is globally enabled and it is not disabled for this user
func (*User) HasNoQuotaRestrictions ¶
HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
func (*User) HasPermissionsInside ¶
HasPermissionsInside returns true if the specified virtualPath has no permissions itself and no subdirs with defined permissions
func (*User) HasPermsDeleteAll ¶
HasPermsDeleteAll returns true if the user can delete both files and directories for the given path
func (*User) HasPermsRenameAll ¶
HasPermsRenameAll returns true if the user can rename both files and directories for the given path
func (*User) HasPrimaryGroup ¶ added in v2.3.0
HasPrimaryGroup returns true if the user has the specified primary group
func (*User) HasQuotaRestrictions ¶
HasQuotaRestrictions returns true if there are any disk quota restrictions
func (*User) HasRecentActivity ¶ added in v2.3.0
HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
func (*User) HasSecondaryGroup ¶ added in v2.3.0
HasSecondaryGroup returns true if the user has the specified secondary group
func (*User) HasTransferQuotaRestrictions ¶ added in v2.3.0
HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
func (*User) HasVirtualFoldersInside ¶
HasVirtualFoldersInside returns true if there are virtual folders inside the specified virtual path. We assume that path are cleaned
func (*User) IsFileAllowed ¶
IsFileAllowed returns true if the specified file is allowed by the file restrictions filters. The second parameter returned is the deny policy
func (*User) IsLoginFromAddrAllowed ¶
IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr. If AllowedIP is defined only the specified IP/Mask can login. If DeniedIP is defined the specified IP/Mask cannot login. If an IP is both allowed and denied then login will be denied
func (*User) IsLoginMethodAllowed ¶
func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool
IsLoginMethodAllowed returns true if the specified login method is allowed
func (*User) IsMappedPath ¶
IsMappedPath returns true if the specified filesystem path has a virtual folder mapping. The filesystem path must be cleaned before calling this method
func (*User) IsPartialAuth ¶
IsPartialAuth returns true if the specified login method is a step for a multi-step Authentication. We support publickey+password and publickey+keyboard-interactive, so only publickey can returns partial success. We can have partial success if only multi-step Auth methods are enabled
func (*User) IsPasswordHashed ¶
IsPasswordHashed returns true if the password is hashed
func (*User) IsTLSUsernameVerificationEnabled ¶
IsTLSUsernameVerificationEnabled returns true if we need to extract the username from the client TLS certificate
func (*User) IsVirtualFolder ¶
IsVirtualFolder returns true if the specified virtual path is a virtual folder
func (*User) LoadAndApplyGroupSettings ¶ added in v2.3.0
LoadAndApplyGroupSettings update the user by loading and applying the group settings
func (*User) MustSetSecondFactor ¶ added in v2.3.0
MustSetSecondFactor returns true if the user must set a second factor authentication
func (*User) MustSetSecondFactorForProtocol ¶ added in v2.3.0
MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication for the specified protocol
func (*User) PrepareForRendering ¶
func (u *User) PrepareForRendering()
PrepareForRendering prepares a user for rendering. It hides confidential data and set to nil the empty secrets so they are not serialized
func (*User) RenderAsJSON ¶
RenderAsJSON implements the renderer interface used within plugins
func (*User) ScanQuota ¶
ScanQuota scans the user home dir and virtual folders, included in its quota, and returns the number of files and their size
func (*User) SetEmptySecrets ¶
func (u *User) SetEmptySecrets()
SetEmptySecrets sets to empty any user secret
func (*User) SetEmptySecretsIfNil ¶
func (u *User) SetEmptySecretsIfNil()
SetEmptySecretsIfNil sets the secrets to empty if nil
type UserFilters ¶ added in v2.2.2
type UserFilters struct { sdk.BaseUserFilters // Time-based one time passwords configuration TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"` // Recovery codes to use if the user loses access to their second factor auth device. // Each code can only be used once, you should use these codes to login and disable or // reset 2FA for your account RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"` }
UserFilters defines additional restrictions for a user TODO: rename to UserOptions in v3
type UserTOTPConfig ¶ added in v2.2.2
type UserTOTPConfig struct { Enabled bool `json:"enabled,omitempty"` ConfigName string `json:"config_name,omitempty"` Secret *kms.Secret `json:"secret,omitempty"` // TOTP will be required for the specified protocols. // SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive // authentication. // FTP have no standard way to support two factor authentication, if you // enable the support for this protocol you have to add the TOTP passcode after the password. // For example if your password is "password" and your one time passcode is // "123456" you have to use "password123456" as password. Protocols []string `json:"protocols,omitempty"` }
UserTOTPConfig defines the time-based one time password configuration