Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Require safe CLI configuration migration before network commands

Neeraj Guptad2e24e6e95e2
diff --git a/cli/cmd/root.go b/cli/cmd/root.go
index fd3217387a..832451f71c 100644
--- a/cli/cmd/root.go
+++ b/cli/cmd/root.go
@@ -6,6 +6,7 @@ import (
"runtime"
"github.com/ente/cli/pkg"
+ "github.com/ente/cli/pkg/secrets"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)
@@ -23,9 +24,22 @@ func GenerateDocs() error {
return doc.GenMarkdownTree(rootCmd, "./docs/generated")
}
-func Execute(controller *pkg.ClICtrl, ver string) {
+func Execute(controller *pkg.ClICtrl, ver string, beforeNetwork func() error) {
ctrl = controller
version = ver
+ rootCmd.PersistentPreRunE = func(command *cobra.Command, args []string) error {
+ network := command == exportCmd || command == addAccCmd || command.Parent() == _adminCmd
+ if network {
+ if err := beforeNetwork(); err != nil {
+ return err
+ }
+ }
+ if network || command.Parent() == accountCmd {
+ ctrl.KeyHolder = secrets.NewKeyHolder(secrets.GetOrCreateClISecret())
+ return ctrl.Init()
+ }
+ return nil
+ }
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
diff --git a/cli/docs/selfhost.md b/cli/docs/selfhost.md
index d8a4c7a6ea..7f13402622 100644
--- a/cli/docs/selfhost.md
+++ b/cli/docs/selfhost.md
@@ -4,6 +4,10 @@ If you are self-hosting the server, you can still configure CLI to export data &
To do this, first configure the CLI to point to your server. Define a `config.yaml` and put it in `~/.ente/` or the directory specified by `ENTE_CLI_CONFIG_DIR`.
+`ENTE_CLI_CONFIG_DIR` selects both configuration and the saved account database. The legacy `ENTE_CLI_CONFIG_PATH` is used only when `ENTE_CLI_CONFIG_DIR` is unset. For example, use `ENTE_CLI_CONFIG_DIR=/path/to/existing-cli-directory ente export` when that directory already contains the accounts you intend to use.
+
+If you previously kept configuration in the working directory, migrate its settings into the existing configuration directory, then remove or rename the old file. Network commands stop while a separate working-directory config exists; local account commands remain available. Selecting a different directory, including `.`, also selects a different account database. Invalid trusted configuration must be corrected before running commands.
+
```yaml
endpoint:
api: "http://localhost:8080"
diff --git a/cli/main.go b/cli/main.go
index fc57291b11..92b208a6fd 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -8,7 +8,6 @@ import (
"github.com/ente/cli/pkg"
"github.com/ente/cli/pkg/secrets"
"github.com/ente/cli/utils/constants"
- "github.com/spf13/cobra"
"github.com/spf13/viper"
"log"
"os"
@@ -30,7 +29,9 @@ func main() {
if err != nil {
log.Fatalf("Could not create cli config path\n%v\n", err)
}
- initConfig(cliConfigDir)
+ if err := initConfig(cliConfigDir); err != nil {
+ log.Fatal(err)
+ }
newCliDBPath := filepath.Join(cliConfigDir, "ente-cli.db")
if !strings.HasPrefix(cliConfigDir, "/") {
oldCliPath := fmt.Sprintf("%sente-cli.db", cliConfigDir)
@@ -51,33 +52,17 @@ func main() {
}
}
- skipInitCommands := map[string]struct{}{
- "version": {},
- "docs": {},
- "help": {},
- "completion": {},
- cobra.ShellCompRequestCmd: {},
- cobra.ShellCompNoDescRequestCmd: {},
- }
-
- var keyHolder *secrets.KeyHolder
- shouldInit := len(os.Args) > 1
- if len(os.Args) > 1 {
- if _, skip := skipInitCommands[os.Args[1]]; skip {
- shouldInit = false
+ defer func() {
+ if err := db.Close(); err != nil {
+ panic(err)
}
- }
-
- if shouldInit {
- keyHolder = secrets.NewKeyHolder(secrets.GetOrCreateClISecret())
- }
+ }()
ctrl := pkg.ClICtrl{
Client: api.NewClient(api.Params{
Debug: viper.GetBool("log.http"),
Host: viper.GetString("endpoint.api"),
}),
- DB: db,
- KeyHolder: keyHolder,
+ DB: db,
}
if len(os.Args) == 1 {
@@ -91,36 +76,98 @@ func main() {
}
return
}
- if shouldInit {
- err = ctrl.Init()
- if err != nil {
- panic(err)
- }
- defer func() {
- if err := db.Close(); err != nil {
- panic(err)
- }
- }()
- }
if os.Args[1] == "version" && viper.GetString("endpoint.api") != constants.EnteApiUrl {
log.Printf("Custom endpoint: %s\n", viper.GetString("endpoint.api"))
}
- cmd.Execute(&ctrl, AppVersion)
+ cmd.Execute(&ctrl, AppVersion, func() error {
+ return checkWorkingDirectoryConfig(cliConfigDir)
+ })
}
-func initConfig(cliConfigDir string) {
- viper.SetConfigName("config")
+func initConfig(cliConfigDir string) error {
viper.SetConfigType("yaml")
- viper.AddConfigPath(cliConfigDir + "/")
-
+ path, err := findConfigFile(cliConfigDir)
+ if err != nil {
+ return fmt.Errorf("cannot inspect trusted configuration directory %q", cliConfigDir)
+ }
+ if path != "" {
+ viper.SetConfigFile(path)
+ if err := viper.ReadInConfig(); err != nil {
+ return fmt.Errorf("cannot load trusted configuration %q; check file permissions and YAML syntax", path)
+ }
+ }
+ value := viper.Get("endpoint.api")
+ hasEndpoint := value != nil
+ for _, key := range viper.AllKeys() {
+ if key == "endpoint" || key == "endpoint.api" {
+ hasEndpoint = true
+ }
+ }
+ if hasEndpoint {
+ endpoint, ok := value.(string)
+ if !ok || strings.TrimSpace(endpoint) == "" {
+ return fmt.Errorf("invalid endpoint.api in trusted configuration %q; expected a non-empty string", path)
+ }
+ }
viper.SetDefault("endpoint.api", constants.EnteApiUrl)
viper.SetDefault("log.http", false)
- if err := viper.ReadInConfig(); err != nil {
- if _, ok := err.(viper.ConfigFileNotFoundError); ok {
- } else {
- // Config file was found but another error was produced
+ return nil
+}
+
+func findConfigFile(dir string) (string, error) {
+ info, err := os.Stat(dir)
+ if err != nil {
+ return "", err
+ }
+ if !info.IsDir() {
+ return "", fmt.Errorf("%q is not a directory", dir)
+ }
+ for i := 0; i <= len(viper.SupportedExts); i++ {
+ name := "config"
+ if i < len(viper.SupportedExts) {
+ name += "." + viper.SupportedExts[i]
+ }
+ path := filepath.Join(dir, name)
+ info, err := os.Lstat(path)
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return "", err
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ info, err = os.Stat(path)
+ if err != nil {
+ return "", err
+ }
}
+ if !info.IsDir() {
+ return path, nil
+ }
+ }
+ return "", nil
+}
+
+func checkWorkingDirectoryConfig(cliConfigDir string) error {
+ cwd, err := os.Stat(".")
+ if err != nil {
+ return fmt.Errorf("cannot inspect the working directory")
+ }
+ trustedDir, err := os.Stat(cliConfigDir)
+ if err != nil {
+ return fmt.Errorf("cannot inspect trusted configuration directory %q", cliConfigDir)
+ }
+ if os.SameFile(cwd, trustedDir) {
+ return nil
+ }
+ path, err := findConfigFile(".")
+ if err != nil {
+ return fmt.Errorf("cannot inspect working-directory configuration")
+ }
+ if path != "" {
+ return fmt.Errorf("refusing network command: working-directory configuration %q is ignored. Migrate your settings into %q, then remove or rename the working-directory file. ENTE_CLI_CONFIG_DIR selects both configuration and account storage", path, cliConfigDir)
}
+ return nil
}
func GetCLIConfigDir() (string, error) {
@@ -132,8 +179,7 @@ func GetCLIConfigDir() (string, error) {
}
if configDir != "" {
- configDir = strings.TrimSuffix(configDir, string(filepath.Separator))
- return configDir, nil
+ return filepath.Clean(configDir), nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
diff --git a/cli/main_test.go b/cli/main_test.go
index 07558c5316..50e9cd2211 100644
--- a/cli/main_test.go
+++ b/cli/main_test.go
@@ -16,7 +16,9 @@ func TestCLIConfigDiscovery(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- initConfig(configDir)
+ if err := initConfig(configDir); err != nil {
+ t.Fatal(err)
+ }
if got := viper.GetString("endpoint.api"); got != want {
t.Fatalf("endpoint.api = %q, want %q", got, want)
}
diff --git a/cli/startup_test.go b/cli/startup_test.go
new file mode 100644
index 0000000000..d2bf4f4d0a
--- /dev/null
+++ b/cli/startup_test.go
@@ -0,0 +1,248 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/ente/cli/utils/constants"
+ "github.com/spf13/viper"
+ "github.com/zalando/go-keyring"
+)
+
+func TestCLIStartup(t *testing.T) {
+ if args := os.Getenv("ENTE_CLI_TEST_ARGS"); args != "" {
+ keyring.MockInit()
+ if os.Getenv("ENTE_CLI_TEST_NO_KEYRING") != "" {
+ keyring.MockInitWithError(errors.New("unexpected keyring access"))
+ }
+ var command []string
+ if err := json.Unmarshal([]byte(args), &command); err != nil {
+ t.Fatal(err)
+ }
+ os.Args = append([]string{"ente"}, command...)
+ main()
+ return
+ }
+
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ w.WriteHeader(http.StatusUnauthorized)
+ }))
+ defer server.Close()
+ tests := []struct {
+ name string
+ args []string
+ wantError string
+ wantOutput string
+ keyring bool
+ config string
+ noConfig bool
+ }{
+ {name: "export", args: []string{"export"}, wantError: "refusing network command"},
+ {name: "default endpoint", args: []string{"export"}, wantError: "refusing network command", noConfig: true},
+ {name: "login", args: []string{"account", "add"}, wantError: "refusing network command"},
+ {name: "list users", args: []string{"admin", "list-users"}, wantError: "refusing network command"},
+ {name: "get user", args: []string{"admin", "get-user-id", "--user", "[email protected]"}, wantError: "refusing network command"},
+ {name: "disable 2fa", args: []string{"admin", "disable-2fa", "--user", "[email protected]"}, wantError: "refusing network command"},
+ {name: "disable passkey", args: []string{"admin", "disable-passkey", "--user", "[email protected]"}, wantError: "refusing network command"},
+ {name: "delete user", args: []string{"admin", "delete-user", "--user", "[email protected]"}, wantError: "refusing network command"},
+ {name: "subscription", args: []string{"admin", "update-subscription", "--user", "[email protected]"}, wantError: "refusing network command"},
+ {name: "send mail", args: []string{"admin", "send-mail", "[email protected]", "[email protected]", "Test"}, wantError: "refusing network command"},
+ {name: "version", args: []string{"version"}, wantOutput: "Version"},
+ {name: "export help", args: []string{"export", "--help"}, wantOutput: "Usage:"},
+ {name: "login help", args: []string{"account", "add", "--help"}, wantOutput: "Usage:"},
+ {name: "admin help", args: []string{"admin", "list-users", "--help"}, wantOutput: "Usage:"},
+ {name: "completion", args: []string{"completion", "bash"}, wantOutput: "bash completion"},
+ {name: "list accounts", args: []string{"account", "list"}, wantOutput: "Configured accounts: 0", keyring: true},
+ {name: "get token", args: []string{"account", "get-token", "--email", "[email protected]"}, wantOutput: "account not found", keyring: true},
+ {name: "update account", args: []string{"account", "update", "--email", "[email protected]", "--dir", "."}, wantOutput: "account not found", keyring: true},
+ {name: "decrypt", args: []string{"auth", "decrypt", "missing", "output"}, wantError: "error reading file"},
+ {name: "invalid trusted YAML", args: []string{"export"}, wantError: "cannot load trusted configuration", config: "endpoint: [secret-sentinel"},
+ {name: "invalid trusted endpoint", args: []string{"export"}, wantError: "invalid endpoint.api", config: "endpoint:\n api: []\n"},
+ {name: "null trusted endpoint", args: []string{"export"}, wantError: "invalid endpoint.api", config: "endpoint:\n api: null\n"},
+ {name: "null trusted endpoint section", args: []string{"export"}, wantError: "invalid endpoint.api", config: "endpoint: null\n"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ root := t.TempDir()
+ home := filepath.Join(root, "home")
+ cwd := filepath.Join(root, "cwd")
+ body := tt.config
+ if body == "" {
+ body = "endpoint:\n api: " + server.URL + "\n"
+ }
+ if !tt.noConfig {
+ writeTestConfig(t, filepath.Join(home, ".ente", "config.yaml"), body)
+ }
+ writeTestConfig(t, filepath.Join(cwd, "config.yaml"), "not valid YAML: [secret-sentinel")
+ args, err := json.Marshal(tt.args)
+ if err != nil {
+ t.Fatal(err)
+ }
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, executable, "-test.run=^TestCLIStartup$")
+ command.Dir = cwd
+ command.Env = append(os.Environ(),
+ "HOME="+home, "USERPROFILE="+home,
+ "ENTE_CLI_CONFIG_DIR=", "ENTE_CLI_CONFIG_PATH=",
+ "ENTE_CLI_SECRETS_PATH=",
+ "ENTE_CLI_TMP_PATH="+root,
+ "ENTE_CLI_TEST_ARGS="+string(args), "ENTE_CLI_TEST_NO_KEYRING=",
+ )
+ if !tt.keyring {
+ command.Env = append(command.Env, "ENTE_CLI_TEST_NO_KEYRING=1")
+ }
+ var stdout, stderr bytes.Buffer
+ command.Stdout, command.Stderr = &stdout, &stderr
+ err = command.Run()
+ if tt.wantError != "" {
+ if err == nil || !strings.Contains(stderr.String(), tt.wantError) || stdout.Len() != 0 {
+ t.Fatalf("error=%v stdout=%q stderr=%q", err, stdout.String(), stderr.String())
+ }
+ } else if err != nil || !strings.Contains(stdout.String(), tt.wantOutput) {
+ t.Fatalf("error=%v stdout=%q stderr=%q", err, stdout.String(), stderr.String())
+ }
+ if strings.Contains(stderr.String(), "secret-sentinel") || strings.Contains(stderr.String(), "unexpected keyring access") {
+ t.Fatalf("unsafe startup: %s", stderr.String())
+ }
+ })
+ }
+ if got := requests.Load(); got != 0 {
+ t.Fatalf("received %d unexpected network requests", got)
+ }
+}
+
+func TestInvalidTrustedConfig(t *testing.T) {
+ for name, body := range map[string]string{
+ "malformed YAML": "endpoint: [secret-sentinel",
+ "endpoint list": "endpoint:\n api: []\n",
+ "empty endpoint": "endpoint:\n api: ''\n",
+ "null endpoint": "endpoint:\n api: null\n",
+ "null endpoint section": "endpoint: null\n",
+ "endpoint object": "endpoint:\n api: {}\n",
+ "TOML": "[endpoint]\napi = 'secret-sentinel'\n",
+ } {
+ t.Run(name, func(t *testing.T) {
+ viper.Reset()
+ dir := t.TempDir()
+ writeTestConfig(t, filepath.Join(dir, "config.yaml"), body)
+ err := initConfig(dir)
+ if err == nil || strings.Contains(err.Error(), "secret-sentinel") {
+ t.Fatalf("expected sanitized configuration error, got %v", err)
+ }
+ })
+ }
+ t.Cleanup(viper.Reset)
+}
+
+func TestTrustedConfigSymlink(t *testing.T) {
+ for name, exists := range map[string]bool{"missing target": false, "existing target": true} {
+ t.Run(name, func(t *testing.T) {
+ viper.Reset()
+ dir := t.TempDir()
+ target := filepath.Join(t.TempDir(), "settings.yaml")
+ if exists {
+ writeTestConfig(t, target, "endpoint:\n api: https://trusted.invalid\n")
+ }
+ if err := os.Symlink(target, filepath.Join(dir, "config.yaml")); err != nil {
+ t.Skipf("file symlinks unavailable: %v", err)
+ }
+ err := initConfig(dir)
+ if !exists {
+ if err == nil || !strings.Contains(err.Error(), "cannot inspect trusted configuration") {
+ t.Fatalf("expected configuration error, got %v", err)
+ }
+ } else if err != nil || viper.GetString("endpoint.api") != "https://trusted.invalid" {
+ t.Fatalf("linked configuration not loaded: %v", err)
+ }
+ })
+ }
+ t.Cleanup(viper.Reset)
+}
+
+func TestTrustedConfigWithoutEndpoint(t *testing.T) {
+ viper.Reset()
+ t.Cleanup(viper.Reset)
+ dir := t.TempDir()
+ writeTestConfig(t, filepath.Join(dir, "config.yaml"), "log:\n http: true\n")
+ if err := initConfig(dir); err != nil {
+ t.Fatal(err)
+ }
+ if viper.GetString("endpoint.api") != constants.EnteApiUrl || !viper.GetBool("log.http") {
+ t.Fatal("configuration without an endpoint did not retain the default API")
+ }
+}
+
+func TestWorkingDirectoryConfig(t *testing.T) {
+ for _, name := range []string{"config.yaml", "config.json", "config.toml", "config"} {
+ t.Run(name, func(t *testing.T) {
+ cwd, trusted := t.TempDir(), t.TempDir()
+ t.Chdir(cwd)
+ writeTestConfig(t, filepath.Join(cwd, name), "not valid YAML: [secret-sentinel")
+ err := checkWorkingDirectoryConfig(trusted)
+ if err == nil || !strings.Contains(err.Error(), "refusing network command") || strings.Contains(err.Error(), "secret-sentinel") {
+ t.Fatalf("expected migration error, got %v", err)
+ }
+ })
+ }
+ t.Run("same directory", func(t *testing.T) {
+ cwd := t.TempDir()
+ t.Chdir(cwd)
+ writeTestConfig(t, filepath.Join(cwd, "config.yaml"), "endpoint:\n api: https://trusted.invalid\n")
+ alias := filepath.Join(t.TempDir(), "alias")
+ if err := os.Symlink(cwd, alias); err != nil {
+ t.Skipf("directory symlinks unavailable: %v", err)
+ }
+ for _, dir := range []string{".", "./", cwd, alias} {
+ if err := checkWorkingDirectoryConfig(dir); err != nil {
+ t.Fatalf("trusted directory %q: %v", dir, err)
+ }
+ }
+ })
+ t.Run("no configuration file", func(t *testing.T) {
+ cwd := t.TempDir()
+ t.Chdir(cwd)
+ if err := os.Mkdir("config.yaml", 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := checkWorkingDirectoryConfig(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ })
+}
+
+func TestConfigDirectoryRoot(t *testing.T) {
+ dir := filepath.VolumeName(t.TempDir()) + string(filepath.Separator)
+ t.Setenv("ENTE_CLI_CONFIG_DIR", dir)
+ got, err := GetCLIConfigDir()
+ if err != nil || got != dir {
+ t.Fatalf("config directory = %q, %v; want %q", got, err, dir)
+ }
+}
+
+func writeTestConfig(t *testing.T, path, body string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0600); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/docs/docs/self-hosting/administration/cli.md b/docs/docs/self-hosting/administration/cli.md
index a1244650a5..7edd04e3ad 100644
--- a/docs/docs/self-hosting/administration/cli.md
+++ b/docs/docs/self-hosting/administration/cli.md
@@ -19,6 +19,10 @@ To do this, first configure the CLI to use your server's endpoint.
Define `config.yaml` and place it in `~/.ente/` or the directory specified by `ENTE_CLI_CONFIG_DIR`.
+`ENTE_CLI_CONFIG_DIR` selects both configuration and the saved account database. The legacy `ENTE_CLI_CONFIG_PATH` is used only when `ENTE_CLI_CONFIG_DIR` is unset. For example, `ENTE_CLI_CONFIG_DIR=/path/to/existing-cli-directory ente export` uses the accounts already stored in that directory.
+
+If you previously kept configuration in the working directory, migrate its settings into the existing configuration directory, then remove or rename the old file. Network commands stop while a separate working-directory config exists; local account commands remain available. Setting `ENTE_CLI_CONFIG_DIR=.` also changes the account database location. Invalid trusted configuration must be corrected before running commands.
+
```yaml
# Set the API endpoint to your domain where Museum is being served.
endpoint: