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 AddEventAction(action *BaseEventAction, executor, ipAddress string) error
- func AddEventRule(rule *EventRule, executor, ipAddress string) error
- func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress string) error
- func AddGroup(group *Group, executor, ipAddress string) error
- func AddRole(role *Role, executor, ipAddress string) error
- func AddShare(share *Share, executor, ipAddress string) error
- func AddSharedSession(session Session) error
- func AddTask(name string) error
- func AddUser(user *User, executor, ipAddress string) error
- func AuthenticateNodeToken(token string) (string, 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 DeleteEventAction(name string, executor, ipAddress string) error
- func DeleteEventRule(name string, executor, ipAddress string) error
- func DeleteFolder(folderName, executor, ipAddress string) error
- func DeleteGroup(name string, executor, ipAddress string) error
- func DeleteRole(name string, executor, ipAddress string) error
- func DeleteShare(shareID string, executor, ipAddress string) error
- func DeleteSharedSession(key string) error
- func DeleteUser(username, executor, ipAddress, role string) error
- func DumpFolders() ([]vfs.BaseVirtualFolder, error)
- func ExecuteBackup() (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 GetNodeName() string
- func GetQuotaTracking() int
- func GetUsedQuota(username string) (int, int64, int64, int64, error)
- func GetUsedVirtualFolderQuota(name string) (int, int64, error)
- func GetUserVariants(username, role 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 RemoveEventRule(rule EventRule) error
- func ResetDatabase(cnf Config, basePath string) error
- func RevertDatabase(cnf Config, basePath string, targetVersion int) error
- func SetAllowSelfConnections(value int)
- func SetDefenderBanTime(ip string, banTime int64) error
- func SetEventRulesCallbacks(reload FnReloadRules, remove FnRemoveRule, handle FnHandleRuleForProviderEvent)
- 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 UpdateEventAction(action *BaseEventAction, executor, ipAddress string) error
- func UpdateEventRule(rule *EventRule, executor, ipAddress string) 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 UpdateRole(role *Role, executor, ipAddress string) error
- func UpdateShare(share *Share, executor, ipAddress string) error
- func UpdateShareLastUse(share *Share, numTokens int) error
- func UpdateTask(name string, version int64) error
- func UpdateTaskTimestamp(name string) 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 UpdateUserTransferTimestamps(username string, isUpload 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) GetGroupsAsString() 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 AdminGroupMapping
- type AdminGroupMappingOptions
- type AdminPreferences
- func (p *AdminPreferences) HideACLs() bool
- func (p *AdminPreferences) HideAdvancedSettings() bool
- func (p *AdminPreferences) HideDiskQuotaAndBandwidthLimits() bool
- func (p *AdminPreferences) HideFilesystem() bool
- func (p *AdminPreferences) HideGroups() bool
- func (p *AdminPreferences) HideProfile() bool
- func (p *AdminPreferences) HideVirtualFolders() bool
- func (p *AdminPreferences) VisibleUserPageSections() int
- type AdminTOTPConfig
- type Argon2Options
- type BackupData
- type BaseEventAction
- type BaseEventActionOptions
- type BcryptOptions
- type BoltProvider
- type CachedUser
- type ConditionOptions
- type ConditionPattern
- type Config
- type DefenderEntry
- type EnumMapping
- type EventAction
- type EventActionCommandConfig
- type EventActionDataRetentionConfig
- type EventActionEmailConfig
- type EventActionFilesystemConfig
- type EventActionFsCompress
- type EventActionHTTPConfig
- func (c *EventActionHTTPConfig) GetContext() (context.Context, context.CancelFunc)
- func (c *EventActionHTTPConfig) GetHTTPClient() *http.Client
- func (c *EventActionHTTPConfig) HasMultipartFiles() bool
- func (c *EventActionHTTPConfig) HasObjectData() bool
- func (c *EventActionHTTPConfig) TryDecryptPassword() error
- type EventActionOptions
- type EventConditions
- type EventRule
- func (r *EventRule) CheckActionsConsistency(providerObjectType string) error
- func (r *EventRule) GetActionsAsString() string
- func (r *EventRule) GetTriggerAsString() string
- func (r *EventRule) GuardFromConcurrentExecution() bool
- func (r *EventRule) PrepareForRendering()
- func (r *EventRule) RenderAsJSON(reload bool) ([]byte, error)
- type FnHandleRuleForProviderEvent
- type FnReloadRules
- type FnRemoveRule
- type FolderRetention
- type Group
- func (g *Group) GetAllowedIPAsString() string
- func (g *Group) GetDeniedIPAsString() string
- func (g *Group) GetEncryptionAdditionalData() string
- func (g *Group) GetMembersAsString() string
- func (g *Group) GetPermissions() []sdk.DirectoryPermissions
- func (g *Group) HasExternalAuth() bool
- func (g *Group) PrepareForRendering()
- func (g *Group) RenderAsJSON(reload bool) ([]byte, error)
- func (g *Group) SetEmptySecretsIfNil()
- type GroupUserSettings
- type HTTPPart
- type KeyValue
- type MemoryProvider
- type MySQLProvider
- type Node
- type NodeConfig
- type NodeData
- type ObjectsActions
- type PGSQLProvider
- type PasswordHashing
- type PasswordValidation
- type PasswordValidationRules
- type Provider
- type ProviderStatus
- type RecoveryCode
- type Role
- type SQLiteProvider
- type Schedule
- 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 Task
- 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 DumpUsers() ([]User, error)
- func GetFTPPreAuthUser(username, ip string) (User, error)
- func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error)
- func GetUserWithGroupSettings(username, role string) (User, error)
- func GetUsers(limit, offset int, order, role string) ([]User, error)
- func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error)
- func UserExists(username, role 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) 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) HasExternalAuth() bool
- func (u *User) HasMembershipGroup(name string) 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" PermAdminManageEventRules = "manage_event_rules" PermAdminManageRoles = "manage_roles" )
Available permissions for SFTPGo admins
const ( // GroupAddToUsersAsMembership defines that the admin's group will be added as membership group for new users GroupAddToUsersAsMembership = iota // GroupAddToUsersAsPrimary defines that the admin's group will be added as primary group for new users GroupAddToUsersAsPrimary // GroupAddToUsersAsSecondary defines that the admin's group will be added as secondary group for new users GroupAddToUsersAsSecondary )
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 = 14 )
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 ( ActionTypeHTTP = iota + 1 ActionTypeCommand ActionTypeEmail ActionTypeBackup ActionTypeUserQuotaReset ActionTypeFolderQuotaReset ActionTypeTransferQuotaReset ActionTypeDataRetentionCheck ActionTypeFilesystem ActionTypeMetadataCheck )
Supported event actions
const ( // Filesystem events such as upload, download, mkdir ... EventTriggerFsEvent = iota + 1 // Provider events such as add, update, delete EventTriggerProviderEvent EventTriggerSchedule EventTriggerIPBlocked EventTriggerCertificate )
Supported event triggers
const ( FilesystemActionRename = iota + 1 FilesystemActionDelete FilesystemActionMkdirs FilesystemActionExist FilesystemActionCompress )
Supported filesystem actions
const ( NodeProtoHTTP = "http" NodeProtoHTTPS = "https" )
Supported protocols for connecting to other nodes
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
const (
// NodeTokenHeader defines the header to use for the node auth token
NodeTokenHeader = "X-SFTPGO-Node"
)
const (
// RetentionReportPlaceHolder defines the placeholder for data retention reports
RetentionReportPlaceHolder = "{{RetentionReports}}"
)
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") )
var ( // SupportedFsEvents defines the supported filesystem events SupportedFsEvents = []string{"upload", "first-upload", "download", "first-download", "delete", "rename", "mkdir", "rmdir", "ssh_cmd"} // SupportedProviderEvents defines the supported provider events SupportedProviderEvents = []string{operationAdd, operationUpdate, operationDelete} // SupportedRuleConditionProtocols defines the supported protcols for rule conditions SupportedRuleConditionProtocols = []string{"SFTP", "SCP", "SSH", "FTP", "DAV", "HTTP", "HTTPShare", "OIDC"} // SupporteRuleConditionProviderObjects defines the supported provider objects for rule conditions SupporteRuleConditionProviderObjects = []string{actionObjectUser, actionObjectFolder, actionObjectGroup, actionObjectAdmin, actionObjectAPIKey, actionObjectShare, actionObjectEventRule, actionObjectEventAction} // SupportedHTTPActionMethods defines the supported methods for HTTP actions SupportedHTTPActionMethods = []string{http.MethodPost, http.MethodGet, http.MethodPut} )
TODO: replace the copied strings with shared constants
var ( EventActionTypes []EnumMapping EventTriggerTypes []EnumMapping FsActionTypes []EnumMapping )
enum mappings
Functions ¶
func AddActiveTransfer ¶
func AddActiveTransfer(transfer ActiveTransfer)
AddActiveTransfer stores the specified transfer
func AddEventAction ¶
func AddEventAction(action *BaseEventAction, executor, ipAddress string) error
AddEventAction adds a new event action
func AddEventRule ¶
AddEventRule adds a new event rule
func AddFolder ¶
func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress string) error
AddFolder adds a new virtual folder.
func AddSharedSession ¶
AddSharedSession stores a new session within the data provider
func AuthenticateNodeToken ¶
AuthenticateNodeToken check the validity of the provided token
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 ¶
CleanupActiveTransfers removes the transfer before the specified time
func CleanupDefender ¶
CleanupDefender removes events and hosts older than "from" from the data provider
func CleanupSharedSessions ¶
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 ¶
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 ¶
DeleteDefenderHost removes the specified IP from the defender lists
func DeleteEventAction ¶
DeleteEventAction deletes an existing event action
func DeleteEventRule ¶
DeleteEventRule deletes an existing event rule
func DeleteFolder ¶
DeleteFolder deletes an existing folder.
func DeleteGroup ¶
DeleteGroup deletes an existing Group
func DeleteRole ¶
DeleteRole deletes an existing Role
func DeleteShare ¶
DeleteShare deletes an existing share
func DeleteSharedSession ¶
DeleteSharedSession deletes the session with the specified key
func DeleteUser ¶
DeleteUser deletes an existing SFTPGo user.
func DumpFolders ¶
func DumpFolders() ([]vfs.BaseVirtualFolder, error)
DumpFolders returns all folders, including confidential data
func ExecutePostLoginHook ¶
ExecutePostLoginHook executes the post login hook if defined
func GetBackupsPath ¶
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 ¶
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 ¶
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 ¶
RemoveActiveTransfer removes the specified transfer
func RemoveCachedWebDAVUser ¶
func RemoveCachedWebDAVUser(username string)
RemoveCachedWebDAVUser removes a cached WebDAV user
func RemoveEventRule ¶
RemoveEventRule delets an existing event rule without marking it as deleted
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 SetAllowSelfConnections ¶
func SetAllowSelfConnections(value int)
SetAllowSelfConnections sets the desired behaviour for self connections
func SetDefenderBanTime ¶
SetDefenderBanTime sets the ban time for the specified IP
func SetEventRulesCallbacks ¶
func SetEventRulesCallbacks(reload FnReloadRules, remove FnRemoveRule, handle FnHandleRuleForProviderEvent)
SetEventRulesCallbacks sets the event rules callbacks
func UpdateAPIKey ¶
UpdateAPIKey updates an existing API key
func UpdateAPIKeyLastUse ¶
UpdateAPIKeyLastUse updates the LastUseAt field for the given API key
func UpdateActiveTransferSizes ¶
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 ¶
UpdateDefenderBanTime increments ban time for the specified ip
func UpdateEventAction ¶
func UpdateEventAction(action *BaseEventAction, executor, ipAddress string) error
UpdateEventAction updates an existing event action
func UpdateEventRule ¶
UpdateEventRule updates an existing event rule
func UpdateFolder ¶
func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress string) error
UpdateFolder updates the specified virtual folder
func UpdateGroup ¶
UpdateGroup updates an existing Group
func UpdateLastLogin ¶
func UpdateLastLogin(user *User)
UpdateLastLogin updates the last login field for the given SFTPGo user
func UpdateRole ¶
UpdateRole updates an existing Role
func UpdateShare ¶
UpdateShare updates an existing share
func UpdateShareLastUse ¶
UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share
func UpdateTask ¶
UpdateTask updates the task with the specified name and version
func UpdateTaskTimestamp ¶
UpdateTaskTimestamp updates the timestamp for the task with the specified name
func UpdateUser ¶
UpdateUser updates an existing SFTPGo user.
func UpdateUserPassword ¶
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 ¶
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 UpdateUserTransferTimestamps ¶
UpdateUserTransferTimestamps updates the first download/upload fields if unset
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 ¶
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 ¶
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"` // Groups membership Groups []AdminGroupMapping `json:"groups,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"` // Role name. If set the admin can only administer users with the same role. // Role admins cannot have the following permissions: // - manage_admins // - manage_apikeys // - manage_system // - manage_event_rules // - manage_roles Role string `json:"role,omitempty"` }
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) GetGroupsAsString ¶
GetGroupsAsString returns the user's groups as a string
func (*Admin) GetLastLoginAsString ¶
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 will 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"` Preferences AdminPreferences `json:"preferences"` }
AdminFilters defines additional restrictions for SFTPGo admins TODO: rename to AdminOptions in v3
type AdminGroupMapping ¶
type AdminGroupMapping struct { Name string `json:"name"` Options AdminGroupMappingOptions `json:"options"` }
AdminGroupMapping defines the mapping between an SFTPGo admin and a group
type AdminGroupMappingOptions ¶
type AdminGroupMappingOptions struct {
AddToUsersAs int `json:"add_to_users_as,omitempty"`
}
AdminGroupMappingOptions defines the options for admin/group mapping
func (*AdminGroupMappingOptions) GetUserGroupType ¶
func (o *AdminGroupMappingOptions) GetUserGroupType() int
GetUserGroupType returns the type for the matching user group
type AdminPreferences ¶
type AdminPreferences struct { // Allow to hide some sections from the user page. // These are not security settings and are not enforced server side // in any way. They are only intended to simplify the user page in // the WebAdmin UI. // // 1 means hide groups section // 2 means hide filesystem section, "users_base_dir" must be set in the config file otherwise this setting is ignored // 4 means hide virtual folders section // 8 means hide profile section // 16 means hide ACLs section // 32 means hide disk and bandwidth quota limits section // 64 means hide advanced settings section // // The settings can be combined HideUserPageSections int `json:"hide_user_page_sections,omitempty"` // Defines the default expiration for newly created users as number of days. // 0 means no expiration DefaultUsersExpiration int `json:"default_users_expiration,omitempty"` }
AdminPreferences defines the admin preferences
func (*AdminPreferences) HideACLs ¶
func (p *AdminPreferences) HideACLs() bool
HideACLs returns true if the ACLs section should be hidden
func (*AdminPreferences) HideAdvancedSettings ¶
func (p *AdminPreferences) HideAdvancedSettings() bool
HideAdvancedSettings returns true if the advanced settings section should be hidden
func (*AdminPreferences) HideDiskQuotaAndBandwidthLimits ¶
func (p *AdminPreferences) HideDiskQuotaAndBandwidthLimits() bool
HideDiskQuotaAndBandwidthLimits returns true if the disk quota and bandwidth limits section should be hidden
func (*AdminPreferences) HideFilesystem ¶
func (p *AdminPreferences) HideFilesystem() bool
HideFilesystem returns true if the filesystem section should be hidden
func (*AdminPreferences) HideGroups ¶
func (p *AdminPreferences) HideGroups() bool
HideGroups returns true if the groups section should be hidden
func (*AdminPreferences) HideProfile ¶
func (p *AdminPreferences) HideProfile() bool
HideProfile returns true if the profile section should be hidden
func (*AdminPreferences) HideVirtualFolders ¶
func (p *AdminPreferences) HideVirtualFolders() bool
HideVirtualFolders returns true if the virtual folder section should be hidden
func (*AdminPreferences) VisibleUserPageSections ¶
func (p *AdminPreferences) VisibleUserPageSections() int
VisibleUserPageSections returns the number of visible sections in the user page
type AdminTOTPConfig ¶
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 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"` EventActions []BaseEventAction `json:"event_actions"` EventRules []EventRule `json:"event_rules"` Roles []Role `json:"roles"` Version int `json:"version"` }
BackupData defines the structure for the backup/restore files
func DumpData ¶
func DumpData() (BackupData, error)
DumpData returns all users, groups, folders, admins, api keys, shares, actions, rules
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 BaseEventAction ¶
type BaseEventAction struct { // Data provider unique identifier ID int64 `json:"id"` // Action name Name string `json:"name"` // optional description Description string `json:"description,omitempty"` // ActionType, see the above enum Type int `json:"type"` // Configuration options specific for the action type Options BaseEventActionOptions `json:"options"` // list of rule names associated with this event action Rules []string `json:"rules,omitempty"` }
BaseEventAction defines the common fields for an event action
func EventActionExists ¶
func EventActionExists(name string) (BaseEventAction, error)
EventActionExists returns the event action with the given name if it exists
func GetEventActions ¶
func GetEventActions(limit, offset int, order string, minimal bool) ([]BaseEventAction, error)
GetEventActions returns an array of event actions respecting limit and offset
func (*BaseEventAction) GetRulesAsString ¶
func (a *BaseEventAction) GetRulesAsString() string
GetRulesAsString returns the list of rules as comma separated string
func (*BaseEventAction) GetTypeAsString ¶
func (a *BaseEventAction) GetTypeAsString() string
GetTypeAsString returns the action type as string
func (*BaseEventAction) PrepareForRendering ¶
func (a *BaseEventAction) PrepareForRendering()
PrepareForRendering prepares a BaseEventAction for rendering. It hides confidential data and set to nil the empty secrets so they are not serialized
func (*BaseEventAction) RenderAsJSON ¶
func (a *BaseEventAction) RenderAsJSON(reload bool) ([]byte, error)
RenderAsJSON implements the renderer interface used within plugins
type BaseEventActionOptions ¶
type BaseEventActionOptions struct { HTTPConfig EventActionHTTPConfig `json:"http_config"` CmdConfig EventActionCommandConfig `json:"cmd_config"` EmailConfig EventActionEmailConfig `json:"email_config"` RetentionConfig EventActionDataRetentionConfig `json:"retention_config"` FsConfig EventActionFilesystemConfig `json:"fs_config"` }
BaseEventActionOptions defines the supported configuration options for a base event actions
func (*BaseEventActionOptions) SetEmptySecretsIfNil ¶
func (o *BaseEventActionOptions) SetEmptySecretsIfNil()
SetEmptySecretsIfNil sets the secrets to empty if nil
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 ConditionOptions ¶
type ConditionOptions struct { // Usernames or folder names Names []ConditionPattern `json:"names,omitempty"` // Group names GroupNames []ConditionPattern `json:"group_names,omitempty"` // Virtual paths FsPaths []ConditionPattern `json:"fs_paths,omitempty"` Protocols []string `json:"protocols,omitempty"` ProviderObjects []string `json:"provider_objects,omitempty"` MinFileSize int64 `json:"min_size,omitempty"` MaxFileSize int64 `json:"max_size,omitempty"` // allow to execute scheduled tasks concurrently from multiple instances ConcurrentExecution bool `json:"concurrent_execution,omitempty"` }
ConditionOptions defines options for event conditions
type ConditionPattern ¶
type ConditionPattern struct { Pattern string `json:"pattern,omitempty"` InverseMatch bool `json:"inverse_match,omitempty"` }
ConditionPattern defines a pattern for condition filters
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. For postgresql and cockroachdb driver you can specify multiple hosts separated by commas 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"` // Used for drivers mysql, postgresql and cockroachdb. Set to true to disable SNI DisableSNI bool `json:"disable_sni" mapstructure:"disable_sni"` // TargetSessionAttrs is a postgresql and cockroachdb specific option. // It determines whether the session must have certain properties to be acceptable. // It's typically used in combination with multiple host names to select the first // acceptable alternative among several hosts TargetSessionAttrs string `json:"target_session_attrs" mapstructure:"target_session_attrs"` // 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"` // 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"` // Node defines the configuration for this cluster node. // Ignored if the provider is not shared/shareable Node NodeConfig `json:"node" mapstructure:"node"` // 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"` }
Config defines the provider configuration
func GetProviderConfig ¶
func GetProviderConfig() Config
GetProviderConfig returns the current provider configuration
func (*Config) GetShared ¶
GetShared returns the provider share mode. This method is called before the provider is initialized
func (*Config) IsDefenderSupported ¶
IsDefenderSupported returns true if the configured provider supports the defender
type DefenderEntry ¶
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 ¶
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 ¶
func GetDefenderHostByIP(ip string, from int64) (DefenderEntry, error)
GetDefenderHostByIP returns a defender host by ip, if any
func GetDefenderHosts ¶
func GetDefenderHosts(from int64, limit int) ([]DefenderEntry, error)
GetDefenderHosts returns hosts that are banned or for which some violations have been detected
func IsDefenderHostBanned ¶
func IsDefenderHostBanned(ip string) (DefenderEntry, error)
IsDefenderHostBanned returns a defender entry and no error if the specified host is banned
func (*DefenderEntry) GetBanTime ¶
func (d *DefenderEntry) GetBanTime() string
GetBanTime returns the ban time for a defender entry as string
func (*DefenderEntry) GetID ¶
func (d *DefenderEntry) GetID() string
GetID returns an unique ID for a defender entry
func (*DefenderEntry) MarshalJSON ¶
func (d *DefenderEntry) MarshalJSON() ([]byte, error)
MarshalJSON returns the JSON encoding of a DefenderEntry.
type EnumMapping ¶
EnumMapping defines a mapping between enum values and names
type EventAction ¶
type EventAction struct { BaseEventAction // Order defines the execution order Order int `json:"order,omitempty"` Options EventActionOptions `json:"relation_options"` }
EventAction defines an event action
type EventActionCommandConfig ¶
type EventActionCommandConfig struct { Cmd string `json:"cmd,omitempty"` Args []string `json:"args,omitempty"` Timeout int `json:"timeout,omitempty"` EnvVars []KeyValue `json:"env_vars,omitempty"` }
EventActionCommandConfig defines the configuration for a command event target
func (EventActionCommandConfig) GetArgumentsAsString ¶
func (c EventActionCommandConfig) GetArgumentsAsString() string
GetArgumentsAsString returns the list of command arguments as comma separated string
type EventActionDataRetentionConfig ¶
type EventActionDataRetentionConfig struct {
Folders []FolderRetention `json:"folders,omitempty"`
}
EventActionDataRetentionConfig defines the configuration for a data retention check
type EventActionEmailConfig ¶
type EventActionEmailConfig struct { Recipients []string `json:"recipients,omitempty"` Subject string `json:"subject,omitempty"` Body string `json:"body,omitempty"` Attachments []string `json:"attachments,omitempty"` }
EventActionEmailConfig defines the configuration options for SMTP event actions
func (EventActionEmailConfig) GetAttachmentsAsString ¶
func (c EventActionEmailConfig) GetAttachmentsAsString() string
GetAttachmentsAsString returns the list of attachments as comma separated string
func (EventActionEmailConfig) GetRecipientsAsString ¶
func (c EventActionEmailConfig) GetRecipientsAsString() string
GetRecipientsAsString returns the list of recipients as comma separated string
type EventActionFilesystemConfig ¶
type EventActionFilesystemConfig struct { // Filesystem actions, see the above enum Type int `json:"type,omitempty"` // files/dirs to rename, key is the source and target the value Renames []KeyValue `json:"renames,omitempty"` // directories to create MkDirs []string `json:"mkdirs,omitempty"` // files/dirs to delete Deletes []string `json:"deletes,omitempty"` // file/dirs to check for existence Exist []string `json:"exist,omitempty"` // paths to compress and archive name Compress EventActionFsCompress `json:"compress"` }
EventActionFilesystemConfig defines the configuration for filesystem actions
func (EventActionFilesystemConfig) GetCompressPathsAsString ¶
func (c EventActionFilesystemConfig) GetCompressPathsAsString() string
GetCompressPathsAsString returns the list of items to compress as comma separated string. Using a pointer receiver will not work in web templates
func (EventActionFilesystemConfig) GetDeletesAsString ¶
func (c EventActionFilesystemConfig) GetDeletesAsString() string
GetDeletesAsString returns the list of items to delete as comma separated string. Using a pointer receiver will not work in web templates
func (EventActionFilesystemConfig) GetExistAsString ¶
func (c EventActionFilesystemConfig) GetExistAsString() string
GetExistAsString returns the list of items to check for existence as comma separated string. Using a pointer receiver will not work in web templates
func (EventActionFilesystemConfig) GetMkDirsAsString ¶
func (c EventActionFilesystemConfig) GetMkDirsAsString() string
GetMkDirsAsString returns the list of directories to create as comma separated string. Using a pointer receiver will not work in web templates
type EventActionFsCompress ¶
type EventActionFsCompress struct { // Archive path Name string `json:"name,omitempty"` // Paths to compress Paths []string `json:"paths,omitempty"` }
EventActionFsCompress defines the configuration for the compress filesystem action
type EventActionHTTPConfig ¶
type EventActionHTTPConfig struct { Endpoint string `json:"endpoint,omitempty"` Username string `json:"username,omitempty"` Password *kms.Secret `json:"password,omitempty"` Headers []KeyValue `json:"headers,omitempty"` Timeout int `json:"timeout,omitempty"` SkipTLSVerify bool `json:"skip_tls_verify,omitempty"` Method string `json:"method,omitempty"` QueryParameters []KeyValue `json:"query_parameters,omitempty"` Body string `json:"body,omitempty"` Parts []HTTPPart `json:"parts,omitempty"` }
EventActionHTTPConfig defines the configuration for an HTTP event target
func (*EventActionHTTPConfig) GetContext ¶
func (c *EventActionHTTPConfig) GetContext() (context.Context, context.CancelFunc)
GetContext returns the context and the cancel func to use for the HTTP request
func (*EventActionHTTPConfig) GetHTTPClient ¶
func (c *EventActionHTTPConfig) GetHTTPClient() *http.Client
GetHTTPClient returns an HTTP client based on the config
func (*EventActionHTTPConfig) HasMultipartFiles ¶
func (c *EventActionHTTPConfig) HasMultipartFiles() bool
HasMultipartFiles returns true if at least a file must be uploaded via a multipart request
func (*EventActionHTTPConfig) HasObjectData ¶
func (c *EventActionHTTPConfig) HasObjectData() bool
HasObjectData returns true if the {{ObjectData}} placeholder is defined
func (*EventActionHTTPConfig) TryDecryptPassword ¶
func (c *EventActionHTTPConfig) TryDecryptPassword() error
TryDecryptPassword decrypts the password if encryptet
type EventActionOptions ¶
type EventActionOptions struct { IsFailureAction bool `json:"is_failure_action"` StopOnFailure bool `json:"stop_on_failure"` ExecuteSync bool `json:"execute_sync"` }
EventActionOptions defines the supported configuration options for an event action
type EventConditions ¶
type EventConditions struct { // Only one between FsEvents, ProviderEvents and Schedule is allowed FsEvents []string `json:"fs_events,omitempty"` ProviderEvents []string `json:"provider_events,omitempty"` Schedules []Schedule `json:"schedules,omitempty"` Options ConditionOptions `json:"options"` }
EventConditions defines the conditions for an event rule
type EventRule ¶
type EventRule struct { // Data provider unique identifier ID int64 `json:"id"` // Rule name Name string `json:"name"` // optional description Description string `json:"description,omitempty"` // Creation time as unix timestamp in milliseconds CreatedAt int64 `json:"created_at"` // last update time as unix timestamp in milliseconds UpdatedAt int64 `json:"updated_at"` // Event trigger Trigger int `json:"trigger"` // Event conditions Conditions EventConditions `json:"conditions"` // actions to execute Actions []EventAction `json:"actions"` // in multi node setups we mark the rule as deleted to be able to update the cache DeletedAt int64 `json:"-"` }
EventRule defines the trigger, conditions and actions for an event
func EventRuleExists ¶
EventRuleExists returns the event rule with the given name if it exists
func GetEventRules ¶
GetEventRules returns an array of event rules respecting limit and offset
func GetRecentlyUpdatedRules ¶
GetRecentlyUpdatedRules returns the event rules updated after the specified time
func (*EventRule) CheckActionsConsistency ¶
CheckActionsConsistency returns an error if the actions cannot be executed
func (*EventRule) GetActionsAsString ¶
GetActionsAsString returns the list of action names as comma separated string
func (*EventRule) GetTriggerAsString ¶
GetTriggerAsString returns the rule trigger as string
func (*EventRule) GuardFromConcurrentExecution ¶
GuardFromConcurrentExecution returns true if the rule cannot be executed concurrently from multiple instances
func (*EventRule) PrepareForRendering ¶
func (r *EventRule) PrepareForRendering()
PrepareForRendering prepares an EventRule for rendering. It hides confidential data and set to nil the empty secrets so they are not serialized
type FnHandleRuleForProviderEvent ¶
type FnHandleRuleForProviderEvent func(operation, executor, ip, objectType, objectName string, object plugin.Renderer)
FnHandleRuleForProviderEvent define the callback to handle event rules for provider events
type FnReloadRules ¶
type FnReloadRules func()
FnReloadRules defined the callback to reload event rules
type FnRemoveRule ¶
type FnRemoveRule func(name string)
FnRemoveRule defines the callback to remove an event rule
type FolderRetention ¶
type FolderRetention struct { // Path is the exposed virtual directory path, if no other specific retention is defined, // the retention applies for sub directories too. For example if retention is defined // for the paths "/" and "/sub" then the retention for "/" is applied for any file outside // the "/sub" directory Path string `json:"path"` // Retention time in hours. 0 means exclude this path Retention int `json:"retention"` // DeleteEmptyDirs defines if empty directories will be deleted. // The user need the delete permission DeleteEmptyDirs bool `json:"delete_empty_dirs,omitempty"` // IgnoreUserPermissions defines whether to delete files even if the user does not have the delete permission. // The default is "false" which means that files will be skipped if the user does not have the permission // to delete them. This applies to sub directories too. IgnoreUserPermissions bool `json:"ignore_user_permissions,omitempty"` }
FolderRetention defines a folder retention configuration
func (*FolderRetention) Validate ¶
func (f *FolderRetention) Validate() error
Validate returns an error if the configuration is not valid
type Group ¶
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 ¶
GroupExists returns the Group with the given name if it exists
func (*Group) GetAllowedIPAsString ¶
GetAllowedIPAsString returns the allowed IP as comma separated string
func (*Group) GetDeniedIPAsString ¶
GetDeniedIPAsString returns the denied IP as comma separated string
func (*Group) GetEncryptionAdditionalData ¶
GetEncryptionAdditionalData returns the additional data to use for AEAD
func (*Group) GetMembersAsString ¶
GetMembersAsString returns a string representation for the group members
func (*Group) GetPermissions ¶
func (g *Group) GetPermissions() []sdk.DirectoryPermissions
GetPermissions returns the permissions as list
func (*Group) HasExternalAuth ¶
HasExternalAuth returns true if the external authentication is globally enabled and it is not disabled for this group
func (*Group) PrepareForRendering ¶
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 ¶
RenderAsJSON implements the renderer interface used within plugins
func (*Group) SetEmptySecretsIfNil ¶
func (g *Group) SetEmptySecretsIfNil()
SetEmptySecretsIfNil sets the secrets to empty if nil
type GroupUserSettings ¶
type GroupUserSettings struct { sdk.BaseGroupUserSettings // Filesystem configuration details FsConfig vfs.Filesystem `json:"filesystem"` }
GroupUserSettings defines the settings to apply to users
type HTTPPart ¶
type HTTPPart struct { Name string `json:"name,omitempty"` Filepath string `json:"filepath,omitempty"` Headers []KeyValue `json:"headers,omitempty"` Body string `json:"body,omitempty"` Order int `json:"-"` }
HTTPPart defines a part for HTTP multipart requests
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 Node ¶
type Node struct { Name string `json:"name"` Data NodeData `json:"data"` CreatedAt int64 `json:"created_at"` UpdatedAt int64 `json:"updated_at"` }
Node defines a cluster node
func GetNodeByName ¶
GetNodeByName returns a node, different from the current one, by name
func (*Node) SendDeleteRequest ¶
SendDeleteRequest sends an HTTP DELETE request to this node
type NodeConfig ¶
type NodeConfig struct { Host string `json:"host" mapstructure:"host"` Port int `json:"port" mapstructure:"port"` Proto string `json:"proto" mapstructure:"proto"` }
NodeConfig defines the node configuration
type NodeData ¶
type NodeData struct { Host string `json:"host"` Port int `json:"port"` Proto string `json:"proto"` Key *kms.Secret `json:"api_key"` }
NodeData defines the details to connect to a cluster node
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 ¶
RecoveryCode defines a 2FA recovery code
type Role ¶
type Role struct { // Data provider unique identifier ID int64 `json:"id"` // Role name Name string `json:"name"` // optional description Description string `json:"description,omitempty"` // Creation time as unix timestamp in milliseconds CreatedAt int64 `json:"created_at"` // last update time as unix timestamp in milliseconds UpdatedAt int64 `json:"updated_at"` // list of admins associated with this role Admins []string `json:"admins,omitempty"` // list of usernames associated with this role Users []string `json:"users,omitempty"` }
Role defines an SFTPGo role.
func RoleExists ¶
RoleExists returns the Role with the given name if it exists
func (*Role) GetMembersAsString ¶
GetMembersAsString returns a string representation for the role members
type SQLiteProvider ¶
type SQLiteProvider struct {
// contains filtered or unexported fields
}
SQLiteProvider defines the auth provider for SQLite database
type Schedule ¶
type Schedule struct { Hours string `json:"hour"` DayOfWeek string `json:"day_of_week"` DayOfMonth string `json:"day_of_month"` Month string `json:"month"` }
Schedule defines an event schedule
func (*Schedule) GetCronSpec ¶
GetCronSpec returns the cron compatible schedule string
type Session ¶
type Session struct { Key string Data any Type SessionType Timestamp int64 }
Session defines a shared session persisted in the data provider
func GetSharedSession ¶
GetSharedSession retrieves the session with the specified key
type SessionType ¶
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 ¶
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 ¶
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 Task ¶
type Task struct { Name string `json:"name"` UpdateAt int64 `json:"updated_at"` Version int64 `json:"version"` }
Task stores the state for a scheduled task
func GetTaskByName ¶
GetTaskByName returns the task with the specified name
type TransferQuota ¶
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 ¶
func (q *TransferQuota) HasDownloadSpace() bool
HasDownloadSpace returns true if there is transfer download space available
func (*TransferQuota) HasSizeLimits ¶
func (q *TransferQuota) HasSizeLimits() bool
HasSizeLimits returns true if any size limit is set
func (*TransferQuota) HasUploadSpace ¶
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"` // in multi node setups we mark the user as deleted to be able to update the webdav cache DeletedAt int64 `json:"-"` // 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 GetFTPPreAuthUser ¶
GetFTPPreAuthUser returns the SFTPGo user with the specified username after receiving the FTP "USER" command. If a pre-login hook is defined it will be executed so the SFTPGo user can be created if it does not exist
func GetUserAfterIDPAuth ¶
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 ¶
GetUserWithGroupSettings tries to return the user with the specified username loading also the group settings
func GetUsersForQuotaCheck ¶
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 ¶
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 ¶
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 ¶
GetBandwidthForIP returns the upload and download bandwidth for the specified IP
func (*User) GetCleanedPath ¶
GetCleanedPath returns a clean POSIX absolute path using the user start directory as base if the provided rawVirtualPath is relative
func (*User) GetDataTransferLimits ¶
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) GetGroupsAsString ¶
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 ¶
GetLastLoginAsString returns the last login as string
func (*User) GetLastQuotaUpdateAsString ¶
GetLastQuotaUpdateAsString returns the last quota update as string
func (*User) GetMFAStatusAsString ¶
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 will change after an update
func (*User) GetStatusAsString ¶
GetStatusAsString returns the user status as a string
func (*User) GetStorageDescrition ¶
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) HasExternalAuth ¶
HasExternalAuth returns true if the external authentication is globally enabled and it is not disabled for this user
func (*User) HasMembershipGroup ¶
HasMembershipGroup returns true if the user has the specified membership group
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 ¶
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 ¶
HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
func (*User) HasSecondaryGroup ¶
HasSecondaryGroup returns true if the user has the specified secondary group
func (*User) HasTransferQuotaRestrictions ¶
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 allowed
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 ¶
LoadAndApplyGroupSettings update the user by loading and applying the group settings
func (*User) MustSetSecondFactor ¶
MustSetSecondFactor returns true if the user must set a second factor authentication
func (*User) MustSetSecondFactorForProtocol ¶
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 ¶
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 ¶
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