dataprovider

package
v2.0.0-...-83f77b2 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2022 License: AGPL-3.0 Imports: 68 Imported by: 0

Documentation

Overview

Package dataprovider provides data access. It abstracts different data providers and exposes a common API.

Index

Constants

View Source
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__"
)
View Source
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

View Source
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
)
View Source
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
)
View Source
const (
	HashingAlgoBcrypt   = "bcrypt"
	HashingAlgoArgon2ID = "argon2id"
)

Supported algorithms for hashing passwords. These algorithms can be used when SFTPGo hashes a plain text password

View Source
const (
	OrderASC  = "ASC"
	OrderDESC = "DESC"
)

ordering constants

View Source
const (
	ActionTypeHTTP = iota + 1
	ActionTypeCommand
	ActionTypeEmail
	ActionTypeBackup
	ActionTypeUserQuotaReset
	ActionTypeFolderQuotaReset
	ActionTypeTransferQuotaReset
	ActionTypeDataRetentionCheck
	ActionTypeFilesystem
	ActionTypeMetadataCheck
)

Supported event actions

View Source
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

View Source
const (
	FilesystemActionRename = iota + 1
	FilesystemActionDelete
	FilesystemActionMkdirs
	FilesystemActionExist
	FilesystemActionCompress
)

Supported filesystem actions

View Source
const (
	NodeProtoHTTP  = "http"
	NodeProtoHTTPS = "https"
)

Supported protocols for connecting to other nodes

View Source
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

View Source
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

View Source
const (
	// NodeTokenHeader defines the header to use for the node auth token
	NodeTokenHeader = "X-SFTPGO-Node"
)
View Source
const (
	// RetentionReportPlaceHolder defines the placeholder for data retention reports
	RetentionReportPlaceHolder = "{{RetentionReports}}"
)

Variables

View Source
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")
)
View Source
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

View Source
var (
	EventActionTypes  []EnumMapping
	EventTriggerTypes []EnumMapping
	FsActionTypes     []EnumMapping
)

enum mappings

Functions

func AddAPIKey

func AddAPIKey(apiKey *APIKey, executor, ipAddress string) error

AddAPIKey adds a new API key

func AddActiveTransfer

func AddActiveTransfer(transfer ActiveTransfer)

AddActiveTransfer stores the specified transfer

func AddAdmin

func AddAdmin(admin *Admin, executor, ipAddress string) error

AddAdmin adds a new SFTPGo admin

func AddEventAction

func AddEventAction(action *BaseEventAction, executor, ipAddress string) error

AddEventAction adds a new event action

func AddEventRule

func AddEventRule(rule *EventRule, executor, ipAddress string) error

AddEventRule adds a new event rule

func AddFolder

func AddFolder(folder *vfs.BaseVirtualFolder, executor, ipAddress string) error

AddFolder adds a new virtual folder.

func AddGroup

func AddGroup(group *Group, executor, ipAddress string) error

AddGroup adds a new group

func AddRole

func AddRole(role *Role, executor, ipAddress string) error

AddRole adds a new role

func AddShare

func AddShare(share *Share, executor, ipAddress string) error

AddShare adds a new share

func AddSharedSession

func AddSharedSession(session Session) error

AddSharedSession stores a new session within the data provider

func AddTask

func AddTask(name string) error

AddTask add a task with the specified name

func AddUser

func AddUser(user *User, executor, ipAddress string) error

AddUser adds a new SFTPGo user.

func AuthenticateNodeToken

func AuthenticateNodeToken(token string) (string, string, error)

AuthenticateNodeToken check the validity of the provided token

func CacheWebDAVUser

func CacheWebDAVUser(cachedUser *CachedUser)

CacheWebDAVUser add a user to the WebDAV cache

func CheckCachedPassword

func CheckCachedPassword(username, password string) (bool, bool)

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

func CleanupActiveTransfers(before time.Time) error

CleanupActiveTransfers removes the transfer before the specified time

