dataprovider

package
v2.3.6 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2022 License: AGPL-3.0 Imports: 65 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"
)

Available permissions for SFTPGo admins

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 = 12
)
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 (
	// 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

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

Functions

func AddAPIKey

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

AddAPIKey adds a new API key

func AddActiveTransfer added in v2.3.0

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 AddFolder

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

AddFolder adds a new virtual folder.

func AddGroup added in v2.3.0

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

AddGroup adds a new group

func AddShare

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

AddShare adds a new share

func AddSharedSession added in v2.3.0

func AddSharedSession(session Session) error

AddSharedSession stores a new session within the data provider

func AddUser

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

AddUser adds a new SFTPGo user.

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 added in v2.3.0

func CleanupActiveTransfers(before time.Time) error

CleanupActiveTransfers removes the transfer before the specified time

func CleanupDefender added in v2.2.1

func CleanupDefender(from int64) error

CleanupDefender removes events and hosts older than "from" from the data provider

func CleanupSharedSessions added in v2.3.0

func CleanupSharedSessions(sessionType SessionType, before time.Time) error

CleanupSharedSessions removes the shared session with the specified type and before the specified time

func Close

func Close() error

Close releases all provider resources. This method is used in test cases. Closing an uninitialized provider is not supported

func ConvertName added in v2.3.0

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 added in v2.2.1

func DeleteDefenderHost(ip string) error

DeleteDefenderHost removes the specified IP from the defender lists

func DeleteFolder

func DeleteFolder(folderName, executor, ipAddress string) error

DeleteFolder deletes an existing folder.

func DeleteGroup added in v2.3.0

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

DeleteGroup deletes an existing Group

func DeleteShare

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

DeleteShare deletes an existing share

func DeleteSharedSession added in v2.3.0

func DeleteSharedSession(key string) error

DeleteSharedSession deletes the session with the specified key

func DeleteUser

func DeleteUser(username, executor, ipAddress string) error

DeleteUser deletes an existing SFTPGo user.

func ExecutePostLoginHook

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

ExecutePostLoginHook executes the post login hook if defined

func GetBackupsPath added in v2.3.0

func GetBackupsPath() string

GetBackupsPath returns the normalized backups path

func GetFolderByName

func GetFolderByName(name string) (vfs.BaseVirtualFolder, error)

GetFolderByName returns the folder with the specified name if any

func GetFolders

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

GetFolders returns an array of folders respecting limit and offset

func GetQuotaTracking

func GetQuotaTracking() int

GetQuotaTracking returns the configured mode for user's quota tracking

func GetUsedQuota

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 added in v2.3.0

func GetUserVariants(username 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 added in v2.2.2

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 added in v2.3.0

func RemoveActiveTransfer(transferID int64, connectionID string)

RemoveActiveTransfer removes the specified transfer

func RemoveCachedWebDAVUser

func RemoveCachedWebDAVUser(username string)

RemoveCachedWebDAVUser removes a cached WebDAV user

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 SetDefenderBanTime added in v2.2.1

func SetDefenderBanTime(ip string, banTime int64) error

SetDefenderBanTime sets the ban time for the specified IP

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 added in v2.3.0

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 added in v2.2.1

func UpdateDefenderBanTime(ip string, minutes int) error

UpdateDefenderBanTime increments ban time for the specified ip

func UpdateFolder

func UpdateFolder(folder *vfs.BaseVirtualFolder, users []string, groups []string, executor, ipAddress string) error

UpdateFolder updates the specified virtual folder

func UpdateGroup added in v2.3.0

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

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

UpdateUser updates an existing SFTPGo user.

func UpdateUserPassword added in v2.3.0

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 added in v2.3.0

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 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 added in v2.3.0

type ActiveTransfer struct {
	ID            int64
	Type          int
	ConnID        string
	Username      string
	FolderName    string
	IP            string
	TruncatedSize int64
	CurrentULSize int64
	CurrentDLSize int64
	CreatedAt     int64
	UpdatedAt     int64
}

ActiveTransfer defines an active protocol transfer

func GetActiveTransfers added in v2.3.0

func GetActiveTransfers(from time.Time) ([]ActiveTransfer, error)

GetActiveTransfers retrieves the active transfers with an update time after the specified value

type Admin

type Admin struct {
	// Database unique identifier
	ID int64 `json:"id"`
	// 1 enabled, 0 disabled (login is not allowed)
	Status int `json:"status"`
	// Username
	Username       string       `json:"username"`
	Password       string       `json:"password,omitempty"`
	Email          string       `json:"email,omitempty"`
	Permissions    []string     `json:"permissions"`
	Filters        AdminFilters `json:"filters,omitempty"`
	Description    string       `json:"description,omitempty"`
	AdditionalInfo string       `json:"additional_info,omitempty"`
	// Creation time as unix timestamp in milliseconds. It will be 0 for admins created before v2.2.0
	CreatedAt int64 `json:"created_at"`
	// last update time as unix timestamp in milliseconds
	UpdatedAt int64 `json:"updated_at"`
	// Last login as unix timestamp in milliseconds
	LastLogin int64 `json:"last_login"`
}

Admin defines a SFTPGo admin

func AdminExists

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) GetLastLoginAsString added in v2.3.0

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 could 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"`
}

