httpd

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

Documentation

Overview

Package httpd implements REST API and Web interface for SFTPGo. The OpenAPI 3 schema for the exposed API can be found inside the source tree: https://github.com/aKardasz/sftpgo/blob/main/openapi/openapi.yaml

Index

Constants

View Source
const (

	// MaxRestoreSize defines the max size for the loaddata input file
	MaxRestoreSize = 10485760 // 10 MB

)

Variables

This section is empty.

Functions

func GetHTTPRouter

func GetHTTPRouter(b Binding) http.Handler

GetHTTPRouter returns an HTTP handler suitable to use for test cases

func ReloadCertificateMgr

func ReloadCertificateMgr() error

ReloadCertificateMgr reloads the certificate manager

func RestoreAPIKeys

func RestoreAPIKeys(apiKeys []dataprovider.APIKey, inputFile string, mode int, executor, ipAddress string) error

RestoreAPIKeys restores the specified API keys

func RestoreAdmins

func RestoreAdmins(admins []dataprovider.Admin, inputFile string, mode int, executor, ipAddress string) error

RestoreAdmins restores the specified admins

func RestoreEventActions

func RestoreEventActions(actions []dataprovider.BaseEventAction, inputFile string, mode int, executor, ipAddress string) error

RestoreEventActions restores the specified event actions

func RestoreEventRules

func RestoreEventRules(rules []dataprovider.EventRule, inputFile string, mode int, executor, ipAddress string) error

RestoreEventRules restores the specified event rules

func RestoreFolders

func RestoreFolders(folders []vfs.BaseVirtualFolder, inputFile string, mode, scanQuota int, executor, ipAddress string) error

RestoreFolders restores the specified folders

func RestoreGroups

func RestoreGroups(groups []dataprovider.Group, inputFile string, mode int, executor, ipAddress string) error

RestoreGroups restores the specified groups

func RestoreRoles

func RestoreRoles(roles []dataprovider.Role, inputFile string, mode int, executor, ipAddress string) error

RestoreRoles restores the specified roles

func RestoreShares

func RestoreShares(shares []dataprovider.Share, inputFile string, mode int, executor,
	ipAddress string,
) error

RestoreShares restores the specified shares

func RestoreUsers

func RestoreUsers(users []dataprovider.User, inputFile string, mode, scanQuota int, executor, ipAddress string) error

RestoreUsers restores the specified users

func SetInstallationCodeResolver

func SetInstallationCodeResolver(fn FnInstallationCodeResolver)

SetInstallationCodeResolver sets a function to call to resolve the installation code

Types

type Binding