func CleanupDefender

func CleanupDefender(from int64) error

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

func ConvertName(name string) string

ConvertName converts the given name based on the configured rules

func DeleteAPIKey

func DeleteAPIKey(keyID string, executor, ipAddress string) error

DeleteAPIKey deletes an existing API key

func DeleteAdmin

func DeleteAdmin(username, executor, ipAddress string) error

DeleteAdmin deletes an existing SFTPGo admin

func DeleteDefenderHost

func DeleteDefenderHost(ip string) error

DeleteDefenderHost removes the specified IP from the defender lists

func DeleteEventAction

func DeleteEventAction(name string, executor, ipAddress string) error

DeleteEventAction deletes an existing event action

func DeleteEventRule

func DeleteEventRule(name string, executor, ipAddress string) error

DeleteEventRule deletes an existing event rule

func DeleteFolder

func DeleteFolder(folderName, executor, ipAddress string) error

DeleteFolder deletes an existing folder.

func DeleteGroup

func DeleteGroup(name string, executor, ipAddress string) error

DeleteGroup deletes an existing Group

func DeleteRole

func DeleteRole(name string, executor, ipAddress string) error

DeleteRole deletes an existing Role

func DeleteShare

func DeleteShare(shareID string, executor, ipAddress string) error

DeleteShare deletes an existing share

func DeleteSharedSession

func DeleteSharedSession(key string) error

DeleteSharedSession deletes the session with the specified key

func DeleteUser

func DeleteUser(username, executor, ipAddress, role string) error

DeleteUser deletes an existing SFTPGo user.

func DumpFolders

func DumpFolders() ([]vfs.BaseVirtualFolder, error)

DumpFolders returns all folders, including confidential data

func ExecuteBackup

func ExecuteBackup() (string, error)

ExecuteBackup executes a backup

func ExecutePostLoginHook

func ExecutePostLoginHook(user *User, loginMethod, ip, protocol string, err error)

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

func GetFolders(limit, offset int, order string, minimal bool) ([]vfs.BaseVirtualFolder, error)

GetFolders returns an array of folders respecting limit and offset

func GetNodeName

func GetNodeName() string

GetNodeName returns the node name or an empty string

func GetQuotaTracking

func GetQuotaTracking() int

GetQuotaTracking returns the configured mode for user's quota tracking

func GetUsedQuota

func GetUsedQuota(username string) (int, int64, int64, int64, error)

GetUsedQuota returns the used quota for the given SFTPGo user.

func GetUsedVirtualFolderQuota

func GetUsedVirtualFolderQuota(name string) (int, int64, error)

GetUsedVirtualFolderQuota returns the used quota for the given virtual folder.

func GetUserVariants

func GetUserVariants(username, role string) (User, User, error)

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

func Initialize(cnf Config, basePath string, checkAdmins bool) error

Initialize the data provider. An error is returned if the configured driver is invalid or if the data provider cannot be initialized

func InitializeDatabase

func InitializeDatabase(cnf Config, basePath string) error

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

func RemoveActiveTransfer(transferID int64, connectionID string)

RemoveActiveTransfer removes the specified transfer

func RemoveCachedWebDAVUser

func RemoveCachedWebDAVUser(username string)

RemoveCachedWebDAVUser removes a cached WebDAV user

func RemoveEventRule

func RemoveEventRule(rule EventRule) error

RemoveEventRule delets an existing event rule without marking it as deleted

func ResetDatabase

func ResetDatabase(cnf Config, basePath string) error

ResetDatabase restores schema and/or data to a previous version

func RevertDatabase

func RevertDatabase(cnf Config, basePath string, targetVersion int) error

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

func SetDefenderBanTime(ip string, banTime int64) error

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 SetTempPath

func SetTempPath(fsPath string)

SetTempPath sets the path for temporary files

func UpdateAPIKey

func UpdateAPIKey(apiKey *APIKey, executor, ipAddress string) error

UpdateAPIKey updates an existing API key