AdminFilters defines additional restrictions for SFTPGo admins TODO: rename to AdminOptions in v3

type AdminTOTPConfig added in v2.2.2

type AdminTOTPConfig struct {
	Enabled    bool        `json:"enabled,omitempty"`
	ConfigName string      `json:"config_name,omitempty"`
	Secret     *kms.Secret `json:"secret,omitempty"`
}

AdminTOTPConfig defines the time-based one time password configuration

type Argon2Options

type Argon2Options struct {
	Memory      uint32 `json:"memory" mapstructure:"memory"`
	Iterations  uint32 `json:"iterations" mapstructure:"iterations"`
	Parallelism uint8  `json:"parallelism" mapstructure:"parallelism"`
}

Argon2Options defines the options for argon2 password hashing

type AutoBackup added in v2.3.0

type AutoBackup struct {
	Enabled bool `json:"enabled" mapstructure:"enabled"`
	// hour as standard cron expression. Allowed values: 0-23.
	// Allowed special characters: asterisk (*), slash (/), comma (,), hyphen (-).
	// More info about special characters here:
	// https://pkg.go.dev/github.com/robfig/cron#hdr-Special_Characters
	Hour string `json:"hour" mapstructure:"hour"`
	// Day of the week as cron expression. Allowed values: 0-6 (Sunday to Saturday).
	// Allowed special characters: asterisk (*), slash (/), comma (,), hyphen (-), question mark (?).
	// More info about special characters here:
	// https://pkg.go.dev/github.com/robfig/cron#hdr-Special_Characters
	DayOfWeek string `json:"day_of_week" mapstructure:"day_of_week"`
}

AutoBackup defines the settings for automatic provider backups. Example: hour "0" and day_of_week "*" means a backup every day at midnight. The backup file name is in the format backup_<day_of_week>_<hour>.json files with the same name will be overwritten

type BackupData

type BackupData struct {
	Users   []User                  `json:"users"`
	Groups  []Group                 `json:"groups"`
	Folders []vfs.BaseVirtualFolder `json:"folders"`
	Admins  []Admin                 `json:"admins"`
	APIKeys []APIKey                `json:"api_keys"`
	Shares  []Share                 `json:"shares"`
	Version int                     `json:"version"`
}

BackupData defines the structure for the backup/restore files

func DumpData

func DumpData() (BackupData, error)

DumpData returns all users, folders, admins, api keys, shares

func ParseDumpData

func ParseDumpData(data []byte) (BackupData, error)

ParseDumpData tries to parse data as BackupData

func (*BackupData) HasFolder

func (d *BackupData) HasFolder(name string) bool

HasFolder returns true if the folder with the given name is included

type BcryptOptions

type BcryptOptions struct {
	Cost int `json:"cost" mapstructure:"cost"`
}

BcryptOptions defines the options for bcrypt password hashing

type BoltProvider

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

BoltProvider defines the auth provider for bolt key/value store

type CachedUser

type CachedUser struct {
	User       User
	Expiration time.Time
	Password   string
	LockSystem webdav.LockSystem
}

CachedUser adds fields useful for caching to a SFTPGo user

func GetCachedWebDAVUser

func GetCachedWebDAVUser(username string) (*CachedUser, bool)

GetCachedWebDAVUser returns a previously cached WebDAV user

func (*CachedUser) IsExpired

func (c *CachedUser) IsExpired() bool

IsExpired returns true if the cached user is expired

type Config