type Binding struct {
	// The address to listen on. A blank value means listen on all available network interfaces.
	Address string `json:"address" mapstructure:"address"`
	// The port used for serving requests
	Port int `json:"port" mapstructure:"port"`
	// Enable the built-in admin interface.
	// You have to define TemplatesPath and StaticFilesPath for this to work
	EnableWebAdmin bool `json:"enable_web_admin" mapstructure:"enable_web_admin"`
	// Enable the built-in client interface.
	// You have to define TemplatesPath and StaticFilesPath for this to work
	EnableWebClient bool `json:"enable_web_client" mapstructure:"enable_web_client"`
	// Enable REST API
	EnableRESTAPI bool `json:"enable_rest_api" mapstructure:"enable_rest_api"`
	// Defines the login methods available for the WebAdmin and WebClient UIs:
	//
	// - 0 means any configured method: username/password login form and OIDC, if enabled
	// - 1 means OIDC for the WebAdmin UI
	// - 2 means OIDC for the WebClient UI
	// - 4 means login form for the WebAdmin UI
	// - 8 means login form for the WebClient UI
	//
	// You can combine the values. For example 3 means that you can only login using OIDC on
	// both WebClient and WebAdmin UI.
	EnabledLoginMethods int `json:"enabled_login_methods" mapstructure:"enabled_login_methods"`
	// you also need to provide a certificate for enabling HTTPS
	EnableHTTPS bool `json:"enable_https" mapstructure:"enable_https"`
	// Certificate and matching private key for this specific binding, if empty the global
	// ones will be used, if any
	CertificateFile    string `json:"certificate_file" mapstructure:"certificate_file"`
	CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
	// Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
	MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
	// set to 1 to require client certificate authentication in addition to basic auth.
	// You need to define at least a certificate authority for this to work
	ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
	// TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
	// If CipherSuites is nil/empty, a default list of secure cipher suites
	// is used, with a preference order based on hardware performance.
	// Note that TLS 1.3 ciphersuites are not configurable.
	// The supported ciphersuites names are defined here:
	//
	// https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
	//
	// any invalid name will be silently ignored.
	// The order matters, the ciphers listed first will be the preferred ones.
	TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
	// List of IP addresses and IP ranges allowed to set client IP proxy headers and
	// X-Forwarded-Proto header.
	ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
	// Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
	ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
	// Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
	// define the position to trust starting from the right. For example if we have:
	// "10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1" and the depth is 0, SFTPGo will use "13.0.0.1"
	// as client IP, if depth is 1, "12.0.0.1" will be used and so on
	ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
	// If both web admin and web client are enabled each login page will show a link
	// to the other one. This setting allows to hide this link:
	// - 0 login links are displayed on both admin and client login page. This is the default
	// - 1 the login link to the web client login page is hidden on admin login page
	// - 2 the login link to the web admin login page is hidden on client login page
	// The flags can be combined, for example 3 will disable both login links.
	HideLoginURL int `json:"hide_login_url" mapstructure:"hide_login_url"`
	// Enable the built-in OpenAPI renderer
	RenderOpenAPI bool `json:"render_openapi" mapstructure:"render_openapi"`
	// Enabling web client integrations you can render or modify the files with the specified
	// extensions using an external tool.
	WebClientIntegrations []WebClientIntegration `json:"web_client_integrations" mapstructure:"web_client_integrations"`
	// Defining an OIDC configuration the web admin and web client UI will use OpenID to authenticate users.
	OIDC OIDC `json:"oidc" mapstructure:"oidc"`
	// Security defines security headers to add to HTTP responses and allows to restrict allowed hosts
	Security SecurityConf `json:"security" mapstructure:"security"`
	// Branding defines customizations to suit your brand
	Branding Branding `json:"branding" mapstructure:"branding"`
	// contains filtered or unexported fields
}

Binding defines the configuration for a network listener

func (*Binding) GetAddress

func (b *Binding) GetAddress() string

GetAddress returns the binding address

func (*Binding) IsValid

func (b *Binding) IsValid() bool

IsValid returns true if the binding is valid

type Branding

type Branding struct {
	WebAdmin  UIBranding `json:"web_admin" mapstructure:"web_admin"`
	WebClient UIBranding `json:"web_client" mapstructure:"web_client"`
}

Branding defines the branding-related customizations supported

type Conf

type Conf struct {
	// Addresses and ports to bind to
	Bindings []Binding `json:"bindings" mapstructure:"bindings"`
	// Path to the HTML web templates. This can be an absolute path or a path relative to the config dir
	TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
	// Path to the static files for the web interface. This can be an absolute path or a path relative to the config dir.
	// If both TemplatesPath and StaticFilesPath are empty the built-in web interface will be disabled
	StaticFilesPath string `json:"static_files_path" mapstructure:"static_files_path"`
	// 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"`
	// Path to the directory that contains the OpenAPI schema and the default renderer.
	// This can be an absolute path or a path relative to the config dir
	OpenAPIPath string `json:"openapi_path" mapstructure:"openapi_path"`
	// Defines a base URL for the web admin and client interfaces. If empty web admin and client resources will
	// be available at the root ("/") URI. If defined it must be an absolute URI or it will be ignored.
	WebRoot string `json:"web_root" mapstructure:"web_root"`
	// If files containing a certificate and matching private key for the server are provided you can enable
	// HTTPS connections for the configured bindings.
	// Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
	// "paramchange" request to the running service on Windows.
	CertificateFile    string `json:"certificate_file" mapstructure:"certificate_file"`
	CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
	// CACertificates defines the set of root certificate authorities to be used to verify client certificates.
	CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
	// CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
	// if a client certificate has been revoked
	CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
	// SigningPassphrase defines the passphrase to use to derive the signing key for JWT and CSRF tokens.
	// If empty a random signing key will be generated each time SFTPGo starts. If you set a
	// signing passphrase you should consider rotating it periodically for added security
	SigningPassphrase string `json:"signing_passphrase" mapstructure:"signing_passphrase"`
	// TokenValidation allows to define how to validate JWT tokens, cookies and CSRF tokens.
	// By default all the available security checks are enabled. Set to 1 to disable the requirement
	// that a token must be used by the same IP for which it was issued.
	TokenValidation int `json:"token_validation" mapstructure:"token_validation"`
	// MaxUploadFileSize Defines the maximum request body size, in bytes, for Web Client/API HTTP upload requests.
	// 0 means no limit
	MaxUploadFileSize int64 `json:"max_upload_file_size" mapstructure:"max_upload_file_size"`
	// CORS configuration
	Cors CorsConfig `json:"cors" mapstructure:"cors"`
	// Initial setup configuration
	Setup SetupConfig `json:"setup" mapstructure:"setup"`
	// If enabled, the link to the sponsors section will not appear on the setup screen page
	HideSupportLink bool `json:"hide_support_link" mapstructure:"hide_support_link"`
}