func UpdateAPIKeyLastUse

func UpdateAPIKeyLastUse(apiKey *APIKey) error

UpdateAPIKeyLastUse updates the LastUseAt field for the given API key

func UpdateActiveTransferSizes

func UpdateActiveTransferSizes(ulSize, dlSize, transferID int64, connectionID string)

UpdateActiveTransferSizes updates the current upload and download sizes for the specified transfer

func UpdateAdmin

func UpdateAdmin(admin *Admin, executor, ipAddress string) error

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

func UpdateDefenderBanTime(ip string, minutes int) error

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

func UpdateEventRule(rule *EventRule, executor, ipAddress string) error

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

func UpdateGroup(group *Group, users []string, executor, ipAddress string) error

UpdateGroup updates an existing Group

func UpdateLastLogin

func UpdateLastLogin(user *User)

UpdateLastLogin updates the last login field for the given SFTPGo user

func UpdateRole

func UpdateRole(role *Role, executor, ipAddress string) error

UpdateRole updates an existing Role

func UpdateShare

func UpdateShare(share *Share, executor, ipAddress string) error

UpdateShare updates an existing share

func UpdateShareLastUse

func UpdateShareLastUse(share *Share, numTokens int) error

UpdateShareLastUse updates the LastUseAt and UsedTokens for the given share

func UpdateTask

func UpdateTask(name string, version int64) error

UpdateTask updates the task with the specified name and version

func UpdateTaskTimestamp

func UpdateTaskTimestamp(name string) error

UpdateTaskTimestamp updates the timestamp for the task with the specified name

func UpdateUser

func UpdateUser(user *User, executor, ipAddress string) error

UpdateUser updates an existing SFTPGo user.

func UpdateUserPassword

func UpdateUserPassword(username, plainPwd, executor, ipAddress string) error

UpdateUserPassword updates the user password

func UpdateUserQuota

func UpdateUserQuota(user *User, filesAdd int, sizeAdd int64, reset bool) error

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

func UpdateUserTransferQuota(user *User, uploadSize, downloadSize int64, reset bool) error

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

func UpdateUserTransferTimestamps(username string, isUpload bool) error

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

func ValidateUser(user *User) error

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

func APIKeyExists(keyID string) (APIKey, error)

APIKeyExists returns the API key with the given ID if it exists

func GetAPIKeys

func GetAPIKeys(limit, offset int, order string) ([]APIKey, error)

GetAPIKeys returns an array of API keys respecting limit and offset

func (*APIKey) Authenticate

func (k *APIKey) Authenticate(plainKey string) error

Authenticate tries to authenticate the provided plain key

func (*APIKey) DisplayKey

func (k *APIKey) DisplayKey() string

DisplayKey returns the key to show to the user

func (*APIKey) HideConfidentialData

func (k *APIKey) HideConfidentialData()

HideConfidentialData hides API key confidential data

func (*APIKey) RenderAsJSON

func (k *APIKey) RenderAsJSON(reload bool) ([]byte, error)

RenderAsJSON implements the renderer interface used within plugins

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

func AdminExists(username string) (Admin, error)

AdminExists returns the admin with the given username if it exists

func CheckAdminAndPass

func CheckAdminAndPass(username, password, ip string) (Admin, error)

CheckAdminAndPass validates the given admin and password connecting from ip

func GetAdmins

func GetAdmins(limit, offset int, order string) ([]Admin, error)

GetAdmins returns an array of admins respecting limit and offset

func (*Admin) CanLogin

func (a *Admin) CanLogin(ip string) error

CanLogin returns an error if the login is not allowed

func (*Admin) CanLoginFromIP

func (a *Admin) CanLoginFromIP(ip string) bool

CanLoginFromIP returns true if login from the given IP is allowed

func (*Admin) CanManageMFA

func (a *Admin) CanManageMFA() bool

CanManageMFA returns true if the admin can add a multi-factor authentication configuration

func (*Admin) CheckPassword