type Config struct {
	// Driver name, must be one of the SupportedProviders
	Driver string `json:"driver" mapstructure:"driver"`
	// Database name. For driver sqlite this can be the database name relative to the config dir
	// or the absolute path to the SQLite database.
	Name string `json:"name" mapstructure:"name"`
	// Database host
	Host string `json:"host" mapstructure:"host"`
	// Database port
	Port int `json:"port" mapstructure:"port"`
	// Database username
	Username string `json:"username" mapstructure:"username"`
	// Database password
	Password string `json:"password" mapstructure:"password"`
	// Used for drivers mysql and postgresql.
	// 0 disable SSL/TLS connections.
	// 1 require ssl.
	// 2 set ssl mode to verify-ca for driver postgresql and skip-verify for driver mysql.
	// 3 set ssl mode to verify-full for driver postgresql and preferred for driver mysql.
	SSLMode int `json:"sslmode" mapstructure:"sslmode"`
	// Path to the root certificate authority used to verify that the server certificate was signed by a trusted CA
	RootCert string `json:"root_cert" mapstructure:"root_cert"`
	// Path to the client certificate for two-way TLS authentication
	ClientCert string `json:"client_cert" mapstructure:"client_cert"`
	// Path to the client key for two-way TLS authentication
	ClientKey string `json:"client_key" mapstructure:"client_key"`
	// Custom database connection string.
	// If not empty this connection string will be used instead of build one using the previous parameters
	ConnectionString string `json:"connection_string" mapstructure:"connection_string"`
	// prefix for SQL tables
	SQLTablesPrefix string `json:"sql_tables_prefix" mapstructure:"sql_tables_prefix"`
	// Set the preferred way to track users quota between the following choices:
	// 0, disable quota tracking. REST API to scan user dir and update quota will do nothing
	// 1, quota is updated each time a user upload or delete a file even if the user has no quota restrictions
	// 2, quota is updated each time a user upload or delete a file but only for users with quota restrictions
	//    and for virtual folders.
	//    With this configuration the "quota scan" REST API can still be used to periodically update space usage
	//    for users without quota restrictions
	TrackQuota int `json:"track_quota" mapstructure:"track_quota"`
	// Sets the maximum number of open connections for mysql and postgresql driver.
	// Default 0 (unlimited)
	PoolSize int `json:"pool_size" mapstructure:"pool_size"`
	// Users default base directory.
	// If no home dir is defined while adding a new user, and this value is
	// a valid absolute path, then the user home dir will be automatically
	// defined as the path obtained joining the base dir and the username
	UsersBaseDir string `json:"users_base_dir" mapstructure:"users_base_dir"`
	// Actions to execute on objects add, update, delete.
	// The supported objects are user, admin, api_key.
	// Update action will not be fired for internal updates such as the last login or the user quota fields.
	Actions ObjectsActions `json:"actions" mapstructure:"actions"`
	// Absolute path to an external program or an HTTP URL to invoke for users authentication.
	// Leave empty to use builtin authentication.
	// If the authentication succeed the user will be automatically added/updated inside the defined data provider.
	// Actions defined for user added/updated will not be executed in this case.
	// This method is slower than built-in authentication methods, but it's very flexible as anyone can
	// easily write his own authentication hooks.
	ExternalAuthHook string `json:"external_auth_hook" mapstructure:"external_auth_hook"`
	// ExternalAuthScope defines the scope for the external authentication hook.
	// - 0 means all supported authentication scopes, the external hook will be executed for password,
	//     public key, keyboard interactive authentication and TLS certificates
	// - 1 means passwords only
	// - 2 means public keys only
	// - 4 means keyboard interactive only
	// - 8 means TLS certificates only
	// you can combine the scopes, for example 3 means password and public key, 5 password and keyboard
	// interactive and so on
	ExternalAuthScope int `json:"external_auth_scope" mapstructure:"external_auth_scope"`
	// CredentialsPath defines the directory for storing user provided credential files such as
	// Google Cloud Storage credentials. It can be a path relative to the config dir or an
	// absolute path
	CredentialsPath string `json:"credentials_path" mapstructure:"credentials_path"`
	// Absolute path to an external program or an HTTP URL to invoke just before the user login.
	// This program/URL allows to modify or create the user trying to login.
	// It is useful if you have users with dynamic fields to update just before the login.
	// Please note that if you want to create a new user, the pre-login hook response must
	// include all the mandatory user fields.
	//
	// The pre-login hook must finish within 30 seconds.
	//
	// If an error happens while executing the "PreLoginHook" then login will be denied.
	// PreLoginHook and ExternalAuthHook are mutally exclusive.
	// Leave empty to disable.
	PreLoginHook string `json:"pre_login_hook" mapstructure:"pre_login_hook"`
	// Absolute path to an external program or an HTTP URL to invoke after the user login.
	// Based on the configured scope you can choose if notify failed or successful logins
	// or both
	PostLoginHook string `json:"post_login_hook" mapstructure:"post_login_hook"`
	// PostLoginScope defines the scope for the post-login hook.
	// - 0 means notify both failed and successful logins
	// - 1 means notify failed logins
	// - 2 means notify successful logins
	PostLoginScope int `json:"post_login_scope" mapstructure:"post_login_scope"`
	// Absolute path to an external program or an HTTP URL to invoke just before password
	// authentication. This hook allows you to externally check the provided password,
	// its main use case is to allow to easily support things like password+OTP for protocols
	// without keyboard interactive support such as FTP and WebDAV. You can ask your users
	// to login using a string consisting of a fixed password and a One Time Token, you
	// can verify the token inside the hook and ask to SFTPGo to verify the fixed part.
	CheckPasswordHook string `json:"check_password_hook" mapstructure:"check_password_hook"`
	// CheckPasswordScope defines the scope for the check password hook.
	// - 0 means all protocols
	// - 1 means SSH
	// - 2 means FTP
	// - 4 means WebDAV
	// you can combine the scopes, for example 6 means FTP and WebDAV
	CheckPasswordScope int `json:"check_password_scope" mapstructure:"check_password_scope"`
	// Defines how the database will be initialized/updated:
	// - 0 means automatically
	// - 1 means manually using the initprovider sub-command
	UpdateMode int `json:"update_mode" mapstructure:"update_mode"`
	// PasswordHashing defines the configuration for password hashing
	PasswordHashing PasswordHashing `json:"password_hashing" mapstructure:"password_hashing"`
	// PasswordValidation defines the password validation rules
	PasswordValidation PasswordValidation `json:"password_validation" mapstructure:"password_validation"`
	// Verifying argon2 passwords has a high memory and computational cost,
	// by enabling, in memory, password caching you reduce this cost.
	PasswordCaching bool `json:"password_caching" mapstructure:"password_caching"`
	// DelayedQuotaUpdate defines the number of seconds to accumulate quota updates.
	// If there are a lot of close uploads, accumulating quota updates can save you many
	// queries to the data provider.
	// If you want to track quotas, a scheduled quota update is recommended in any case, the stored
	// quota size may be incorrect for several reasons, such as an unexpected shutdown, temporary provider
	// failures, file copied outside of SFTPGo, and so on.
	// 0 means immediate quota update.
	DelayedQuotaUpdate int `json:"delayed_quota_update" mapstructure:"delayed_quota_update"`
	// If enabled, a default admin user with username "admin" and password "password" will be created
	// on first start.
	// You can also create the first admin user by using the web interface or by loading initial data.
	CreateDefaultAdmin bool `json:"create_default_admin" mapstructure:"create_default_admin"`
	// Rules for usernames and folder names:
	// - 0 means no rules
	// - 1 means you can use any UTF-8 character. The names are used in URIs for REST API and Web admin.
	//     By default only unreserved URI characters are allowed: ALPHA / DIGIT / "-" / "." / "_" / "~".
	// - 2 means names are converted to lowercase before saving/matching and so case
	//     insensitive matching is possible
	// - 4 means trimming trailing and leading white spaces before saving/matching
	// Rules can be combined, for example 3 means both converting to lowercase and allowing any UTF-8 character.
	// Enabling these options for existing installations could be backward incompatible, some users
	// could be unable to login, for example existing users with mixed cases in their usernames.
	// You have to ensure that all existing users respect the defined rules.
	NamingRules int `json:"naming_rules" mapstructure:"naming_rules"`
	// 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"`
	// Path to the backup directory. This can be an absolute path or a path relative to the config dir
	BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
	// Settings for automatic backups
	AutoBackup AutoBackup `json:"auto_backup" mapstructure:"auto_backup"`
}