Conf httpd daemon configuration

func (*Conf) Initialize

func (c *Conf) Initialize(configDir string, isShared int) error

Initialize configures and starts the HTTP server

func (*Conf) ShouldBind

func (c *Conf) ShouldBind() bool

ShouldBind returns true if there is at least a valid binding

type Connection

type Connection struct {
	*common.BaseConnection
	// contains filtered or unexported fields
}

Connection details for a HTTP connection used to inteact with an SFTPGo filesystem

func (*Connection) Disconnect

func (c *Connection) Disconnect() (err error)

Disconnect closes the active transfer

func (*Connection) GetClientVersion

func (c *Connection) GetClientVersion() string

GetClientVersion returns the connected client's version.

func (*Connection) GetCommand

func (c *Connection) GetCommand() string

GetCommand returns the request method

func (*Connection) GetLocalAddress

func (c *Connection) GetLocalAddress() string

GetLocalAddress returns local connection address

func (*Connection) GetRemoteAddress

func (c *Connection) GetRemoteAddress() string

GetRemoteAddress returns the connected client's address

func (*Connection) ReadDir

func (c *Connection) ReadDir(name string) ([]os.FileInfo, error)

ReadDir returns a list of directory entries

func (*Connection) Stat

func (c *Connection) Stat(name string, mode int) (os.FileInfo, error)

Stat returns a FileInfo describing the named file/directory, or an error, if any happens

type CorsConfig

type CorsConfig struct {
	AllowedOrigins       []string `json:"allowed_origins" mapstructure:"allowed_origins"`
	AllowedMethods       []string `json:"allowed_methods" mapstructure:"allowed_methods"`
	AllowedHeaders       []string `json:"allowed_headers" mapstructure:"allowed_headers"`
	ExposedHeaders       []string `json:"exposed_headers" mapstructure:"exposed_headers"`
	AllowCredentials     bool     `json:"allow_credentials" mapstructure:"allow_credentials"`
	Enabled              bool     `json:"enabled" mapstructure:"enabled"`
	MaxAge               int      `json:"max_age" mapstructure:"max_age"`
	OptionsPassthrough   bool     `json:"options_passthrough" mapstructure:"options_passthrough"`
	OptionsSuccessStatus int      `json:"options_success_status" mapstructure:"options_success_status"`
	AllowPrivateNetwork  bool     `json:"allow_private_network" mapstructure:"allow_private_network"`
}

CorsConfig defines the CORS configuration

type FnInstallationCodeResolver

type FnInstallationCodeResolver func(defaultInstallationCode string) string

FnInstallationCodeResolver defines a method to get the installation code. If the installation code cannot be resolved the provided default must be returned

type HTTPSProxyHeader

type HTTPSProxyHeader struct {
	Key   string
	Value string
}

HTTPSProxyHeader defines an HTTPS proxy header as key/value. For example Key could be "X-Forwarded-Proto" and Value "https"

type OAuth2Config

type OAuth2Config interface {
	AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string
	Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)
	TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource
}

OAuth2Config defines an interface for OAuth2 methods, so we can mock them

type OIDC