func (a *Admin) CheckPassword(password string) (bool, error)

CheckPassword verifies the admin password

func (*Admin) CountUnusedRecoveryCodes

func (a *Admin) CountUnusedRecoveryCodes() int

CountUnusedRecoveryCodes returns the number of unused recovery codes

func (*Admin) GetAllowedIPAsString

func (a *Admin) GetAllowedIPAsString() string

GetAllowedIPAsString returns the allowed IP as comma separated string

func (*Admin) GetGroupsAsString

func (a *Admin) GetGroupsAsString() string

GetGroupsAsString returns the user's groups as a string

func (*Admin) GetLastLoginAsString

func (a *Admin) GetLastLoginAsString() string

GetLastLoginAsString returns the last login as string

func (*Admin) GetPermissionsAsString

func (a *Admin) GetPermissionsAsString() string

GetPermissionsAsString returns permission as string

func (*Admin) GetSignature

func (a *Admin) GetSignature() string

GetSignature returns a signature for this admin. It will change after an update

func (*Admin) GetValidPerms

func (a *Admin) GetValidPerms() []string

GetValidPerms returns the allowed admin permissions

func (*Admin) HasPermission

func (a *Admin) HasPermission(perm string) bool

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

func (a *Admin) RenderAsJSON(reload bool) ([]byte, error)

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"`
	Shares       []Share                 `json:"shares"`
	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"`
	// If the data provider is shared across multiple SFTPGo instances, set this parameter to 1.
	// 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

func (c *Config) GetShared() int

GetShared returns the provider share mode. This method is called before the provider is initialized

func (*Config) IsDefenderSupported

func (c *Config) IsDefenderSupported() bool

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

type EnumMapping struct {
	Name  string
	Value int
}

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

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

func EventRuleExists(name string) (EventRule, error)

EventRuleExists returns the event rule with the given name if it exists

func GetEventRules

func GetEventRules(limit, offset int, order string) ([]EventRule, error)

GetEventRules returns an array of event rules respecting limit and offset

func GetRecentlyUpdatedRules

func GetRecentlyUpdatedRules(after int64) ([]EventRule, error)

GetRecentlyUpdatedRules returns the event rules updated after the specified time

func (*EventRule) CheckActionsConsistency

func (r *EventRule) CheckActionsConsistency(providerObjectType string) error

CheckActionsConsistency returns an error if the actions cannot be executed

func (*EventRule) GetActionsAsString

func (r *EventRule) GetActionsAsString() string

GetActionsAsString returns the list of action names as comma separated string

func (*EventRule) GetTriggerAsString

func (r *EventRule) GetTriggerAsString() string

GetTriggerAsString returns the rule trigger as string

func (*EventRule) GuardFromConcurrentExecution

func (r *EventRule) GuardFromConcurrentExecution() bool

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

func (*EventRule) RenderAsJSON

func (r *EventRule) RenderAsJSON(reload bool) ([]byte, error)

RenderAsJSON implements the renderer interface used within plugins

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 GetGroups

func GetGroups(limit, offset int, order string, minimal bool) ([]Group, error)

GetGroups returns an array of groups respecting limit and offset

func GroupExists

func GroupExists(name string) (Group, error)

GroupExists returns the Group with the given name if it exists

func (*Group) GetAllowedIPAsString

func (g *Group) GetAllowedIPAsString() string

GetAllowedIPAsString returns the allowed IP as comma separated string

func (*Group) GetDeniedIPAsString

func (g *Group) GetDeniedIPAsString() string

GetDeniedIPAsString returns the denied IP as comma separated string

func (*Group) GetEncryptionAdditionalData

func (g *Group) GetEncryptionAdditionalData() string

GetEncryptionAdditionalData returns the additional data to use for AEAD

func (*Group) GetMembersAsString

func (g *Group) GetMembersAsString() string

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

func (g *Group) HasExternalAuth() bool

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