Config provider configuration

func GetProviderConfig added in v2.2.1

func GetProviderConfig() Config

GetProviderConfig returns the current provider configuration

func (*Config) GetShared added in v2.3.0

func (c *Config) GetShared() int

GetShared returns the provider share mode

func (*Config) IsDefenderSupported added in v2.2.1

func (c *Config) IsDefenderSupported() bool

IsDefenderSupported returns true if the configured provider supports the defender

type DefenderEntry added in v2.2.1

type DefenderEntry struct {
	ID      int64     `json:"-"`
	IP      string    `json:"ip"`
	Score   int       `json:"score,omitempty"`
	BanTime time.Time `json:"ban_time,omitempty"`
}

DefenderEntry defines a defender entry

func AddDefenderEvent added in v2.2.1

func AddDefenderEvent(ip string, score int, from int64) (DefenderEntry, error)

AddDefenderEvent adds an event for the given IP with the given score and returns the host with the updated score

func GetDefenderHostByIP added in v2.2.1

func GetDefenderHostByIP(ip string, from int64) (DefenderEntry, error)

GetDefenderHostByIP returns a defender host by ip, if any

func GetDefenderHosts added in v2.2.1

func GetDefenderHosts(from int64, limit int) ([]DefenderEntry, error)

GetDefenderHosts returns hosts that are banned or for which some violations have been detected