type OIDC struct {
	// ClientID is the application's ID
	ClientID string `json:"client_id" mapstructure:"client_id"`
	// ClientSecret is the application's secret
	ClientSecret string `json:"client_secret" mapstructure:"client_secret"`
	// ConfigURL is the identifier for the service.
	// SFTPGo will try to retrieve the provider configuration on startup and then
	// will refuse to start if it fails to connect to the specified URL
	ConfigURL string `json:"config_url" mapstructure:"config_url"`
	// RedirectBaseURL is the base URL to redirect to after OpenID authentication.
	// The suffix "/web/oidc/redirect" will be added to this base URL, adding also the
	// "web_root" if configured
	RedirectBaseURL string `json:"redirect_base_url" mapstructure:"redirect_base_url"`
	// ID token claims field to map to the SFTPGo username
	UsernameField string `json:"username_field" mapstructure:"username_field"`
	// Optional ID token claims field to map to a SFTPGo role.
	// If the defined ID token claims field is set to "admin" the authenticated user
	// is mapped to an SFTPGo admin.
	// You don't need to specify this field if you want to use OpenID only for the
	// Web Client UI
	RoleField string `json:"role_field" mapstructure:"role_field"`
	// If set, the `RoleField` is ignored and the SFTPGo role is assumed based on
	// the login link used
	ImplicitRoles bool `json:"implicit_roles" mapstructure:"implicit_roles"`
	// Scopes required by the OAuth provider to retrieve information about the authenticated user.
	// The "openid" scope is required.
	// Refer to your OAuth provider documentation for more information about this
	Scopes []string `json:"scopes" mapstructure:"scopes"`
	// Custom token claims fields to pass to the pre-login hook
	CustomFields []string `json:"custom_fields" mapstructure:"custom_fields"`
	// InsecureSkipSignatureCheck causes SFTPGo to skip JWT signature validation.
	// It's intended for special cases where providers, such as Azure, use the "none"
	// algorithm. Skipping the signature validation can cause security issues
	InsecureSkipSignatureCheck bool `json:"insecure_skip_signature_check" mapstructure:"insecure_skip_signature_check"`
	// Debug enables the OIDC debug mode. In debug mode, the received id_token will be logged
	// at the debug level
	Debug bool `json:"debug" mapstructure:"debug"`
	// contains filtered or unexported fields
}

OIDC defines the OpenID Connect configuration

type OIDCTokenVerifier

type OIDCTokenVerifier interface {
	Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error)
}

OIDCTokenVerifier defines an interface for OpenID token verifier, so we can mock them

type SecurityConf

type SecurityConf struct {
	// Set to true to enable the security configurations
	Enabled bool `json:"enabled" mapstructure:"enabled"`
	// AllowedHosts is a list of fully qualified domain names that are allowed.
	// Default is empty list, which allows any and all host names.
	AllowedHosts []string `json:"allowed_hosts" mapstructure:"allowed_hosts"`
	// AllowedHostsAreRegex determines if the provided allowed hosts contains valid regular expressions
	AllowedHostsAreRegex bool `json:"allowed_hosts_are_regex" mapstructure:"allowed_hosts_are_regex"`
	// HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request.
	HostsProxyHeaders []string `json:"hosts_proxy_headers" mapstructure:"hosts_proxy_headers"`
	// Set to true to redirect HTTP requests to HTTPS
	HTTPSRedirect bool `json:"https_redirect" mapstructure:"https_redirect"`
	// HTTPSHost defines the host name that is used to redirect HTTP requests to HTTPS.
	// Default is "", which indicates to use the same host.
	HTTPSHost string `json:"https_host" mapstructure:"https_host"`
	// HTTPSProxyHeaders is a list of header keys with associated values that would indicate a valid https request.
	HTTPSProxyHeaders []HTTPSProxyHeader `json:"https_proxy_headers" mapstructure:"https_proxy_headers"`
	// STSSeconds is the max-age of the Strict-Transport-Security header.
	// Default is 0, which would NOT include the header.
	STSSeconds int64 `json:"sts_seconds" mapstructure:"sts_seconds"`
	// If STSIncludeSubdomains is set to true, the "includeSubdomains" will be appended to the
	// Strict-Transport-Security header. Default is false.
	STSIncludeSubdomains bool `json:"sts_include_subdomains" mapstructure:"sts_include_subdomains"`
	// If STSPreload is set to true, the `preload` flag will be appended to the
	// Strict-Transport-Security header. Default is false.
	STSPreload bool `json:"sts_preload" mapstructure:"sts_preload"`
	// If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value "nosniff". Default is false.
	ContentTypeNosniff bool `json:"content_type_nosniff" mapstructure:"content_type_nosniff"`
	// ContentSecurityPolicy allows to set the Content-Security-Policy header value. Default is "".
	ContentSecurityPolicy string `json:"content_security_policy" mapstructure:"content_security_policy"`
	// PermissionsPolicy allows to set the Permissions-Policy header value. Default is "".
	PermissionsPolicy string `json:"permissions_policy" mapstructure:"permissions_policy"`
	// CrossOriginOpenerPolicy allows to set the `Cross-Origin-Opener-Policy` header value. Default is "".
	CrossOriginOpenerPolicy string `json:"cross_origin_opener_policy" mapstructure:"cross_origin_opener_policy"`
	// ExpectCTHeader allows to set the Expect-CT header value. Default is "".
	ExpectCTHeader string `json:"expect_ct_header" mapstructure:"expect_ct_header"`
	// contains filtered or unexported fields
}

