diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 8dad0e7f..5781711c 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -15,14 +15,14 @@ jobs: - name: Set up Go 1.14 uses: actions/setup-go@v2 with: - go-version: '1.14' + go-version: 1.14 id: go - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Install golangci-lint - run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.25.1 + run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.26.0 - name: Run golangci-lint - run: golangci-lint run --timeout=3m --tests=false --enable=goconst,gofmt,goimports,golint,unconvert,unparam,bodyclose,gocyclo,misspell,maligned,whitespace,dupl,scopelint + run: golangci-lint run diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..7fca1f1f --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,42 @@ +run: + timeout: 5m + issues-exit-code: 1 + tests: true + + +linters-settings: + dupl: + threshold: 150 + errcheck: + check-type-assertions: false + check-blank: false + goconst: + min-len: 3 + min-occurrences: 3 + gocyclo: + min-complexity: 15 + gofmt: + simplify: true + goimports: + local-prefixes: github.com/drakkan/sftpgo + maligned: + suggest-new: true + +linters: + enable: + - goconst + - errcheck + - gofmt + - goimports + - golint + - unconvert + - unparam + - bodyclose + - gocyclo + - misspell + - maligned + - whitespace + - dupl + - scopelint + - rowserrcheck + - dogsled \ No newline at end of file diff --git a/cmd/initprovider.go b/cmd/initprovider.go index c97dc553..63325f75 100644 --- a/cmd/initprovider.go +++ b/cmd/initprovider.go @@ -1,13 +1,14 @@ package cmd import ( + "github.com/rs/zerolog" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/drakkan/sftpgo/config" "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/utils" - "github.com/rs/zerolog" - "github.com/spf13/cobra" - "github.com/spf13/viper" ) var ( diff --git a/cmd/install_windows.go b/cmd/install_windows.go index 9d00c4a5..8ae22e31 100644 --- a/cmd/install_windows.go +++ b/cmd/install_windows.go @@ -4,9 +4,10 @@ import ( "fmt" "strconv" + "github.com/spf13/cobra" + "github.com/drakkan/sftpgo/service" "github.com/drakkan/sftpgo/utils" - "github.com/spf13/cobra" ) var ( diff --git a/cmd/portable.go b/cmd/portable.go index 550d9722..92bd8f93 100644 --- a/cmd/portable.go +++ b/cmd/portable.go @@ -9,11 +9,12 @@ import ( "path/filepath" "strings" + "github.com/spf13/cobra" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/service" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/vfs" - "github.com/spf13/cobra" ) var ( diff --git a/cmd/reload_windows.go b/cmd/reload_windows.go index 1abeaf91..62eeb189 100644 --- a/cmd/reload_windows.go +++ b/cmd/reload_windows.go @@ -3,8 +3,9 @@ package cmd import ( "fmt" - "github.com/drakkan/sftpgo/service" "github.com/spf13/cobra" + + "github.com/drakkan/sftpgo/service" ) var ( diff --git a/cmd/root.go b/cmd/root.go index 6b4b0be8..7b9bd617 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -5,10 +5,11 @@ import ( "fmt" "os" - "github.com/drakkan/sftpgo/config" - "github.com/drakkan/sftpgo/utils" "github.com/spf13/cobra" "github.com/spf13/viper" + + "github.com/drakkan/sftpgo/config" + "github.com/drakkan/sftpgo/utils" ) const ( @@ -77,71 +78,71 @@ func Execute() { func addConfigFlags(cmd *cobra.Command) { viper.SetDefault(configDirKey, defaultConfigDir) - viper.BindEnv(configDirKey, "SFTPGO_CONFIG_DIR") //nolint: errcheck // err is not nil only if the key to bind is missing + viper.BindEnv(configDirKey, "SFTPGO_CONFIG_DIR") //nolint:errcheck // err is not nil only if the key to bind is missing cmd.Flags().StringVarP(&configDir, configDirFlag, "c", viper.GetString(configDirKey), "Location for SFTPGo config dir. This directory should contain the \"sftpgo\" configuration file or the configured "+ "config-file and it is used as the base for files with a relative path (eg. the private keys for the SFTP server, "+ "the SQLite database if you use SQLite as data provider). This flag can be set using SFTPGO_CONFIG_DIR env var too.") - viper.BindPFlag(configDirKey, cmd.Flags().Lookup(configDirFlag)) //nolint: errcheck + viper.BindPFlag(configDirKey, cmd.Flags().Lookup(configDirFlag)) //nolint:errcheck viper.SetDefault(configFileKey, defaultConfigName) - viper.BindEnv(configFileKey, "SFTPGO_CONFIG_FILE") //nolint: errcheck + viper.BindEnv(configFileKey, "SFTPGO_CONFIG_FILE") //nolint:errcheck cmd.Flags().StringVarP(&configFile, configFileFlag, "f", viper.GetString(configFileKey), "Name for SFTPGo configuration file. It must be the name of a file stored in config-dir not the absolute path to the "+ "configuration file. The specified file name must have no extension we automatically load JSON, YAML, TOML, HCL and "+ "Java properties. Therefore if you set \"sftpgo\" then \"sftpgo.json\", \"sftpgo.yaml\" and so on are searched. "+ "This flag can be set using SFTPGO_CONFIG_FILE env var too.") - viper.BindPFlag(configFileKey, cmd.Flags().Lookup(configFileFlag)) //nolint: errcheck + viper.BindPFlag(configFileKey, cmd.Flags().Lookup(configFileFlag)) //nolint:errcheck } func addServeFlags(cmd *cobra.Command) { addConfigFlags(cmd) viper.SetDefault(logFilePathKey, defaultLogFile) - viper.BindEnv(logFilePathKey, "SFTPGO_LOG_FILE_PATH") //nolint: errcheck + viper.BindEnv(logFilePathKey, "SFTPGO_LOG_FILE_PATH") //nolint:errcheck cmd.Flags().StringVarP(&logFilePath, logFilePathFlag, "l", viper.GetString(logFilePathKey), "Location for the log file. Leave empty to write logs to the standard output. This flag can be set using SFTPGO_LOG_FILE_PATH "+ "env var too.") - viper.BindPFlag(logFilePathKey, cmd.Flags().Lookup(logFilePathFlag)) //nolint: errcheck + viper.BindPFlag(logFilePathKey, cmd.Flags().Lookup(logFilePathFlag)) //nolint:errcheck viper.SetDefault(logMaxSizeKey, defaultLogMaxSize) - viper.BindEnv(logMaxSizeKey, "SFTPGO_LOG_MAX_SIZE") //nolint: errcheck + viper.BindEnv(logMaxSizeKey, "SFTPGO_LOG_MAX_SIZE") //nolint:errcheck cmd.Flags().IntVarP(&logMaxSize, logMaxSizeFlag, "s", viper.GetInt(logMaxSizeKey), "Maximum size in megabytes of the log file before it gets rotated. This flag can be set using SFTPGO_LOG_MAX_SIZE "+ "env var too. It is unused if log-file-path is empty.") - viper.BindPFlag(logMaxSizeKey, cmd.Flags().Lookup(logMaxSizeFlag)) //nolint: errcheck + viper.BindPFlag(logMaxSizeKey, cmd.Flags().Lookup(logMaxSizeFlag)) //nolint:errcheck viper.SetDefault(logMaxBackupKey, defaultLogMaxBackup) - viper.BindEnv(logMaxBackupKey, "SFTPGO_LOG_MAX_BACKUPS") //nolint: errcheck + viper.BindEnv(logMaxBackupKey, "SFTPGO_LOG_MAX_BACKUPS") //nolint:errcheck cmd.Flags().IntVarP(&logMaxBackups, "log-max-backups", "b", viper.GetInt(logMaxBackupKey), "Maximum number of old log files to retain. This flag can be set using SFTPGO_LOG_MAX_BACKUPS env var too. "+ "It is unused if log-file-path is empty.") - viper.BindPFlag(logMaxBackupKey, cmd.Flags().Lookup(logMaxBackupFlag)) //nolint: errcheck + viper.BindPFlag(logMaxBackupKey, cmd.Flags().Lookup(logMaxBackupFlag)) //nolint:errcheck viper.SetDefault(logMaxAgeKey, defaultLogMaxAge) - viper.BindEnv(logMaxAgeKey, "SFTPGO_LOG_MAX_AGE") //nolint: errcheck + viper.BindEnv(logMaxAgeKey, "SFTPGO_LOG_MAX_AGE") //nolint:errcheck cmd.Flags().IntVarP(&logMaxAge, "log-max-age", "a", viper.GetInt(logMaxAgeKey), "Maximum number of days to retain old log files. This flag can be set using SFTPGO_LOG_MAX_AGE env var too. "+ "It is unused if log-file-path is empty.") - viper.BindPFlag(logMaxAgeKey, cmd.Flags().Lookup(logMaxAgeFlag)) //nolint: errcheck + viper.BindPFlag(logMaxAgeKey, cmd.Flags().Lookup(logMaxAgeFlag)) //nolint:errcheck viper.SetDefault(logCompressKey, defaultLogCompress) - viper.BindEnv(logCompressKey, "SFTPGO_LOG_COMPRESS") //nolint: errcheck + viper.BindEnv(logCompressKey, "SFTPGO_LOG_COMPRESS") //nolint:errcheck cmd.Flags().BoolVarP(&logCompress, logCompressFlag, "z", viper.GetBool(logCompressKey), "Determine if the rotated "+ "log files should be compressed using gzip. This flag can be set using SFTPGO_LOG_COMPRESS env var too. "+ "It is unused if log-file-path is empty.") - viper.BindPFlag(logCompressKey, cmd.Flags().Lookup(logCompressFlag)) //nolint: errcheck + viper.BindPFlag(logCompressKey, cmd.Flags().Lookup(logCompressFlag)) //nolint:errcheck viper.SetDefault(logVerboseKey, defaultLogVerbose) - viper.BindEnv(logVerboseKey, "SFTPGO_LOG_VERBOSE") //nolint: errcheck + viper.BindEnv(logVerboseKey, "SFTPGO_LOG_VERBOSE") //nolint:errcheck cmd.Flags().BoolVarP(&logVerbose, logVerboseFlag, "v", viper.GetBool(logVerboseKey), "Enable verbose logs. "+ "This flag can be set using SFTPGO_LOG_VERBOSE env var too.") - viper.BindPFlag(logVerboseKey, cmd.Flags().Lookup(logVerboseFlag)) //nolint: errcheck + viper.BindPFlag(logVerboseKey, cmd.Flags().Lookup(logVerboseFlag)) //nolint:errcheck viper.SetDefault(profilerKey, defaultProfiler) - viper.BindEnv(profilerKey, "SFTPGO_PROFILER") //nolint: errcheck + viper.BindEnv(profilerKey, "SFTPGO_PROFILER") //nolint:errcheck cmd.Flags().BoolVarP(&profiler, profilerFlag, "p", viper.GetBool(profilerKey), "Enable the built-in profiler. "+ "The profiler will be accessible via HTTP/HTTPS using the base URL \"/debug/pprof/\". "+ "This flag can be set using SFTPGO_PROFILER env var too.") - viper.BindPFlag(profilerKey, cmd.Flags().Lookup(profilerFlag)) //nolint: errcheck + viper.BindPFlag(profilerKey, cmd.Flags().Lookup(profilerFlag)) //nolint:errcheck } diff --git a/cmd/serve.go b/cmd/serve.go index aacba175..8827c3ec 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -1,9 +1,10 @@ package cmd import ( + "github.com/spf13/cobra" + "github.com/drakkan/sftpgo/service" "github.com/drakkan/sftpgo/utils" - "github.com/spf13/cobra" ) var ( diff --git a/cmd/start_windows.go b/cmd/start_windows.go index 671fc41f..edd8e532 100644 --- a/cmd/start_windows.go +++ b/cmd/start_windows.go @@ -4,9 +4,10 @@ import ( "fmt" "path/filepath" + "github.com/spf13/cobra" + "github.com/drakkan/sftpgo/service" "github.com/drakkan/sftpgo/utils" - "github.com/spf13/cobra" ) var ( diff --git a/cmd/status_windows.go b/cmd/status_windows.go index 5b281dc3..03f77654 100644 --- a/cmd/status_windows.go +++ b/cmd/status_windows.go @@ -3,8 +3,9 @@ package cmd import ( "fmt" - "github.com/drakkan/sftpgo/service" "github.com/spf13/cobra" + + "github.com/drakkan/sftpgo/service" ) var ( diff --git a/cmd/stop_windows.go b/cmd/stop_windows.go index 657f7226..46660ee9 100644 --- a/cmd/stop_windows.go +++ b/cmd/stop_windows.go @@ -3,8 +3,9 @@ package cmd import ( "fmt" - "github.com/drakkan/sftpgo/service" "github.com/spf13/cobra" + + "github.com/drakkan/sftpgo/service" ) var ( diff --git a/cmd/uninstall_windows.go b/cmd/uninstall_windows.go index 669b6dec..e1d61a3e 100644 --- a/cmd/uninstall_windows.go +++ b/cmd/uninstall_windows.go @@ -3,8 +3,9 @@ package cmd import ( "fmt" - "github.com/drakkan/sftpgo/service" "github.com/spf13/cobra" + + "github.com/drakkan/sftpgo/service" ) var ( diff --git a/config/config.go b/config/config.go index f92b2eb8..4a66bba6 100644 --- a/config/config.go +++ b/config/config.go @@ -9,13 +9,14 @@ import ( "fmt" "strings" + "github.com/spf13/viper" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/httpclient" "github.com/drakkan/sftpgo/httpd" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" - "github.com/spf13/viper" ) const ( @@ -222,19 +223,19 @@ func LoadConfig(configDir, configName string) error { func checkHooksCompatibility() { // we copy deprecated fields to new ones to keep backward compatibility so lint is disabled - if len(globalConf.ProviderConf.ExternalAuthProgram) > 0 && len(globalConf.ProviderConf.ExternalAuthHook) == 0 { //nolint: staticcheck + if len(globalConf.ProviderConf.ExternalAuthProgram) > 0 && len(globalConf.ProviderConf.ExternalAuthHook) == 0 { //nolint:staticcheck logger.Warn(logSender, "", "external_auth_program is deprecated, please use external_auth_hook") logger.WarnToConsole("external_auth_program is deprecated, please use external_auth_hook") - globalConf.ProviderConf.ExternalAuthHook = globalConf.ProviderConf.ExternalAuthProgram //nolint: staticcheck + globalConf.ProviderConf.ExternalAuthHook = globalConf.ProviderConf.ExternalAuthProgram //nolint:staticcheck } - if len(globalConf.ProviderConf.PreLoginProgram) > 0 && len(globalConf.ProviderConf.PreLoginHook) == 0 { //nolint: staticcheck + if len(globalConf.ProviderConf.PreLoginProgram) > 0 && len(globalConf.ProviderConf.PreLoginHook) == 0 { //nolint:staticcheck logger.Warn(logSender, "", "pre_login_program is deprecated, please use pre_login_hook") logger.WarnToConsole("pre_login_program is deprecated, please use pre_login_hook") - globalConf.ProviderConf.PreLoginHook = globalConf.ProviderConf.PreLoginProgram //nolint: staticcheck + globalConf.ProviderConf.PreLoginHook = globalConf.ProviderConf.PreLoginProgram //nolint:staticcheck } - if len(globalConf.SFTPD.KeyboardInteractiveProgram) > 0 && len(globalConf.SFTPD.KeyboardInteractiveHook) == 0 { //nolint: staticcheck + if len(globalConf.SFTPD.KeyboardInteractiveProgram) > 0 && len(globalConf.SFTPD.KeyboardInteractiveHook) == 0 { //nolint:staticcheck logger.Warn(logSender, "", "keyboard_interactive_auth_program is deprecated, please use keyboard_interactive_auth_hook") logger.WarnToConsole("keyboard_interactive_auth_program is deprecated, please use keyboard_interactive_auth_hook") - globalConf.SFTPD.KeyboardInteractiveHook = globalConf.SFTPD.KeyboardInteractiveProgram //nolint: staticcheck + globalConf.SFTPD.KeyboardInteractiveHook = globalConf.SFTPD.KeyboardInteractiveProgram //nolint:staticcheck } } diff --git a/config/config_test.go b/config/config_test.go index 14c20e21..b5d7719f 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -8,12 +8,13 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/drakkan/sftpgo/config" "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/httpclient" "github.com/drakkan/sftpgo/httpd" "github.com/drakkan/sftpgo/sftpd" - "github.com/stretchr/testify/assert" ) const ( @@ -173,8 +174,8 @@ func TestHookCompatibity(t *testing.T) { err := config.LoadConfig(configDir, configName) assert.NoError(t, err) providerConf := config.GetProviderConf() - providerConf.ExternalAuthProgram = "ext_auth_program" - providerConf.PreLoginProgram = "pre_login_program" + providerConf.ExternalAuthProgram = "ext_auth_program" //nolint:staticcheck + providerConf.PreLoginProgram = "pre_login_program" //nolint:staticcheck c := make(map[string]dataprovider.Config) c["data_provider"] = providerConf jsonConf, err := json.Marshal(c) @@ -189,7 +190,7 @@ func TestHookCompatibity(t *testing.T) { err = os.Remove(configFilePath) assert.NoError(t, err) sftpdConf := config.GetSFTPDConfig() - sftpdConf.KeyboardInteractiveProgram = "key_int_program" + sftpdConf.KeyboardInteractiveProgram = "key_int_program" //nolint:staticcheck cnf := make(map[string]sftpd.Configuration) cnf["sftpd"] = sftpdConf jsonConf, err = json.Marshal(cnf) diff --git a/dataprovider/bolt.go b/dataprovider/bolt.go index f90904bb..d93cba28 100644 --- a/dataprovider/bolt.go +++ b/dataprovider/bolt.go @@ -8,9 +8,10 @@ import ( "path/filepath" "time" + bolt "go.etcd.io/bbolt" + "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/utils" - bolt "go.etcd.io/bbolt" ) const ( diff --git a/dataprovider/dataprovider.go b/dataprovider/dataprovider.go index 2202d1d8..b73a89f6 100644 --- a/dataprovider/dataprovider.go +++ b/dataprovider/dataprovider.go @@ -33,6 +33,7 @@ import ( "github.com/alexedwards/argon2id" "github.com/go-chi/render" + unixcrypt "github.com/nathanaelle/password/v2" "github.com/rs/xid" "golang.org/x/crypto/bcrypt" "golang.org/x/crypto/pbkdf2" @@ -43,7 +44,6 @@ import ( "github.com/drakkan/sftpgo/metrics" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - unixcrypt "github.com/nathanaelle/password/v2" ) const ( diff --git a/dataprovider/sqlcommon.go b/dataprovider/sqlcommon.go index 5bb398f7..dff934a1 100644 --- a/dataprovider/sqlcommon.go +++ b/dataprovider/sqlcommon.go @@ -271,9 +271,9 @@ func sqlCommonGetUsers(limit int, offset int, order string, username string, dbH defer stmt.Close() var rows *sql.Rows if len(username) > 0 { - rows, err = stmt.Query(username, limit, offset) + rows, err = stmt.Query(username, limit, offset) //nolint:rowserrcheck // err is checked } else { - rows, err = stmt.Query(limit, offset) + rows, err = stmt.Query(limit, offset) //nolint:rowserrcheck // err is checked } if err == nil { defer rows.Close() diff --git a/httpd/api_quota.go b/httpd/api_quota.go index 8e190d38..b3bce523 100644 --- a/httpd/api_quota.go +++ b/httpd/api_quota.go @@ -3,10 +3,11 @@ package httpd import ( "net/http" + "github.com/go-chi/render" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/sftpd" - "github.com/go-chi/render" ) func getQuotaScans(w http.ResponseWriter, r *http.Request) { diff --git a/httpd/api_user.go b/httpd/api_user.go index 15e40f09..5ff59643 100644 --- a/httpd/api_user.go +++ b/httpd/api_user.go @@ -5,10 +5,11 @@ import ( "net/http" "strconv" - "github.com/drakkan/sftpgo/dataprovider" - "github.com/drakkan/sftpgo/utils" "github.com/go-chi/chi" "github.com/go-chi/render" + + "github.com/drakkan/sftpgo/dataprovider" + "github.com/drakkan/sftpgo/utils" ) func getUsers(w http.ResponseWriter, r *http.Request) { diff --git a/httpd/api_utils.go b/httpd/api_utils.go index 35725832..228ef435 100644 --- a/httpd/api_utils.go +++ b/httpd/api_utils.go @@ -16,11 +16,12 @@ import ( "strconv" "strings" + "github.com/go-chi/render" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/httpclient" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" - "github.com/go-chi/render" ) var ( diff --git a/httpd/auth.go b/httpd/auth.go index efd94087..6eeef637 100644 --- a/httpd/auth.go +++ b/httpd/auth.go @@ -9,10 +9,11 @@ import ( "strings" "sync" - "github.com/drakkan/sftpgo/logger" - "github.com/drakkan/sftpgo/utils" unixcrypt "github.com/nathanaelle/password/v2" "golang.org/x/crypto/bcrypt" + + "github.com/drakkan/sftpgo/logger" + "github.com/drakkan/sftpgo/utils" ) const ( diff --git a/httpd/httpd.go b/httpd/httpd.go index c2eb52df..a51899bd 100644 --- a/httpd/httpd.go +++ b/httpd/httpd.go @@ -13,10 +13,11 @@ import ( "path/filepath" "time" + "github.com/go-chi/chi" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/utils" - "github.com/go-chi/chi" ) const ( diff --git a/httpd/httpd_test.go b/httpd/httpd_test.go index 8cb9a953..a91aca47 100644 --- a/httpd/httpd_test.go +++ b/httpd/httpd_test.go @@ -46,9 +46,6 @@ const ( activeConnectionsPath = "/api/v1/connection" quotaScanPath = "/api/v1/quota_scan" versionPath = "/api/v1/version" - providerStatusPath = "/api/v1/providerstatus" - dumpDataPath = "/api/v1/dumpdata" - loadDataPath = "/api/v1/loaddata" metricsPath = "/metrics" pprofPath = "/debug/pprof/" webBasePath = "/web" @@ -94,16 +91,20 @@ func TestMain(m *testing.M) { homeBasePath = os.TempDir() logfilePath := filepath.Join(configDir, "sftpgo_api_test.log") logger.InitLogger(logfilePath, 5, 1, 28, false, zerolog.DebugLevel) - config.LoadConfig(configDir, "") + err := config.LoadConfig(configDir, "") + if err != nil { + logger.WarnToConsole("error loading configuration: %v", err) + os.Exit(1) + } providerConf := config.GetProviderConf() credentialsPath = filepath.Join(os.TempDir(), "test_credentials") providerConf.CredentialsPath = credentialsPath providerDriverName = providerConf.Driver - os.RemoveAll(credentialsPath) + os.RemoveAll(credentialsPath) //nolint:errcheck - err := dataprovider.Initialize(providerConf, configDir) + err = dataprovider.Initialize(providerConf, configDir) if err != nil { - logger.Warn(logSender, "", "error initializing data provider: %v", err) + logger.WarnToConsole("error initializing data provider: %v", err) os.Exit(1) } @@ -117,14 +118,18 @@ func TestMain(m *testing.M) { httpd.SetBaseURLAndCredentials("http://127.0.0.1:8081", "", "") backupsPath = filepath.Join(os.TempDir(), "test_backups") httpdConf.BackupsPath = backupsPath - os.MkdirAll(backupsPath, 0777) + err = os.MkdirAll(backupsPath, 0777) + if err != nil { + logger.WarnToConsole("error creating backups path: %v", err) + os.Exit(1) + } sftpd.SetDataProvider(dataProvider) httpd.SetDataProvider(dataProvider) go func() { if err := httpdConf.Initialize(configDir, true); err != nil { - logger.Error(logSender, "", "could not start HTTP server: %v", err) + logger.ErrorToConsole("could not start HTTP server: %v", err) } }() @@ -132,8 +137,16 @@ func TestMain(m *testing.M) { // now start an https server certPath := filepath.Join(os.TempDir(), "test.crt") keyPath := filepath.Join(os.TempDir(), "test.key") - ioutil.WriteFile(certPath, []byte(httpsCert), 0666) - ioutil.WriteFile(keyPath, []byte(httpsKey), 0666) + err = ioutil.WriteFile(certPath, []byte(httpsCert), 0666) + if err != nil { + logger.WarnToConsole("error writing HTTPS certificate: %v", err) + os.Exit(1) + } + err = ioutil.WriteFile(keyPath, []byte(httpsKey), 0666) + if err != nil { + logger.WarnToConsole("error writing HTTPS private key: %v", err) + os.Exit(1) + } httpdConf.BindPort = 8443 httpdConf.CertificateFile = certPath httpdConf.CertificateKeyFile = keyPath @@ -144,18 +157,18 @@ func TestMain(m *testing.M) { } }() waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort)) - httpd.ReloadTLSCertificate() + httpd.ReloadTLSCertificate() //nolint:errcheck testServer = httptest.NewServer(httpd.GetHTTPRouter()) - defer testServer.Close() + defer testServer.Close() //nolint:errcheck exitCode := m.Run() - os.Remove(logfilePath) - os.RemoveAll(backupsPath) - os.RemoveAll(credentialsPath) - os.Remove(certPath) - os.Remove(keyPath) - os.Exit(exitCode) + os.Remove(logfilePath) //nolint:errcheck + os.RemoveAll(backupsPath) //nolint:errcheck + os.RemoveAll(credentialsPath) //nolint:errcheck + os.Remove(certPath) //nolint:errcheck + os.Remove(keyPath) //nolint:errcheck + os.Exit(exitCode) //nolint:errcheck } func TestInitialization(t *testing.T) { @@ -163,7 +176,7 @@ func TestInitialization(t *testing.T) { assert.NoError(t, err) httpdConf := config.GetHTTPDConfig() httpdConf.BackupsPath = "test_backups" - httpdConf.AuthUserFile = "invalid file" + httpdConf.AuthUserFile = "invalid_file" err = httpdConf.Initialize(configDir, true) assert.Error(t, err) httpdConf.BackupsPath = backupsPath @@ -241,7 +254,7 @@ func TestAddUserNoHomeDir(t *testing.T) { func TestAddUserInvalidHomeDir(t *testing.T) { u := getTestUser() - u.HomeDir = "relative_path" + u.HomeDir = "relative_path" //nolint:goconst _, _, err := httpd.AddUser(u, http.StatusBadRequest) assert.NoError(t, err) } @@ -333,13 +346,13 @@ func TestAddUserInvalidFsConfig(t *testing.T) { assert.NoError(t, err) err = os.MkdirAll(credentialsPath, 0700) assert.NoError(t, err) - u.FsConfig.S3Config.Bucket = "test" + u.FsConfig.S3Config.Bucket = "testbucket" u.FsConfig.S3Config.Region = "eu-west-1" u.FsConfig.S3Config.AccessKey = "access-key" u.FsConfig.S3Config.AccessSecret = "access-secret" u.FsConfig.S3Config.Endpoint = "http://127.0.0.1:9000/path?a=b" - u.FsConfig.S3Config.StorageClass = "Standard" - u.FsConfig.S3Config.KeyPrefix = "/somedir/subdir/" + u.FsConfig.S3Config.StorageClass = "Standard" //nolint:goconst + u.FsConfig.S3Config.KeyPrefix = "/adir/subdir/" _, _, err = httpd.AddUser(u, http.StatusBadRequest) assert.NoError(t, err) u.FsConfig.S3Config.KeyPrefix = "" @@ -355,13 +368,13 @@ func TestAddUserInvalidFsConfig(t *testing.T) { u.FsConfig.GCSConfig.Bucket = "" _, _, err = httpd.AddUser(u, http.StatusBadRequest) assert.NoError(t, err) - u.FsConfig.GCSConfig.Bucket = "test" + u.FsConfig.GCSConfig.Bucket = "abucket" u.FsConfig.GCSConfig.StorageClass = "Standard" u.FsConfig.GCSConfig.KeyPrefix = "/somedir/subdir/" u.FsConfig.GCSConfig.Credentials = base64.StdEncoding.EncodeToString([]byte("test")) _, _, err = httpd.AddUser(u, http.StatusBadRequest) assert.NoError(t, err) - u.FsConfig.GCSConfig.KeyPrefix = "somedir/subdir/" + u.FsConfig.GCSConfig.KeyPrefix = "somedir/subdir/" //nolint:goconst u.FsConfig.GCSConfig.Credentials = "" u.FsConfig.GCSConfig.AutomaticCredentials = 0 _, _, err = httpd.AddUser(u, http.StatusBadRequest) @@ -542,8 +555,8 @@ func TestUserS3Config(t *testing.T) { user, _, err := httpd.AddUser(getTestUser(), http.StatusOK) assert.NoError(t, err) user.FsConfig.Provider = 1 - user.FsConfig.S3Config.Bucket = "test" - user.FsConfig.S3Config.Region = "us-east-1" + user.FsConfig.S3Config.Bucket = "test" //nolint:goconst + user.FsConfig.S3Config.Region = "us-east-1" //nolint:goconst user.FsConfig.S3Config.AccessKey = "Server-Access-Key" user.FsConfig.S3Config.AccessSecret = "Server-Access-Secret" user.FsConfig.S3Config.Endpoint = "http://127.0.0.1:9000" @@ -559,11 +572,11 @@ func TestUserS3Config(t *testing.T) { user, _, err = httpd.AddUser(user, http.StatusOK) assert.NoError(t, err) user.FsConfig.Provider = 1 - user.FsConfig.S3Config.Bucket = "test1" - user.FsConfig.S3Config.Region = "us-east-1" + user.FsConfig.S3Config.Bucket = "test-bucket" + user.FsConfig.S3Config.Region = "us-east-1" //nolint:goconst user.FsConfig.S3Config.AccessKey = "Server-Access-Key1" user.FsConfig.S3Config.Endpoint = "http://localhost:9000" - user.FsConfig.S3Config.KeyPrefix = "somedir/subdir" + user.FsConfig.S3Config.KeyPrefix = "somedir/subdir" //nolint:goconst user.FsConfig.S3Config.UploadConcurrency = 5 user, _, err = httpd.UpdateUser(user, http.StatusOK) assert.NoError(t, err) @@ -580,7 +593,7 @@ func TestUserS3Config(t *testing.T) { assert.NoError(t, err) // test user without access key and access secret (shared config state) user.FsConfig.Provider = 1 - user.FsConfig.S3Config.Bucket = "test1" + user.FsConfig.S3Config.Bucket = "testbucket" user.FsConfig.S3Config.Region = "us-east-1" user.FsConfig.S3Config.AccessKey = "" user.FsConfig.S3Config.AccessSecret = "" @@ -820,7 +833,8 @@ func TestProviderErrors(t *testing.T) { backupData.Users = append(backupData.Users, user) backupContent, _ := json.Marshal(backupData) backupFilePath := filepath.Join(backupsPath, "backup.json") - ioutil.WriteFile(backupFilePath, backupContent, 0666) + err = ioutil.WriteFile(backupFilePath, backupContent, 0666) + assert.NoError(t, err) _, _, err = httpd.Loaddata(backupFilePath, "", "", http.StatusInternalServerError) assert.NoError(t, err) err = os.Remove(backupFilePath) @@ -978,11 +992,14 @@ func TestHTTPSConnection(t *testing.T) { client := &http.Client{ Timeout: 5 * time.Second, } - _, err := client.Get("https://localhost:8443" + metricsPath) - assert.Error(t, err) - if !strings.Contains(err.Error(), "certificate is not valid") && - !strings.Contains(err.Error(), "certificate signed by unknown authority") { - assert.Fail(t, err.Error()) + resp, err := client.Get("https://localhost:8443" + metricsPath) + if assert.Error(t, err) { + if !strings.Contains(err.Error(), "certificate is not valid") && + !strings.Contains(err.Error(), "certificate signed by unknown authority") { + assert.Fail(t, err.Error()) + } + } else { + resp.Body.Close() } } @@ -1276,7 +1293,8 @@ func TestStartQuotaScanMock(t *testing.T) { req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON)) rr = executeRequest(req) checkResponseCode(t, http.StatusConflict, rr.Code) - sftpd.RemoveQuotaScan(user.Username) + err = sftpd.RemoveQuotaScan(user.Username) + assert.NoError(t, err) userAsJSON = getUserAsJSON(t, user) req, _ = http.NewRequest(http.MethodPost, quotaScanPath, bytes.NewBuffer(userAsJSON)) @@ -1584,7 +1602,8 @@ func TestWebUserAddMock(t *testing.T) { rr = executeRequest(req) checkResponseCode(t, http.StatusOK, rr.Code) var users []dataprovider.User - render.DecodeJSON(rr.Body, &users) + err := render.DecodeJSON(rr.Body, &users) + assert.NoError(t, err) assert.Equal(t, 1, len(users)) newUser := users[0] assert.Equal(t, user.UID, newUser.UID) @@ -1650,7 +1669,8 @@ func TestWebUserUpdateMock(t *testing.T) { rr = executeRequest(req) checkResponseCode(t, http.StatusOK, rr.Code) var users []dataprovider.User - render.DecodeJSON(rr.Body, &users) + err = render.DecodeJSON(rr.Body, &users) + assert.NoError(t, err) assert.Equal(t, 1, len(users)) updateUser := users[0] assert.Equal(t, user.HomeDir, updateUser.HomeDir) @@ -1661,9 +1681,8 @@ func TestWebUserUpdateMock(t *testing.T) { assert.Equal(t, user.GID, updateUser.GID) if val, ok := updateUser.Permissions["/otherdir"]; ok { - if !utils.IsStringInSlice(dataprovider.PermListItems, val) || !utils.IsStringInSlice(dataprovider.PermUpload, val) { - t.Error("permssions for /otherdir does not match") - } + assert.True(t, utils.IsStringInSlice(dataprovider.PermListItems, val)) + assert.True(t, utils.IsStringInSlice(dataprovider.PermUpload, val)) } else { assert.Fail(t, "user permissions must contains /otherdir", "actual: %v", updateUser.Permissions) } @@ -1672,7 +1691,8 @@ func TestWebUserUpdateMock(t *testing.T) { assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, updateUser.Filters.DeniedLoginMethods)) assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, updateUser.Filters.DeniedLoginMethods)) assert.True(t, utils.IsStringInSlice(".zip", updateUser.Filters.FileExtensions[0].DeniedExtensions)) - req, _ = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil) + req, err = http.NewRequest(http.MethodDelete, userPath+"/"+strconv.FormatInt(user.ID, 10), nil) + assert.NoError(t, err) rr = executeRequest(req) checkResponseCode(t, http.StatusOK, rr.Code) } @@ -1827,7 +1847,8 @@ func TestWebUserGCSMock(t *testing.T) { rr = executeRequest(req) checkResponseCode(t, http.StatusOK, rr.Code) var users []dataprovider.User - render.DecodeJSON(rr.Body, &users) + err = render.DecodeJSON(rr.Body, &users) + assert.NoError(t, err) assert.Equal(t, 1, len(users)) updateUser := users[0] assert.Equal(t, int64(1577836800000), updateUser.ExpirationDate) @@ -1871,11 +1892,13 @@ func TestProviderClosedMock(t *testing.T) { req, _ = http.NewRequest(http.MethodPost, webUserPath+"/0", strings.NewReader(form.Encode())) rr = executeRequest(req) checkResponseCode(t, http.StatusInternalServerError, rr.Code) - config.LoadConfig(configDir, "") + err := config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() providerConf.CredentialsPath = credentialsPath - os.RemoveAll(credentialsPath) - err := dataprovider.Initialize(providerConf, configDir) + err = os.RemoveAll(credentialsPath) + assert.NoError(t, err) + err = dataprovider.Initialize(providerConf, configDir) assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) @@ -1938,7 +1961,10 @@ func checkResponseCode(t *testing.T, expected, actual int) { func createTestFile(path string, size int64) error { baseDir := filepath.Dir(path) if _, err := os.Stat(baseDir); os.IsNotExist(err) { - os.MkdirAll(baseDir, 0777) + err = os.MkdirAll(baseDir, 0777) + if err != nil { + return err + } } content := make([]byte, size) if size > 0 { diff --git a/httpd/internal_test.go b/httpd/internal_test.go index f5232c21..0c87f8ba 100644 --- a/httpd/internal_test.go +++ b/httpd/internal_test.go @@ -14,12 +14,13 @@ import ( "strings" "testing" + "github.com/go-chi/chi" + "github.com/stretchr/testify/assert" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - "github.com/go-chi/chi" - "github.com/stretchr/testify/assert" ) const ( @@ -304,8 +305,9 @@ func TestGCSWebInvalidFormFile(t *testing.T) { form.Set("fs_provider", "2") req, _ := http.NewRequest(http.MethodPost, webUserPath, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.ParseForm() - _, err := getFsConfigFromUserPostFields(req) + err := req.ParseForm() + assert.NoError(t, err) + _, err = getFsConfigFromUserPostFields(req) assert.EqualError(t, err, http.ErrNotMultipart.Error()) } @@ -370,9 +372,10 @@ func TestBasicAuth(t *testing.T) { oldAuthPassword := authPassword authUserFile := filepath.Join(os.TempDir(), "http_users.txt") authUserData := []byte("test1:$2y$05$bcHSED7aO1cfLto6ZdDBOOKzlwftslVhtpIkRhAtSa4GuLmk5mola\n") - ioutil.WriteFile(authUserFile, authUserData, 0666) + err := ioutil.WriteFile(authUserFile, authUserData, 0666) + assert.NoError(t, err) httpAuth, _ = newBasicAuthProvider(authUserFile) - _, _, err := GetVersion(http.StatusUnauthorized) + _, _, err = GetVersion(http.StatusUnauthorized) assert.NoError(t, err) SetBaseURLAndCredentials(httpBaseURL, "test1", "password1") _, _, err = GetVersion(http.StatusOK) @@ -391,12 +394,14 @@ func TestBasicAuth(t *testing.T) { _, _, err = GetVersion(http.StatusOK) assert.Error(t, err) authUserData = append(authUserData, []byte("test3:$apr1$gLnIkRIf$Xr/6$aJfmIr$ihP4b2N2tcs/\n")...) - ioutil.WriteFile(authUserFile, authUserData, 0666) + err = ioutil.WriteFile(authUserFile, authUserData, 0666) + assert.NoError(t, err) SetBaseURLAndCredentials(httpBaseURL, "test3", "wrong_password") _, _, err = GetVersion(http.StatusUnauthorized) assert.NoError(t, err) authUserData = append(authUserData, []byte("test4:$invalid$gLnIkRIf$Xr/6$aJfmIr$ihP4b2N2tcs/\n")...) - ioutil.WriteFile(authUserFile, authUserData, 0666) + err = ioutil.WriteFile(authUserFile, authUserData, 0666) + assert.NoError(t, err) SetBaseURLAndCredentials(httpBaseURL, "test3", "password2") _, _, err = GetVersion(http.StatusUnauthorized) assert.NoError(t, err) diff --git a/httpd/router.go b/httpd/router.go index 8bcf1c18..6b2b81b1 100644 --- a/httpd/router.go +++ b/httpd/router.go @@ -4,14 +4,15 @@ import ( "net/http" "strings" - "github.com/drakkan/sftpgo/dataprovider" - "github.com/drakkan/sftpgo/logger" - "github.com/drakkan/sftpgo/sftpd" - "github.com/drakkan/sftpgo/utils" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/render" "github.com/prometheus/client_golang/prometheus/promhttp" + + "github.com/drakkan/sftpgo/dataprovider" + "github.com/drakkan/sftpgo/logger" + "github.com/drakkan/sftpgo/sftpd" + "github.com/drakkan/sftpgo/utils" ) // GetHTTPRouter returns the configured HTTP handler diff --git a/httpd/web.go b/httpd/web.go index aedea77b..b0acbaae 100644 --- a/httpd/web.go +++ b/httpd/web.go @@ -13,11 +13,12 @@ import ( "strings" "time" + "github.com/go-chi/chi" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - "github.com/go-chi/chi" ) const ( diff --git a/logger/request_logger.go b/logger/request_logger.go index 22cd8ac5..eeb84afa 100644 --- a/logger/request_logger.go +++ b/logger/request_logger.go @@ -5,9 +5,10 @@ import ( "net/http" "time" - "github.com/drakkan/sftpgo/metrics" "github.com/go-chi/chi/middleware" "github.com/rs/zerolog" + + "github.com/drakkan/sftpgo/metrics" ) // StructuredLogger defines a simple wrapper around zerolog logger. diff --git a/main.go b/main.go index 1604364e..2144df49 100644 --- a/main.go +++ b/main.go @@ -4,10 +4,11 @@ package main // import "github.com/drakkan/sftpgo" import ( - "github.com/drakkan/sftpgo/cmd" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" + + "github.com/drakkan/sftpgo/cmd" ) func main() { diff --git a/service/service.go b/service/service.go index 706ec451..923ecf6b 100644 --- a/service/service.go +++ b/service/service.go @@ -11,14 +11,15 @@ import ( "syscall" "time" + "github.com/grandcat/zeroconf" + "github.com/rs/zerolog" + "github.com/drakkan/sftpgo/config" "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/httpd" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" - "github.com/grandcat/zeroconf" - "github.com/rs/zerolog" ) const ( diff --git a/service/service_windows.go b/service/service_windows.go index 71b579d0..d82290e9 100644 --- a/service/service_windows.go +++ b/service/service_windows.go @@ -7,13 +7,13 @@ import ( "strings" "time" - "github.com/drakkan/sftpgo/dataprovider" - "github.com/drakkan/sftpgo/httpd" - "github.com/drakkan/sftpgo/logger" - "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/eventlog" "golang.org/x/sys/windows/svc/mgr" + + "github.com/drakkan/sftpgo/dataprovider" + "github.com/drakkan/sftpgo/httpd" + "github.com/drakkan/sftpgo/logger" ) const ( diff --git a/sftpd/handler.go b/sftpd/handler.go index 9865f781..3cd5527e 100644 --- a/sftpd/handler.go +++ b/sftpd/handler.go @@ -8,13 +8,12 @@ import ( "sync" "time" - "github.com/drakkan/sftpgo/vfs" + "github.com/pkg/sftp" "golang.org/x/crypto/ssh" "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" - - "github.com/pkg/sftp" + "github.com/drakkan/sftpgo/vfs" ) // Connection details for an authenticated user diff --git a/sftpd/internal_test.go b/sftpd/internal_test.go index 9572a54e..122be70f 100644 --- a/sftpd/internal_test.go +++ b/sftpd/internal_test.go @@ -10,18 +10,21 @@ import ( "os" "path/filepath" "runtime" - "strings" "sync" "testing" "time" + "github.com/eikenb/pipeat" + "github.com/pkg/sftp" + "github.com/stretchr/testify/assert" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - "github.com/eikenb/pipeat" - "github.com/pkg/sftp" ) +const osWindows = "windows" + type MockChannel struct { Buffer *bytes.Buffer StdErrBuffer *bytes.Buffer @@ -132,37 +135,26 @@ func TestNewActionNotification(t *testing.T) { Bucket: "gcsbucket", } a := newActionNotification(user, operationDownload, "path", "target", "", 123, nil) - if a.Username != "username" { - t.Errorf("unexpected username") - } - if len(a.Bucket) > 0 { - t.Errorf("unexpected bucket") - } - if len(a.Endpoint) > 0 { - t.Errorf("unexpected endpoint") - } + assert.Equal(t, user.Username, a.Username) + assert.Equal(t, 0, len(a.Bucket)) + assert.Equal(t, 0, len(a.Endpoint)) + user.FsConfig.Provider = 1 a = newActionNotification(user, operationDownload, "path", "target", "", 123, nil) - if a.Bucket != "s3bucket" { - t.Errorf("unexpected s3 bucket") - } - if a.Endpoint != "endpoint" { - t.Errorf("unexpected endpoint") - } + assert.Equal(t, "s3bucket", a.Bucket) + assert.Equal(t, "endpoint", a.Endpoint) + user.FsConfig.Provider = 2 a = newActionNotification(user, operationDownload, "path", "target", "", 123, nil) - if a.Bucket != "gcsbucket" { - t.Errorf("unexpected gcs bucket") - } - if len(a.Endpoint) > 0 { - t.Errorf("unexpected endpoint") - } + assert.Equal(t, "gcsbucket", a.Bucket) + assert.Equal(t, 0, len(a.Endpoint)) } func TestWrongActions(t *testing.T) { actionsCopy := actions + badCommand := "/bad/command" - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { badCommand = "C:\\bad\\command" } actions = Actions{ @@ -174,19 +166,15 @@ func TestWrongActions(t *testing.T) { Username: "username", } err := executeAction(newActionNotification(user, operationDownload, "path", "", "", 0, nil)) - if err == nil { - t.Errorf("action with bad command must fail") - } + assert.Error(t, err, "action with bad command must fail") + err = executeAction(newActionNotification(user, operationDelete, "path", "", "", 0, nil)) - if err != nil { - t.Errorf("action not configured must silently fail") - } + assert.NoError(t, err) actions.Command = "" actions.HTTPNotificationURL = "http://foo\x7f.com/" err = executeAction(newActionNotification(user, operationDownload, "path", "", "", 0, nil)) - if err == nil { - t.Errorf("action with bad url must fail") - } + assert.Error(t, err, "action with bad url must fail") + actions = actionsCopy } @@ -201,9 +189,7 @@ func TestActionHTTP(t *testing.T) { Username: "username", } err := executeAction(newActionNotification(user, operationDownload, "path", "", "", 0, nil)) - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) actions = actionsCopy } @@ -211,16 +197,12 @@ func TestActionHTTP(t *testing.T) { func TestRemoveNonexistentTransfer(t *testing.T) { transfer := Transfer{} err := removeTransfer(&transfer) - if err == nil { - t.Errorf("remove nonexistent transfer must fail") - } + assert.Error(t, err, "remove nonexistent transfer must fail") } func TestRemoveNonexistentQuotaScan(t *testing.T) { err := RemoveQuotaScan("username") - if err == nil { - t.Errorf("remove nonexistent transfer must fail") - } + assert.Error(t, err, "remove nonexistent quota scan must fail") } func TestGetOSOpenFlags(t *testing.T) { @@ -228,19 +210,19 @@ func TestGetOSOpenFlags(t *testing.T) { flags.Write = true flags.Excl = true osFlags := getOSOpenFlags(flags) - if osFlags&os.O_WRONLY == 0 || osFlags&os.O_EXCL == 0 { - t.Errorf("error getting os flags from sftp file open flags") - } + assert.NotEqual(t, 0, osFlags&os.O_WRONLY) + assert.NotEqual(t, 0, osFlags&os.O_EXCL) + flags.Append = true // append flag should be ignored to allow resume - if osFlags&os.O_WRONLY == 0 || osFlags&os.O_EXCL == 0 { - t.Errorf("error getting os flags from sftp file open flags") - } + assert.NotEqual(t, 0, osFlags&os.O_WRONLY) + assert.NotEqual(t, 0, osFlags&os.O_EXCL) } func TestUploadResumeInvalidOffset(t *testing.T) { - testfile := "testfile" - file, _ := os.Create(testfile) + testfile := "testfile" //nolint:goconst + file, err := os.Create(testfile) + assert.NoError(t, err) transfer := Transfer{ file: file, path: file.Name(), @@ -260,20 +242,20 @@ func TestUploadResumeInvalidOffset(t *testing.T) { minWriteOffset: 10, lock: new(sync.Mutex), } - _, err := transfer.WriteAt([]byte("test"), 0) - if err == nil { - t.Errorf("upload with invalid offset must fail") - } + _, err = transfer.WriteAt([]byte("test"), 0) + assert.Error(t, err, "upload with invalid offset must fail") err = transfer.Close() - if err == nil || !strings.Contains(err.Error(), "Invalid write offset") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), "Invalid write offset") } - os.Remove(testfile) + err = os.Remove(testfile) + assert.NoError(t, err) } func TestReadWriteErrors(t *testing.T) { testfile := "testfile" - file, _ := os.Create(testfile) + file, err := os.Create(testfile) + assert.NoError(t, err) transfer := Transfer{ file: file, path: file.Name(), @@ -294,21 +276,18 @@ func TestReadWriteErrors(t *testing.T) { expectedSize: 10, lock: new(sync.Mutex), } - file.Close() - _, err := transfer.WriteAt([]byte("test"), 0) - if err == nil { - t.Error("writing to closed file must fail") - } + err = file.Close() + assert.NoError(t, err) + _, err = transfer.WriteAt([]byte("test"), 0) + assert.Error(t, err, "writing to closed file must fail") buf := make([]byte, 32768) _, err = transfer.ReadAt(buf, 0) - if err == nil { - t.Error("reading from a closed file must fail") - } + assert.Error(t, err, "reading from a closed file must fail") err = transfer.Close() - if err == nil { - t.Error("upoload must fail the expected size does not match") - } - r, _, _ := pipeat.Pipe() + assert.Error(t, err, "upoload must fail: the expected size does not match") + + r, _, err := pipeat.Pipe() + assert.NoError(t, err) transfer = Transfer{ readerAt: r, writerAt: nil, @@ -327,12 +306,13 @@ func TestReadWriteErrors(t *testing.T) { isFinished: false, lock: new(sync.Mutex), } - transfer.closeIO() + err = transfer.closeIO() + assert.NoError(t, err) _, err = transfer.ReadAt(buf, 0) - if err == nil { - t.Error("reading from a closed pipe must fail") - } - r, w, _ := pipeat.Pipe() + assert.Error(t, err, "reading from a closed pipe must fail") + + r, w, err := pipeat.Pipe() + assert.NoError(t, err) transfer = Transfer{ readerAt: nil, writerAt: w, @@ -351,18 +331,21 @@ func TestReadWriteErrors(t *testing.T) { isFinished: false, lock: new(sync.Mutex), } - r.Close() - transfer.closeIO() + err = r.Close() + assert.NoError(t, err) + err = transfer.closeIO() + assert.NoError(t, err) _, err = transfer.WriteAt([]byte("test"), 0) - if err == nil { - t.Error("writing to closed pipe must fail") - } - os.Remove(testfile) + assert.Error(t, err, "writing to closed pipe must fail") + + err = os.Remove(testfile) + assert.NoError(t, err) } func TestTransferCancelFn(t *testing.T) { testfile := "testfile" - file, _ := os.Create(testfile) + file, err := os.Create(testfile) + assert.NoError(t, err) isCancelled := false cancelFn := func() { isCancelled = true @@ -388,19 +371,21 @@ func TestTransferCancelFn(t *testing.T) { expectedSize: 10, lock: new(sync.Mutex), } - transfer.TransferError(errors.New("fake error, this will trigger cancelFn")) - transfer.Close() - if !isCancelled { - t.Error("cancelFn not called") - } - os.Remove(testfile) + errFake := errors.New("fake error, this will trigger cancelFn") + transfer.TransferError(errFake) + err = transfer.Close() + assert.EqualError(t, err, errFake.Error()) + assert.True(t, isCancelled, "cancelFn not called!") + + err = os.Remove(testfile) + assert.NoError(t, err) } func TestMockFsErrors(t *testing.T) { errFake := errors.New("fake error") fs := newMockOsFs(errFake, errFake, false, "123", os.TempDir()) u := dataprovider.User{} - u.Username = "test" + u.Username = "test_username" u.Permissions = make(map[string][]string) u.Permissions["/"] = []string{dataprovider.PermAny} u.HomeDir = os.TempDir() @@ -410,24 +395,22 @@ func TestMockFsErrors(t *testing.T) { } testfile := filepath.Join(u.HomeDir, "testfile") request := sftp.NewRequest("Remove", testfile) - ioutil.WriteFile(testfile, []byte("test"), 0666) - err := c.handleSFTPRemove(testfile, request) - if err != sftp.ErrSSHFxFailure { - t.Errorf("unexpected error: %v", err) - } + err := ioutil.WriteFile(testfile, []byte("test"), 0666) + assert.NoError(t, err) + err = c.handleSFTPRemove(testfile, request) + assert.EqualError(t, err, sftp.ErrSSHFxFailure.Error()) _, err = c.Filewrite(request) - if err != sftp.ErrSSHFxFailure { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, sftp.ErrSSHFxFailure.Error()) + var flags sftp.FileOpenFlags flags.Write = true flags.Trunc = false flags.Append = true _, err = c.handleSFTPUploadToExistingFile(flags, testfile, testfile, 0, false) - if err != sftp.ErrSSHFxOpUnsupported { - t.Errorf("unexpected error: %v", err) - } - os.Remove(testfile) + assert.EqualError(t, err, sftp.ErrSSHFxOpUnsupported.Error()) + + err = os.Remove(testfile) + assert.NoError(t, err) } func TestUploadFiles(t *testing.T) { @@ -440,103 +423,87 @@ func TestUploadFiles(t *testing.T) { flags.Write = true flags.Trunc = true _, err := c.handleSFTPUploadToExistingFile(flags, "missing_path", "other_missing_path", 0, false) - if err == nil { - t.Errorf("upload to existing file must fail if one or both paths are invalid") - } + assert.Error(t, err, "upload to existing file must fail if one or both paths are invalid") + uploadMode = uploadModeStandard _, err = c.handleSFTPUploadToExistingFile(flags, "missing_path", "other_missing_path", 0, false) - if err == nil { - t.Errorf("upload to existing file must fail if one or both paths are invalid") - } + assert.Error(t, err, "upload to existing file must fail if one or both paths are invalid") + missingFile := "missing/relative/file.txt" - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { missingFile = "missing\\relative\\file.txt" } _, err = c.handleSFTPUploadToNewFile(".", missingFile, false) - if err == nil { - t.Errorf("upload new file in missing path must fail") - } + assert.Error(t, err, "upload new file in missing path must fail") + c.fs = newMockOsFs(nil, nil, false, "123", os.TempDir()) - f, _ := ioutil.TempFile("", "temp") - f.Close() + f, err := ioutil.TempFile("", "temp") + assert.NoError(t, err) + err = f.Close() + assert.NoError(t, err) + _, err = c.handleSFTPUploadToExistingFile(flags, f.Name(), f.Name(), 123, false) - if err != nil { - t.Errorf("unexpected error: %v", err) + assert.NoError(t, err) + if assert.Equal(t, 1, len(activeTransfers)) { + transfer := activeTransfers[0] + assert.Equal(t, int64(123), transfer.initialSize) + err = transfer.Close() + assert.NoError(t, err) + assert.Equal(t, 0, len(activeTransfers)) } - if len(activeTransfers) != 1 { - t.Errorf("unexpected number of transfer, expected 1, current: %v", len(activeTransfers)) - } - transfer := activeTransfers[0] - if transfer.initialSize != 123 { - t.Errorf("unexpected initial size: %v", transfer.initialSize) - } - err = transfer.Close() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(activeTransfers) != 0 { - t.Errorf("unexpected number of transfer, expected 0, current: %v", len(activeTransfers)) - } - os.Remove(f.Name()) + err = os.Remove(f.Name()) + assert.NoError(t, err) uploadMode = oldUploadMode } func TestWithInvalidHome(t *testing.T) { u := dataprovider.User{} - u.HomeDir = "home_rel_path" + u.HomeDir = "home_rel_path" //nolint:goconst _, err := loginUser(u, dataprovider.SSHLoginMethodPassword, "", nil) - if err == nil { - t.Errorf("login a user with an invalid home_dir must fail") - } + assert.Error(t, err, "login a user with an invalid home_dir must fail") + u.HomeDir = os.TempDir() - fs, _ := u.GetFilesystem("123") + fs, err := u.GetFilesystem("123") + assert.NoError(t, err) c := Connection{ User: u, fs: fs, } _, err = c.fs.ResolvePath("../upper_path") - if err == nil { - t.Errorf("tested path is not a home subdir") - } + assert.Error(t, err, "tested path is not a home subdir") } func TestSFTPCmdTargetPath(t *testing.T) { u := dataprovider.User{} - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { u.HomeDir = "C:\\invalid_home" } else { u.HomeDir = "/invalid_home" } - u.Username = "test" + u.Username = "testuser" u.Permissions = make(map[string][]string) u.Permissions["/"] = []string{dataprovider.PermAny} - fs, _ := u.GetFilesystem("123") + fs, err := u.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ User: u, fs: fs, } - _, err := connection.getSFTPCmdTargetPath("invalid_path") - if err != sftp.ErrSSHFxNoSuchFile { - t.Errorf("getSFTPCmdTargetPath must fal with the expected error: %v", err) - } + _, err = connection.getSFTPCmdTargetPath("invalid_path") + assert.EqualError(t, err, sftp.ErrSSHFxNoSuchFile.Error()) } func TestGetSFTPErrorFromOSError(t *testing.T) { err := os.ErrNotExist fs := vfs.NewOsFs("", os.TempDir(), nil) err = vfs.GetSFTPError(fs, err) - if err != sftp.ErrSSHFxNoSuchFile { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, sftp.ErrSSHFxNoSuchFile.Error()) + err = os.ErrPermission err = vfs.GetSFTPError(fs, err) - if err != sftp.ErrSSHFxPermissionDenied { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, sftp.ErrSSHFxPermissionDenied.Error()) err = vfs.GetSFTPError(fs, nil) - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) } func TestSetstatModeIgnore(t *testing.T) { @@ -544,9 +511,7 @@ func TestSetstatModeIgnore(t *testing.T) { setstatMode = 1 connection := Connection{} err := connection.handleSFTPSetstat("invalid", nil) - if err != nil { - t.Errorf("unexpected error: %v setstat should be silently ignore in mode 1", err) - } + assert.NoError(t, err) setstatMode = originalMode } @@ -561,21 +526,15 @@ func TestSFTPGetUsedQuota(t *testing.T) { connection := Connection{ User: u, } - res := connection.hasSpace(false) - if res != false { - t.Errorf("has space must return false if the user is invalid") - } + assert.False(t, connection.hasSpace(false)) } func TestSupportedSSHCommands(t *testing.T) { cmds := GetSupportedSSHCommands() - if len(cmds) != len(supportedSSHCommands) { - t.Errorf("supported ssh commands does not match") - } + assert.Equal(t, len(supportedSSHCommands), len(cmds)) + for _, c := range cmds { - if !utils.IsStringInSlice(c, supportedSSHCommands) { - t.Errorf("invalid ssh command: %v", c) - } + assert.True(t, utils.IsStringInSlice(c, supportedSSHCommands)) } } @@ -595,78 +554,48 @@ func TestSSHCommandPath(t *testing.T) { connection: connection, args: []string{}, } - path := sshCommand.getDestPath() - if path != "" { - t.Errorf("path must be empty") - } + assert.Equal(t, "", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "/tmp/../path"} - path = sshCommand.getDestPath() - if path != "/path" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/path", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "/tmp/"} - path = sshCommand.getDestPath() - if path != "/tmp/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/tmp/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "tmp/"} - path = sshCommand.getDestPath() - if path != "/tmp/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/tmp/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "/tmp/../../../path"} - path = sshCommand.getDestPath() - if path != "/path" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/path", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", ".."} - path = sshCommand.getDestPath() - if path != "/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "."} - path = sshCommand.getDestPath() - if path != "/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "//"} - path = sshCommand.getDestPath() - if path != "/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "../.."} - path = sshCommand.getDestPath() - if path != "/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/", sshCommand.getDestPath()) + sshCommand.args = []string{"-t", "/.."} - path = sshCommand.getDestPath() - if path != "/" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/", sshCommand.getDestPath()) + sshCommand.args = []string{"-f", "/a space.txt"} - path = sshCommand.getDestPath() - if path != "/a space.txt" { - t.Errorf("unexpected path: %v", path) - } + assert.Equal(t, "/a space.txt", sshCommand.getDestPath()) } func TestSSHParseCommandPayload(t *testing.T) { cmd := "command -a -f /ab\\ à/some\\ spaces\\ \\ \\(\\).txt" name, args, _ := parseCommandPayload(cmd) - if name != "command" { - t.Errorf("unexpected command: %v", name) - } - if len(args) != 3 { - t.Errorf("unexpected number of arguments %v/3", len(args)) - } - if args[2] != "/ab à/some spaces ().txt" { - t.Errorf("command parsing error, expected arguments not found: %v", args) - } + assert.Equal(t, "command", name) + assert.Equal(t, 3, len(args)) + assert.Equal(t, "/ab à/some spaces ().txt", args[2]) + _, _, err := parseCommandPayload("") - if err == nil { - t.Error("parsing invalid command must fail") - } + assert.Error(t, err, "parsing invalid command must fail") } func TestSSHCommandErrors(t *testing.T) { @@ -679,12 +608,19 @@ func TestSSHCommandErrors(t *testing.T) { ReadError: readErr, } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() user := dataprovider.User{} user.Permissions = make(map[string][]string) user.Permissions["/"] = []string{dataprovider.PermAny} - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -696,77 +632,68 @@ func TestSSHCommandErrors(t *testing.T) { connection: connection, args: []string{}, } - err := cmd.handle() - if err == nil { - t.Errorf("ssh command must fail, we are sending a fake error") - } + err = cmd.handle() + assert.Error(t, err, "ssh command must fail, we are sending a fake error") + cmd = sshCommand{ command: "md5sum", connection: connection, args: []string{"/../../test_file.dat"}, } err = cmd.handle() - if err == nil { - t.Errorf("ssh command must fail, we are requesting an invalid path") - } + assert.Error(t, err, "ssh command must fail, we are requesting an invalid path") + cmd = sshCommand{ command: "git-receive-pack", connection: connection, args: []string{"/../../testrepo"}, } err = cmd.handle() - if err == nil { - t.Errorf("ssh command must fail, we are requesting an invalid path") - } + assert.Error(t, err, "ssh command must fail, we are requesting an invalid path") + cmd.connection.User.HomeDir = os.TempDir() cmd.connection.User.QuotaFiles = 1 cmd.connection.User.UsedQuotaFiles = 2 - fs, _ = cmd.connection.User.GetFilesystem("123") + fs, err = cmd.connection.User.GetFilesystem("123") + assert.NoError(t, err) cmd.connection.fs = fs err = cmd.handle() - if err != errQuotaExceeded { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errQuotaExceeded.Error()) + cmd.connection.User.QuotaFiles = 0 cmd.connection.User.UsedQuotaFiles = 0 cmd.connection.User.Permissions = make(map[string][]string) cmd.connection.User.Permissions["/"] = []string{dataprovider.PermListItems} err = cmd.handle() - if err != errPermissionDenied { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errPermissionDenied.Error()) + cmd.connection.User.Permissions["/"] = []string{dataprovider.PermAny} cmd.command = "invalid_command" command, err := cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) + err = cmd.executeSystemCommand(command) - if err == nil { - t.Errorf("invalid command must fail") - } + assert.Error(t, err, "invalid command must fail") + command, err = cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - command.cmd.StderrPipe() + assert.NoError(t, err) + + _, err = command.cmd.StderrPipe() + assert.NoError(t, err) + err = cmd.executeSystemCommand(command) - if err == nil { - t.Errorf("command must fail, pipe was already assigned") - } + assert.Error(t, err, "command must fail, pipe was already assigned") + err = cmd.executeSystemCommand(command) - if err == nil { - t.Errorf("command must fail, pipe was already assigned") - } + assert.Error(t, err, "command must fail, pipe was already assigned") + command, err = cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - command.cmd.StdoutPipe() + assert.NoError(t, err) + + _, err = command.cmd.StdoutPipe() + assert.NoError(t, err) err = cmd.executeSystemCommand(command) - if err == nil { - t.Errorf("command must fail, pipe was already assigned") - } + assert.Error(t, err, "command must fail, pipe was already assigned") } func TestCommandsWithExtensionsFilter(t *testing.T) { @@ -792,7 +719,8 @@ func TestCommandsWithExtensionsFilter(t *testing.T) { }, } - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -804,46 +732,40 @@ func TestCommandsWithExtensionsFilter(t *testing.T) { connection: connection, args: []string{"subdir/test.png"}, } - err := cmd.handleHashCommands() - if err != errPermissionDenied { - t.Errorf("unexpected error: %v", err) - } + err = cmd.handleHashCommands() + assert.EqualError(t, err, errPermissionDenied.Error()) + cmd = sshCommand{ command: "rsync", connection: connection, args: []string{"--server", "-vlogDtprze.iLsfxC", ".", "/"}, } _, err = cmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errUnsupportedConfig.Error()) + cmd = sshCommand{ command: "git-receive-pack", connection: connection, args: []string{"/subdir"}, } _, err = cmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errUnsupportedConfig.Error()) + cmd = sshCommand{ command: "git-receive-pack", connection: connection, args: []string{"/subdir/dir"}, } _, err = cmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errUnsupportedConfig.Error()) + cmd = sshCommand{ command: "git-receive-pack", connection: connection, args: []string{"/adir/subdir"}, } _, err = cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) } func TestSSHCommandsRemoteFs(t *testing.T) { @@ -854,12 +776,25 @@ func TestSSHCommandsRemoteFs(t *testing.T) { StdErrBuffer: bytes.NewBuffer(stdErrBuf), } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() user := dataprovider.User{} user.FsConfig = dataprovider.Filesystem{ - Provider: 1} - fs, _ := user.GetFilesystem("123") + Provider: 1, + S3Config: vfs.S3FsConfig{ + Bucket: "s3bucket", + Endpoint: "endpoint", + Region: "eu-west-1", + }, + } + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -871,18 +806,14 @@ func TestSSHCommandsRemoteFs(t *testing.T) { connection: connection, args: []string{}, } - err := cmd.handleHashCommands() - if err == nil { - t.Error("command must fail for a non local filesystem") - } + err = cmd.handleHashCommands() + assert.Error(t, err, "command must fail for a non local filesystem") + command, err := cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) + err = cmd.executeSystemCommand(command) - if err == nil { - t.Error("command must fail for a non local filesystem") - } + assert.Error(t, err, "command must fail for a non local filesystem") } func TestSSHCommandQuotaScan(t *testing.T) { @@ -895,8 +826,14 @@ func TestSSHCommandQuotaScan(t *testing.T) { ReadError: readErr, } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() permissions := make(map[string][]string) permissions["/"] = []string{dataprovider.PermAny} user := dataprovider.User{ @@ -904,7 +841,8 @@ func TestSSHCommandQuotaScan(t *testing.T) { QuotaFiles: 1, HomeDir: "invalid_path", } - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -916,10 +854,8 @@ func TestSSHCommandQuotaScan(t *testing.T) { connection: connection, args: []string{"/testrepo"}, } - err := cmd.rescanHomeDir() - if err == nil { - t.Errorf("scanning an invalid home dir must fail") - } + err = cmd.rescanHomeDir() + assert.Error(t, err, "scanning an invalid home dir must fail") } func TestGitVirtualFolders(t *testing.T) { @@ -929,7 +865,8 @@ func TestGitVirtualFolders(t *testing.T) { Permissions: permissions, HomeDir: os.TempDir(), } - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) conn := Connection{ User: user, fs: fs, @@ -943,10 +880,9 @@ func TestGitVirtualFolders(t *testing.T) { VirtualPath: "/vdir", MappedPath: os.TempDir(), }) - _, err := cmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + _, err = cmd.getSystemCommand() + assert.EqualError(t, err, errUnsupportedConfig.Error()) + cmd.connection.User.VirtualFolders = nil cmd.connection.User.VirtualFolders = append(cmd.connection.User.VirtualFolders, vfs.VirtualFolder{ VirtualPath: "/vdir", @@ -954,14 +890,11 @@ func TestGitVirtualFolders(t *testing.T) { }) cmd.args = []string{"/vdir/subdir"} _, err = cmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errUnsupportedConfig.Error()) + cmd.args = []string{"/adir/subdir"} _, err = cmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) } func TestRsyncOptions(t *testing.T) { @@ -971,7 +904,8 @@ func TestRsyncOptions(t *testing.T) { Permissions: permissions, HomeDir: os.TempDir(), } - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) conn := Connection{ User: user, fs: fs, @@ -982,16 +916,16 @@ func TestRsyncOptions(t *testing.T) { args: []string{"--server", "-vlogDtprze.iLsfxC", ".", "/"}, } cmd, err := sshCmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !utils.IsStringInSlice("--safe-links", cmd.cmd.Args) { - t.Errorf("--safe-links must be added if the user has the create symlinks permission") - } + assert.NoError(t, err) + assert.True(t, utils.IsStringInSlice("--safe-links", cmd.cmd.Args), + "--safe-links must be added if the user has the create symlinks permission") + permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermCreateDirs, dataprovider.PermListItems, dataprovider.PermOverwrite, dataprovider.PermDelete, dataprovider.PermRename} user.Permissions = permissions - fs, _ = user.GetFilesystem("123") + fs, err = user.GetFilesystem("123") + assert.NoError(t, err) + conn = Connection{ User: user, fs: fs, @@ -1002,20 +936,16 @@ func TestRsyncOptions(t *testing.T) { args: []string{"--server", "-vlogDtprze.iLsfxC", ".", "/"}, } cmd, err = sshCmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if !utils.IsStringInSlice("--munge-links", cmd.cmd.Args) { - t.Errorf("--munge-links must be added if the user has the create symlinks permission") - } + assert.NoError(t, err) + assert.True(t, utils.IsStringInSlice("--munge-links", cmd.cmd.Args), + "--munge-links must be added if the user has the create symlinks permission") + sshCmd.connection.User.VirtualFolders = append(sshCmd.connection.User.VirtualFolders, vfs.VirtualFolder{ VirtualPath: "/vdir", MappedPath: os.TempDir(), }) _, err = sshCmd.getSystemCommand() - if err != errUnsupportedConfig { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errUnsupportedConfig.Error()) } func TestSystemCommandErrors(t *testing.T) { @@ -1030,15 +960,22 @@ func TestSystemCommandErrors(t *testing.T) { WriteError: writeErr, } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() permissions := make(map[string][]string) permissions["/"] = []string{dataprovider.PermAny} user := dataprovider.User{ Permissions: permissions, HomeDir: os.TempDir(), } - fs, _ := user.GetFilesystem("123") + fs, err := user.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -1051,13 +988,13 @@ func TestSystemCommandErrors(t *testing.T) { args: []string{"/"}, } systemCmd, err := sshCmd.getSystemCommand() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) + systemCmd.cmd.Dir = os.TempDir() // FIXME: the command completes but the fake client was unable to read the response - // no error is reported in this case - sshCmd.executeSystemCommand(systemCmd) + // no error is reported in this case. We can see that the expected code is executed + // reading the test coverage + sshCmd.executeSystemCommand(systemCmd) //nolint:errcheck mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1072,9 +1009,7 @@ func TestSystemCommandErrors(t *testing.T) { destBuff := make([]byte, 65535) dst := bytes.NewBuffer(destBuff) _, err = transfer.copyFromReaderToWriter(dst, sshCmd.connection.channel, 0) - if err != readErr { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, readErr.Error()) mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1084,9 +1019,7 @@ func TestSystemCommandErrors(t *testing.T) { } sshCmd.connection.channel = &mockSSHChannel _, err = transfer.copyFromReaderToWriter(dst, sshCmd.connection.channel, 1) - if err != errQuotaExceeded { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errQuotaExceeded.Error()) mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1097,9 +1030,7 @@ func TestSystemCommandErrors(t *testing.T) { } sshCmd.connection.channel = &mockSSHChannel _, err = transfer.copyFromReaderToWriter(sshCmd.connection.channel, dst, 0) - if err != io.ErrShortWrite { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, io.ErrShortWrite.Error()) } func TestTransferUpdateQuota(t *testing.T) { @@ -1108,9 +1039,7 @@ func TestTransferUpdateQuota(t *testing.T) { bytesReceived: 123, lock: new(sync.Mutex)} transfer.TransferError(errors.New("fake error")) - if transfer.updateQuota(1) { - t.Errorf("update quota must fail, there is a error and this is a remote upload") - } + assert.False(t, transfer.updateQuota(1)) } func TestGetConnectionInfo(t *testing.T) { @@ -1123,66 +1052,52 @@ func TestGetConnectionInfo(t *testing.T) { SSHCommand: "sha1sum /test_file.dat", } info := c.GetConnectionInfo() - if !strings.Contains(info, "sha1sum /test_file.dat") { - t.Errorf("ssh command not found in connection info") - } + assert.Contains(t, info, "sha1sum /test_file.dat") } func TestSCPFileMode(t *testing.T) { mode := getFileModeAsString(0, true) - if mode != "0755" { - t.Errorf("invalid file mode: %v expected: 0755", mode) - } + assert.Equal(t, "0755", mode) + mode = getFileModeAsString(0700, true) - if mode != "0700" { - t.Errorf("invalid file mode: %v expected: 0700", mode) - } + assert.Equal(t, "0700", mode) + mode = getFileModeAsString(0750, true) - if mode != "0750" { - t.Errorf("invalid file mode: %v expected: 0750", mode) - } + assert.Equal(t, "0750", mode) + mode = getFileModeAsString(0777, true) - if mode != "0777" { - t.Errorf("invalid file mode: %v expected: 0777", mode) - } + assert.Equal(t, "0777", mode) + mode = getFileModeAsString(0640, false) - if mode != "0640" { - t.Errorf("invalid file mode: %v expected: 0640", mode) - } + assert.Equal(t, "0640", mode) + mode = getFileModeAsString(0600, false) - if mode != "0600" { - t.Errorf("invalid file mode: %v expected: 0600", mode) - } + assert.Equal(t, "0600", mode) + mode = getFileModeAsString(0, false) - if mode != "0644" { - t.Errorf("invalid file mode: %v expected: 0644", mode) - } + assert.Equal(t, "0644", mode) + fileMode := uint32(0777) fileMode = fileMode | uint32(os.ModeSetgid) fileMode = fileMode | uint32(os.ModeSetuid) fileMode = fileMode | uint32(os.ModeSticky) mode = getFileModeAsString(os.FileMode(fileMode), false) - if mode != "7777" { - t.Errorf("invalid file mode: %v expected: 7777", mode) - } + assert.Equal(t, "7777", mode) + fileMode = uint32(0644) fileMode = fileMode | uint32(os.ModeSetgid) mode = getFileModeAsString(os.FileMode(fileMode), false) - if mode != "4644" { - t.Errorf("invalid file mode: %v expected: 4644", mode) - } + assert.Equal(t, "4644", mode) + fileMode = uint32(0600) fileMode = fileMode | uint32(os.ModeSetuid) mode = getFileModeAsString(os.FileMode(fileMode), false) - if mode != "2600" { - t.Errorf("invalid file mode: %v expected: 2600", mode) - } + assert.Equal(t, "2600", mode) + fileMode = uint32(0044) fileMode = fileMode | uint32(os.ModeSticky) mode = getFileModeAsString(os.FileMode(fileMode), false) - if mode != "1044" { - t.Errorf("invalid file mode: %v expected: 1044", mode) - } + assert.Equal(t, "1044", mode) } func TestSCPParseUploadMessage(t *testing.T) { @@ -1205,21 +1120,16 @@ func TestSCPParseUploadMessage(t *testing.T) { }, } _, _, err := scpCommand.parseUploadMessage("invalid") - if err == nil { - t.Errorf("parsing invalid upload message must fail") - } + assert.Error(t, err, "parsing invalid upload message must fail") + _, _, err = scpCommand.parseUploadMessage("D0755 0") - if err == nil { - t.Errorf("parsing incomplete upload message must fail") - } + assert.Error(t, err, "parsing incomplete upload message must fail") + _, _, err = scpCommand.parseUploadMessage("D0755 invalidsize testdir") - if err == nil { - t.Errorf("parsing upload message with invalid size must fail") - } + assert.Error(t, err, "parsing upload message with invalid size must fail") + _, _, err = scpCommand.parseUploadMessage("D0755 0 ") - if err == nil { - t.Errorf("parsing upload message with invalid name must fail") - } + assert.Error(t, err, "parsing upload message with invalid name must fail") } func TestSCPProtocolMessages(t *testing.T) { @@ -1244,21 +1154,17 @@ func TestSCPProtocolMessages(t *testing.T) { }, } _, err := scpCommand.readProtocolMessage() - if err == nil || err != readErr { - t.Errorf("read protocol message must fail, we are sending a fake error") - } + assert.EqualError(t, err, readErr.Error()) + err = scpCommand.sendConfirmationMessage() - if err != writeErr { - t.Errorf("write confirmation message must fail, we are sending a fake error") - } + assert.EqualError(t, err, writeErr.Error()) + err = scpCommand.sendProtocolMessage("E\n") - if err != writeErr { - t.Errorf("write confirmation message must fail, we are sending a fake error") - } + assert.EqualError(t, err, writeErr.Error()) + _, err = scpCommand.getNextUploadProtocolMessage() - if err == nil || err != readErr { - t.Errorf("read next upload protocol message must fail, we are sending a fake read error") - } + assert.EqualError(t, err, readErr.Error()) + mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer([]byte("T1183832947 0 1183833773 0\n")), StdErrBuffer: bytes.NewBuffer(stdErrBuf), @@ -1267,9 +1173,8 @@ func TestSCPProtocolMessages(t *testing.T) { } scpCommand.connection.channel = &mockSSHChannel _, err = scpCommand.getNextUploadProtocolMessage() - if err == nil || err != writeErr { - t.Errorf("read next upload protocol message must fail, we are sending a fake write error") - } + assert.EqualError(t, err, writeErr.Error()) + respBuffer := []byte{0x02} protocolErrorMsg := "protocol error msg" respBuffer = append(respBuffer, protocolErrorMsg...) @@ -1282,8 +1187,8 @@ func TestSCPProtocolMessages(t *testing.T) { } scpCommand.connection.channel = &mockSSHChannel err = scpCommand.readConfirmationMessage() - if err == nil || err.Error() != protocolErrorMsg { - t.Errorf("read confirmation message must return the expected protocol error, actual err: %v", err) + if assert.Error(t, err) { + assert.Equal(t, protocolErrorMsg, err.Error()) } } @@ -1309,12 +1214,12 @@ func TestSCPTestDownloadProtocolMessages(t *testing.T) { }, } path := "testDir" - os.Mkdir(path, 0777) - stat, _ := os.Stat(path) - err := scpCommand.sendDownloadProtocolMessages(path, stat) - if err != writeErr { - t.Errorf("sendDownloadProtocolMessages must return the expected error: %v", err) - } + err := os.Mkdir(path, 0777) + assert.NoError(t, err) + stat, err := os.Stat(path) + assert.NoError(t, err) + err = scpCommand.sendDownloadProtocolMessages(path, stat) + assert.EqualError(t, err, writeErr.Error()) mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1324,9 +1229,7 @@ func TestSCPTestDownloadProtocolMessages(t *testing.T) { } err = scpCommand.sendDownloadProtocolMessages(path, stat) - if err != readErr { - t.Errorf("sendDownloadProtocolMessages must return the expected error: %v", err) - } + assert.EqualError(t, err, readErr.Error()) mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1337,9 +1240,7 @@ func TestSCPTestDownloadProtocolMessages(t *testing.T) { scpCommand.args = []string{"-f", "/tmp"} scpCommand.connection.channel = &mockSSHChannel err = scpCommand.sendDownloadProtocolMessages(path, stat) - if err != writeErr { - t.Errorf("sendDownloadProtocolMessages must return the expected error: %v", err) - } + assert.EqualError(t, err, writeErr.Error()) mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), @@ -1349,10 +1250,10 @@ func TestSCPTestDownloadProtocolMessages(t *testing.T) { } scpCommand.connection.channel = &mockSSHChannel err = scpCommand.sendDownloadProtocolMessages(path, stat) - if err != readErr { - t.Errorf("sendDownloadProtocolMessages must return the expected error: %v", err) - } - os.Remove(path) + assert.EqualError(t, err, readErr.Error()) + + err = os.Remove(path) + assert.NoError(t, err) } func TestSCPCommandHandleErrors(t *testing.T) { @@ -1367,8 +1268,14 @@ func TestSCPCommandHandleErrors(t *testing.T) { WriteError: writeErr, } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -1381,19 +1288,15 @@ func TestSCPCommandHandleErrors(t *testing.T) { }, } err := scpCommand.handle() - if err == nil || err != readErr { - t.Errorf("scp download must fail, we are sending a fake error") - } + assert.EqualError(t, err, readErr.Error()) scpCommand.args = []string{"-i", "/tmp"} err = scpCommand.handle() - if err == nil { - t.Errorf("invalid scp command must fail") - } + assert.Error(t, err, "invalid scp command must fail") } func TestSCPErrorsMockFs(t *testing.T) { errFake := errors.New("fake error") - fs := newMockOsFs(errFake, errFake, false, "123", os.TempDir()) + fs := newMockOsFs(errFake, errFake, false, "1234", os.TempDir()) u := dataprovider.User{} u.Username = "test" u.Permissions = make(map[string][]string) @@ -1406,8 +1309,14 @@ func TestSCPErrorsMockFs(t *testing.T) { StdErrBuffer: bytes.NewBuffer(stdErrBuf), } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -1422,26 +1331,24 @@ func TestSCPErrorsMockFs(t *testing.T) { }, } err := scpCommand.handleUpload("test", 0) - if err != errFake { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errFake.Error()) + testfile := filepath.Join(u.HomeDir, "testfile") - ioutil.WriteFile(testfile, []byte("test"), 0666) - stat, _ := os.Stat(u.HomeDir) + err = ioutil.WriteFile(testfile, []byte("test"), 0666) + assert.NoError(t, err) + stat, err := os.Stat(u.HomeDir) + assert.NoError(t, err) err = scpCommand.handleRecursiveDownload(u.HomeDir, stat) - if err != errFake { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errFake.Error()) + scpCommand.sshCommand.connection.fs = newMockOsFs(errFake, nil, true, "123", os.TempDir()) err = scpCommand.handleUpload(filepath.Base(testfile), 0) - if err != errFake { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, errFake.Error()) + err = scpCommand.handleUploadFile(testfile, testfile, 0, false, 4, false) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - os.Remove(testfile) + assert.NoError(t, err) + err = os.Remove(testfile) + assert.NoError(t, err) } func TestSCPRecursiveDownloadErrors(t *testing.T) { @@ -1456,8 +1363,14 @@ func TestSCPRecursiveDownloadErrors(t *testing.T) { WriteError: writeErr, } server, client := net.Pipe() - defer server.Close() - defer client.Close() + defer func() { + err := server.Close() + assert.NoError(t, err) + }() + defer func() { + err := client.Close() + assert.NoError(t, err) + }() connection := Connection{ channel: &mockSSHChannel, netConn: client, @@ -1471,12 +1384,13 @@ func TestSCPRecursiveDownloadErrors(t *testing.T) { }, } path := "testDir" - os.Mkdir(path, 0777) - stat, _ := os.Stat(path) - err := scpCommand.handleRecursiveDownload("invalid_dir", stat) - if err != writeErr { - t.Errorf("recursive upload download must fail with the expected error: %v", err) - } + err := os.Mkdir(path, 0777) + assert.NoError(t, err) + stat, err := os.Stat(path) + assert.NoError(t, err) + err = scpCommand.handleRecursiveDownload("invalid_dir", stat) + assert.EqualError(t, err, writeErr.Error()) + mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), StdErrBuffer: bytes.NewBuffer(stdErrBuf), @@ -1485,11 +1399,10 @@ func TestSCPRecursiveDownloadErrors(t *testing.T) { } scpCommand.connection.channel = &mockSSHChannel err = scpCommand.handleRecursiveDownload("invalid_dir", stat) - if err == nil { - t.Errorf("recursive upload download must fail for a non existing dir") - } + assert.Error(t, err, "recursive upload download must fail for a non existing dir") - os.Remove(path) + err = os.Remove(path) + assert.NoError(t, err) } func TestSCPRecursiveUploadErrors(t *testing.T) { @@ -1514,9 +1427,8 @@ func TestSCPRecursiveUploadErrors(t *testing.T) { }, } err := scpCommand.handleRecursiveUpload() - if err == nil { - t.Errorf("recursive upload must fail, we send a fake error message") - } + assert.Error(t, err, "recursive upload must fail, we send a fake error message") + mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), StdErrBuffer: bytes.NewBuffer(stdErrBuf), @@ -1525,9 +1437,7 @@ func TestSCPRecursiveUploadErrors(t *testing.T) { } scpCommand.connection.channel = &mockSSHChannel err = scpCommand.handleRecursiveUpload() - if err == nil { - t.Errorf("recursive upload must fail, we send a fake error message") - } + assert.Error(t, err, "recursive upload must fail, we send a fake error message") } func TestSCPCreateDirs(t *testing.T) { @@ -1544,7 +1454,8 @@ func TestSCPCreateDirs(t *testing.T) { ReadError: nil, WriteError: nil, } - fs, _ := u.GetFilesystem("123") + fs, err := u.GetFilesystem("123") + assert.NoError(t, err) connection := Connection{ User: u, channel: &mockSSHChannel, @@ -1557,10 +1468,8 @@ func TestSCPCreateDirs(t *testing.T) { args: []string{"-r", "-t", "/tmp"}, }, } - err := scpCommand.handleCreateDir("invalid_dir") - if err == nil { - t.Errorf("create invalid dir must fail") - } + err = scpCommand.handleCreateDir("invalid_dir") + assert.Error(t, err, "create invalid dir must fail") } func TestSCPDownloadFileData(t *testing.T) { @@ -1591,28 +1500,27 @@ func TestSCPDownloadFileData(t *testing.T) { args: []string{"-r", "-f", "/tmp"}, }, } - ioutil.WriteFile(testfile, []byte("test"), 0666) - stat, _ := os.Stat(testfile) - err := scpCommand.sendDownloadFileData(testfile, stat, nil) - if err != readErr { - t.Errorf("send download file data must fail with the expected error: %v", err) - } + err := ioutil.WriteFile(testfile, []byte("test"), 0666) + assert.NoError(t, err) + stat, err := os.Stat(testfile) + assert.NoError(t, err) + err = scpCommand.sendDownloadFileData(testfile, stat, nil) + assert.EqualError(t, err, readErr.Error()) + scpCommand.connection.channel = &mockSSHChannelWriteErr err = scpCommand.sendDownloadFileData(testfile, stat, nil) - if err != writeErr { - t.Errorf("send download file data must fail with the expected error: %v", err) - } + assert.EqualError(t, err, writeErr.Error()) + scpCommand.args = []string{"-r", "-p", "-f", "/tmp"} err = scpCommand.sendDownloadFileData(testfile, stat, nil) - if err != writeErr { - t.Errorf("send download file data must fail with the expected error: %v", err) - } + assert.EqualError(t, err, writeErr.Error()) + scpCommand.connection.channel = &mockSSHChannelReadErr err = scpCommand.sendDownloadFileData(testfile, stat, nil) - if err != readErr { - t.Errorf("send download file data must fail with the expected error: %v", err) - } - os.Remove(testfile) + assert.EqualError(t, err, readErr.Error()) + + err = os.Remove(testfile) + assert.NoError(t, err) } func TestSCPUploadFiledata(t *testing.T) { @@ -1642,7 +1550,9 @@ func TestSCPUploadFiledata(t *testing.T) { args: []string{"-r", "-t", "/tmp"}, }, } - file, _ := os.Create(testfile) + file, err := os.Create(testfile) + assert.NoError(t, err) + transfer := Transfer{ file: file, path: file.Name(), @@ -1661,10 +1571,9 @@ func TestSCPUploadFiledata(t *testing.T) { lock: new(sync.Mutex), } addTransfer(&transfer) - err := scpCommand.getUploadFileData(2, &transfer) - if err == nil { - t.Errorf("upload must fail, we send a fake write error message") - } + err = scpCommand.getUploadFileData(2, &transfer) + assert.Error(t, err, "upload must fail, we send a fake write error message") + mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), StdErrBuffer: bytes.NewBuffer(stdErrBuf), @@ -1672,14 +1581,13 @@ func TestSCPUploadFiledata(t *testing.T) { WriteError: nil, } scpCommand.connection.channel = &mockSSHChannel - file, _ = os.Create(testfile) + file, err = os.Create(testfile) + assert.NoError(t, err) transfer.file = file transfer.isFinished = false addTransfer(&transfer) err = scpCommand.getUploadFileData(2, &transfer) - if err == nil { - t.Errorf("upload must fail, we send a fake read error message") - } + assert.Error(t, err, "upload must fail, we send a fake read error message") respBuffer := []byte("12") respBuffer = append(respBuffer, 0x02) @@ -1690,14 +1598,13 @@ func TestSCPUploadFiledata(t *testing.T) { WriteError: nil, } scpCommand.connection.channel = &mockSSHChannel - file, _ = os.Create(testfile) + file, err = os.Create(testfile) + assert.NoError(t, err) transfer.file = file transfer.isFinished = false addTransfer(&transfer) err = scpCommand.getUploadFileData(2, &transfer) - if err == nil { - t.Errorf("upload must fail, we have not enough data to read") - } + assert.Error(t, err, "upload must fail, we have not enough data to read") // the file is already closed so we have an error on trasfer closing mockSSHChannel = MockChannel{ @@ -1708,9 +1615,8 @@ func TestSCPUploadFiledata(t *testing.T) { } addTransfer(&transfer) err = scpCommand.getUploadFileData(0, &transfer) - if err != errTransferClosed { - t.Errorf("upload must fail, the transfer is already closed, err: %v", err) - } + assert.EqualError(t, err, errTransferClosed.Error()) + mockSSHChannel = MockChannel{ Buffer: bytes.NewBuffer(buf), StdErrBuffer: bytes.NewBuffer(stdErrBuf), @@ -1719,13 +1625,10 @@ func TestSCPUploadFiledata(t *testing.T) { } addTransfer(&transfer) err = scpCommand.getUploadFileData(2, &transfer) - if !errors.Is(err, os.ErrClosed) { - t.Errorf("the file is closed and writes must fail, err: %v", err) - } + assert.True(t, errors.Is(err, os.ErrClosed)) + err = os.Remove(testfile) - if err != nil { - t.Errorf("error removing test file: %v", err) - } + assert.NoError(t, err) } func TestUploadError(t *testing.T) { @@ -1739,7 +1642,8 @@ func TestUploadError(t *testing.T) { } testfile := "testfile" fileTempName := "temptestfile" - file, _ := os.Create(fileTempName) + file, err := os.Create(fileTempName) + assert.NoError(t, err) transfer := Transfer{ file: file, path: testfile, @@ -1760,21 +1664,13 @@ func TestUploadError(t *testing.T) { addTransfer(&transfer) errFake := errors.New("fake error") transfer.TransferError(errFake) - err := transfer.Close() - if err != errFake { - t.Errorf("unexpected error: %v", err) - } - if transfer.bytesReceived > 0 { - t.Errorf("bytes received should be 0 for a failed transfer: %v", transfer.bytesReceived) - } - _, err = os.Stat(testfile) - if !os.IsNotExist(err) { - t.Errorf("file uploaded must be deleted after an error: %v", err) - } - _, err = os.Stat(fileTempName) - if !os.IsNotExist(err) { - t.Errorf("file uploaded must be deleted after an error: %v", err) - } + err = transfer.Close() + assert.EqualError(t, err, errFake.Error()) + assert.Equal(t, int64(0), transfer.bytesReceived) + + assert.NoFileExists(t, testfile) + assert.NoFileExists(t, fileTempName) + uploadMode = oldUploadMode } @@ -1807,41 +1703,34 @@ func TestConnectionStatusStruct(t *testing.T) { Transfers: transfers, } durationString := c.GetConnectionDuration() - if len(durationString) == 0 { - t.Errorf("error getting connection duration") - } + assert.NotEqual(t, 0, len(durationString)) + transfersString := c.GetTransfersAsString() - if len(transfersString) == 0 { - t.Errorf("error getting transfers as string") - } + assert.NotEqual(t, 0, len(transfersString)) + connInfo := c.GetConnectionInfo() - if len(connInfo) == 0 { - t.Errorf("error getting connection info") - } + assert.NotEqual(t, 0, len(connInfo)) } func TestProxyProtocolVersion(t *testing.T) { c := Configuration{ ProxyProtocol: 1, } - proxyListener, _ := c.getProxyListener(nil) - if proxyListener.Policy != nil { - t.Error("proxy listener policy must be nil") - } + proxyListener, err := c.getProxyListener(nil) + assert.NoError(t, err) + assert.Nil(t, proxyListener.Policy) + c.ProxyProtocol = 2 proxyListener, _ = c.getProxyListener(nil) - if proxyListener.Policy == nil { - t.Error("proxy listener policy must be not nil") - } + assert.NoError(t, err) + assert.NotNil(t, proxyListener.Policy) + c.ProxyProtocol = 1 c.ProxyAllowed = []string{"invalid"} - _, err := c.getProxyListener(nil) - if err == nil { - t.Error("get proxy listener with invalid IP must fail") - } + _, err = c.getProxyListener(nil) + assert.Error(t, err) + c.ProxyProtocol = 2 _, err = c.getProxyListener(nil) - if err == nil { - t.Error("get proxy listener with invalid IP must fail") - } + assert.Error(t, err) } diff --git a/sftpd/internal_unix_test.go b/sftpd/internal_unix_test.go index 6ccf87be..893499fe 100644 --- a/sftpd/internal_unix_test.go +++ b/sftpd/internal_unix_test.go @@ -5,15 +5,13 @@ package sftpd import ( "os/exec" "testing" + + "github.com/stretchr/testify/assert" ) func TestWrapCmd(t *testing.T) { cmd := exec.Command("ls") cmd = wrapCmd(cmd, 1000, 1001) - if cmd.SysProcAttr.Credential.Uid != 1000 { - t.Errorf("unexpected uid") - } - if cmd.SysProcAttr.Credential.Gid != 1001 { - t.Errorf("unexpected gid") - } + assert.Equal(t, uint32(1000), cmd.SysProcAttr.Credential.Uid) + assert.Equal(t, uint32(1001), cmd.SysProcAttr.Credential.Gid) } diff --git a/sftpd/server.go b/sftpd/server.go index 866df27a..26f04627 100644 --- a/sftpd/server.go +++ b/sftpd/server.go @@ -13,13 +13,14 @@ import ( "strings" "time" + "github.com/pires/go-proxyproto" + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/metrics" "github.com/drakkan/sftpgo/utils" - "github.com/pires/go-proxyproto" - "github.com/pkg/sftp" - "golang.org/x/crypto/ssh" ) const ( diff --git a/sftpd/sftpd.go b/sftpd/sftpd.go index 80fac772..de831ad0 100644 --- a/sftpd/sftpd.go +++ b/sftpd/sftpd.go @@ -49,7 +49,7 @@ const ( ) const ( - uploadModeStandard = iota //nolint:varcheck,deadcode + uploadModeStandard = iota uploadModeAtomic uploadModeAtomicWithResume ) diff --git a/sftpd/sftpd_test.go b/sftpd/sftpd_test.go index 108a2172..77cad891 100644 --- a/sftpd/sftpd_test.go +++ b/sftpd/sftpd_test.go @@ -29,6 +29,9 @@ import ( _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" + "github.com/pkg/sftp" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" "golang.org/x/crypto/ssh" "github.com/drakkan/sftpgo/config" @@ -38,8 +41,6 @@ import ( "github.com/drakkan/sftpgo/sftpd" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - "github.com/pkg/sftp" - "github.com/rs/zerolog" ) const ( @@ -87,7 +88,9 @@ NbbCNsVroqKlChT5wyPNGS+phi2bPARBno7WSDvshTZ7dAVEP2c9MJW0XwoSevwKlhgSdt RLFFQ/5nclJSdzPBOmQouC0OBcMFSrYtMeknJ4VvueVvve5HcHFaEsaMc7ABAGaLYaBQOm iixITGvaNZh/tjAAAACW5pY29sYUBwMQE= -----END OPENSSH PRIVATE KEY-----` - configDir = ".." + configDir = ".." + permissionErrorString = "Permission Denied" + osWindows = "windows" ) var ( @@ -109,14 +112,22 @@ func TestMain(m *testing.M) { logFilePath = filepath.Join(configDir, "sftpgo_sftpd_test.log") loginBannerFileName := "login_banner" loginBannerFile := filepath.Join(configDir, loginBannerFileName) - ioutil.WriteFile(loginBannerFile, []byte("simple login banner\n"), 0777) logger.InitLogger(logFilePath, 5, 1, 28, false, zerolog.DebugLevel) - config.LoadConfig(configDir, "") + err := ioutil.WriteFile(loginBannerFile, []byte("simple login banner\n"), 0777) + if err != nil { + logger.WarnToConsole("error creating login banner: %v", err) + os.Exit(1) + } + err = config.LoadConfig(configDir, "") + if err != nil { + logger.WarnToConsole("error loading configuration: %v", err) + os.Exit(1) + } providerConf := config.GetProviderConf() - err := dataprovider.Initialize(providerConf, configDir) + err = dataprovider.Initialize(providerConf, configDir) if err != nil { - logger.Warn(logSender, "", "error initializing data provider: %v", err) + logger.WarnToConsole("error initializing data provider: %v", err) os.Exit(1) } @@ -141,39 +152,30 @@ func TestMain(m *testing.M) { sftpdConf.UploadMode = 2 homeBasePath = os.TempDir() var scriptArgs string - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { scriptArgs = "%*" } else { sftpdConf.Actions.ExecuteOn = []string{"download", "upload", "rename", "delete", "ssh_cmd"} sftpdConf.Actions.Command = "/usr/bin/true" sftpdConf.Actions.HTTPNotificationURL = "http://127.0.0.1:8083/" scriptArgs = "$@" + scpPath, err = exec.LookPath("scp") + if err != nil { + logger.Warn(logSender, "", "unable to get scp command. SCP tests will be skipped, err: %v", err) + logger.WarnToConsole("unable to get scp command. SCP tests will be skipped, err: %v", err) + scpPath = "" + } } + checkGitCommand() + keyIntAuthPath = filepath.Join(homeBasePath, "keyintauth.sh") - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + if err != nil { + logger.WarnToConsole("error writing keyboard interactive script: %v", err) + os.Exit(1) + } sftpdConf.KeyboardInteractiveHook = keyIntAuthPath - scpPath, err = exec.LookPath("scp") - if err != nil { - logger.Warn(logSender, "", "unable to get scp command. SCP tests will be skipped, err: %v", err) - logger.WarnToConsole("unable to get scp command. SCP tests will be skipped, err: %v", err) - scpPath = "" - } - - gitPath, err = exec.LookPath("git") - if err != nil { - logger.Warn(logSender, "", "unable to get git command. GIT tests will be skipped, err: %v", err) - logger.WarnToConsole("unable to get git command. GIT tests will be skipped, err: %v", err) - gitPath = "" - } - - sshPath, err = exec.LookPath("ssh") - if err != nil { - logger.Warn(logSender, "", "unable to get ssh command. GIT tests will be skipped, err: %v", err) - logger.WarnToConsole("unable to get ssh command. GIT tests will be skipped, err: %v", err) - gitPath = "" - } - pubKeyPath = filepath.Join(homeBasePath, "ssh_key.pub") privateKeyPath = filepath.Join(homeBasePath, "ssh_key") gitWrapPath = filepath.Join(homeBasePath, "gitwrap.sh") @@ -246,33 +248,26 @@ func TestMain(m *testing.M) { } func TestInitialization(t *testing.T) { - config.LoadConfig(configDir, "") + err := config.LoadConfig(configDir, "") + assert.NoError(t, err) sftpdConf := config.GetSFTPDConfig() sftpdConf.Umask = "invalid umask" sftpdConf.BindPort = 2022 sftpdConf.LoginBannerFile = "invalid_file" sftpdConf.EnabledSSHCommands = append(sftpdConf.EnabledSSHCommands, "ls") - err := sftpdConf.Initialize(configDir) - if err == nil { - t.Error("Inizialize must fail, a SFTP server should be already running") - } + err = sftpdConf.Initialize(configDir) + assert.Error(t, err) sftpdConf.KeyboardInteractiveHook = "invalid_file" err = sftpdConf.Initialize(configDir) - if err == nil { - t.Error("Inizialize must fail, a SFTP server should be already running") - } + assert.Error(t, err) sftpdConf.KeyboardInteractiveHook = filepath.Join(homeBasePath, "invalid_file") err = sftpdConf.Initialize(configDir) - if err == nil { - t.Error("Inizialize must fail, a SFTP server should be already running") - } + assert.Error(t, err) sftpdConf.BindPort = 4444 sftpdConf.ProxyProtocol = 1 sftpdConf.ProxyAllowed = []string{"1270.0.0.1"} err = sftpdConf.Initialize(configDir) - if err == nil { - t.Error("Inizialize must fail, proxy IP allowed is invalid") - } + assert.Error(t, err) } func TestBasicSFTPHandling(t *testing.T) { @@ -280,605 +275,401 @@ func TestBasicSFTPHandling(t *testing.T) { u := getTestUser(usePubKey) u.QuotaSize = 6553600 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - testFileName := "test_file.dat" + testFileName := "test_file.dat" //nolint:goconst testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) expectedQuotaSize := user.UsedQuotaSize + testFileSize expectedQuotaFiles := user.UsedQuotaFiles + 1 - createTestFile(testFilePath, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) err = sftpUploadFile(testFilePath, path.Join("/missing_dir", testFileName), testFileSize, client) - if err == nil { - t.Errorf("upload a file to a missing dir must fail") - } + assert.Error(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if err != nil { - t.Errorf("file download error: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } + assert.NoError(t, err) _, err = client.Lstat(testFileName) - if err == nil { - t.Errorf("stat for deleted file must not succeed") - } + assert.Error(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if (expectedQuotaFiles - 1) != user.UsedQuotaFiles { - t.Errorf("quota files does not match after delete, expected: %v, actual: %v", expectedQuotaFiles-1, user.UsedQuotaFiles) - } - if (expectedQuotaSize - testFileSize) != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize-testFileSize, user.UsedQuotaSize) - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles-1, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize-testFileSize, user.UsedQuotaSize) + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestProxyProtocol(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) // remove the home dir to test auto creation - os.RemoveAll(user.HomeDir) + err = os.RemoveAll(user.HomeDir) + assert.NoError(t, err) client, err := getSftpClientWithAddr(user, usePubKey, "127.0.0.1:2222") - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("error mkdir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } client, err = getSftpClientWithAddr(user, usePubKey, "127.0.0.1:2224") - if err == nil { - t.Error("request without a proxy header must be rejected") + if !assert.Error(t, err) { + client.Close() } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestUploadResume(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) appendDataSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = appendToTestFile(testFilePath, appendDataSize) - if err != nil { - t.Errorf("unable to append to test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, false, client) - if err != nil { - t.Errorf("file upload resume error: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize+appendDataSize, client) - if err != nil { - t.Errorf("file download error: %v", err) - } + assert.NoError(t, err) initialHash, err := computeHashForFile(sha256.New(), testFilePath) - if err != nil { - t.Errorf("error computing file hash: %v", err) - } + assert.NoError(t, err) donwloadedFileHash, err := computeHashForFile(sha256.New(), localDownloadPath) - if err != nil { - t.Errorf("error computing downloaded file hash: %v", err) - } - if donwloadedFileHash != initialHash { - t.Errorf("resume failed: file hash does not match") - } + assert.NoError(t, err) + assert.Equal(t, initialHash, donwloadedFileHash) err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, true, client) - if err == nil { - t.Errorf("file upload resume with invalid offset must fail") - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.Error(t, err, "file upload resume with invalid offset must fail") + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestDirCommands(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) // remove the home dir to test auto creation - os.RemoveAll(user.HomeDir) + err = os.RemoveAll(user.HomeDir) + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("test1") - if err != nil { - t.Errorf("error mkdir: %v", err) - } + assert.NoError(t, err) err = client.Rename("test1", "test") - if err != nil { - t.Errorf("error rename: %v", err) - } + assert.NoError(t, err) _, err = client.Lstat("/test1") - if err == nil { - t.Errorf("stat for renamed dir must not succeed") - } + assert.Error(t, err, "stat for renamed dir must not succeed") err = client.PosixRename("test", "test1") - if err != nil { - t.Errorf("error posix rename: %v", err) - } + assert.NoError(t, err) err = client.Remove("test1") - if err != nil { - t.Errorf("error rmdir: %v", err) - } + assert.NoError(t, err) err = client.Mkdir("/test/test1") - if err == nil { - t.Errorf("recursive mkdir must fail") - } - client.Mkdir("/test") + assert.Error(t, err, "recursive mkdir must fail") + err = client.Mkdir("/test") + assert.NoError(t, err) err = client.Mkdir("/test/test1") - if err != nil { - t.Errorf("mkdir dir error: %v", err) - } + assert.NoError(t, err) _, err = client.ReadDir("/this/dir/does/not/exist") - if err == nil { - t.Errorf("reading a missing dir must fail") - } + assert.Error(t, err, "reading a missing dir must fail") err = client.RemoveDirectory("/test/test1") - if err != nil { - t.Errorf("remove dir error: %v", err) - } + assert.NoError(t, err) err = client.RemoveDirectory("/test") - if err != nil { - t.Errorf("remove dir error: %v", err) - } + assert.NoError(t, err) _, err = client.Lstat("/test") - if err == nil { - t.Errorf("stat for deleted dir must not succeed") - } + assert.Error(t, err, "stat for deleted dir must not succeed") err = client.RemoveDirectory("/test") - if err == nil { - t.Errorf("remove missing path must fail") - } + assert.Error(t, err, "remove missing path must fail") } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestRemove(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("test") - if err != nil { - t.Errorf("error mkdir: %v", err) - } + assert.NoError(t, err) err = client.Mkdir("/test/test1") - if err != nil { - t.Errorf("error mkdir subdir: %v", err) - } + assert.NoError(t, err) testFileName := "/test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, path.Join("/test", testFileName), testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Remove("/test") - if err == nil { - t.Errorf("remove non empty dir must fail") - } + assert.Error(t, err, "remove non empty dir must fail") err = client.RemoveDirectory(path.Join("/test", testFileName)) - if err == nil { - t.Errorf("remove a file with rmdir must fail") - } + assert.Error(t, err, "remove a file with rmdir must fail") err = client.Remove(path.Join("/test", testFileName)) - if err != nil { - t.Errorf("remove file error: %v", err) - } + assert.NoError(t, err) err = client.Remove(path.Join("/test", testFileName)) - if err == nil { - t.Errorf("remove missing file must fail") - } + assert.Error(t, err, "remove missing file must fail") err = client.Remove("/test/test1") - if err != nil { - t.Errorf("remove dir error: %v", err) - } + assert.NoError(t, err) err = client.Remove("/test") - if err != nil { - t.Errorf("remove dir error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLink(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Symlink(testFileName, testFileName+".link") - if err != nil { - t.Errorf("error creating symlink: %v", err) - } + assert.NoError(t, err) _, err = client.ReadLink(testFileName + ".link") - if err == nil { - t.Errorf("readlink is currently not implemented so must fail") - } + assert.Error(t, err, "readlink is currently not implemented so must fail") err = client.Symlink(testFileName, testFileName+".link") - if err == nil { - t.Errorf("creating a symlink to an existing one must fail") - } + assert.Error(t, err, "creating a symlink to an existing one must fail") err = client.Link(testFileName, testFileName+".hlink") - if err == nil { - t.Errorf("hard link is not supported and must fail") - } + assert.Error(t, err, "hard link is not supported and must fail") err = client.Remove(testFileName + ".link") - if err != nil { - t.Errorf("error removing symlink: %v", err) - } + assert.NoError(t, err) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestStat(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) - createTestFile(testFilePath, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) _, err := client.Lstat(testFileName) - if err != nil { - t.Errorf("stat error: %v", err) - } + assert.NoError(t, err) // mode 0666 and 0444 works on Windows too newPerm := os.FileMode(0666) err = client.Chmod(testFileName, newPerm) - if err != nil { - t.Errorf("chmod error: %v", err) - } + assert.NoError(t, err) newFi, err := client.Lstat(testFileName) - if err != nil { - t.Errorf("stat error: %v", err) - } - if newPerm != newFi.Mode().Perm() { - t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm()) - } + assert.NoError(t, err) + assert.Equal(t, newPerm, newFi.Mode().Perm()) newPerm = os.FileMode(0444) err = client.Chmod(testFileName, newPerm) - if err != nil { - t.Errorf("chmod error: %v", err) - } + assert.NoError(t, err) newFi, err = client.Lstat(testFileName) - if err != nil { - t.Errorf("stat error: %v", err) - } - if newPerm != newFi.Mode().Perm() { - t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm()) - } + assert.NoError(t, err) + assert.Equal(t, newPerm, newFi.Mode().Perm()) _, err = client.ReadLink(testFileName) - if err == nil { - t.Errorf("readlink is not supported and must fail") - } + assert.Error(t, err, "readlink is not supported and must fail") err = client.Truncate(testFileName, 0) - if err != nil { - t.Errorf("truncate must be silently ignored: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestStatChownChmod(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("chown is not supported on Windows, chmod is partially supported") } usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) - createTestFile(testFilePath, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Chown(testFileName, os.Getuid(), os.Getgid()) - if err != nil { - t.Errorf("chown error: %v", err) - } + assert.NoError(t, err) newPerm := os.FileMode(0600) err = client.Chmod(testFileName, newPerm) - if err != nil { - t.Errorf("chmod error: %v", err) - } + assert.NoError(t, err) newFi, err := client.Lstat(testFileName) - if err != nil { - t.Errorf("stat error: %v", err) - } - if newPerm != newFi.Mode().Perm() { - t.Errorf("chown failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm()) - } + assert.NoError(t, err) + assert.Equal(t, newPerm, newFi.Mode().Perm()) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - // l'errore viene riconvertito da sftp.ErrSSHFxNoSuchFile in os.ErrNotExist + assert.NoError(t, err) err = client.Chmod(testFileName, newPerm) - if err != os.ErrNotExist { - t.Errorf("unexpected chmod error: %v expected: %v", err, os.ErrNotExist) - } + assert.EqualError(t, err, os.ErrNotExist.Error()) err = client.Chown(testFileName, os.Getuid(), os.Getgid()) - if err != os.ErrNotExist { - t.Errorf("unexpected chown error: %v expected: %v", err, os.ErrNotExist) - } - os.Remove(testFilePath) + assert.EqualError(t, err, os.ErrNotExist.Error()) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestChtimes(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) testDir := "test" - createTestFile(testFilePath, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) acmodTime := time.Now() err = client.Chtimes(testFileName, acmodTime, acmodTime) - if err != nil { - t.Errorf("error changing file times") - } + assert.NoError(t, err) newFi, err := client.Lstat(testFileName) - if err != nil { - t.Errorf("file stat error: %v", err) - } + assert.NoError(t, err) diff := math.Abs(newFi.ModTime().Sub(acmodTime).Seconds()) - if diff > 1 { - t.Errorf("diff between wanted and real modification time too big: %v", diff) - } + assert.LessOrEqual(t, diff, float64(1)) err = client.Chtimes("invalidFile", acmodTime, acmodTime) - if !os.IsNotExist(err) { - t.Errorf("unexpected error: %v", err) - } + assert.EqualError(t, err, os.ErrNotExist.Error()) err = client.Mkdir(testDir) - if err != nil { - t.Errorf("unable to create dir: %v", err) - } + assert.NoError(t, err) err = client.Chtimes(testDir, acmodTime, acmodTime) - if err != nil { - t.Errorf("error changing dir times") - } + assert.NoError(t, err) newFi, err = client.Lstat(testDir) - if err != nil { - t.Errorf("dir stat error: %v", err) - } + assert.NoError(t, err) diff = math.Abs(newFi.ModTime().Sub(acmodTime).Seconds()) - if diff > 1 { - t.Errorf("diff between wanted and real modification time too big: %v", diff) - } - os.Remove(testFilePath) + assert.LessOrEqual(t, diff, float64(1)) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } // basic tests to verify virtual chroot, should be improved to cover more cases ... func TestEscapeHomeDir(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - testDir := "testDir" + assert.NoError(t, checkBasicSFTP(client)) + testDir := "testDir" //nolint:goconst linkPath := filepath.Join(homeBasePath, defaultUsername, testDir) err = os.Symlink(homeBasePath, linkPath) - if err != nil { - t.Errorf("error making local symlink: %v", err) - } + assert.NoError(t, err) _, err = client.ReadDir(testDir) - if err == nil { - t.Errorf("reading a symbolic link outside home dir should not succeeded") - } - os.Remove(linkPath) + assert.Error(t, err, "reading a symbolic link outside home dir should not succeeded") + err = os.Remove(linkPath) + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteDestPath := path.Join("..", "..", testFileName) err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) _, err = client.Lstat(testFileName) - if err != nil { - t.Errorf("file stat error: %v the file was created outside the user dir!", err) - } + assert.NoError(t, err) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } + assert.NoError(t, err) linkPath = filepath.Join(homeBasePath, defaultUsername, testFileName) err = os.Symlink(homeBasePath, linkPath) - if err != nil { - t.Errorf("error making local symlink: %v", err) - } + assert.NoError(t, err) err = sftpDownloadFile(testFileName, testFilePath, 0, client) - if err == nil { - t.Errorf("download file outside home dir must fail") - } + assert.Error(t, err, "download file outside home dir must fail") err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client) - if err == nil { - t.Errorf("overwrite a file outside home dir must fail") - } + assert.Error(t, err, "overwrite a file outside home dir must fail") err = client.Chmod(remoteDestPath, 0644) - if err == nil { - t.Errorf("setstat on a file outside home dir must fail") - } - os.Remove(linkPath) - os.Remove(testFilePath) + assert.Error(t, err, "setstat on a file outside home dir must fail") + err = os.Remove(linkPath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestHomeSpecialChars(t *testing.T) { @@ -886,123 +677,78 @@ func TestHomeSpecialChars(t *testing.T) { u := getTestUser(usePubKey) u.HomeDir = filepath.Join(homeBasePath, "abc açà#&%lk") user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) files, err := client.ReadDir(".") - if err != nil { - t.Errorf("unable to read remote dir: %v", err) - } - if len(files) < 1 { - t.Errorf("expected at least 1 file in this dir") - } + assert.NoError(t, err) + assert.GreaterOrEqual(t, len(files), 1) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLogin(t *testing.T) { u := getTestUser(false) u.PublicKeys = []string{testPubKey} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, false) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with valid password must work") - } + assert.NoError(t, checkBasicSFTP(client)) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if user.LastLogin <= 0 { - t.Errorf("last login must be updated after a successful login: %v", user.LastLogin) - } + assert.NoError(t, err) + assert.Greater(t, user.LastLogin, int64(0), "last login must be updated after a successful login: %v", user.LastLogin) } client, err = getSftpClient(user, true) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with valid public key must work") - } + assert.NoError(t, checkBasicSFTP(client)) } user.Password = "invalid password" client, err = getSftpClient(user, false) - if err == nil { - t.Errorf("login with invalid password must fail") - defer client.Close() + if !assert.Error(t, err, "login with invalid password must fail") { + client.Close() } // testPubKey1 is not authorized user.PublicKeys = []string{testPubKey1} user.Password = "" _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, true) - if err == nil { - t.Errorf("login with invalid public key must fail") + if !assert.Error(t, err, "login with invalid public key must fail") { defer client.Close() } // login a user with multiple public keys, only the second one is valid user.PublicKeys = []string{testPubKey1, testPubKey} user.Password = "" _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, true) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with multiple public key must work if at least one public key is valid") - } + assert.NoError(t, checkBasicSFTP(client)) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestMultiStepLoginKeyAndPwd(t *testing.T) { @@ -1015,49 +761,35 @@ func TestMultiStepLoginKeyAndPwd(t *testing.T) { dataprovider.SSHLoginMethodKeyboardInteractive, }...) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) _, err = getSftpClient(user, true) - if err == nil { - t.Error("login with public key is disallowed and must fail") - } + assert.Error(t, err, "login with public key is disallowed and must fail") _, err = getSftpClient(user, true) - if err == nil { - t.Error("login with password is disallowed and must fail") - } + assert.Error(t, err, "login with password is disallowed and must fail") key, _ := ssh.ParsePrivateKey([]byte(testPrivateKey)) authMethods := []ssh.AuthMethod{ ssh.PublicKeys(key), ssh.Password(defaultPassword), } client, err := getCustomAuthSftpClient(user, authMethods) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } authMethods = []ssh.AuthMethod{ ssh.Password(defaultPassword), ssh.PublicKeys(key), } _, err = getCustomAuthSftpClient(user, authMethods) - if err == nil { - t.Error("multi step auth login with wrong order must fail") - } + assert.Error(t, err, "multi step auth login with wrong order must fail") _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestMultiStepLoginKeyAndKeyInt(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } u := getTestUser(true) @@ -1069,14 +801,12 @@ func TestMultiStepLoginKeyAndKeyInt(t *testing.T) { dataprovider.SSHLoginMethodKeyboardInteractive, }...) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + assert.NoError(t, err) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + assert.NoError(t, err) _, err = getSftpClient(user, true) - if err == nil { - t.Error("login with public key is disallowed and must fail") - } + assert.Error(t, err, "login with public key is disallowed and must fail") + key, _ := ssh.ParsePrivateKey([]byte(testPrivateKey)) authMethods := []ssh.AuthMethod{ ssh.PublicKeys(key), @@ -1085,14 +815,9 @@ func TestMultiStepLoginKeyAndKeyInt(t *testing.T) { }), } client, err := getCustomAuthSftpClient(user, authMethods) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } authMethods = []ssh.AuthMethod{ ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) { @@ -1101,120 +826,85 @@ func TestMultiStepLoginKeyAndKeyInt(t *testing.T) { ssh.PublicKeys(key), } _, err = getCustomAuthSftpClient(user, authMethods) - if err == nil { - t.Error("multi step auth login with wrong order must fail") - } + assert.Error(t, err, "multi step auth login with wrong order must fail") + authMethods = []ssh.AuthMethod{ ssh.PublicKeys(key), ssh.Password(defaultPassword), } _, err = getCustomAuthSftpClient(user, authMethods) - if err == nil { - t.Error("multi step auth login with wrong method must fail") - } + assert.Error(t, err, "multi step auth login with wrong method must fail") + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginUserStatus(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with valid credentials must work") - } + assert.NoError(t, checkBasicSFTP(client)) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if user.LastLogin <= 0 { - t.Errorf("last login must be updated after a successful login: %v", user.LastLogin) - } + assert.NoError(t, err) + assert.Greater(t, user.LastLogin, int64(0), "last login must be updated after a successful login: %v", user.LastLogin) } user.Status = 0 user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login for a disabled user must fail") - defer client.Close() + if !assert.Error(t, err, "login for a disabled user must fail") { + client.Close() } + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginUserExpiration(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with valid credentials must work") - } + assert.NoError(t, checkBasicSFTP(client)) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if user.LastLogin <= 0 { - t.Errorf("last login must be updated after a successful login: %v", user.LastLogin) - } + assert.NoError(t, err) + assert.Greater(t, user.LastLogin, int64(0), "last login must be updated after a successful login: %v", user.LastLogin) } user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) - 120000 user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login for an expired user must fail") - defer client.Close() + if !assert.Error(t, err, "login for an expired user must fail") { + client.Close() } user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) + 120000 _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("login for a non expired user must succeed: %v", err) - } else { - defer client.Close() + if assert.NoError(t, err) { + client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginInvalidFs(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } - config.LoadConfig(configDir, "") + err := config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() if providerConf.Driver != dataprovider.SQLiteDataProviderName { t.Skip("this test require sqlite provider") @@ -1226,76 +916,60 @@ func TestLoginInvalidFs(t *testing.T) { usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) + // we update the database using sqlite3 CLI since we cannot add a user with an invalid config - time.Sleep(200 * time.Millisecond) updateUserQuery := fmt.Sprintf("UPDATE users SET filesystem='{\"provider\":1}' WHERE id=%v", user.ID) - cmd := exec.Command("sqlite3", dbPath, updateUserQuery) + cmd := exec.Command("sqlite3", "-cmd", "\".timeout 2000\"", dbPath, updateUserQuery) out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("unexpected error: %v, cmd out: %v", err, string(out)) - } - time.Sleep(200 * time.Millisecond) - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Error("login must fail, the user has an invalid filesystem config") + assert.NoError(t, err, "unexpected error: %v, cmd out: %v", err, string(out)) + + client, err := getSftpClient(user, usePubKey) + if !assert.Error(t, err, "login must fail, the user has an invalid filesystem config") { + client.Close() } + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestDeniedLoginMethods(t *testing.T) { u := getTestUser(true) u.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodPassword} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - _, err = getSftpClient(user, true) - if err == nil { - t.Error("public key login is disabled, authentication must fail") + assert.NoError(t, err) + client, err := getSftpClient(user, true) + if !assert.Error(t, err, "public key login is disabled, authentication must fail") { + client.Close() } user.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodKeyboardInteractive, dataprovider.SSHLoginMethodPassword} user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } - client, err := getSftpClient(user, true) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + assert.NoError(t, err) + client, err = getSftpClient(user, true) + if assert.NoError(t, err) { client.Close() } user.Password = defaultPassword user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } - _, err = getSftpClient(user, false) - if err == nil { - t.Error("password login is disabled, authentication must fail") + assert.NoError(t, err) + + client, err = getSftpClient(user, false) + if !assert.Error(t, err, "password login is disabled, authentication must fail") { + client.Close() } user.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodKeyboardInteractive, dataprovider.SSHLoginMethodPublicKey} user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, false) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginWithIPFilters(t *testing.T) { @@ -1304,699 +978,529 @@ func TestLoginWithIPFilters(t *testing.T) { u.Filters.DeniedIP = []string{"192.167.0.0/24", "172.18.0.0/16"} u.Filters.AllowedIP = []string{} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("sftp client with valid credentials must work") - } + assert.NoError(t, checkBasicSFTP(client)) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if user.LastLogin <= 0 { - t.Errorf("last login must be updated after a successful login: %v", user.LastLogin) - } + assert.NoError(t, err) + assert.Greater(t, user.LastLogin, int64(0), "last login must be updated after a successful login: %v", user.LastLogin) } user.Filters.AllowedIP = []string{"127.0.0.0/8"} _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("login from an allowed IP must succeed: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() + assert.NoError(t, checkBasicSFTP(client)) } user.Filters.AllowedIP = []string{"172.19.0.0/16"} _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login from an not allowed IP must fail") + if !assert.Error(t, err, "login from an not allowed IP must fail") { client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginAfterUserUpdateEmptyPwd(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) user.Password = "" user.PublicKeys = []string{} // password and public key should remain unchanged _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - _, err = client.ReadDir(".") - if err != nil { - t.Errorf("unable to read remote dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginAfterUserUpdateEmptyPubKey(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) user.Password = "" user.PublicKeys = []string{} // password and public key should remain unchanged _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - _, err = client.ReadDir(".") - if err != nil { - t.Errorf("unable to read remote dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestLoginKeyboardInteractiveAuth(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } user, _, err := httpd.AddUser(getTestUser(false), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + assert.NoError(t, err) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + assert.NoError(t, err) client, err := getKeyboardInteractiveSftpClient(user, []string{"1", "2"}) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - _, err = client.ReadDir(".") - if err != nil { - t.Errorf("unable to read remote dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } user.Status = 0 user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("error updating user: %v", err) - } + assert.NoError(t, err) client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"}) - if err == nil { - t.Error("keyboard interactive auth must fail the user is disabled") + if !assert.Error(t, err, "keyboard interactive auth must fail the user is disabled") { + client.Close() } user.Status = 1 user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("error updating user: %v", err) - } - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, -1), 0755) + assert.NoError(t, err) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, -1), 0755) + assert.NoError(t, err) client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"}) - if err == nil { - t.Error("keyboard interactive auth must fail the script returned -1") + if !assert.Error(t, err, "keyboard interactive auth must fail the script returned -1") { + client.Close() } - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, true, 1), 0755) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, true, 1), 0755) + assert.NoError(t, err) client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"}) - if err == nil { - t.Error("keyboard interactive auth must fail the script returned bad json") + if !assert.Error(t, err, "keyboard interactive auth must fail the script returned bad json") { + client.Close() } - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 5, true, 1), 0755) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 5, true, 1), 0755) + assert.NoError(t, err) client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"}) - if err == nil { - t.Error("keyboard interactive auth must fail the script returned bad json") + if !assert.Error(t, err, "keyboard interactive auth must fail the script returned bad json") { + client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPreLoginScript(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := true u := getTestUser(usePubKey) dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() - ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(u, false), 0755) + err = ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(u, false), 0755) + assert.NoError(t, err) providerConf.PreLoginHook = preLoginPath - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } - ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, true), 0755) - _, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("pre-login script returned a non json response, login must fail") + err = ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, true), 0755) + assert.NoError(t, err) + client, err = getSftpClient(u, usePubKey) + if !assert.Error(t, err, "pre-login script returned a non json response, login must fail") { + client.Close() } user.Status = 0 - ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, false), 0755) - _, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("pre-login script returned a disabled user, login must fail") + err = ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, false), 0755) + assert.NoError(t, err) + client, err = getSftpClient(u, usePubKey) + if !assert.Error(t, err, "pre-login script returned a disabled user, login must fail") { + client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(preLoginPath) + err = os.Remove(preLoginPath) + assert.NoError(t, err) } func TestPreLoginUserCreation(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := false u := getTestUser(usePubKey) dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() - ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(u, false), 0755) + err = ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(u, false), 0755) + assert.NoError(t, err) providerConf.PreLoginHook = preLoginPath - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 0 { - t.Errorf("number of users mismatch, expected: 0, actual: %v", len(users)) - } + users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 0, len(users)) client, err := getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - } - users, out, err = httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 1 { - t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users)) + assert.NoError(t, checkBasicSFTP(client)) } + users, _, err = httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 1, len(users)) user := users[0] - os.RemoveAll(user.GetHomeDir()) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(preLoginPath) + err = os.Remove(preLoginPath) + assert.NoError(t, err) } func TestLoginExternalAuthPwdAndPubKey(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := true u := getTestUser(usePubKey) u.QuotaFiles = 1000 dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755) + err = ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, false), 0755) + assert.NoError(t, err) providerConf.ExternalAuthHook = extAuthPath providerConf.ExternalAuthScope = 0 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) client, err := getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } u.Username = defaultUsername + "1" client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with invalid user must fail") + if !assert.Error(t, err, "external auth login with invalid user must fail") { + client.Close() } usePubKey = false u = getTestUser(usePubKey) u.PublicKeys = []string{} - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755) + err = ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, false), 0755) + assert.NoError(t, err) client, err = getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - } - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 1 { - t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users)) + assert.NoError(t, checkBasicSFTP(client)) } + users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 1, len(users)) user := users[0] - if len(user.PublicKeys) != 0 { - t.Errorf("number of public keys mismatch, expected: 0, actual: %v", len(user.PublicKeys)) - } - if user.UsedQuotaSize == 0 { - t.Error("quota size must be > 0") - } + assert.Equal(t, 0, len(user.PublicKeys)) + assert.Greater(t, user.UsedQuotaSize, int64(0)) + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(extAuthPath) + err = os.Remove(extAuthPath) + assert.NoError(t, err) } -func TestLoginExternalAuthPwd(t *testing.T) { - if runtime.GOOS == "windows" { +func TestLoginExternalAuth(t *testing.T) { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } - usePubKey := false - u := getTestUser(usePubKey) - dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") - providerConf := config.GetProviderConf() - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755) - providerConf.ExternalAuthHook = extAuthPath - providerConf.ExternalAuthScope = 1 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } - httpd.SetDataProvider(dataprovider.GetProvider()) - sftpd.SetDataProvider(dataprovider.GetProvider()) - - client, err := getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { - defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) + extAuthScopes := []int{1, 2} + for _, authScope := range extAuthScopes { + var usePubKey bool + if authScope == 1 { + usePubKey = false + } else { + usePubKey = true } - } - u.Username = defaultUsername + "1" - client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with invalid user must fail") - } - usePubKey = true - u = getTestUser(usePubKey) - client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with valid user but invalid auth scope must fail") - } - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 1 { - t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users)) - } - user := users[0] - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + u := getTestUser(usePubKey) + dataProvider := dataprovider.GetProvider() + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) + providerConf := config.GetProviderConf() + err = ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, false), 0755) + assert.NoError(t, err) + providerConf.ExternalAuthHook = extAuthPath + providerConf.ExternalAuthScope = authScope + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) + httpd.SetDataProvider(dataprovider.GetProvider()) + sftpd.SetDataProvider(dataprovider.GetProvider()) - dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") - providerConf = config.GetProviderConf() - err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } - httpd.SetDataProvider(dataprovider.GetProvider()) - sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(extAuthPath) -} - -func TestLoginExternalAuthPubKey(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("this test is not available on Windows") - } - usePubKey := true - u := getTestUser(usePubKey) - dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") - providerConf := config.GetProviderConf() - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755) - providerConf.ExternalAuthHook = extAuthPath - providerConf.ExternalAuthScope = 2 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } - httpd.SetDataProvider(dataprovider.GetProvider()) - sftpd.SetDataProvider(dataprovider.GetProvider()) - - client, err := getSftpClient(u, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { - defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) + client, err := getSftpClient(u, usePubKey) + if assert.NoError(t, err) { + defer client.Close() + assert.NoError(t, checkBasicSFTP(client)) } - } - u.Username = defaultUsername + "1" - client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with invalid user must fail") - } - usePubKey = false - u = getTestUser(usePubKey) - client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with valid user but invalid auth scope must fail") - } - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 1 { - t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users)) - } - user := users[0] - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + u.Username = defaultUsername + "1" + client, err = getSftpClient(u, usePubKey) + if !assert.Error(t, err, "external auth login with invalid user must fail") { + client.Close() + } + usePubKey = !usePubKey + u = getTestUser(usePubKey) + client, err = getSftpClient(u, usePubKey) + if !assert.Error(t, err, "external auth login with valid user but invalid auth scope must fail") { + client.Close() + } + users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 1, len(users)) - dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") - providerConf = config.GetProviderConf() - err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") + user := users[0] + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + + dataProvider = dataprovider.GetProvider() + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) + providerConf = config.GetProviderConf() + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) + httpd.SetDataProvider(dataprovider.GetProvider()) + sftpd.SetDataProvider(dataprovider.GetProvider()) + err = os.Remove(extAuthPath) + assert.NoError(t, err) } - httpd.SetDataProvider(dataprovider.GetProvider()) - sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(extAuthPath) } func TestLoginExternalAuthInteractive(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := false u := getTestUser(usePubKey) dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755) + err = ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, false), 0755) + assert.NoError(t, err) providerConf.ExternalAuthHook = extAuthPath providerConf.ExternalAuthScope = 4 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + err = ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755) + assert.NoError(t, err) client, err := getKeyboardInteractiveSftpClient(u, []string{"1", "2"}) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } u.Username = defaultUsername + "1" client, err = getKeyboardInteractiveSftpClient(u, []string{"1", "2"}) - if err == nil { - t.Error("external auth login with invalid user must fail") + if !assert.Error(t, err, "external auth login with invalid user must fail") { + client.Close() } usePubKey = true u = getTestUser(usePubKey) client, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("external auth login with valid user but invalid auth scope must fail") - } - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 1 { - t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users)) + if !assert.Error(t, err, "external auth login with valid user but invalid auth scope must fail") { + client.Close() } + users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 1, len(users)) user := users[0] _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(extAuthPath) + err = os.Remove(extAuthPath) + assert.NoError(t, err) } func TestLoginExternalAuthErrors(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := true u := getTestUser(usePubKey) dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() - ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, true), 0755) + err = ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, true), 0755) + assert.NoError(t, err) providerConf.ExternalAuthHook = extAuthPath providerConf.ExternalAuthScope = 0 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - _, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("login must fail, external auth returns a non json response") + client, err := getSftpClient(u, usePubKey) + if !assert.Error(t, err, "login must fail, external auth returns a non json response") { + client.Close() } + usePubKey = false u = getTestUser(usePubKey) - _, err = getSftpClient(u, usePubKey) - if err == nil { - t.Error("login must fail, external auth returns a non json response") - } - users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) - if err != nil { - t.Errorf("unable to get users: %v, out: %v", err, string(out)) - } - if len(users) != 0 { - t.Errorf("number of users mismatch, expected: 0, actual: %v", len(users)) + client, err = getSftpClient(u, usePubKey) + if !assert.Error(t, err, "login must fail, external auth returns a non json response") { + client.Close() } + users, _, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK) + assert.NoError(t, err) + assert.Equal(t, 0, len(users)) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) - os.Remove(extAuthPath) + err = os.Remove(extAuthPath) + assert.NoError(t, err) } func TestQuotaDisabledError(t *testing.T) { dataProvider := dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err := dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf := config.GetProviderConf() providerConf.TrackQuota = 0 - err := dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + err = dataprovider.Initialize(providerConf, configDir) + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) usePubKey := false u := getTestUser(usePubKey) u.QuotaFiles = 10 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) dataProvider = dataprovider.GetProvider() - dataprovider.Close(dataProvider) - config.LoadConfig(configDir, "") + err = dataprovider.Close(dataProvider) + assert.NoError(t, err) + err = config.LoadConfig(configDir, "") + assert.NoError(t, err) providerConf = config.GetProviderConf() err = dataprovider.Initialize(providerConf, configDir) - if err != nil { - t.Errorf("error initializing data provider") - } + assert.NoError(t, err) httpd.SetDataProvider(dataprovider.GetProvider()) sftpd.SetDataProvider(dataprovider.GetProvider()) } @@ -2007,32 +1511,18 @@ func TestMaxSessions(t *testing.T) { u.Username += "1" u.MaxSessions = 1 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err := client.Getwd() - if err != nil { - t.Errorf("unable to get working dir: %v", err) - } - _, err = client.ReadDir(".") - if err != nil { - t.Errorf("unable to read remote dir: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("max sessions exceeded, new login should not succeed") - } + assert.Error(t, err, "max sessions exceeded, new login should not succeed") } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestQuotaFileReplace(t *testing.T) { @@ -2040,147 +1530,97 @@ func TestQuotaFileReplace(t *testing.T) { u := getTestUser(usePubKey) u.QuotaFiles = 1000 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) testFileSize := int64(65535) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() expectedQuotaSize := user.UsedQuotaSize + testFileSize expectedQuotaFiles := user.UsedQuotaFiles + 1 err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } + assert.NoError(t, err) // now replace the same file, the quota must not change err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) } // now set a quota size restriction and upload the same file, upload should fail for space limit exceeded user.QuotaSize = testFileSize - 1 user, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("error updating user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err == nil { - t.Errorf("quota size exceeded, file upload must fail") - } + assert.Error(t, err, "quota size exceeded, file upload must fail") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.Remove(testFilePath) - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestQuotaScan(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileSize := int64(65535) expectedQuotaSize := user.UsedQuotaSize + testFileSize expectedQuotaFiles := user.UsedQuotaFiles + 1 client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) // create user with the same home dir, so there is at least an untracked file user, _, err = httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) _, err = httpd.StartQuotaScan(user, http.StatusCreated) - if err != nil { - t.Errorf("error starting quota scan: %v", err) - } + assert.NoError(t, err) err = waitQuotaScans() - if err != nil { - t.Errorf("error waiting for active quota scans: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match after scan, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match after scan, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestMultipleQuotaScans(t *testing.T) { - if !sftpd.AddQuotaScan(defaultUsername) { - t.Errorf("add quota failed") - } - if sftpd.AddQuotaScan(defaultUsername) { - t.Errorf("add quota must fail if another scan is already active") - } - sftpd.RemoveQuotaScan(defaultUsername) + res := sftpd.AddQuotaScan(defaultUsername) + assert.True(t, res) + res = sftpd.AddQuotaScan(defaultUsername) + assert.False(t, res, "add quota must fail if another scan is already active") + err := sftpd.RemoveQuotaScan(defaultUsername) + assert.NoError(t, err) activeScans := sftpd.GetQuotaScans() - if len(activeScans) > 0 { - t.Errorf("no quota scan must be active: %v", len(activeScans)) - } + assert.Equal(t, 0, len(activeScans)) } func TestQuotaSize(t *testing.T) { @@ -2190,39 +1630,27 @@ func TestQuotaSize(t *testing.T) { u.QuotaFiles = 1 u.QuotaSize = testFileSize - 1 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName+".quota", testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName+".quota.1", testFileSize, client) - if err == nil { - t.Errorf("user is over quota file upload must fail") - } + assert.Error(t, err, "user is over quota file upload must fail") err = client.Remove(testFileName + ".quota") - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestBandwidthAndConnections(t *testing.T) { @@ -2237,29 +1665,19 @@ func TestBandwidthAndConnections(t *testing.T) { wantedUploadElapsed -= 100 wantedDownloadElapsed -= 100 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) startTime := time.Now() err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) elapsed := time.Since(startTime).Nanoseconds() / 1000000 - if elapsed < (wantedUploadElapsed) { - t.Errorf("upload bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedUploadElapsed) - } + assert.GreaterOrEqual(t, elapsed, wantedUploadElapsed, "upload bandwidth throttling not respected") startTime = time.Now() localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") c := sftpDownloadNonBlocking(testFileName, localDownloadPath, testFileSize, client) @@ -2269,13 +1687,9 @@ func TestBandwidthAndConnections(t *testing.T) { time.Sleep(100 * time.Millisecond) sftpd.CheckIdleConnections() err = <-c - if err != nil { - t.Errorf("file download error: %v", err) - } + assert.NoError(t, err) elapsed = time.Since(startTime).Nanoseconds() / 1000000 - if elapsed < (wantedDownloadElapsed) { - t.Errorf("download bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedDownloadElapsed) - } + assert.GreaterOrEqual(t, elapsed, wantedDownloadElapsed, "download bandwidth throttling not respected") // test disconnection c = sftpUploadNonBlocking(testFilePath, testFileName+"_partial", testFileSize, client) waitForActiveTransfer() @@ -2286,43 +1700,34 @@ func TestBandwidthAndConnections(t *testing.T) { sftpd.CloseActiveConnection(stat.ConnectionID) } err = <-c - if err == nil { - t.Errorf("connection closed upload must fail") - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.Error(t, err, "connection closed while uploading: the upload must fail") + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestExtensionsFilters(t *testing.T) { usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileSize := int64(131072) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) } user.Filters.FileExtensions = []dataprovider.ExtensionsFilter{ { @@ -2332,108 +1737,78 @@ func TestExtensionsFilters(t *testing.T) { }, } _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) client, err = getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err == nil { - t.Error("file upload must fail") - } + assert.Error(t, err) err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if err == nil { - t.Error("file download must fail") - } + assert.Error(t, err) err = client.Rename(testFileName, testFileName+"1") - if err == nil { - t.Error("rename must fail") - } + assert.Error(t, err) err = client.Remove(testFileName) - if err == nil { - t.Error("remove must fail") - } + assert.Error(t, err) err = client.Mkdir("dir.zip") - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) err = client.Rename("dir.zip", "dir1.zip") - if err != nil { - t.Errorf("unexpected error: %v", err) - } + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestVirtualFolders(t *testing.T) { usePubKey := true u := getTestUser(usePubKey) mappedPath := filepath.Join(os.TempDir(), "vdir") - vdirPath := "/vdir" + vdirPath := "/vdir" //nolint:goconst u.VirtualFolders = append(u.VirtualFolders, vfs.VirtualFolder{ VirtualPath: vdirPath, MappedPath: mappedPath, }) - os.MkdirAll(mappedPath, 0777) + err := os.MkdirAll(mappedPath, 0777) + assert.NoError(t, err) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileSize := int64(131072) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpUploadFile(testFilePath, path.Join(vdirPath, testFileName), testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpDownloadFile(path.Join(vdirPath, testFileName), localDownloadPath, testFileSize, client) - if err != nil { - t.Errorf("file download error: %v", err) - } + assert.NoError(t, err) err = client.Rename(vdirPath, "new_name") - if err == nil { - t.Error("renaming a virtual folder must fail") - } + assert.Error(t, err, "renaming a virtual folder must fail") err = client.RemoveDirectory(vdirPath) - if err == nil { - t.Error("removing a virtual folder must fail") - } + assert.Error(t, err, "removing a virtual folder must fail") err = client.Mkdir(vdirPath) - if err == nil { - t.Error("creating a virtual folder must fail") - } + assert.Error(t, err, "creating a virtual folder must fail") err = client.Symlink(path.Join(vdirPath, testFileName), vdirPath) - if err == nil { - t.Error("symlink to a virtual folder must fail") - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.Error(t, err, "symlink to a virtual folder must fail") + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(mappedPath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath) + assert.NoError(t, err) } func TestVirtualFoldersQuota(t *testing.T) { @@ -2453,334 +1828,208 @@ func TestVirtualFoldersQuota(t *testing.T) { MappedPath: mappedPath2, ExcludeFromQuota: true, }) - os.MkdirAll(mappedPath1, 0777) - os.MkdirAll(mappedPath2, 0777) - user, _, _ := httpd.AddUser(u, http.StatusOK) + err := os.MkdirAll(mappedPath1, 0777) + assert.NoError(t, err) + err = os.MkdirAll(mappedPath2, 0777) + assert.NoError(t, err) + user, _, err := httpd.AddUser(u, http.StatusOK) + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFileSize := int64(131072) testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, path.Join(vdirPath1, testFileName), testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, path.Join(vdirPath2, testFileName), testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, path.Join(vdirPath2, testFileName), testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) expectedQuotaFiles := 2 expectedQuotaSize := testFileSize * 2 user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) err = client.Remove(path.Join(vdirPath2, testFileName)) - if err != nil { - t.Errorf("unexpected error removing uploaded file: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(mappedPath1) - os.RemoveAll(mappedPath2) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath1) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath2) + assert.NoError(t, err) } func TestMissingFile(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile("missing_file", localDownloadPath, 0, client) - if err == nil { - t.Errorf("download missing file must fail") - } - os.Remove(localDownloadPath) + assert.Error(t, err, "download missing file must fail") + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestOpenError(t *testing.T) { - if runtime.GOOS == "windows" { + if runtime.GOOS == osWindows { t.Skip("this test is not available on Windows") } usePubKey := false u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - os.Chmod(user.GetHomeDir(), 0001) + err = os.Chmod(user.GetHomeDir(), 0001) + assert.NoError(t, err) _, err = client.ReadDir(".") - if err == nil { - t.Errorf("read dir must fail if we have no filesystem read permissions") - } - os.Chmod(user.GetHomeDir(), 0755) + assert.Error(t, err, "read dir must fail if we have no filesystem read permissions") + err = os.Chmod(user.GetHomeDir(), 0755) + assert.NoError(t, err) testFileSize := int64(65535) testFileName := "test_file.dat" testFilePath := filepath.Join(user.GetHomeDir(), testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) _, err = client.Stat(testFileName) - if err != nil { - t.Errorf("file stat error: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if err != nil { - t.Errorf("file download error: %v", err) - } - os.Chmod(testFilePath, 0001) + assert.NoError(t, err) + err = os.Chmod(testFilePath, 0001) + assert.NoError(t, err) err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if err == nil { - t.Errorf("file download must fail if we have no filesystem read permissions") - } + assert.Error(t, err, "file download must fail if we have no filesystem read permissions") err = sftpUploadFile(localDownloadPath, testFileName, testFileSize, client) - if err == nil { - t.Errorf("upload must fail if we have no filesystem write permissions") - } + assert.Error(t, err, "upload must fail if we have no filesystem write permissions") err = client.Mkdir("test") - if err != nil { - t.Errorf("error making dir: %v", err) - } - os.Chmod(user.GetHomeDir(), 0000) + assert.NoError(t, err) + err = os.Chmod(user.GetHomeDir(), 0000) + assert.NoError(t, err) _, err = client.Lstat(testFileName) - if err == nil { - t.Errorf("file stat must fail if we have no filesystem read permissions") - } - os.Chmod(user.GetHomeDir(), 0755) - os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0000) + assert.Error(t, err, "file stat must fail if we have no filesystem read permissions") + err = os.Chmod(user.GetHomeDir(), 0755) + assert.NoError(t, err) + err = os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0000) + assert.NoError(t, err) err = client.Rename(testFileName, path.Join("test", testFileName)) - if err == nil || !strings.Contains(err.Error(), sftp.ErrSSHFxPermissionDenied.Error()) { - t.Errorf("unexpected error: %v expected: %v", err, sftp.ErrSSHFxPermissionDenied) - } - os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0755) - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.Error(t, err) + assert.Contains(t, err.Error(), sftp.ErrSSHFxPermissionDenied.Error()) + err = os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0755) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestOverwriteDirWithFile(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileSize := int64(65535) testFileName := "test_file.dat" - testDirName := "test_dir" + testDirName := "test_dir" //nolint:goconst testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = client.Mkdir(testDirName) - if err != nil { - t.Errorf("mkdir error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testDirName, testFileSize, client) - if err == nil { - t.Errorf("copying a file over an existing dir must fail") - } + assert.Error(t, err, "copying a file over an existing dir must fail") err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Rename(testFileName, testDirName) - if err == nil { - t.Errorf("rename a file over an existing dir must fail") - } + assert.Error(t, err, "rename a file over an existing dir must fail") err = client.RemoveDirectory(testDirName) - if err != nil { - t.Errorf("dir remove error: %v", err) - } + assert.NoError(t, err) err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } -func TestPasswordsHashPbkdf2Sha1(t *testing.T) { - pbkdf2Pwd := "$pbkdf2-sha1$150000$DveVjgYUD05R$X6ydQZdyMeOvpgND2nqGR/0GGic=" - pbkdf2ClearPwd := "password" +func TestHashedPasswords(t *testing.T) { usePubKey := false - u := getTestUser(usePubKey) - u.Password = pbkdf2Pwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = pbkdf2ClearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with pkkdf2 sha1 password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err) - } - } - user.Password = pbkdf2Pwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} + pwdMapping := make(map[string]string) + pwdMapping["$pbkdf2-sha1$150000$DveVjgYUD05R$X6ydQZdyMeOvpgND2nqGR/0GGic="] = "password" //nolint:goconst + pwdMapping["$pbkdf2-sha256$150000$E86a9YMX3zC7$R5J62hsSq+pYw00hLLPKBbcGXmq7fj5+/M0IFoYtZbo="] = "password" + pwdMapping["$pbkdf2-sha512$150000$dsu7T5R3IaVQ$1hFXPO1ntRBcoWkSLKw+s4sAP09Xtu4Ya7CyxFq64jM9zdUg8eRJVr3NcR2vQgb0W9HHvZaILHsL4Q/Vr6arCg=="] = "password" + pwdMapping["$1$b5caebda$VODr/nyhGWgZaY8sJ4x05."] = "password" + pwdMapping["$2a$14$ajq8Q7fbtFRQvXpdCq7Jcuy.Rx1h/L4J60Otx.gyNLbAYctGMJ9tK"] = "secret" + pwdMapping["$6$459ead56b72e44bc$uog86fUxscjt28BZxqFBE2pp2QD8P/1e98MNF75Z9xJfQvOckZnQ/1YJqiq1XeytPuDieHZvDAMoP7352ELkO1"] = "secret" + pwdMapping["$apr1$OBWLeSme$WoJbB736e7kKxMBIAqilb1"] = "password" -func TestPasswordsHashPbkdf2Sha256(t *testing.T) { - pbkdf2Pwd := "$pbkdf2-sha256$150000$E86a9YMX3zC7$R5J62hsSq+pYw00hLLPKBbcGXmq7fj5+/M0IFoYtZbo=" - pbkdf2ClearPwd := "password" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = pbkdf2Pwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = pbkdf2ClearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with pkkdf2 sha256 password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with pkkdf2 sha256 password: %v", err) + for pwd, clearPwd := range pwdMapping { + u := getTestUser(usePubKey) + u.Password = pwd + user, _, err := httpd.AddUser(u, http.StatusOK) + assert.NoError(t, err) + user.Password = clearPwd + client, err := getSftpClient(user, usePubKey) + if assert.NoError(t, err, "unable to login with password %#v", pwd) { + defer client.Close() + assert.NoError(t, checkBasicSFTP(client)) } - } - user.Password = pbkdf2Pwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} - -func TestPasswordsHashPbkdf2Sha512(t *testing.T) { - pbkdf2Pwd := "$pbkdf2-sha512$150000$dsu7T5R3IaVQ$1hFXPO1ntRBcoWkSLKw+s4sAP09Xtu4Ya7CyxFq64jM9zdUg8eRJVr3NcR2vQgb0W9HHvZaILHsL4Q/Vr6arCg==" - pbkdf2ClearPwd := "password" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = pbkdf2Pwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = pbkdf2ClearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with pkkdf2 sha512 password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with pkkdf2 sha512 password: %v", err) + user.Password = pwd + client, err = getSftpClient(user, usePubKey) + if !assert.Error(t, err, "login with wrong password must fail") { + client.Close() } + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } - user.Password = pbkdf2Pwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) } func TestPasswordsHashPbkdf2Sha256_389DS(t *testing.T) { pbkdf389dsPwd := "{PBKDF2_SHA256}AAAIAMZIKG4ie44zJY4HOXI+upFR74PzWLUQV63jg+zzkbEjCK3N4qW583WF7EdcpeoOMQ4HY3aWEXB6lnXhXJixbJkU4vVSJkL6YCbU3TrD0qn1uUUVSkaIgAOtmZENitwbhYhiWfEzGyAtFqkFd75P5xhWJEog9XhQKYrR0f7S3WGGZq03JRcLJ460xpU97bE/sWRn7sshgkWzLuyrs0I+XRKmK7FJeaA9zd+1m44Y3IVmZ2YLdKATzjRHAIgpBC6i1TWOcpKJT1+feP1C9hrxH8vU9baw9thNiO8jSHaZlwb//KpJFe0ahVnG/1ubiG8cO0+CCqDqXVJR6Vr4QZxHP+4pwooW+4TP/L+HFdyA1y6z4gKfqYnBsmb3sD1R1TbxfH4btTdvgZAnBk9CmR3QASkFXxeTYsrmNd5+9IAHc6dm" pbkdf389dsPwd = pbkdf389dsPwd[15:] hashBytes, err := base64.StdEncoding.DecodeString(pbkdf389dsPwd) - if err != nil { - t.Errorf("unable to decode 389ds password: %v", err) - } + assert.NoError(t, err) iterBytes := hashBytes[0:4] var iterations int32 - binary.Read(bytes.NewBuffer(iterBytes), binary.BigEndian, &iterations) + err = binary.Read(bytes.NewBuffer(iterBytes), binary.BigEndian, &iterations) + assert.NoError(t, err) salt := hashBytes[4:68] targetKey := hashBytes[68:] key := base64.StdEncoding.EncodeToString(targetKey) @@ -2790,162 +2039,22 @@ func TestPasswordsHashPbkdf2Sha256_389DS(t *testing.T) { u := getTestUser(usePubKey) u.Password = pbkdf2Pwd user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) user.Password = pbkdf2ClearPwd client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with pkkdf2 sha256 password: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with pkkdf2 sha256 password: %v", err) - } + assert.NoError(t, checkBasicSFTP(client)) } user.Password = pbkdf2Pwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") + client, err = getSftpClient(user, usePubKey) + if !assert.Error(t, err, "login with wrong password must fail") { + client.Close() } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} - -func TestPasswordsHashBcrypt(t *testing.T) { - bcryptPwd := "$2a$14$ajq8Q7fbtFRQvXpdCq7Jcuy.Rx1h/L4J60Otx.gyNLbAYctGMJ9tK" - bcryptClearPwd := "secret" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = bcryptPwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = bcryptClearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with bcrypt password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with bcrypt password: %v", err) - } - } - user.Password = bcryptPwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} - -func TestPasswordsHashSHA512Crypt(t *testing.T) { - sha512CryptPwd := "$6$459ead56b72e44bc$uog86fUxscjt28BZxqFBE2pp2QD8P/1e98MNF75Z9xJfQvOckZnQ/1YJqiq1XeytPuDieHZvDAMoP7352ELkO1" - clearPwd := "secret" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = sha512CryptPwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = clearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with sha512 crypt password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with sha512 crypt password: %v", err) - } - } - user.Password = sha512CryptPwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} - -func TestPasswordsHashMD5Crypt(t *testing.T) { - md5CryptPwd := "$1$b5caebda$VODr/nyhGWgZaY8sJ4x05." - clearPwd := "password" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = md5CryptPwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = clearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with md5 crypt password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with md5 crypt password: %v", err) - } - } - user.Password = md5CryptPwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) -} - -func TestPasswordsHashMD5CryptApr1(t *testing.T) { - md5CryptPwd := "$apr1$OBWLeSme$WoJbB736e7kKxMBIAqilb1" - clearPwd := "password" - usePubKey := false - u := getTestUser(usePubKey) - u.Password = md5CryptPwd - user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - user.Password = clearPwd - client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to login with md5 crypt password: %v", err) - } else { - defer client.Close() - _, err = client.Getwd() - if err != nil { - t.Errorf("unable to get working dir with md5 crypt password: %v", err) - } - } - user.Password = md5CryptPwd - _, err = getSftpClient(user, usePubKey) - if err == nil { - t.Errorf("login with wrong password must fail") - } - _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermList(t *testing.T) { @@ -2955,28 +2064,19 @@ func TestPermList(t *testing.T) { dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() _, err = client.ReadDir(".") - if err == nil { - t.Errorf("read remote dir without permission should not succeed") - } + assert.Error(t, err, "read remote dir without permission should not succeed") _, err = client.Stat("test_file") - if err == nil { - t.Errorf("stat remote file without permission should not succeed") - } + assert.Error(t, err, "stat remote file without permission should not succeed") } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermDownload(t *testing.T) { @@ -2986,42 +2086,31 @@ func TestPermDownload(t *testing.T) { dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if err == nil { - t.Errorf("file download without permission should not succeed") - } + assert.Error(t, err, "file download without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) - os.Remove(localDownloadPath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermUpload(t *testing.T) { @@ -3031,32 +2120,24 @@ func TestPermUpload(t *testing.T) { dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err == nil { - t.Errorf("file upload without permission should not succeed") - } - os.Remove(testFilePath) + assert.Error(t, err, "file upload without permission should not succeed") + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermOverwrite(t *testing.T) { @@ -3066,36 +2147,26 @@ func TestPermOverwrite(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("error uploading file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err == nil { - t.Errorf("file overwrite without permission should not succeed") - } - os.Remove(testFilePath) + assert.Error(t, err, "file overwrite without permission should not succeed") + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermDelete(t *testing.T) { @@ -3105,38 +2176,29 @@ func TestPermDelete(t *testing.T) { dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Remove(testFileName) - if err == nil { - t.Errorf("delete without permission should not succeed") - } - os.Remove(testFilePath) + assert.Error(t, err, "delete without permission should not succeed") + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } +//nolint:dupl func TestPermRename(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) @@ -3144,40 +2206,28 @@ func TestPermRename(t *testing.T) { dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Rename(testFileName, testFileName+".rename") - if err == nil { - t.Errorf("rename without permission should not succeed") - } + assert.Error(t, err, "rename without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermCreateDirs(t *testing.T) { @@ -3187,26 +2237,20 @@ func TestPermCreateDirs(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("testdir") - if err == nil { - t.Errorf("mkdir without permission should not succeed") - } + assert.Error(t, err, "mkdir without permission should not succeed") } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } +//nolint:dupl func TestPermSymlink(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) @@ -3214,40 +2258,28 @@ func TestPermSymlink(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Symlink(testFilePath, testFilePath+".symlink") - if err == nil { - t.Errorf("symlink without permission should not succeed") - } + assert.Error(t, err, "symlink without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermChmod(t *testing.T) { @@ -3257,42 +2289,31 @@ func TestPermChmod(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChown, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Chmod(testFileName, 0666) - if err == nil { - t.Errorf("chmod without permission should not succeed") - } + assert.Error(t, err, "chmod without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } +//nolint:dupl func TestPermChown(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) @@ -3300,42 +2321,31 @@ func TestPermChown(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChtimes} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Chown(testFileName, os.Getuid(), os.Getgid()) - if err == nil { - t.Errorf("chown without permission should not succeed") - } + assert.Error(t, err, "chown without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } +//nolint:dupl func TestPermChtimes(t *testing.T) { usePubKey := false u := getTestUser(usePubKey) @@ -3343,40 +2353,28 @@ func TestPermChtimes(t *testing.T) { dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Chtimes(testFileName, time.Now(), time.Now()) - if err == nil { - t.Errorf("chtimes without permission should not succeed") - } + assert.Error(t, err, "chtimes without permission should not succeed") err = client.Remove(testFileName) - if err != nil { - t.Errorf("error removing uploaded file: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestSubDirsUploads(t *testing.T) { @@ -3385,62 +2383,49 @@ func TestSubDirsUploads(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/subdir"] = []string{dataprovider.PermChtimes, dataprovider.PermDownload} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("subdir") - if err != nil { - t.Errorf("unexpected mkdir error: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFileNameSub := "/subdir/test_file_dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileNameSub, testFileSize, client) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected upload error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink(testFileName, testFileNameSub+".link") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected upload error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink(testFileName, testFileName+".link") - if err != nil { - t.Errorf("symlink error: %v", err) - } + assert.NoError(t, err) err = client.Rename(testFileName, testFileNameSub+".rename") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected rename error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Rename(testFileName, testFileName+".rename") - if err != nil { - t.Errorf("rename error: %v", err) - } + assert.NoError(t, err) err = client.Remove(testFileNameSub) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected upload error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Remove(testFileName + ".rename") - if err != nil { - t.Errorf("remove error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestSubDirsOverwrite(t *testing.T) { @@ -3449,38 +2434,31 @@ func TestSubDirsOverwrite(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/subdir"] = []string{dataprovider.PermOverwrite, dataprovider.PermListItems} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - testFileName := "/subdir/test_file.dat" + testFileName := "/subdir/test_file.dat" //nolint:goconst testFilePath := filepath.Join(homeBasePath, "test_file.dat") testFileSFTPPath := filepath.Join(u.GetHomeDir(), "subdir", "test_file.dat") testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = createTestFile(testFileSFTPPath, 16384) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName+".new", testFileSize, client) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected upload error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("unexpected overwrite error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestSubDirsDownloads(t *testing.T) { @@ -3489,59 +2467,53 @@ func TestSubDirsDownloads(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/subdir"] = []string{dataprovider.PermChmod, dataprovider.PermUpload, dataprovider.PermListItems} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("subdir") - if err != nil { - t.Errorf("unexpected mkdir error: %v", err) - } + assert.NoError(t, err) testFileName := "/subdir/test_file.dat" testFilePath := filepath.Join(homeBasePath, "test_file.dat") testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) localDownloadPath := filepath.Join(homeBasePath, "test_download.dat") err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected upload error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected overwrite error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Chtimes(testFileName, time.Now(), time.Now()) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected chtimes error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Rename(testFileName, testFileName+".rename") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected rename error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink(testFileName, testFileName+".link") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected symlink error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Remove(testFileName) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected remove error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } - os.Remove(localDownloadPath) - os.Remove(testFilePath) + err = os.Remove(localDownloadPath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermsSubDirsSetstat(t *testing.T) { @@ -3552,45 +2524,36 @@ func TestPermsSubDirsSetstat(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermCreateDirs} u.Permissions["/subdir"] = []string{dataprovider.PermAny} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Mkdir("subdir") - if err != nil { - t.Errorf("unexpected mkdir error: %v", err) - } + assert.NoError(t, err) testFileName := "/subdir/test_file.dat" testFilePath := filepath.Join(homeBasePath, "test_file.dat") testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) err = client.Chtimes("/subdir/", time.Now(), time.Now()) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected chtimes error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Chtimes("subdir/", time.Now(), time.Now()) - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected chtimes error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Chtimes(testFileName, time.Now(), time.Now()) - if err != nil { - t.Errorf("unexpected chtimes error: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestPermsSubDirsCommands(t *testing.T) { @@ -3599,64 +2562,52 @@ func TestPermsSubDirsCommands(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() - client.Mkdir("subdir") + err = client.Mkdir("subdir") + assert.NoError(t, err) acmodTime := time.Now() err = client.Chtimes("/subdir", acmodTime, acmodTime) - if err != nil { - t.Errorf("unexpected chtimes error: %v", err) - } + assert.NoError(t, err) _, err = client.Stat("/subdir") - if err != nil { - t.Errorf("unexpected stat error: %v", err) - } + assert.NoError(t, err) _, err = client.ReadDir("/") - if err != nil { - t.Errorf("unexpected readdir error: %v", err) - } + assert.NoError(t, err) _, err = client.ReadDir("/subdir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.RemoveDirectory("/subdir/dir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Mkdir("/subdir/dir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } - client.Mkdir("/otherdir") + err = client.Mkdir("/otherdir") + assert.NoError(t, err) err = client.Rename("/otherdir", "/subdir/otherdir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink("/otherdir", "/subdir/otherdir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink("/otherdir", "/otherdir_link") - if err != nil { - t.Errorf("unexpected rename dir error: %v", err) - } + assert.NoError(t, err) err = client.Rename("/otherdir", "/otherdir1") - if err != nil { - t.Errorf("unexpected rename dir error: %v", err) - } + assert.NoError(t, err) err = client.RemoveDirectory("/subdir") - if err != nil { - t.Errorf("unexpected remove dir error: %v", err) - } + assert.NoError(t, err) } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestRootDirCommands(t *testing.T) { @@ -3665,29 +2616,27 @@ func TestRootDirCommands(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() err = client.Rename("/", "rootdir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error renaming root dir: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.Symlink("/", "rootdir") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error symlinking root dir: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } err = client.RemoveDirectory("/") - if !strings.Contains(err.Error(), "Permission Denied") { - t.Errorf("unexpected error removing root dir: %v", err) + if assert.Error(t, err) { + assert.Contains(t, err.Error(), permissionErrorString) } } - httpd.RemoveUser(user, http.StatusOK) - os.RemoveAll(user.GetHomeDir()) + _, err = httpd.RemoveUser(user, http.StatusOK) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestRelativePaths(t *testing.T) { @@ -3703,60 +2652,41 @@ func TestRelativePaths(t *testing.T) { KeyPrefix: keyPrefix, } gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig) - if runtime.GOOS != "windows" { + if runtime.GOOS != osWindows { filesystems = append(filesystems, s3fs, gcsfs) } + rootPath := "/" for _, fs := range filesystems { path = filepath.Join(user.HomeDir, "/") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "//") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "../..") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "../../../../../") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "/..") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "/../../../..") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, ".") rel = fs.GetRelativePath(path) - if rel != "/" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, rootPath, rel) path = filepath.Join(user.HomeDir, "somedir") rel = fs.GetRelativePath(path) - if rel != "/somedir" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, "/somedir", rel) path = filepath.Join(user.HomeDir, "/somedir/subdir") rel = fs.GetRelativePath(path) - if rel != "/somedir/subdir" { - t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name()) - } + assert.Equal(t, "/somedir/subdir", rel) } } @@ -3768,56 +2698,47 @@ func TestResolvePaths(t *testing.T) { keyPrefix := strings.TrimPrefix(user.GetHomeDir(), "/") + "/" s3config := vfs.S3FsConfig{ KeyPrefix: keyPrefix, + Bucket: "bucket", + Region: "us-east-1", } - os.MkdirAll(user.GetHomeDir(), 0777) - s3fs, _ := vfs.NewS3Fs("", user.GetHomeDir(), s3config) + err = os.MkdirAll(user.GetHomeDir(), 0777) + assert.NoError(t, err) + s3fs, err := vfs.NewS3Fs("", user.GetHomeDir(), s3config) + assert.NoError(t, err) gcsConfig := vfs.GCSFsConfig{ KeyPrefix: keyPrefix, } gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig) - if runtime.GOOS != "windows" { + if runtime.GOOS != osWindows { filesystems = append(filesystems, s3fs, gcsfs) } for _, fs := range filesystems { path = "/" resolved, _ = fs.ResolvePath(filepath.ToSlash(path)) - if resolved != fs.Join(user.GetHomeDir(), "/") { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Equal(t, fs.Join(user.GetHomeDir(), "/"), resolved) path = "." resolved, _ = fs.ResolvePath(filepath.ToSlash(path)) - if resolved != fs.Join(user.GetHomeDir(), "/") { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Equal(t, fs.Join(user.GetHomeDir(), "/"), resolved) path = "test/sub" resolved, _ = fs.ResolvePath(filepath.ToSlash(path)) - if resolved != fs.Join(user.GetHomeDir(), "/test/sub") { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Equal(t, fs.Join(user.GetHomeDir(), "/test/sub"), resolved) path = "../test/sub" resolved, err = fs.ResolvePath(filepath.ToSlash(path)) if vfs.IsLocalOsFs(fs) { - if err == nil { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Error(t, err, "Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) } else { - if resolved != fs.Join(user.GetHomeDir(), "/test/sub") && err == nil { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Equal(t, fs.Join(user.GetHomeDir(), "/test/sub"), resolved) } path = "../../../test/../sub" resolved, err = fs.ResolvePath(filepath.ToSlash(path)) if vfs.IsLocalOsFs(fs) { - if err == nil { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Error(t, err, "Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) } else { - if resolved != fs.Join(user.GetHomeDir(), "/sub") && err == nil { - t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name()) - } + assert.Equal(t, fs.Join(user.GetHomeDir(), "/sub"), resolved) } } - os.RemoveAll(user.GetHomeDir()) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestVirtualRelativePaths(t *testing.T) { @@ -3828,29 +2749,20 @@ func TestVirtualRelativePaths(t *testing.T) { VirtualPath: vdirPath, MappedPath: mappedPath, }) - os.MkdirAll(mappedPath, 0777) + err := os.MkdirAll(mappedPath, 0777) + assert.NoError(t, err) fs := vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders) rel := fs.GetRelativePath(mappedPath) - if rel != vdirPath { - t.Errorf("Unexpected relative path: %v", rel) - } + assert.Equal(t, vdirPath, rel) rel = fs.GetRelativePath(filepath.Join(mappedPath, "..")) - if rel != "/" { - t.Errorf("Unexpected relative path: %v", rel) - } + assert.Equal(t, "/", rel) // path outside home and virtual dir rel = fs.GetRelativePath(filepath.Join(mappedPath, "../vdir1")) - if rel != "/" { - t.Errorf("Unexpected relative path: %v", rel) - } + assert.Equal(t, "/", rel) rel = fs.GetRelativePath(filepath.Join(mappedPath, "../vdir/file.txt")) - if rel != "/vdir/file.txt" { - t.Errorf("Unexpected relative path: %v", rel) - } + assert.Equal(t, "/vdir/file.txt", rel) rel = fs.GetRelativePath(filepath.Join(user.HomeDir, "vdir1/file.txt")) - if rel != "/vdir1/file.txt" { - t.Errorf("Unexpected relative path: %v", rel) - } + assert.Equal(t, "/vdir1/file.txt", rel) } func TestResolveVirtualPaths(t *testing.T) { @@ -3861,36 +2773,21 @@ func TestResolveVirtualPaths(t *testing.T) { VirtualPath: vdirPath, MappedPath: mappedPath, }) - os.MkdirAll(mappedPath, 0777) + err := os.MkdirAll(mappedPath, 0777) + assert.NoError(t, err) osFs := vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders).(vfs.OsFs) b, f := osFs.GetFsPaths("/vdir/a.txt") - if b != mappedPath { - t.Errorf("unexpected base path: %#v expected: %#v", b, mappedPath) - } - if f != filepath.Join(mappedPath, "a.txt") { - t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(mappedPath, "a.txt")) - } + assert.Equal(t, mappedPath, b) + assert.Equal(t, filepath.Join(mappedPath, "a.txt"), f) b, f = osFs.GetFsPaths("/vdir/sub with space & spécial chars/a.txt") - if b != mappedPath { - t.Errorf("unexpected base path: %#v expected: %#v", b, mappedPath) - } - if f != filepath.Join(mappedPath, "sub with space & spécial chars/a.txt") { - t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(mappedPath, "sub with space & spécial chars/a.txt")) - } + assert.Equal(t, mappedPath, b) + assert.Equal(t, filepath.Join(mappedPath, "sub with space & spécial chars/a.txt"), f) b, f = osFs.GetFsPaths("/vdir/../a.txt") - if b != user.GetHomeDir() { - t.Errorf("unexpected base path: %#v expected: %#v", b, user.GetHomeDir()) - } - if f != filepath.Join(user.GetHomeDir(), "a.txt") { - t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(user.GetHomeDir(), "a.txt")) - } + assert.Equal(t, user.GetHomeDir(), b) + assert.Equal(t, filepath.Join(user.GetHomeDir(), "a.txt"), f) b, f = osFs.GetFsPaths("/vdir1/a.txt") - if b != user.GetHomeDir() { - t.Errorf("unexpected base path: %#v expected: %#v", b, user.GetHomeDir()) - } - if f != filepath.Join(user.GetHomeDir(), "/vdir1/a.txt") { - t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(user.GetHomeDir(), "/vdir1/a.txt")) - } + assert.Equal(t, user.GetHomeDir(), b) + assert.Equal(t, filepath.Join(user.GetHomeDir(), "/vdir1/a.txt"), f) } func TestVirtualFoldersExcludeQuota(t *testing.T) { @@ -3915,28 +2812,14 @@ func TestVirtualFoldersExcludeQuota(t *testing.T) { ExcludeFromQuota: true, }) - if user.IsFileExcludedFromQuota("/file") { - t.Errorf("unexpected file excluded from quota") - } - if user.IsFileExcludedFromQuota(path.Join(vdirPath, "file")) { - t.Errorf("unexpected file excluded from quota") - } - if !user.IsFileExcludedFromQuota(path.Join(vSubDirPath, "file")) { - t.Errorf("unexpected file included in quota") - } - if !user.IsFileExcludedFromQuota(path.Join(vSubDir1Path, "..", "file")) { - t.Errorf("unexpected file included in quota") - } - if user.IsFileExcludedFromQuota(path.Join(vSubDir1Path, "file")) { - t.Errorf("unexpected file excluded from quota") - } - if user.IsFileExcludedFromQuota(path.Join(vSubDirPath, "..", "file")) { - t.Errorf("unexpected file excluded from quota") - } + assert.False(t, user.IsFileExcludedFromQuota("/file")) + assert.False(t, user.IsFileExcludedFromQuota(path.Join(vdirPath, "file"))) + assert.True(t, user.IsFileExcludedFromQuota(path.Join(vSubDirPath, "file"))) + assert.True(t, user.IsFileExcludedFromQuota(path.Join(vSubDir1Path, "..", "file"))) + assert.False(t, user.IsFileExcludedFromQuota(path.Join(vSubDir1Path, "file"))) + assert.False(t, user.IsFileExcludedFromQuota(path.Join(vSubDirPath, "..", "file"))) // we check the parent dir for a file - if user.IsFileExcludedFromQuota(vSubDirPath) { - t.Errorf("unexpected file excluded from quota") - } + assert.False(t, user.IsFileExcludedFromQuota(vSubDirPath)) } func TestUserPerms(t *testing.T) { @@ -3949,50 +2832,22 @@ func TestUserPerms(t *testing.T) { user.Permissions["/p/3"] = []string{dataprovider.PermChmod} user.Permissions["/p/3/4"] = []string{dataprovider.PermChtimes} user.Permissions["/tmp"] = []string{dataprovider.PermRename} - if !user.HasPerm(dataprovider.PermListItems, "/") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermListItems, ".") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermListItems, "") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermListItems, "../") { - t.Error("expected permission not found") - } + assert.True(t, user.HasPerm(dataprovider.PermListItems, "/")) + assert.True(t, user.HasPerm(dataprovider.PermListItems, ".")) + assert.True(t, user.HasPerm(dataprovider.PermListItems, "")) + assert.True(t, user.HasPerm(dataprovider.PermListItems, "../")) // path p and /p are the same - if !user.HasPerm(dataprovider.PermDelete, "/p") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermDownload, "/p/1") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermCreateDirs, "p/2") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermChmod, "/p/3") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/../4") { - t.Error("expected permission not found") - } + assert.True(t, user.HasPerm(dataprovider.PermDelete, "/p")) + assert.True(t, user.HasPerm(dataprovider.PermDownload, "/p/1")) + assert.True(t, user.HasPerm(dataprovider.PermCreateDirs, "p/2")) + assert.True(t, user.HasPerm(dataprovider.PermChmod, "/p/3")) + assert.True(t, user.HasPerm(dataprovider.PermChtimes, "p/3/4/")) + assert.True(t, user.HasPerm(dataprovider.PermChtimes, "p/3/4/../4")) // undefined paths have permissions of the nearest path - if !user.HasPerm(dataprovider.PermListItems, "/p34") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermListItems, "/p34/p1/file.dat") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermChtimes, "/p/3/4/5/6") { - t.Error("expected permission not found") - } - if !user.HasPerm(dataprovider.PermDownload, "/p/1/test/file.dat") { - t.Error("expected permission not found") - } + assert.True(t, user.HasPerm(dataprovider.PermListItems, "/p34")) + assert.True(t, user.HasPerm(dataprovider.PermListItems, "/p34/p1/file.dat")) + assert.True(t, user.HasPerm(dataprovider.PermChtimes, "/p/3/4/5/6")) + assert.True(t, user.HasPerm(dataprovider.PermDownload, "/p/1/test/file.dat")) } func TestFilterFileExtensions(t *testing.T) { @@ -4006,71 +2861,47 @@ func TestFilterFileExtensions(t *testing.T) { FileExtensions: []dataprovider.ExtensionsFilter{extension}, } user.Filters = filters - if !user.IsFileAllowed("/test/test.jPg") { - t.Error("this file must be allowed") - } - if user.IsFileAllowed("/test/test.pdf") { - t.Error("this file must be denied") - } - if !user.IsFileAllowed("/test.pDf") { - t.Error("this file must be allowed") - } + assert.True(t, user.IsFileAllowed("/test/test.jPg")) + assert.False(t, user.IsFileAllowed("/test/test.pdf")) + assert.True(t, user.IsFileAllowed("/test.pDf")) + filters.FileExtensions = append(filters.FileExtensions, dataprovider.ExtensionsFilter{ Path: "/", AllowedExtensions: []string{".zip", ".rar", ".pdf"}, DeniedExtensions: []string{".gz"}, }) user.Filters = filters - if user.IsFileAllowed("/test1/test.gz") { - t.Error("this file must be denied") - } - if !user.IsFileAllowed("/test1/test.zip") { - t.Error("this file must be allowed") - } - if user.IsFileAllowed("/test/sub/test.pdf") { - t.Error("this file must be denied") - } - if user.IsFileAllowed("/test1/test.png") { - t.Error("this file must be denied") - } + assert.False(t, user.IsFileAllowed("/test1/test.gz")) + assert.True(t, user.IsFileAllowed("/test1/test.zip")) + assert.False(t, user.IsFileAllowed("/test/sub/test.pdf")) + assert.False(t, user.IsFileAllowed("/test1/test.png")) + filters.FileExtensions = append(filters.FileExtensions, dataprovider.ExtensionsFilter{ Path: "/test/sub", DeniedExtensions: []string{".tar"}, }) user.Filters = filters - if user.IsFileAllowed("/test/sub/sub/test.tar") { - t.Error("this file must be denied") - } - if !user.IsFileAllowed("/test/sub/test.gz") { - t.Error("this file must be allowed") - } - if user.IsFileAllowed("/test/test.zip") { - t.Error("this file must be denied") - } + assert.False(t, user.IsFileAllowed("/test/sub/sub/test.tar")) + assert.True(t, user.IsFileAllowed("/test/sub/test.gz")) + assert.False(t, user.IsFileAllowed("/test/test.zip")) } func TestUserAllowedLoginMethods(t *testing.T) { user := getTestUser(true) user.Filters.DeniedLoginMethods = dataprovider.ValidSSHLoginMethods allowedMethods := user.GetAllowedLoginMethods() - if len(allowedMethods) != 0 { - t.Errorf("unexpected allowed methods: %+v", allowedMethods) - } + assert.Equal(t, 0, len(allowedMethods)) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPassword, dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodKeyboardInteractive, } allowedMethods = user.GetAllowedLoginMethods() - if len(allowedMethods) != 2 { - t.Errorf("unexpected allowed methods: %+v", allowedMethods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyAndKeyboardInt, allowedMethods) { - t.Errorf("unexpected allowed methods: %+v", allowedMethods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyAndPassword, allowedMethods) { - t.Errorf("unexpected allowed methods: %+v", allowedMethods) - } + assert.Equal(t, 2, len(allowedMethods)) + + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyAndKeyboardInt, allowedMethods)) + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyAndPassword, allowedMethods)) } func TestUserPartialAuth(t *testing.T) { @@ -4080,29 +2911,21 @@ func TestUserPartialAuth(t *testing.T) { dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodKeyboardInteractive, } - if user.IsPartialAuth(dataprovider.SSHLoginMethodPassword) { - t.Error("unexpected partial auth method") - } - if user.IsPartialAuth(dataprovider.SSHLoginMethodKeyboardInteractive) { - t.Error("unexpected partial auth method") - } - if !user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey) { - t.Error("public key must be a partial auth method with this configuration") - } + assert.False(t, user.IsPartialAuth(dataprovider.SSHLoginMethodPassword)) + assert.False(t, user.IsPartialAuth(dataprovider.SSHLoginMethodKeyboardInteractive)) + assert.True(t, user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey)) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPassword, dataprovider.SSHLoginMethodKeyboardInteractive, } - if user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey) { - t.Error("public key must not be a partial auth method with this configuration") - } + assert.False(t, user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey)) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPassword, dataprovider.SSHLoginMethodPublicKey, } - if user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey) { - t.Error("public key must not be a partial auth method with this configuration") - } + assert.False(t, user.IsPartialAuth(dataprovider.SSHLoginMethodPublicKey)) } func TestUserGetNextAuthMethods(t *testing.T) { @@ -4113,34 +2936,25 @@ func TestUserGetNextAuthMethods(t *testing.T) { dataprovider.SSHLoginMethodKeyboardInteractive, } methods := user.GetNextAuthMethods(nil) - if len(methods) != 0 { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 0, len(methods)) + methods = user.GetNextAuthMethods([]string{dataprovider.SSHLoginMethodPassword}) - if len(methods) != 0 { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 0, len(methods)) + methods = user.GetNextAuthMethods([]string{dataprovider.SSHLoginMethodKeyboardInteractive}) - if len(methods) != 0 { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 0, len(methods)) + methods = user.GetNextAuthMethods([]string{ dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodKeyboardInteractive, }) - if len(methods) != 0 { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 0, len(methods)) + methods = user.GetNextAuthMethods([]string{dataprovider.SSHLoginMethodPublicKey}) - if len(methods) != 2 { - t.Errorf("unexpected next auth methods: %+v", methods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodPassword, methods) { - t.Errorf("unexpected next auth methods: %+v", methods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, methods) { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 2, len(methods)) + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodPassword, methods)) + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, methods)) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPassword, dataprovider.SSHLoginMethodPublicKey, @@ -4148,12 +2962,9 @@ func TestUserGetNextAuthMethods(t *testing.T) { dataprovider.SSHLoginMethodKeyAndKeyboardInt, } methods = user.GetNextAuthMethods([]string{dataprovider.SSHLoginMethodPublicKey}) - if len(methods) != 1 { - t.Errorf("unexpected next auth methods: %+v", methods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodPassword, methods) { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 1, len(methods)) + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodPassword, methods)) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPassword, dataprovider.SSHLoginMethodPublicKey, @@ -4161,12 +2972,8 @@ func TestUserGetNextAuthMethods(t *testing.T) { dataprovider.SSHLoginMethodKeyAndPassword, } methods = user.GetNextAuthMethods([]string{dataprovider.SSHLoginMethodPublicKey}) - if len(methods) != 1 { - t.Errorf("unexpected next auth methods: %+v", methods) - } - if !utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, methods) { - t.Errorf("unexpected next auth methods: %+v", methods) - } + assert.Equal(t, 1, len(methods)) + assert.True(t, utils.IsStringInSlice(dataprovider.SSHLoginMethodKeyboardInteractive, methods)) } func TestUserIsLoginMethodAllowed(t *testing.T) { @@ -4176,22 +2983,15 @@ func TestUserIsLoginMethodAllowed(t *testing.T) { dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodKeyboardInteractive, } - if user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, nil) { - t.Error("unexpected login method allowed") - } - if !user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, []string{dataprovider.SSHLoginMethodPublicKey}) { - t.Error("unexpected login method denied") - } - if !user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodKeyboardInteractive, []string{dataprovider.SSHLoginMethodPublicKey}) { - t.Error("unexpected login method denied") - } + assert.False(t, user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, nil)) + assert.True(t, user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, []string{dataprovider.SSHLoginMethodPublicKey})) + assert.True(t, user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodKeyboardInteractive, []string{dataprovider.SSHLoginMethodPublicKey})) + user.Filters.DeniedLoginMethods = []string{ dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodKeyboardInteractive, } - if !user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, nil) { - t.Error("unexpected login method denied") - } + assert.True(t, user.IsLoginMethodAllowed(dataprovider.SSHLoginMethodPassword, nil)) } func TestUserEmptySubDirPerms(t *testing.T) { @@ -4199,274 +2999,195 @@ func TestUserEmptySubDirPerms(t *testing.T) { user.Permissions = make(map[string][]string) user.Permissions["/emptyperms"] = []string{} for _, p := range dataprovider.ValidPerms { - if user.HasPerm(p, "/emptyperms") { - t.Errorf("unexpected permission %#v for dir /emptyperms", p) - } + assert.False(t, user.HasPerm(p, "/emptyperms")) } } func TestUserFiltersIPMaskConditions(t *testing.T) { user := getTestUser(true) // with no filter login must be allowed even if the remoteIP is invalid - if !user.IsLoginFromAddrAllowed("192.168.1.5") { - t.Error("unexpected login denied") - } - if !user.IsLoginFromAddrAllowed("invalid") { - t.Error("unexpected login denied") - } + assert.True(t, user.IsLoginFromAddrAllowed("192.168.1.5")) + assert.True(t, user.IsLoginFromAddrAllowed("invalid")) + user.Filters.DeniedIP = append(user.Filters.DeniedIP, "192.168.1.0/24") - if user.IsLoginFromAddrAllowed("192.168.1.5") { - t.Error("unexpected login allowed") - } - if !user.IsLoginFromAddrAllowed("192.168.2.6") { - t.Error("unexpected login denied") - } + assert.False(t, user.IsLoginFromAddrAllowed("192.168.1.5")) + assert.True(t, user.IsLoginFromAddrAllowed("192.168.2.6")) + user.Filters.AllowedIP = append(user.Filters.AllowedIP, "192.168.1.5/32") // if the same ip/mask is both denied and allowed then login must be denied - if user.IsLoginFromAddrAllowed("192.168.1.5") { - t.Error("unexpected login allowed") - } - if user.IsLoginFromAddrAllowed("192.168.3.6") { - t.Error("unexpected login allowed") - } + assert.False(t, user.IsLoginFromAddrAllowed("192.168.1.5")) + assert.False(t, user.IsLoginFromAddrAllowed("192.168.3.6")) + user.Filters.DeniedIP = []string{} - if !user.IsLoginFromAddrAllowed("192.168.1.5") { - t.Error("unexpected login denied") - } - if user.IsLoginFromAddrAllowed("192.168.1.6") { - t.Error("unexpected login allowed") - } + assert.True(t, user.IsLoginFromAddrAllowed("192.168.1.5")) + assert.False(t, user.IsLoginFromAddrAllowed("192.168.1.6")) + user.Filters.DeniedIP = []string{"192.168.0.0/16", "172.16.0.0/16"} user.Filters.AllowedIP = []string{} - if user.IsLoginFromAddrAllowed("192.168.5.255") { - t.Error("unexpected login allowed") - } - if user.IsLoginFromAddrAllowed("172.16.1.2") { - t.Error("unexpected login allowed") - } - if !user.IsLoginFromAddrAllowed("172.18.2.1") { - t.Error("unexpected login denied") - } + assert.False(t, user.IsLoginFromAddrAllowed("192.168.5.255")) + assert.False(t, user.IsLoginFromAddrAllowed("172.16.1.2")) + assert.True(t, user.IsLoginFromAddrAllowed("172.18.2.1")) + user.Filters.AllowedIP = []string{"10.4.4.0/24"} - if user.IsLoginFromAddrAllowed("10.5.4.2") { - t.Error("unexpected login allowed") - } - if !user.IsLoginFromAddrAllowed("10.4.4.2") { - t.Error("unexpected login denied") - } - if !user.IsLoginFromAddrAllowed("invalid") { - t.Error("unexpected login denied") - } + assert.False(t, user.IsLoginFromAddrAllowed("10.5.4.2")) + assert.True(t, user.IsLoginFromAddrAllowed("10.4.4.2")) + assert.True(t, user.IsLoginFromAddrAllowed("invalid")) } func TestSSHCommands(t *testing.T) { usePubKey := false user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) _, err = runSSHCommand("ls", user, usePubKey) - if err == nil { - t.Errorf("unsupported ssh command must fail") - } + assert.Error(t, err, "unsupported ssh command must fail") + _, err = runSSHCommand("cd", user, usePubKey) - if err != nil { - t.Errorf("unexpected error for ssh cd command: %v", err) - } + assert.NoError(t, err) out, err := runSSHCommand("pwd", user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } - if string(out) != "/\n" { - t.Errorf("invalid response for ssh pwd command: %v", string(out)) + if assert.NoError(t, err) { + assert.Equal(t, "/\n", string(out)) } out, err = runSSHCommand("md5sum", user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } + assert.NoError(t, err) // echo -n '' | md5sum - if !strings.Contains(string(out), "d41d8cd98f00b204e9800998ecf8427e") { - t.Errorf("invalid md5sum: %v", string(out)) - } + assert.Contains(t, string(out), "d41d8cd98f00b204e9800998ecf8427e") + out, err = runSSHCommand("sha1sum", user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } - if !strings.Contains(string(out), "da39a3ee5e6b4b0d3255bfef95601890afd80709") { - t.Errorf("invalid sha1sum: %v", string(out)) - } + assert.NoError(t, err) + assert.Contains(t, string(out), "da39a3ee5e6b4b0d3255bfef95601890afd80709") + out, err = runSSHCommand("sha256sum", user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } - if !strings.Contains(string(out), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") { - t.Errorf("invalid sha256sum: %v", string(out)) - } + assert.NoError(t, err) + assert.Contains(t, string(out), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") + out, err = runSSHCommand("sha384sum", user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } - if !strings.Contains(string(out), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") { - t.Errorf("invalid sha384sum: %v", string(out)) - } + assert.NoError(t, err) + assert.Contains(t, string(out), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSSHFileHash(t *testing.T) { usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) client, err := getSftpClient(user, usePubKey) - if err != nil { - t.Errorf("unable to create sftp client: %v", err) - } else { + if assert.NoError(t, err) { defer client.Close() testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = sftpUploadFile(testFilePath, testFileName, testFileSize, client) - if err != nil { - t.Errorf("file upload error: %v", err) - } + assert.NoError(t, err) user.Permissions = make(map[string][]string) user.Permissions["/"] = []string{dataprovider.PermUpload} _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) _, err = runSSHCommand("sha512sum "+testFileName, user, usePubKey) - if err == nil { - t.Errorf("hash command with no list permission must fail") - } + assert.Error(t, err, "hash command with no list permission must fail") + user.Permissions["/"] = []string{dataprovider.PermAny} _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) + initialHash, err := computeHashForFile(sha512.New(), testFilePath) - if err != nil { - t.Errorf("error computing file hash: %v", err) - } + assert.NoError(t, err) + out, err := runSSHCommand("sha512sum "+testFileName, user, usePubKey) - if err != nil { - t.Errorf("unexpected error: %v", err) - t.Fail() - } - if !strings.Contains(string(out), initialHash) { - t.Errorf("invalid sha512sum: %v", string(out)) + if assert.NoError(t, err) { + assert.Contains(t, string(out), initialHash) } _, err = runSSHCommand("sha512sum invalid_path", user, usePubKey) - if err == nil { - t.Errorf("hash for an invalid path must fail") - } - os.Remove(testFilePath) + assert.Error(t, err, "hash for an invalid path must fail") + + err = os.Remove(testFilePath) + assert.NoError(t, err) } _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestBasicGitCommands(t *testing.T) { - if len(gitPath) == 0 || len(sshPath) == 0 { - t.Skip("git and/or ssh command not found, unable to execute this test") + if len(gitPath) == 0 || len(sshPath) == 0 || runtime.GOOS == osWindows { + t.Skip("git and/or ssh command not found or OS is windows, unable to execute this test") } usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) + repoName := "testrepo" clonePath := filepath.Join(homeBasePath, repoName) - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(filepath.Join(homeBasePath, repoName)) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(filepath.Join(homeBasePath, repoName)) + assert.NoError(t, err) out, err := initGitRepo(filepath.Join(user.HomeDir, repoName)) - if err != nil { - t.Errorf("unexpected error: %v out: %v", err, string(out)) - } + assert.NoError(t, err, "unexpected error, out: %v", string(out)) + out, err = cloneGitRepo(homeBasePath, "/"+repoName, user.Username) - if err != nil { - t.Errorf("unexpected error: %v out: %v", err, string(out)) - } + assert.NoError(t, err, "unexpected error, out: %v", string(out)) + out, err = addFileToGitRepo(clonePath, 128) - if err != nil { - t.Errorf("unexpected error: %v out: %v", err, string(out)) - } + assert.NoError(t, err, "unexpected error, out: %v", string(out)) + user.QuotaFiles = 100000 _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) + out, err = pushToGitRepo(clonePath) - if err != nil { - t.Errorf("unexpected error: %v out: %v", err, string(out)) + if assert.NoError(t, err, "unexpected error, out: %v", string(out)) { printLatestLogs(10) } + err = waitQuotaScans() - if err != nil { - t.Errorf("error waiting for active quota scans: %v", err) - } + assert.NoError(t, err) + user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("unable to get user: %v", err) - } + assert.NoError(t, err) user.QuotaSize = user.UsedQuotaSize - 1 _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) out, err = pushToGitRepo(clonePath) - if err == nil { - t.Errorf("git push must fail if quota is exceeded, out: %v", string(out)) - } + assert.Error(t, err, "git push must fail if quota is exceeded, out: %v", string(out)) + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(clonePath) + assert.NoError(t, err) + + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(clonePath) + assert.NoError(t, err) } func TestGitErrors(t *testing.T) { - if len(gitPath) == 0 || len(sshPath) == 0 { - t.Skip("git and/or ssh command not found, unable to execute this test") + if len(gitPath) == 0 || len(sshPath) == 0 || runtime.GOOS == osWindows { + t.Skip("git and/or ssh command not found or OS is windows, unable to execute this test") } usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) repoName := "testrepo" clonePath := filepath.Join(homeBasePath, repoName) - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(filepath.Join(homeBasePath, repoName)) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(filepath.Join(homeBasePath, repoName)) + assert.NoError(t, err) out, err := cloneGitRepo(homeBasePath, "/"+repoName, user.Username) - if err == nil { - t.Errorf("cloning a missing repo must fail, out: %v", string(out)) - } + assert.Error(t, err, "cloning a missing repo must fail, out: %v", string(out)) + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(clonePath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(clonePath) + assert.NoError(t, err) } // Start SCP tests @@ -4478,63 +3199,40 @@ func TestSCPBasicHandling(t *testing.T) { u := getTestUser(usePubKey) u.QuotaSize = 6553600 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(131074) expectedQuotaSize := user.UsedQuotaSize + testFileSize expectedQuotaFiles := user.UsedQuotaFiles + 1 err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") // test to download a missing file err = scpDownload(localPath, remoteDownPath, false, false) - if err == nil { - t.Errorf("downloading a missing file via scp must fail") - } + assert.Error(t, err, "downloading a missing file via scp must fail") err = scpUpload(testFilePath, remoteUpPath, false, false) - if err != nil { - t.Errorf("error uploading file via scp: %v", err) - } + assert.NoError(t, err) err = scpDownload(localPath, remoteDownPath, false, false) - if err != nil { - t.Errorf("error downloading file via scp: %v", err) - } + assert.NoError(t, err) fi, err := os.Stat(localPath) - if err != nil { - t.Errorf("stat for the downloaded file must succeed") - } else { - if fi.Size() != testFileSize { - t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v", - fi.Size(), testFileSize) - } + if assert.NoError(t, err) { + assert.Equal(t, testFileSize, fi.Size()) } - os.Remove(localPath) + err = os.Remove(localPath) + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } - err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) + + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.Remove(testFilePath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) } func TestSCPUploadFileOverwrite(t *testing.T) { @@ -4545,60 +3243,42 @@ func TestSCPUploadFileOverwrite(t *testing.T) { u := getTestUser(usePubKey) u.QuotaFiles = 1000 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(32760) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) err = scpUpload(testFilePath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading file via scp: %v", err) - } + assert.NoError(t, err) // test a new upload that must overwrite the existing file err = scpUpload(testFilePath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading existing file via scp: %v", err) - } + assert.NoError(t, err) user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if user.UsedQuotaSize != testFileSize || user.UsedQuotaFiles != 1 { - t.Errorf("update quota error on file overwrite, actual size: %v, expected: %v actual files: %v, expected: 1", - user.UsedQuotaSize, testFileSize, user.UsedQuotaFiles) - } + assert.NoError(t, err) + assert.Equal(t, testFileSize, user.UsedQuotaSize) + assert.Equal(t, 1, user.UsedQuotaFiles) + remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") err = scpDownload(localPath, remoteDownPath, false, false) - if err != nil { - t.Errorf("error downloading file via scp: %v", err) - } + assert.NoError(t, err) + fi, err := os.Stat(localPath) - if err != nil { - t.Errorf("stat for the downloaded file must succeed") - } else { - if fi.Size() != testFileSize { - t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v", - fi.Size(), testFileSize) - } + if assert.NoError(t, err) { + assert.Equal(t, testFileSize, fi.Size()) } - os.Remove(localPath) - os.Remove(testFilePath) + err = os.Remove(localPath) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPRecursive(t *testing.T) { @@ -4608,76 +3288,57 @@ func TestSCPRecursive(t *testing.T) { usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testBaseDirName := "test_dir" testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName) - testBaseDirDownName := "test_dir_down" + testBaseDirDownName := "test_dir_down" //nolint:goconst testBaseDirDownPath := filepath.Join(homeBasePath, testBaseDirDownName) testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName) testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName) testFileSize := int64(131074) - createTestFile(testFilePath, testFileSize) - createTestFile(testFilePath1, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) + err = createTestFile(testFilePath1, testFileSize) + assert.NoError(t, err) remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testBaseDirName)) // test to download a missing dir err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true) - if err == nil { - t.Errorf("downloading a missing dir via scp must fail") - } + assert.Error(t, err, "downloading a missing dir via scp must fail") + remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") err = scpUpload(testBaseDirPath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading dir via scp: %v", err) - } + assert.NoError(t, err) // overwrite existing dir err = scpUpload(testBaseDirPath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading dir via scp: %v", err) - } + assert.NoError(t, err) err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true) - if err != nil { - t.Errorf("error downloading dir via scp: %v", err) - } + assert.NoError(t, err) // test download without passing -r err = scpDownload(testBaseDirDownPath, remoteDownPath, true, false) - if err == nil { - t.Errorf("recursive download without -r must fail") - } + assert.Error(t, err, "recursive download without -r must fail") + fi, err := os.Stat(filepath.Join(testBaseDirDownPath, testFileName)) - if err != nil { - t.Errorf("error downloading file using scp recursive: %v", err) - } else { - if fi.Size() != testFileSize { - t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize) - } + if assert.NoError(t, err) { + assert.Equal(t, testFileSize, fi.Size()) } fi, err = os.Stat(filepath.Join(testBaseDirDownPath, testBaseDirName, testFileName)) - if err != nil { - t.Errorf("error downloading file using scp recursive: %v", err) - } else { - if fi.Size() != testFileSize { - t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize) - } + if assert.NoError(t, err) { + assert.Equal(t, testFileSize, fi.Size()) } // upload to a non existent dir remoteUpPath = fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/non_existent_dir") err = scpUpload(testBaseDirPath, remoteUpPath, true, false) - if err == nil { - t.Errorf("uploading via scp to a non existent dir must fail") - } - os.RemoveAll(testBaseDirPath) - os.RemoveAll(testBaseDirDownPath) + assert.Error(t, err, "uploading via scp to a non existent dir must fail") + + err = os.RemoveAll(testBaseDirPath) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirDownPath) + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPExtensionsFilter(t *testing.T) { @@ -4687,9 +3348,7 @@ func TestSCPExtensionsFilter(t *testing.T) { usePubKey := true u := getTestUser(usePubKey) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileSize := int64(131072) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) @@ -4697,13 +3356,9 @@ func TestSCPExtensionsFilter(t *testing.T) { remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = scpUpload(testFilePath, remoteUpPath, false, false) - if err != nil { - t.Errorf("error uploading file via scp: %v", err) - } + assert.NoError(t, err) user.Filters.FileExtensions = []dataprovider.ExtensionsFilter{ { Path: "/", @@ -4712,24 +3367,23 @@ func TestSCPExtensionsFilter(t *testing.T) { }, } _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) err = scpDownload(localPath, remoteDownPath, false, false) - if err == nil { - t.Errorf("scp download must fail") - } + assert.Error(t, err, "scp download must fail") err = scpUpload(testFilePath, remoteUpPath, false, false) - if err == nil { - t.Error("scp upload must fail") - } + assert.Error(t, err, "scp upload must fail") + _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) + assert.NoError(t, err) + err = os.Remove(testFilePath) + assert.NoError(t, err) + _, err = os.Stat(localPath) + if err == nil { + err = os.Remove(localPath) + assert.NoError(t, err) } - os.Remove(testFilePath) - os.Remove(localPath) - os.RemoveAll(user.GetHomeDir()) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) } func TestSCPVirtualFolders(t *testing.T) { @@ -4744,11 +3398,10 @@ func TestSCPVirtualFolders(t *testing.T) { VirtualPath: vdirPath, MappedPath: mappedPath, }) - os.MkdirAll(mappedPath, 0777) + err := os.MkdirAll(mappedPath, 0777) + assert.NoError(t, err) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testBaseDirName := "test_dir" testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName) @@ -4757,27 +3410,27 @@ func TestSCPVirtualFolders(t *testing.T) { testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName) testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName) testFileSize := int64(131074) - createTestFile(testFilePath, testFileSize) - createTestFile(testFilePath1, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) + err = createTestFile(testFilePath1, testFileSize) + assert.NoError(t, err) remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", vdirPath)) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, vdirPath) err = scpUpload(testBaseDirPath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading dir via scp: %v", err) - } + assert.NoError(t, err) err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true) - if err != nil { - t.Errorf("error downloading dir via scp: %v", err) - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(testBaseDirPath) - os.RemoveAll(testBaseDirDownPath) - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(mappedPath) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirPath) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirDownPath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath) + assert.NoError(t, err) } func TestSCPVirtualFoldersQuota(t *testing.T) { @@ -4800,12 +3453,12 @@ func TestSCPVirtualFoldersQuota(t *testing.T) { MappedPath: mappedPath2, ExcludeFromQuota: true, }) - os.MkdirAll(mappedPath1, 0777) - os.MkdirAll(mappedPath2, 0777) + err := os.MkdirAll(mappedPath1, 0777) + assert.NoError(t, err) + err = os.MkdirAll(mappedPath2, 0777) + assert.NoError(t, err) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testBaseDirName := "test_dir" testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName) @@ -4814,50 +3467,41 @@ func TestSCPVirtualFoldersQuota(t *testing.T) { testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName) testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName) testFileSize := int64(131074) - createTestFile(testFilePath, testFileSize) - createTestFile(testFilePath1, testFileSize) + err = createTestFile(testFilePath, testFileSize) + assert.NoError(t, err) + err = createTestFile(testFilePath1, testFileSize) + assert.NoError(t, err) remoteDownPath1 := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", vdirPath1)) remoteUpPath1 := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, vdirPath1) remoteDownPath2 := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", vdirPath2)) remoteUpPath2 := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, vdirPath2) err = scpUpload(testBaseDirPath, remoteUpPath1, true, false) - if err != nil { - t.Errorf("error uploading dir via scp: %v", err) - } + assert.NoError(t, err) err = scpDownload(testBaseDirDownPath, remoteDownPath1, true, true) - if err != nil { - t.Errorf("error downloading dir via scp: %v", err) - } + assert.NoError(t, err) err = scpUpload(testBaseDirPath, remoteUpPath2, true, false) - if err != nil { - t.Errorf("error uploading dir via scp: %v", err) - } + assert.NoError(t, err) err = scpDownload(testBaseDirDownPath, remoteDownPath2, true, true) - if err != nil { - t.Errorf("error downloading dir via scp: %v", err) - } + assert.NoError(t, err) expectedQuotaFiles := 2 expectedQuotaSize := testFileSize * 2 user, _, err = httpd.GetUserByID(user.ID, http.StatusOK) - if err != nil { - t.Errorf("error getting user: %v", err) - } - if expectedQuotaFiles != user.UsedQuotaFiles { - t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles) - } - if expectedQuotaSize != user.UsedQuotaSize { - t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize) - } + assert.NoError(t, err) + assert.Equal(t, expectedQuotaFiles, user.UsedQuotaFiles) + assert.Equal(t, expectedQuotaSize, user.UsedQuotaSize) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } - os.RemoveAll(testBaseDirPath) - os.RemoveAll(testBaseDirDownPath) - os.RemoveAll(user.GetHomeDir()) - os.RemoveAll(mappedPath1) - os.RemoveAll(mappedPath1) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirPath) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirDownPath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath1) + assert.NoError(t, err) + err = os.RemoveAll(mappedPath1) + assert.NoError(t, err) } func TestSCPPermsSubDirs(t *testing.T) { @@ -4869,39 +3513,34 @@ func TestSCPPermsSubDirs(t *testing.T) { u.Permissions["/"] = []string{dataprovider.PermAny} u.Permissions["/somedir"] = []string{dataprovider.PermListItems, dataprovider.PermUpload} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) localPath := filepath.Join(homeBasePath, "scp_download.dat") subPath := filepath.Join(user.GetHomeDir(), "somedir") testFileSize := int64(65535) - os.MkdirAll(subPath, 0777) + err = os.MkdirAll(subPath, 0777) + assert.NoError(t, err) remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/somedir") err = scpDownload(localPath, remoteDownPath, false, true) - if err == nil { - t.Error("download a dir with no permissions must fail") - } - os.Remove(subPath) + assert.Error(t, err, "download a dir with no permissions must fail") + err = os.Remove(subPath) + assert.NoError(t, err) err = createTestFile(subPath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = scpDownload(localPath, remoteDownPath, false, false) - if err != nil { - t.Errorf("unexpected download error: %v", err) - } - os.Chmod(subPath, 0001) + assert.NoError(t, err) + err = os.Chmod(subPath, 0001) + assert.NoError(t, err) err = scpDownload(localPath, remoteDownPath, false, false) - if err == nil { - t.Error("download a file with no system permissions must fail") - } - os.Chmod(subPath, 0755) - os.Remove(localPath) - os.RemoveAll(user.GetHomeDir()) + assert.Error(t, err, "download a file with no system permissions must fail") + + err = os.Chmod(subPath, 0755) + assert.NoError(t, err) + err = os.Remove(localPath) + assert.NoError(t, err) + err = os.RemoveAll(user.GetHomeDir()) + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPPermCreateDirs(t *testing.T) { @@ -4912,9 +3551,7 @@ func TestSCPPermCreateDirs(t *testing.T) { u := getTestUser(usePubKey) u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(32760) @@ -4922,35 +3559,23 @@ func TestSCPPermCreateDirs(t *testing.T) { testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName) testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) err = createTestFile(testFilePath1, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/tmp/") err = scpUpload(testFilePath, remoteUpPath, true, false) - if err == nil { - t.Errorf("scp upload must fail, the user cannot create files in a missing dir") - } + assert.Error(t, err, "scp upload must fail, the user cannot create files in a missing dir") err = scpUpload(testBaseDirPath, remoteUpPath, true, false) - if err == nil { - t.Errorf("scp upload must fail, the user cannot create new dirs") - } + assert.Error(t, err, "scp upload must fail, the user cannot create new dirs") + err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } - os.RemoveAll(testBaseDirPath) + assert.NoError(t, err) + err = os.RemoveAll(testBaseDirPath) + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPPermUpload(t *testing.T) { @@ -4961,33 +3586,21 @@ func TestSCPPermUpload(t *testing.T) { u := getTestUser(usePubKey) u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermCreateDirs} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65536) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/tmp") err = scpUpload(testFilePath, remoteUpPath, true, false) - if err == nil { - t.Errorf("scp upload must fail, the user cannot upload") - } + assert.Error(t, err, "scp upload must fail, the user cannot upload") err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPPermOverwrite(t *testing.T) { @@ -4998,37 +3611,24 @@ func TestSCPPermOverwrite(t *testing.T) { u := getTestUser(usePubKey) u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65536) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/tmp") err = scpUpload(testFilePath, remoteUpPath, true, false) - if err != nil { - t.Errorf("scp upload error: %v", err) - } + assert.NoError(t, err) err = scpUpload(testFilePath, remoteUpPath, true, false) - if err == nil { - t.Errorf("scp upload must fail, the user cannot ovewrite existing files") - } + assert.Error(t, err, "scp upload must fail, the user cannot ovewrite existing files") + err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPPermDownload(t *testing.T) { @@ -5039,39 +3639,26 @@ func TestSCPPermDownload(t *testing.T) { u := getTestUser(usePubKey) u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs} user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65537) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") err = scpUpload(testFilePath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading existing file via scp: %v", err) - } + assert.NoError(t, err) remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") err = scpDownload(localPath, remoteDownPath, false, false) - if err == nil { - t.Errorf("scp download must fail, the user cannot download") - } + assert.Error(t, err, "scp download must fail, the user cannot download") + err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPQuotaSize(t *testing.T) { @@ -5084,36 +3671,23 @@ func TestSCPQuotaSize(t *testing.T) { u.QuotaFiles = 1 u.QuotaSize = testFileSize - 1 user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) err = scpUpload(testFilePath, remoteUpPath, true, false) - if err != nil { - t.Errorf("error uploading existing file via scp: %v", err) - } + assert.NoError(t, err) err = scpUpload(testFilePath, remoteUpPath+".quota", true, false) - if err == nil { - t.Errorf("user is over quota scp upload must fail") - } + assert.Error(t, err, "user is over quota scp upload must fail") + err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPEscapeHomeDir(t *testing.T) { @@ -5122,51 +3696,35 @@ func TestSCPEscapeHomeDir(t *testing.T) { } usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } - os.MkdirAll(user.GetHomeDir(), 0777) + assert.NoError(t, err) + err = os.MkdirAll(user.GetHomeDir(), 0777) + assert.NoError(t, err) testDir := "testDir" linkPath := filepath.Join(homeBasePath, defaultUsername, testDir) err = os.Symlink(homeBasePath, linkPath) - if err != nil { - t.Errorf("error making local symlink: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join(testDir, testDir)) err = scpUpload(testFilePath, remoteUpPath, false, false) - if err == nil { - t.Errorf("uploading to a dir with a symlink outside home dir must fail") - } + assert.Error(t, err, "uploading to a dir with a symlink outside home dir must fail") remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testDir, testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") err = scpDownload(localPath, remoteDownPath, false, false) - if err == nil { - t.Errorf("scp download must fail, the requested file has a symlink outside user home") - } + assert.Error(t, err, "scp download must fail, the requested file has a symlink outside user home") remoteDownPath = fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testDir)) err = scpDownload(homeBasePath, remoteDownPath, false, true) - if err == nil { - t.Errorf("scp download must fail, the requested dir is a symlink outside user home") - } + assert.Error(t, err, "scp download must fail, the requested dir is a symlink outside user home") + err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPUploadPaths(t *testing.T) { @@ -5175,45 +3733,34 @@ func TestSCPUploadPaths(t *testing.T) { } usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) testDirName := "testDir" testDirPath := filepath.Join(user.GetHomeDir(), testDirName) - os.MkdirAll(testDirPath, 0777) + err = os.MkdirAll(testDirPath, 0777) + assert.NoError(t, err) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, testDirName) remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join(testDirName, testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") err = scpUpload(testFilePath, remoteUpPath, false, false) - if err != nil { - t.Errorf("scp upload error: %v", err) - } + assert.NoError(t, err) err = scpDownload(localPath, remoteDownPath, false, false) - if err != nil { - t.Errorf("scp download error: %v", err) - } + assert.NoError(t, err) // upload a file to a missing dir remoteUpPath = fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join(testDirName, testDirName, testFileName)) err = scpUpload(testFilePath, remoteUpPath, false, false) - if err == nil { - t.Errorf("scp upload to a missing dir must fail") - } + assert.Error(t, err, "scp upload to a missing dir must fail") + err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } - os.Remove(localPath) + assert.NoError(t, err) + err = os.Remove(localPath) + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPOverwriteDirWithFile(t *testing.T) { @@ -5222,31 +3769,23 @@ func TestSCPOverwriteDirWithFile(t *testing.T) { } usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) testDirPath := filepath.Join(user.GetHomeDir(), testFileName) - os.MkdirAll(testDirPath, 0777) + err = os.MkdirAll(testDirPath, 0777) + assert.NoError(t, err) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") err = scpUpload(testFilePath, remoteUpPath, false, false) - if err == nil { - t.Errorf("copying a file over an existing dir must fail") - } + assert.Error(t, err, "copying a file over an existing dir must fail") + err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } func TestSCPRemoteToRemote(t *testing.T) { @@ -5255,49 +3794,31 @@ func TestSCPRemoteToRemote(t *testing.T) { } usePubKey := true user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) u := getTestUser(usePubKey) u.Username += "1" u.HomeDir += "1" user1, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) testFileSize := int64(65535) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) remote1UpPath := fmt.Sprintf("%v@127.0.0.1:%v", user1.Username, path.Join("/", testFileName)) err = scpUpload(testFilePath, remoteUpPath, false, false) - if err != nil { - t.Errorf("scp upload error: %v", err) - } + assert.NoError(t, err) err = scpUpload(remoteUpPath, remote1UpPath, false, true) - if err != nil { - t.Errorf("scp upload remote to remote error: %v", err) - } + assert.NoError(t, err) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) err = os.RemoveAll(user1.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files for user1") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user1, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user1: %v", err) - } + assert.NoError(t, err) } func TestSCPErrors(t *testing.T) { @@ -5306,66 +3827,52 @@ func TestSCPErrors(t *testing.T) { } u := getTestUser(true) user, _, err := httpd.AddUser(u, http.StatusOK) - if err != nil { - t.Errorf("unable to add user: %v", err) - } + assert.NoError(t, err) testFileSize := int64(524288) testFileName := "test_file.dat" testFilePath := filepath.Join(homeBasePath, testFileName) err = createTestFile(testFilePath, testFileSize) - if err != nil { - t.Errorf("unable to create test file: %v", err) - } + assert.NoError(t, err) remoteUpPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, "/") remoteDownPath := fmt.Sprintf("%v@127.0.0.1:%v", user.Username, path.Join("/", testFileName)) localPath := filepath.Join(homeBasePath, "scp_download.dat") err = scpUpload(testFilePath, remoteUpPath, false, false) - if err != nil { - t.Errorf("error uploading file via scp: %v", err) - } + assert.NoError(t, err) user.UploadBandwidth = 512 user.DownloadBandwidth = 512 _, _, err = httpd.UpdateUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to update user: %v", err) - } + assert.NoError(t, err) cmd := getScpDownloadCommand(localPath, remoteDownPath, false, false) go func() { - if cmd.Run() == nil { - t.Errorf("SCP download must fail") - } + err := cmd.Run() + assert.Error(t, err, "SCP download must fail") }() waitForActiveTransfer() // wait some additional arbitrary time to wait for transfer activity to happen // it is need to reach all the code in CheckIdleConnections time.Sleep(100 * time.Millisecond) - cmd.Process.Kill() + err = cmd.Process.Kill() + assert.NoError(t, err) waitForNoActiveTransfer() cmd = getScpUploadCommand(testFilePath, remoteUpPath, false, false) go func() { - if cmd.Run() == nil { - t.Errorf("SCP upload must fail") - } + err := cmd.Run() + assert.Error(t, err, "SCP upload must fail") }() waitForActiveTransfer() // wait some additional arbitrary time to wait for transfer activity to happen // it is need to reach all the code in CheckIdleConnections time.Sleep(100 * time.Millisecond) - cmd.Process.Kill() + err = cmd.Process.Kill() + assert.NoError(t, err) waitForNoActiveTransfer() err = os.Remove(testFilePath) - if err != nil { - t.Errorf("error removing test file") - } + assert.NoError(t, err) os.Remove(localPath) err = os.RemoveAll(user.GetHomeDir()) - if err != nil { - t.Errorf("error removing uploaded files") - } + assert.NoError(t, err) _, err = httpd.RemoveUser(user, http.StatusOK) - if err != nil { - t.Errorf("unable to remove user: %v", err) - } + assert.NoError(t, err) } // End SCP tests @@ -5405,7 +3912,7 @@ func runSSHCommand(command string, user dataprovider.User, usePubKey bool) ([]by var sshSession *ssh.Session var output []byte config := &ssh.ClientConfig{ - User: defaultUsername, + User: user.Username, HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }, @@ -5512,7 +4019,10 @@ func getCustomAuthSftpClient(user dataprovider.User, authMethods []ssh.AuthMetho func createTestFile(path string, size int64) error { baseDir := filepath.Dir(path) if _, err := os.Stat(baseDir); os.IsNotExist(err) { - os.MkdirAll(baseDir, 0777) + err = os.MkdirAll(baseDir, 0777) + if err != nil { + return err + } } content := make([]byte, size) _, err := rand.Read(content) @@ -5536,12 +4046,21 @@ func appendToTestFile(path string, size int64) error { if err != nil { return err } - if int64(written) != size { + if written != size { return fmt.Errorf("write error, written: %v/%v", written, size) } return nil } +func checkBasicSFTP(client *sftp.Client) error { + _, err := client.Getwd() + if err != nil { + return err + } + _, err = client.ReadDir(".") + return err +} + func sftpUploadFile(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) error { srcFile, err := os.Open(localSourcePath) if err != nil { @@ -5775,8 +4294,28 @@ func waitQuotaScans() error { return nil } +func checkGitCommand() { + var err error + gitPath, err = exec.LookPath("git") + if err != nil { + logger.Warn(logSender, "", "unable to get git command. GIT tests will be skipped, err: %v", err) + logger.WarnToConsole("unable to get git command. GIT tests will be skipped, err: %v", err) + gitPath = "" + } + + sshPath, err = exec.LookPath("ssh") + if err != nil { + logger.Warn(logSender, "", "unable to get ssh command. GIT tests will be skipped, err: %v", err) + logger.WarnToConsole("unable to get ssh command. GIT tests will be skipped, err: %v", err) + gitPath = "" + } +} + func initGitRepo(path string) ([]byte, error) { - os.MkdirAll(path, 0777) + err := os.MkdirAll(path, 0777) + if err != nil { + return nil, err + } args := []string{"init", "--bare"} cmd := exec.Command(gitPath, args...) cmd.Dir = path @@ -5792,8 +4331,8 @@ func pushToGitRepo(repoPath string) ([]byte, error) { } func cloneGitRepo(basePath, remotePath, username string) ([]byte, error) { - remoteUrl := fmt.Sprintf("ssh://%v@127.0.0.1:2022%v", username, remotePath) - args := []string{"clone", remoteUrl} + remoteURL := fmt.Sprintf("ssh://%v@127.0.0.1:2022%v", username, remotePath) + args := []string{"clone", remoteURL} cmd := exec.Command(gitPath, args...) cmd.Dir = basePath cmd.Env = append(os.Environ(), @@ -5830,7 +4369,7 @@ func addFileToGitRepo(repoPath string, fileSize int64) ([]byte, error) { return cmd.CombinedOutput() } -func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJsonResponse bool, result int) []byte { +func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJSONResponse bool, result int) []byte { content := []byte("#!/bin/sh\n\n") q, _ := json.Marshal(questions) echos := []bool{} @@ -5838,7 +4377,7 @@ func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJ echos = append(echos, index%2 == 0) } e, _ := json.Marshal(echos) - if nonJsonResponse { + if nonJSONResponse { content = append(content, []byte(fmt.Sprintf("echo 'questions: %v echos: %v\n", string(q), string(e)))...) } else { content = append(content, []byte(fmt.Sprintf("echo '{\"questions\":%v,\"echos\":%v}'\n", string(q), string(e)))...) @@ -5853,31 +4392,28 @@ func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJ return content } -func getExtAuthScriptContent(user dataprovider.User, sleepTime int, nonJsonResponse bool) []byte { +func getExtAuthScriptContent(user dataprovider.User, nonJSONResponse bool) []byte { extAuthContent := []byte("#!/bin/sh\n\n") u, _ := json.Marshal(user) extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("if test \"$SFTPGO_AUTHD_USERNAME\" = \"%v\"; then\n", user.Username))...) - if nonJsonResponse { + if nonJSONResponse { extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...) } else { extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("echo '%v'\n", string(u)))...) } extAuthContent = append(extAuthContent, []byte("else\n")...) - if nonJsonResponse { + if nonJSONResponse { extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...) } else { extAuthContent = append(extAuthContent, []byte("echo '{\"username\":\"\"}'\n")...) } extAuthContent = append(extAuthContent, []byte("fi\n")...) - if sleepTime > 0 { - extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("sleep %v\n", sleepTime))...) - } return extAuthContent } -func getPreLoginScriptContent(user dataprovider.User, nonJsonResponse bool) []byte { +func getPreLoginScriptContent(user dataprovider.User, nonJSONResponse bool) []byte { content := []byte("#!/bin/sh\n\n") - if nonJsonResponse { + if nonJSONResponse { content = append(content, []byte("echo 'text response'\n")...) return content } diff --git a/sftpd/ssh_cmd.go b/sftpd/ssh_cmd.go index 06982bb6..19bd3001 100644 --- a/sftpd/ssh_cmd.go +++ b/sftpd/ssh_cmd.go @@ -15,13 +15,14 @@ import ( "sync" "time" + "github.com/google/shlex" + "golang.org/x/crypto/ssh" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/metrics" "github.com/drakkan/sftpgo/utils" "github.com/drakkan/sftpgo/vfs" - "github.com/google/shlex" - "golang.org/x/crypto/ssh" ) const scpCmdName = "scp" diff --git a/sftpd/transfer.go b/sftpd/transfer.go index dc282901..80e6708f 100644 --- a/sftpd/transfer.go +++ b/sftpd/transfer.go @@ -8,10 +8,11 @@ import ( "sync" "time" + "github.com/eikenb/pipeat" + "github.com/drakkan/sftpgo/dataprovider" "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/metrics" - "github.com/eikenb/pipeat" ) const ( diff --git a/utils/utils.go b/utils/utils.go index 2ecbfba4..bd8bee7b 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -24,8 +24,9 @@ import ( "strings" "time" - "github.com/drakkan/sftpgo/logger" "golang.org/x/crypto/ssh" + + "github.com/drakkan/sftpgo/logger" ) const logSender = "utils" diff --git a/vfs/gcsfs.go b/vfs/gcsfs.go index 9e4ff468..1f0cbf4e 100644 --- a/vfs/gcsfs.go +++ b/vfs/gcsfs.go @@ -12,12 +12,13 @@ import ( "time" "cloud.google.com/go/storage" - "github.com/drakkan/sftpgo/logger" - "github.com/drakkan/sftpgo/metrics" "github.com/eikenb/pipeat" "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" + + "github.com/drakkan/sftpgo/logger" + "github.com/drakkan/sftpgo/metrics" ) var ( diff --git a/vfs/osfs.go b/vfs/osfs.go index 8222e700..be6834ad 100644 --- a/vfs/osfs.go +++ b/vfs/osfs.go @@ -8,10 +8,11 @@ import ( "strings" "time" - "github.com/drakkan/sftpgo/logger" - "github.com/drakkan/sftpgo/utils" "github.com/eikenb/pipeat" "github.com/rs/xid" + + "github.com/drakkan/sftpgo/logger" + "github.com/drakkan/sftpgo/utils" ) const ( diff --git a/vfs/s3fs.go b/vfs/s3fs.go index f1de85b9..f63eea82 100644 --- a/vfs/s3fs.go +++ b/vfs/s3fs.go @@ -15,10 +15,11 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/eikenb/pipeat" + "github.com/drakkan/sftpgo/logger" "github.com/drakkan/sftpgo/metrics" "github.com/drakkan/sftpgo/utils" - "github.com/eikenb/pipeat" ) // S3FsConfig defines the configuration for S3 based filesystem diff --git a/vfs/vfs.go b/vfs/vfs.go index 8a81d3f6..59f62f75 100644 --- a/vfs/vfs.go +++ b/vfs/vfs.go @@ -10,9 +10,10 @@ import ( "strings" "time" - "github.com/drakkan/sftpgo/logger" "github.com/eikenb/pipeat" "github.com/pkg/sftp" + + "github.com/drakkan/sftpgo/logger" ) // Fs defines the interface for filesystem backends