func IsDefenderHostBanned added in v2.2.1

func IsDefenderHostBanned(ip string) (DefenderEntry, error)

IsDefenderHostBanned returns a defender entry and no error if the specified host is banned

func (*DefenderEntry) GetBanTime added in v2.2.1

func (d *DefenderEntry) GetBanTime() string

GetBanTime returns the ban time for a defender entry as string

func (*DefenderEntry) GetID added in v2.2.1

func (d *DefenderEntry) GetID() string

GetID returns an unique ID for a defender entry

func (*DefenderEntry) MarshalJSON added in v2.2.1

func (d *DefenderEntry) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoding of a DefenderEntry.

type Group added in v2.3.0

type Group struct {
	sdk.BaseGroup
	// settings to apply to users for whom this is a primary group
	UserSettings GroupUserSettings `json:"user_settings,omitempty"`
	// Mapping between virtual paths and virtual folders
	VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
}

Group defines an SFTPGo group. Groups are used to easily configure similar users

func GetGroups added in v2.3.0

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

GetGroups returns an array of groups respecting limit and offset

func GroupExists added in v2.3.0

func GroupExists(name string) (Group, error)

GroupExists returns the Group with the given name if it exists

func (*Group) GetAllowedIPAsString added in v2.3.0

func (g *Group) GetAllowedIPAsString() string

GetAllowedIPAsString returns the allowed IP as comma separated string

func (*Group) GetDeniedIPAsString added in v2.3.0

func (g *Group) GetDeniedIPAsString() string

GetDeniedIPAsString returns the denied IP as comma separated string

func (*Group) GetEncryptionAdditionalData added in v2.3.0

func (g *Group) GetEncryptionAdditionalData() string

GetEncryptionAdditionalData returns the additional data to use for AEAD

func (*Group) GetPermissions added in v2.3.0

func (g *Group) GetPermissions() []sdk.DirectoryPermissions

GetPermissions returns the permissions as list

func (*Group) GetUsersAsString added in v2.3.0

func (g *Group) GetUsersAsString() string

GetUsersAsString returns the list of users as comma separated string

func (*Group) HasExternalAuth added in v2.3.0

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 added in v2.3.0

func (g *Group) PrepareForRendering()

PrepareForRendering prepares a group for rendering. It hides confidential data and set to nil the empty secrets so they are not serialized

func (*Group) RenderAsJSON added in v2.3.0

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

RenderAsJSON implements the renderer interface used within plugins

func (*Group) SetEmptySecretsIfNil added in v2.3.0

func (g *Group) SetEmptySecretsIfNil()

SetEmptySecretsIfNil sets the secrets to empty if nil

type GroupUserSettings added in v2.3.0

type GroupUserSettings struct {
	sdk.BaseGroupUserSettings
	// Filesystem configuration details
	FsConfig vfs.Filesystem `json:"filesystem"`
}

GroupUserSettings defines the settings to apply to users

type MemoryProvider

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

MemoryProvider defines the auth provider for a memory store

type MySQLProvider

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

MySQLProvider defines the auth provider for MySQL/MariaDB database