SecurityConf allows to add some security related headers to HTTP responses and to restrict allowed hosts

type ServicesStatus

type ServicesStatus struct {
	SSH          sftpd.ServiceStatus         `json:"ssh"`
	FTP          ftpd.ServiceStatus          `json:"ftp"`
	WebDAV       webdavd.ServiceStatus       `json:"webdav"`
	DataProvider dataprovider.ProviderStatus `json:"data_provider"`
	Defender     defenderStatus              `json:"defender"`
	MFA          mfa.ServiceStatus           `json:"mfa"`
}

ServicesStatus keep the state of the running services

type SetupConfig

type SetupConfig struct {
	// Installation code to require when creating the first admin account.
	// As for the other configurations, this value is read at SFTPGo startup and not at runtime
	// even if set using an environment variable.
	// This is not a license key or similar, the purpose here is to prevent anyone who can access
	// to the initial setup screen from creating an admin user
	InstallationCode string `json:"installation_code" mapstructure:"installation_code"`
	// Description for the installation code input field
	InstallationCodeHint string `json:"installation_code_hint" mapstructure:"installation_code_hint"`
}

SetupConfig defines the configuration parameters for the initial web admin setup

type UIBranding

type UIBranding struct {
	// Name defines the text to show at the login page and as HTML title
	Name string `json:"name" mapstructure:"name"`
	// ShortName defines the name to show next to the logo image
	ShortName string `json:"short_name" mapstructure:"short_name"`
	// Path to your logo relative to "static_files_path".
	// For example, if you create a directory named "branding" inside the static dir and
	// put the "mylogo.png" file in it, you must set "/branding/mylogo.png" as logo path.
	LogoPath string `json:"logo_path" mapstructure:"logo_path"`
	// Path to the image to show on the login screen relative to "static_files_path"
	LoginImagePath string `json:"login_image_path" mapstructure:"login_image_path"`
	// Path to your favicon relative to "static_files_path"
	FaviconPath string `json:"favicon_path" mapstructure:"favicon_path"`
	// DisclaimerName defines the name for the link to your optional disclaimer
	DisclaimerName string `json:"disclaimer_name" mapstructure:"disclaimer_name"`
	// Path to the HTML page for your disclaimer relative to "static_files_path".
	DisclaimerPath string `json:"disclaimer_path" mapstructure:"disclaimer_path"`
	// Path to a custom CSS file, relative to "static_files_path", which replaces
	// the SB Admin2 default CSS. This is useful, for example, if you rebuild
	// SB Admin2 CSS to use custom colors
	DefaultCSS string `json:"default_css" mapstructure:"default_css"`
	// Additional CSS file paths, relative to "static_files_path", to include
	ExtraCSS []string `json:"extra_css" mapstructure:"extra_css"`
}

UIBranding defines the supported customizations for the web UIs

type WebClientIntegration

type WebClientIntegration struct {
	// Files with these extensions can be sent to the configured URL
	FileExtensions []string `json:"file_extensions" mapstructure:"file_extensions"`
	// URL that will receive the files
	URL string `json:"url" mapstructure:"url"`
}

WebClientIntegration defines the configuration for an external Web Client integration

Jump to

Keyboard shortcuts

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