func (g *Group) RenderAsJSON(reload bool) ([]byte, error)

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 KeyValue

type KeyValue struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

KeyValue defines a key/value pair

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

func GetNodeByName(name string) (Node, error)

GetNodeByName returns a node, different from the current one, by name

func GetNodes

func GetNodes() ([]Node, error)

GetNodes returns the other cluster nodes

func (*Node) SendDeleteRequest

func (n *Node) SendDeleteRequest(username, role, relativeURL string) error

SendDeleteRequest sends an HTTP DELETE request to this node

func (*Node) SendGetRequest

func (n *Node) SendGetRequest(username, role, relativeURL string, responseHolder any) error

SendGetRequest sends an HTTP GET request to this node. The responseHolder must be a pointer

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

type RecoveryCode struct {
	Secret *kms.Secret `json:"secret"`
	Used   bool        `json:"used,omitempty"`
}

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 GetRoles

func GetRoles(limit, offset int, order string, minimal bool) ([]Role, error)

GetRoles returns an array of roles respecting limit and offset

func RoleExists

func RoleExists(name string) (Role, error)

RoleExists returns the Role with the given name if it exists

func (*Role) GetMembersAsString

func (r *Role) GetMembersAsString() string

GetMembersAsString returns a string representation for the role members

func (*Role) RenderAsJSON

func (r *Role) RenderAsJSON(reload bool) ([]byte, error)

RenderAsJSON implements the renderer interface used within plugins

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

func (s *Schedule) GetCronSpec() string

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