type ObjectsActions

type ObjectsActions struct {
	// Valid values are add, update, delete. Empty slice to disable
	ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
	// Valid values are user, admin, api_key
	ExecuteFor []string `json:"execute_for" mapstructure:"execute_for"`
	// Absolute path to an external program or an HTTP URL
	Hook string `json:"hook" mapstructure:"hook"`
}

ObjectsActions defines the action to execute on user create, update, delete for the specified objects

type PGSQLProvider

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

PGSQLProvider defines the auth provider for PostgreSQL database

type PasswordHashing

type PasswordHashing struct {
	BcryptOptions BcryptOptions `json:"bcrypt_options" mapstructure:"bcrypt_options"`
	Argon2Options Argon2Options `json:"argon2_options" mapstructure:"argon2_options"`
	// Algorithm to use for hashing passwords. Available algorithms: argon2id, bcrypt. Default: bcrypt
	Algo string `json:"algo" mapstructure:"algo"`
}

PasswordHashing defines the configuration for password hashing

type PasswordValidation

type PasswordValidation struct {
	// Password validation rules for SFTPGo admin users
	Admins PasswordValidationRules `json:"admins" mapstructure:"admins"`
	// Password validation rules for SFTPGo protocol users
	Users PasswordValidationRules `json:"users" mapstructure:"users"`
}

PasswordValidation defines the password validation rules for admins and protocol users

type PasswordValidationRules

type PasswordValidationRules struct {
	// MinEntropy defines the minimum password entropy.
	// 0 means disabled, any password will be accepted.
	// Take a look at the following link for more details
	// https://github.com/wagslane/go-password-validator#what-entropy-value-should-i-use
	MinEntropy float64 `json:"min_entropy" mapstructure:"min_entropy"`
}

PasswordValidationRules defines the password validation rules

type Provider

type Provider interface {
	// contains filtered or unexported methods
}

Provider defines the interface that data providers must implement.

type ProviderStatus

type ProviderStatus struct {
	Driver   string `json:"driver"`
	IsActive bool   `json:"is_active"`
	Error    string `json:"error"`
}

ProviderStatus defines the provider status

func GetProviderStatus

func GetProviderStatus() ProviderStatus

GetProviderStatus returns an error if the provider is not available

type RecoveryCode added in v2.2.2

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

RecoveryCode defines a 2FA recovery code

type SQLiteProvider

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

SQLiteProvider defines the auth provider for SQLite database

type Session added in v2.3.0

type Session struct {
	Key       string
	Data      any
	Type      SessionType
	Timestamp int64
}

Session defines a shared session persisted in the data provider

func GetSharedSession added in v2.3.0

func GetSharedSession(key string) (Session, error)

GetSharedSession retrieves the session with the specified key

type SessionType added in v2.3.0

type SessionType int

SessionType defines the supported session types

const (
	SessionTypeOIDCAuth SessionType = iota + 1
	SessionTypeOIDCToken
	SessionTypeResetCode
)

Supported session types

type Share

type Share struct {
	// 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 added in v2.3.0

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 added in v2.3.0

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 TransferQuota added in v2.3.0

type TransferQuota struct {
	ULSize           int64
	DLSize           int64
	TotalSize        int64
	AllowedULSize    int64
	AllowedDLSize    int64
	AllowedTotalSize int64
}

TransferQuota stores the allowed transfer quota fields

func (*TransferQuota) HasDownloadSpace added in v2.3.0

func (q *TransferQuota) HasDownloadSpace() bool

HasDownloadSpace returns true if there is transfer download space available

func (*TransferQuota) HasSizeLimits added in v2.3.0

func (q *TransferQuota) HasSizeLimits() bool

HasSizeLimits returns true if any size limit is set

func (*TransferQuota) HasUploadSpace added in v2.3.0

func (q *TransferQuota) HasUploadSpace() bool

HasUploadSpace returns true if there is transfer upload space available

type User

type User struct {
	sdk.BaseUser
	// Additional restrictions
	Filters UserFilters `json:"filters"`
	// Mapping between virtual paths and virtual folders
	VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
	// Filesystem configuration details
	FsConfig vfs.Filesystem `json:"filesystem"`
	// groups associated with this user
	Groups []sdk.GroupMapping `json:"groups,omitempty"`
	// contains filtered or unexported fields
}

User defines a SFTPGo user

func CheckCompositeCredentials

func CheckCompositeCredentials(username, password, ip, loginMethod, protocol string, tlsCert *x509.Certificate) (User, string, error)

CheckCompositeCredentials checks multiple credentials. WebDAV users can send both a password and a TLS certificate within the same request

func CheckKeyboardInteractiveAuth

func CheckKeyboardInteractiveAuth(username, authHook string, client ssh.KeyboardInteractiveChallenge, ip, protocol string) (User, error)

CheckKeyboardInteractiveAuth checks the keyboard interactive authentication and returns the authenticated user or an error

func CheckUserAndPass

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 GetUserAfterIDPAuth added in v2.3.0

func GetUserAfterIDPAuth(username, ip, protocol string, oidcTokenFields *map[string]any) (User, error)

GetUserAfterIDPAuth returns the SFTPGo user with the specified username after a successful authentication with an external identity provider. If a pre-login hook is defined it will be executed so the SFTPGo user can be created if it does not exist

func GetUserWithGroupSettings added in v2.3.0

func GetUserWithGroupSettings(username 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 string) ([]User, error)

GetUsers returns an array of users respecting limit and offset

func GetUsersForQuotaCheck added in v2.3.0

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 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 added in v2.2.1

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 added in v2.3.0

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 added in v2.2.1

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

GetBandwidthForIP returns the upload and download bandwidth for the specified IP

func (*User) GetCleanedPath added in v2.3.0

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 added in v2.3.0

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

func (u *User) GetGCSCredentialsFilePath() string

GetGCSCredentialsFilePath returns the path for GCS credentials

func (*User) GetGID

func (u *User) GetGID() int

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

func (*User) GetGroupsAsString added in v2.3.0

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 added in v2.3.0

func (u *User) GetLastLoginAsString() string

GetLastLoginAsString returns the last login as string

func (*User) GetLastQuotaUpdateAsString added in v2.3.0

func (u *User) GetLastQuotaUpdateAsString() string

GetLastQuotaUpdateAsString returns the last quota update as string

func (*User) GetMFAStatusAsString added in v2.3.0

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 could change after an update

func (*User) GetStatusAsString

func (u *User) GetStatusAsString() string

GetStatusAsString returns the user status as a string

func (*User) GetStorageDescrition added in v2.3.0

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) HasBufferedSFTP added in v2.2.1

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

HasBufferedSFTP returns true if the user has a SFTP filesystem with buffering enabled

func (*User) HasExternalAuth added in v2.3.0

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) 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 added in v2.3.0

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 added in v2.3.0

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 added in v2.3.0

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

HasSecondaryGroup returns true if the user has the specified secondary group

func (*User) HasTransferQuotaRestrictions added in v2.3.0

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 denied

func (*User) IsLoginMethodAllowed

func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool

IsLoginMethodAllowed returns true if the specified login method is allowed

func (*User) IsMappedPath

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 added in v2.3.0

func (u *User) LoadAndApplyGroupSettings() error

LoadAndApplyGroupSettings update the user by loading and applying the group settings

func (*User) MustSetSecondFactor added in v2.3.0

func (u *User) MustSetSecondFactor() bool

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

func (*User) MustSetSecondFactorForProtocol added in v2.3.0

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 added in v2.2.2

type UserFilters struct {
	sdk.BaseUserFilters
	// Time-based one time passwords configuration
	TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"`
	// Recovery codes to use if the user loses access to their second factor auth device.
	// Each code can only be used once, you should use these codes to login and disable or
	// reset 2FA for your account
	RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
}

UserFilters defines additional restrictions for a user TODO: rename to UserOptions in v3

type UserTOTPConfig added in v2.2.2

type UserTOTPConfig struct {
	Enabled    bool        `json:"enabled,omitempty"`
	ConfigName string      `json:"config_name,omitempty"`
	Secret     *kms.Secret `json:"secret,omitempty"`
	// TOTP will be required for the specified protocols.
	// SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive
	// authentication.
	// FTP have no standard way to support two factor authentication, if you
	// enable the support for this protocol you have to add the TOTP passcode after the password.
	// For example if your password is "password" and your one time passcode is
	// "123456" you have to use "password123456" as password.
	Protocols []string `json:"protocols,omitempty"`
}

UserTOTPConfig defines the time-based one time password configuration

Jump to

Keyboard shortcuts

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