func GetSharedSession(key string) (Session, error)

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 {
	// Database unique identifier
	ID int64 `json:"-"`
	// Unique ID used to access this object
	ShareID     string     `json:"id"`
	Name        string     `json:"name"`
	Description string     `json:"description,omitempty"`
	Scope       ShareScope `json:"scope"`
	// Paths to files or directories, for ShareScopeWrite it must be exactly one directory
	Paths []string `json:"paths"`
	// Username who shared this object
	Username  string `json:"username"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
	// 0 means never used
	LastUseAt int64 `json:"last_use_at,omitempty"`
	// ExpiresAt expiration date/time as unix timestamp in milliseconds, 0 means no expiration
	ExpiresAt int64 `json:"expires_at,omitempty"`
	// Optional password to protect the share
	Password string `json:"password"`
	// Limit the available access tokens, 0 means no limit
	MaxTokens int `json:"max_tokens,omitempty"`
	// Used tokens
	UsedTokens int `json:"used_tokens,omitempty"`
	// Limit the share availability to these IPs/CIDR networks
	AllowFrom []string `json:"allow_from,omitempty"`
	// set for restores, we don't have to validate the expiration date
	// otherwise we fail to restore existing shares and we have to insert
	// all the previous values with no modifications
	IsRestore bool `json:"-"`
}

Share defines files and or directories shared with external users

func GetShares

func GetShares(limit, offset int, order, username string) ([]Share, error)

GetShares returns an array of shares respecting limit and offset

func ShareExists

func ShareExists(shareID, username string) (Share, error)

ShareExists returns the share with the given ID if it exists

func (*Share) CheckCredentials

func (s *Share) CheckCredentials(username, password string) (bool, error)

CheckCredentials verifies the share credentials if a password if set

func (*Share) GetAllowedFromAsString

func (s *Share) GetAllowedFromAsString() string

GetAllowedFromAsString returns the allowed IP as comma separated string

func (*Share) GetInfoString

func (s *Share) GetInfoString() string

GetInfoString returns share's info as string.

func (*Share) GetRelativePath

func (s *Share) GetRelativePath(name string) string

GetRelativePath returns the specified absolute path as relative to the share base path

func (*Share) GetScopeAsString

func (s *Share) GetScopeAsString() string

GetScopeAsString returns the share's scope as string. Used in web pages

func (*Share) HasRedactedPassword

func (s *Share) HasRedactedPassword() bool

HasRedactedPassword returns true if this share has a redacted password

func (*Share) HideConfidentialData

func (s *Share) HideConfidentialData()

HideConfidentialData hides share confidential data

func (*Share) IsExpired

func (s *Share) IsExpired() bool

IsExpired returns true if the share is expired

func (*Share) IsUsable

func (s *Share) IsUsable(ip string) (bool, error)

IsUsable checks if the share is usable from the specified IP

func (*Share) RenderAsJSON

func (s *Share) RenderAsJSON(reload bool) ([]byte, error)

RenderAsJSON implements the renderer interface used within plugins

type ShareScope

type ShareScope int

ShareScope defines the supported share scopes

const (
	ShareScopeRead ShareScope = iota + 1
	ShareScopeWrite
	ShareScopeReadWrite
)

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

func GetTaskByName(name string) (Task, error)

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

func CheckUserAndPass(username, password, ip, protocol string) (User, error)

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 DumpUsers

func DumpUsers() ([]User, error)

DumpUsers returns all users, including confidential data

func GetFTPPreAuthUser

func GetFTPPreAuthUser(username, ip string) (User, error)

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

func GetUserWithGroupSettings(username, role string) (User, error)

GetUserWithGroupSettings tries to return the user with the specified username loading also the group settings

func GetUsers

func GetUsers(limit, offset int, order, role string) ([]User, error)

GetUsers returns an array of users respecting limit and offset

func GetUsersForQuotaCheck

func GetUsersForQuotaCheck(toFetch map[string]bool) ([]User, error)

GetUsersForQuotaCheck returns the users with the fields required for a quota check

func UserExists

func UserExists(username, role string) (User, error)

UserExists checks if the given SFTPGo username exists, returns an error if no match is found

func (*User) CanAddDirsFromWeb

func (u *User) CanAddDirsFromWeb(target string) bool

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

func (u *User) CanAddFilesFromWeb(target string) bool

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

func (u *User) CanChangeAPIKeyAuth() bool

CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication

func (*User) CanChangeInfo

func (u *User) CanChangeInfo() bool

CanChangeInfo returns true if this user is allowed to change its info such as email and description

func (*User) CanChangePassword

func (u *User) CanChangePassword() bool

CanChangePassword returns true if this user is allowed to change its password

func (*User) CanDeleteFromWeb

func (u *User) CanDeleteFromWeb(target string) bool

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

func (u *User) CanManageMFA() bool

CanManageMFA returns true if the user can add a multi-factor authentication configuration

func (*User) CanManagePublicKeys

func (u *User) CanManagePublicKeys() bool

CanManagePublicKeys returns true if this user is allowed to manage public keys from the web client. Used in web client UI

func (*User) CanManageShares

func (u *User) CanManageShares() bool

CanManageShares returns true if the user can add, update and list shares

func (*User) CanRenameFromWeb

func (u *User) CanRenameFromWeb(src, dest string) bool

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

func (u *User) CanResetPassword() bool

CanResetPassword returns true if this user is allowed to reset its password

func (*User) CheckFsRoot

func (u *User) CheckFsRoot(connectionID string) error

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

func (u *User) CheckLoginConditions() error

CheckLoginConditions checks if the user is active and not expired

func (*User) CheckMetadataConsistency

func (u *User) CheckMetadataConsistency() error

CheckMetadataConsistency checks the consistency between the metadata stored in the configured metadata plugin and the filesystem

func (*User) CloseFs

func (u *User) CloseFs() error

CloseFs closes the underlying filesystems

func (*User) CountUnusedRecoveryCodes

func (u *User) CountUnusedRecoveryCodes() int

CountUnusedRecoveryCodes returns the number of unused recovery codes

func (*User) FilterListDir

func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo

FilterListDir adds virtual folders and remove hidden items from the given files list

func (*User) GetAllowedIPAsString

func (u *User) GetAllowedIPAsString() string

GetAllowedIPAsString returns the allowed IP as comma separated string

func (*User) GetAllowedLoginMethods

func (u *User) GetAllowedLoginMethods() []string

GetAllowedLoginMethods returns the allowed login methods

func (*User) GetBandwidthAsString

func (u *User) GetBandwidthAsString() string

GetBandwidthAsString returns bandwidth limits if defines

func (*User) GetBandwidthForIP

func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64)

GetBandwidthForIP returns the upload and download bandwidth for the specified IP

func (*User) GetCleanedPath

func (u *User) GetCleanedPath(rawVirtualPath string) string

GetCleanedPath returns a clean POSIX absolute path using the user start directory as base if the provided rawVirtualPath is relative

func (*User) GetDataTransferLimits

func (u *User) GetDataTransferLimits(clientIP string) (int64, int64, int64)

GetDataTransferLimits returns upload, download and total data transfer limits

func (*User) GetDeniedIPAsString

func (u *User) GetDeniedIPAsString() string

GetDeniedIPAsString returns the denied IP as comma separated string

func (*User) GetEncryptionAdditionalData

func (u *User) GetEncryptionAdditionalData() string

GetEncryptionAdditionalData returns the additional data to use for AEAD

func (*User) GetExpirationDateAsString

func (u *User) GetExpirationDateAsString() string

GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD

func (*User) GetFilesystem

func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error)

GetFilesystem returns the base filesystem for this user

func (*User) GetFilesystemForPath

func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error)

GetFilesystemForPath returns the filesystem for the given path

func (*User) GetFiltersAsJSON

func (u *User) GetFiltersAsJSON() ([]byte, error)

GetFiltersAsJSON returns the filters as json byte array

func (*User) GetFsConfigAsJSON

func (u *User) GetFsConfigAsJSON() ([]byte, error)

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) GetGID

func (u *User) GetGID() int

GetGID returns a validate gid, suitable for use with os.Chown

func (*User) GetGroupsAsString

func (u *User) GetGroupsAsString() string

GetGroupsAsString returns the user's groups as a string

func (*User) GetHomeDir

func (u *User) GetHomeDir() string

GetHomeDir returns the shortest path name equivalent to the user's home directory

func (*User) GetInfoString

func (u *User) GetInfoString() string

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

func (u *User) GetLastLoginAsString() string

GetLastLoginAsString returns the last login as string

func (*User) GetLastQuotaUpdateAsString

func (u *User) GetLastQuotaUpdateAsString() string

GetLastQuotaUpdateAsString returns the last quota update as string

func (*User) GetMFAStatusAsString

func (u *User) GetMFAStatusAsString() string

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

func (u *User) GetPermissionsAsJSON() ([]byte, error)

GetPermissionsAsJSON returns the permissions as json byte array

func (*User) GetPermissionsAsString

func (u *User) GetPermissionsAsString() string

GetPermissionsAsString returns the user's permissions as comma separated string

func (*User) GetPermissionsForPath

func (u *User) GetPermissionsForPath(p string) []string

GetPermissionsForPath returns the permissions for the given path. The path must be a SFTPGo exposed path

func (*User) GetPublicKeysAsJSON

func (u *User) GetPublicKeysAsJSON() ([]byte, error)

GetPublicKeysAsJSON returns the public keys as json byte array

func (*User) GetQuotaSummary

func (u *User) GetQuotaSummary() string

GetQuotaSummary returns used quota and limits if defined

func (*User) GetSignature

func (u *User) GetSignature() string

GetSignature returns a signature for this admin. It will change after an update

func (*User) GetStatusAsString

func (u *User) GetStatusAsString() string

GetStatusAsString returns the user status as a string

func (*User) GetStorageDescrition

func (u *User) GetStorageDescrition() string

GetStorageDescrition returns the storage description

func (*User) GetSubDirPermissions

func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions

GetSubDirPermissions returns permissions for sub directories

func (*User) GetUID

func (u *User) GetUID() int

GetUID returns a validate uid, suitable for use with os.Chown

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

func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool

GetVirtualFoldersInPath returns the virtual folders inside virtualPath including any parents

func (*User) HasAnyPerm

func (u *User) HasAnyPerm(permissions []string, path string) bool

HasAnyPerm returns true if the user has at least one of the given permissions

func (*User) HasExternalAuth

func (u *User) HasExternalAuth() bool

HasExternalAuth returns true if the external authentication is globally enabled and it is not disabled for this user

func (*User) HasMembershipGroup

func (u *User) HasMembershipGroup(name string) bool

HasMembershipGroup returns true if the user has the specified membership group

func (*User) HasNoQuotaRestrictions

func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool

HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed

func (*User) HasPerm

func (u *User) HasPerm(permission, path string) bool

HasPerm returns true if the user has the given permission or any permission

func (*User) HasPermissionsInside

func (u *User) HasPermissionsInside(virtualPath string) bool

HasPermissionsInside returns true if the specified virtualPath has no permissions itself and no subdirs with defined permissions

func (*User) HasPerms

func (u *User) HasPerms(permissions []string, path string) bool

HasPerms returns true if the user has all the given permissions

func (*User) HasPermsDeleteAll

func (u *User) HasPermsDeleteAll(path string) bool

HasPermsDeleteAll returns true if the user can delete both files and directories for the given path

func (*User) HasPermsRenameAll

func (u *User) HasPermsRenameAll(path string) bool

HasPermsRenameAll returns true if the user can rename both files and directories for the given path

func (*User) HasPrimaryGroup

func (u *User) HasPrimaryGroup(name string) bool

HasPrimaryGroup returns true if the user has the specified primary group

func (*User) HasQuotaRestrictions

func (u *User) HasQuotaRestrictions() bool

HasQuotaRestrictions returns true if there are any disk quota restrictions

func (*User) HasRecentActivity

func (u *User) HasRecentActivity() bool

HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks

func (*User) HasSecondaryGroup

func (u *User) HasSecondaryGroup(name string) bool

HasSecondaryGroup returns true if the user has the specified secondary group

func (*User) HasTransferQuotaRestrictions

func (u *User) HasTransferQuotaRestrictions() bool

HasTransferQuotaRestrictions returns true if there are any data transfer restrictions

func (*User) HasVirtualFoldersInside

func (u *User) HasVirtualFoldersInside(virtualPath string) bool

HasVirtualFoldersInside returns true if there are virtual folders inside the specified virtual path. We assume that path are cleaned

func (*User) IsFileAllowed

func (u *User) IsFileAllowed(virtualPath string) (bool, int)

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

func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool

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

func (u *User) IsMappedPath(fsPath string) bool

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

func (u *User) IsPartialAuth(loginMethod string) bool

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

func (u *User) IsPasswordHashed() bool

IsPasswordHashed returns true if the password is hashed

func (*User) IsTLSUsernameVerificationEnabled

func (u *User) IsTLSUsernameVerificationEnabled() bool

IsTLSUsernameVerificationEnabled returns true if we need to extract the username from the client TLS certificate

func (*User) IsVirtualFolder

func (u *User) IsVirtualFolder(virtualPath string) bool

IsVirtualFolder returns true if the specified virtual path is a virtual folder

func (*User) LoadAndApplyGroupSettings

func (u *User) LoadAndApplyGroupSettings() error

LoadAndApplyGroupSettings update the user by loading and applying the group settings

func (*User) MustSetSecondFactor

func (u *User) MustSetSecondFactor() bool

MustSetSecondFactor returns true if the user must set a second factor authentication

func (*User) MustSetSecondFactorForProtocol

func (u *User) MustSetSecondFactorForProtocol(protocol string) bool

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

func (u *User) RenderAsJSON(reload bool) ([]byte, error)

RenderAsJSON implements the renderer interface used within plugins

func (*User) ScanQuota

func (u *User) ScanQuota() (int, int64, error)

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

Jump to

Keyboard shortcuts

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