From 6ea0eb3d12ba47a5f59d533e26754e75174c0a01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20L=2E=20Hansen?= Date: Sun, 11 Oct 2026 17:18:17 -0700 Subject: [PATCH 1/4] feat(auth): add gog auth rekey to rotate the file keyring password Add `gog auth rekey `, which reads the file keyring with the current password, re-encrypts every entry under a new password, and writes a verified copy to the separate output directory. The live keyring is opened read-only and left byte-identical, so no crash or bug in output writing can lose or corrupt live credentials. The output directory is a required positional argument, is created with the keyring directory's permissions, and is refused when it is the keyring directory, lies inside it, contains it, or is reached through a symlink or case alias. A non-empty output is refused unless --force is passed, which replaces those entries and reports exactly which were removed; a failed replacement reports the removals that completed and names the entry that may have been partially removed. Before reporting success the command reopens the output with the new password and reads every entry back, comparing data and metadata. It prints paths, counts and key names only, never payloads or passwords, and prints the exact installation command that retains the old directory until the new keyring is proven. --skip-unreadable omits entries that cannot be decrypted and reports their keys; an empty keyring reports that no password was changed. Regenerate the command reference and document output-directory rotation in Paths and State and the installation guide. Validation: make ci gates (fmt-check, lint, deadcode, docs-check), the full internal/secrets and internal/cmd suites, -race, and linux/darwin/windows builds and test binaries. Every safety behaviour has a test that fails when the behaviour is removed, confirmed by mutation testing. --- CHANGELOG.md | 1 + docs/commands.generated.md | 1 + docs/commands/README.md | 3 +- docs/commands/gog-auth-rekey.md | 48 ++ docs/commands/gog-auth.md | 1 + docs/index.md | 2 +- docs/paths.md | 71 ++ internal/cmd/auth.go | 1 + internal/cmd/auth_rekey.go | 208 +++++ internal/cmd/auth_rekey_test.go | 410 +++++++++ internal/secrets/backend.go | 17 +- internal/secrets/file_keyring_safe.go | 31 +- internal/secrets/rekey.go | 520 +++++++++++ internal/secrets/rekey_exchange_darwin.go | 7 + internal/secrets/rekey_exchange_linux.go | 7 + internal/secrets/rekey_exchange_other.go | 9 + internal/secrets/rekey_lock_test.go | 186 ++++ internal/secrets/rekey_sync_unix.go | 19 + internal/secrets/rekey_sync_windows.go | 19 + internal/secrets/rekey_test.go | 993 ++++++++++++++++++++++ internal/secrets/store.go | 8 +- 21 files changed, 2555 insertions(+), 7 deletions(-) create mode 100644 docs/commands/gog-auth-rekey.md create mode 100644 internal/cmd/auth_rekey.go create mode 100644 internal/cmd/auth_rekey_test.go create mode 100644 internal/secrets/rekey.go create mode 100644 internal/secrets/rekey_exchange_darwin.go create mode 100644 internal/secrets/rekey_exchange_linux.go create mode 100644 internal/secrets/rekey_exchange_other.go create mode 100644 internal/secrets/rekey_lock_test.go create mode 100644 internal/secrets/rekey_sync_unix.go create mode 100644 internal/secrets/rekey_sync_windows.go create mode 100644 internal/secrets/rekey_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d96849afa..ee7758650 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Dependencies: refresh the Google API client, golangci-lint, Cloudflare Workers types, Wrangler, PostCSS, and Undici while retaining Go 1.26, pnpm 11, and the worker’s 24-hour release cooldown. - Drive: preserve requested top-level false booleans in `drive get --json`, including the default `starred` and `hasThumbnail` fields; keep conditionally absent fields omitted. (#1223) — thanks @postoso. - CI: use macOS 27 runners for Darwin checks and release preflight while enforcing the macOS 15.0 deployment target. +- Auth: add `gog auth rekey ` to write and verify a separate re-encrypted directory while leaving the live keyring untouched; hold the store lock throughout, publish only complete fsynced output, and retain the old directory during installation. (#1224) — thanks @sorenisanerd. - Dependencies: update Vitest and Cloudflare Workers types within the worker’s 24-hour release cooldown. - Google APIs: add `GOG_GOOGLE_API_BASE_URL` to send `*.googleapis.com` requests to a test server, emulator, proxy, or relay that adds credentials outside gog; requests keep path and query, pass the original host as `X-Forwarded-Host`, carry no gog credentials, and refuse cross-origin redirects. (#1225, #1226) — thanks @km-tr. - Gmail: add `--note-html` and `--note-html-file` to forwards and preserve plain-note line breaks in HTML output. (#1215) — thanks @malob. diff --git a/docs/commands.generated.md b/docs/commands.generated.md index 000e1c1bf..5a07bdcb6 100644 --- a/docs/commands.generated.md +++ b/docs/commands.generated.md @@ -90,6 +90,7 @@ Generated from `gog schema --json`. - [`gog auth keyring [ []]`](commands/gog-auth-keyring.md) - Configure keyring backend - [`gog auth list [flags]`](commands/gog-auth-list.md) - List stored accounts - [`gog auth manage (login) [flags]`](commands/gog-auth-manage.md) - Open interactive accounts manager in browser + - [`gog auth rekey [flags]`](commands/gog-auth-rekey.md) - Write a verified copy of the file keyring to using GOG_KEYRING_NEW_PASSWORD; leave the live keyring untouched - [`gog auth remove `](commands/gog-auth-remove.md) - Remove a stored refresh token - [`gog auth service-account `](commands/gog-auth-service-account.md) - Configure service account (Workspace only; domain-wide delegation) - [`gog auth service-account set [flags]`](commands/gog-auth-service-account-set.md) - Store a service account key for impersonation diff --git a/docs/commands/README.md b/docs/commands/README.md index 1c05b3f86..911bc9677 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -2,7 +2,7 @@ Every `gog` command has a generated docs page. The source of truth is the live CLI schema; run `make docs-commands` after changing command names, flags, help text, aliases, or arguments. -Generated pages: 779. +Generated pages: 780. ## Top-level Commands @@ -144,6 +144,7 @@ Generated pages: 779. - [gog auth keyring](gog-auth-keyring.md) - Configure keyring backend - [gog auth list](gog-auth-list.md) - List stored accounts - [gog auth manage](gog-auth-manage.md) - Open interactive accounts manager in browser + - [gog auth rekey](gog-auth-rekey.md) - Write a verified copy of the file keyring to using GOG_KEYRING_NEW_PASSWORD; leave the live keyring untouched - [gog auth remove](gog-auth-remove.md) - Remove a stored refresh token - [gog auth service-account](gog-auth-service-account.md) - Configure service account (Workspace only; domain-wide delegation) - [gog auth service-account set](gog-auth-service-account-set.md) - Store a service account key for impersonation diff --git a/docs/commands/gog-auth-rekey.md b/docs/commands/gog-auth-rekey.md new file mode 100644 index 000000000..e01c9491e --- /dev/null +++ b/docs/commands/gog-auth-rekey.md @@ -0,0 +1,48 @@ +# `gog auth rekey` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Write a verified copy of the file keyring to using GOG_KEYRING_NEW_PASSWORD; leave the live keyring untouched + +## Usage + +```bash +gog auth rekey [flags] +``` + +## Parent + +- [gog auth](gog-auth.md) + +## Flags + +| Flag | Type | Default | Help | +| --- | --- | --- | --- | +| `--access-token` | `string` | | Use provided access token directly (bypasses stored refresh tokens; token expires in ~1h) | +| `-a`
`--account`
`--acct` | `string` | | Account email, alias, or auto for authenticated Google API commands | +| `--client` | `string` | | OAuth client name (selects stored credentials + token bucket) | +| `--color` | `string` | auto | Color output: auto\|always\|never | +| `--disable-commands` | `string` | | Comma-separated list of disabled commands; dot paths allowed | +| `-n`
`--dry-run`
`--dryrun`
`--noop`
`--preview` | `bool` | | Do not make changes; print intended actions and exit successfully | +| `--enable-commands` | `string` | | Comma-separated list of enabled command prefixes; dot paths allowed (restricts CLI) | +| `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | +| `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | +| `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | +| `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | +| `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | +| `--no-input`
`--non-interactive`
`--noninteractive` | `bool` | | Never prompt; fail instead (useful for CI) | +| `-p`
`--plain`
`--tsv` | `bool` | false | Output stable, parseable text to stdout (TSV; no colors) | +| `--quota-project` | `string` | | Google Cloud project to bill for API usage (sent as X-Goog-User-Project; some APIs require it with --access-token or ADC) | +| `--readonly` | `bool` | false | Block mutating API requests at runtime; auth add also requests read-only OAuth scopes | +| `--results-only` | `bool` | | In JSON mode, emit only the primary result (drops envelope fields like nextPageToken) | +| `--select`
`--pick`
`--project` | `string` | | In JSON mode, select comma-separated fields (best-effort; supports dot paths). Desire path: use --fields for most commands. | +| `--skip-unreadable` | `bool` | | Omit undecryptable items from output and report their keys; live items remain untouched | +| `-v`
`--verbose` | `bool` | | Enable verbose logging | +| `--version` | `kong.VersionFlag` | | Print version and exit | +| `--wrap-untrusted` | `bool` | false | In JSON/raw output, wrap fetched text fields in external untrusted-content markers | + +## See Also + +- [gog auth](gog-auth.md) +- [Command index](README.md) diff --git a/docs/commands/gog-auth.md b/docs/commands/gog-auth.md index b32255fff..af2137e36 100644 --- a/docs/commands/gog-auth.md +++ b/docs/commands/gog-auth.md @@ -25,6 +25,7 @@ gog auth [flags] - [gog auth keyring](gog-auth-keyring.md) - Configure keyring backend - [gog auth list](gog-auth-list.md) - List stored accounts - [gog auth manage](gog-auth-manage.md) - Open interactive accounts manager in browser +- [gog auth rekey](gog-auth-rekey.md) - Write a verified copy of the file keyring to using GOG_KEYRING_NEW_PASSWORD; leave the live keyring untouched - [gog auth remove](gog-auth-remove.md) - Remove a stored refresh token - [gog auth service-account](gog-auth-service-account.md) - Configure service account (Workspace only; domain-wide delegation) - [gog auth services](gog-auth-services.md) - List supported auth services and scopes diff --git a/docs/index.md b/docs/index.md index ebc0cf94a..769a99482 100644 --- a/docs/index.md +++ b/docs/index.md @@ -55,7 +55,7 @@ live binary. - **Serving MCP tools.** [MCP server](mcp.md) exposes typed, allowlisted tools for agent clients without a generic command bridge. - **Discovering runtime contracts.** [Automation](automation.md) explains root help, schema metadata, safety controls, and stable exit codes. - **Polling local events.** [Drive and Docs polling](polling.md) persists cursors and optionally invokes trusted shell hooks. -- **Persisting auth and state.** [Paths and State](paths.md) covers `GOG_HOME`, per-kind directories, XDG paths, and legacy compatibility. +- **Persisting auth and state.** [Paths and State](paths.md) covers `GOG_HOME`, per-kind directories, XDG paths, legacy compatibility, and rotating the file keyring password without re-authorizing accounts. - **Running Workspace at scale.** [Auth Clients](auth-clients.md) for service accounts, named OAuth clients, and domain-wide delegation. - **Managing Workspace.** [Workspace Admin](workspace-admin.md) covers user creation, cleanup, organizational units, and group administration. - **Backing up an account.** [Backup](backup.md) before pointing `gog backup push` at a busy mailbox. diff --git a/docs/paths.md b/docs/paths.md index 5937a273e..d59cd3f1c 100644 --- a/docs/paths.md +++ b/docs/paths.md @@ -58,6 +58,77 @@ Existing installs are read-compatible: New writes use the new path for the selected kind. `auth credentials remove` and service-account removal clean up both new and legacy locations where safe. +## Changing the Keyring Password + +`gog auth rekey ` reads the file keyring with the current password and +writes a verified copy encrypted with the new password to the separate output +directory given as its argument: + +```bash +GOG_KEYRING_PASSWORD='current password' \ +GOG_KEYRING_NEW_PASSWORD='new password' \ +gog auth rekey /path/to/new-keyring +``` + +Credential files are read-only: their contents, permissions and password remain +untouched on success, failure or interruption. Rekey holds the shared store lock +through reading, writing, verification and publication, blocking credential writes +until it finishes. It may create the normal `.lock` bookkeeping file. Rekey never +installs the output into the live keyring. + +The output directory receives the source directory's permissions. It must be +outside the live directory and cannot be that directory or one of its ancestors, +including aliases through symlinks. Existing empty output is accepted. Nonempty +output is refused unless you explicitly pass `--force`, which replaces the whole +output directory and reports the names replaced; it never merges files. It writes +into a private sibling directory, verifies every entry, flushes ciphertext files +and directory metadata, then atomically exchanges the complete directories on +Linux and macOS. A write or verification failure leaves previous output intact; +a publication sync failure rolls back. If rollback also fails, the error identifies +the retained previous output for recovery. Interruption can leave a hidden +`.gog-rekey-*` sibling; inspect it before removing it. On filesystems without atomic +directory exchange, and on Windows, choose a fresh output path: existing output is +refused unchanged. Windows flushes ciphertext files but cannot fsync directories. + +Before reporting success, rekey independently opens the output with the new +password and reads every item back, comparing its data and metadata. Output +contains only this run's entries: no password verifier or internal lock file is +created. An empty keyring produces empty output and explicitly reports that no +password was changed or established. + +Inspect the output and any reported unreadable keys before installing it. The +command prints the exact move command for your paths (a shell command on Linux +and macOS, a PowerShell command on Windows). Stop running `gog` processes before +moving directories so their subsequent writes are not lost. For example: + +```bash +test ! -e '/path/to/keyring.old' && test ! -L '/path/to/keyring.old' && mv -- '/path/to/keyring' '/path/to/keyring.old' && mv -- '/path/to/new-keyring' '/path/to/keyring' +``` + +Keep the old directory until the new keyring is proven. After installing the +output, update `GOG_KEYRING_PASSWORD` in the shell, services and CI that use it, +and test your normal commands. The command refuses to overwrite an existing +`.old` directory. These installation steps are the user's action, separate from +rekey. + +Passwords come from the environment or a no-echo TTY prompt, never from argv. +The interactive new-password prompt asks twice and preserves whitespace. +Paths, counts and key names can appear in output; payloads and passwords cannot. + +- Undecryptable entries abort before output is replaced. With + `--skip-unreadable`, they are omitted from output and their keys are reported; + their live copies remain untouched. A password that opens no entry is always + an error, even with this flag. Inspect omissions before installing the output. +- Only the file backend qualifies. `auto` qualifies on headless Linux without a + D-Bus session, where `gog` forces the file backend. Other `auto` configurations + are refused without opening an OS keychain or creating a live directory; use + `gog auth keyring file` if the file backend is your intended store. +- Legacy filenames are read without modification and written encoded in the + output. Conflicting legacy and encoded copies of a key abort rather than + silently discarding one. +- The lock gives rekey a consistent snapshot. Credentials can change after it + releases the lock, so stop other `gog` processes before installing the output. + ## Containers and Agents For a single persistent root: diff --git a/internal/cmd/auth.go b/internal/cmd/auth.go index dfc1fa1d1..5e01521bf 100644 --- a/internal/cmd/auth.go +++ b/internal/cmd/auth.go @@ -118,6 +118,7 @@ type AuthCmd struct { Aliases AuthAliasCmd `cmd:"" name:"alias" help:"Manage account aliases"` Status AuthStatusCmd `cmd:"" name:"status" help:"Show auth configuration and keyring backend"` Keyring AuthKeyringCmd `cmd:"" name:"keyring" help:"Configure keyring backend"` + Rekey AuthRekeyCmd `cmd:"" name:"rekey" help:"Write a verified copy of the file keyring to using GOG_KEYRING_NEW_PASSWORD; leave the live keyring untouched"` Remove AuthRemoveCmd `cmd:"" name:"remove" help:"Remove a stored refresh token"` Tokens AuthTokensCmd `cmd:"" name:"tokens" help:"Manage stored refresh tokens"` Manage AuthManageCmd `cmd:"" name:"manage" help:"Open interactive accounts manager in browser" aliases:"login"` diff --git a/internal/cmd/auth_rekey.go b/internal/cmd/auth_rekey.go new file mode 100644 index 000000000..bfb1fcf9c --- /dev/null +++ b/internal/cmd/auth_rekey.go @@ -0,0 +1,208 @@ +package cmd + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/openclaw/gogcli/internal/config" + "github.com/openclaw/gogcli/internal/outfmt" + "github.com/openclaw/gogcli/internal/secrets" + "github.com/openclaw/gogcli/internal/ui" +) + +const ( + rekeyPasswordEnv = "GOG_KEYRING_PASSWORD" //nolint:gosec // env var name, not a credential + rekeyNewPasswordEnv = "GOG_KEYRING_NEW_PASSWORD" //nolint:gosec // env var name, not a credential +) + +// AuthRekeyCmd writes a verified, re-encrypted copy to a separate directory. +// It never modifies the live keyring; installation is a later user action. +type AuthRekeyCmd struct { + OutDir string `arg:"" name:"outdir" help:"Separate output directory for the re-encrypted keyring; --force replaces nonempty output"` + SkipUnreadable bool `name:"skip-unreadable" help:"Omit undecryptable items from output and report their keys; live items remain untouched"` +} + +func (c *AuthRekeyCmd) Run(ctx context.Context, flags *RootFlags) error { + u := ui.FromContext(ctx) + + layout, err := commandLayout(ctx, config.PathKindConfig, config.PathKindData) + if err != nil { + return err + } + + backendInfo, err := resolveKeyringBackendInfo(ctx) + if err != nil { + return err + } + + configStore, err := commandConfigStore(ctx) + if err != nil { + return err + } + openOptions := systemKeyringOpenOptions(layout, configStore) + if err = secrets.CheckRekeyBackend(backendInfo.Value, openOptions.GOOS, openOptions.DBusAddress); err != nil { + return err + } + if c.OutDir == "" { + return usagef("output directory is required; pass it as the positional argument") + } + // Only output replacement is destructive, and it requires explicit --force + // in Rekey. A fresh output needs no confirmation and never opens the live + // keyring through the normal (directory-creating) backend resolver. + if flags.DryRun { + return dryRunExit(ctx, flags, "auth.rekey", map[string]any{"outdir": c.OutDir, "skip_unreadable": c.SkipUnreadable, "force": flags.Force}) + } + + oldPassword, oldSet, err := rekeyReadPassword(ctx, rekeyPasswordEnv, "Current keyring password: ", flags.NoInput) + if err != nil { + return err + } + if !oldSet { + return usagef("no current password: set %s, or run on a TTY without --no-input", rekeyPasswordEnv) + } + + newPassword, newSet, err := rekeyReadNewPassword(ctx, flags.NoInput) + if err != nil { + return err + } + if !newSet { + return usagef("no new password: set %s, or run on a TTY without --no-input", rekeyNewPasswordEnv) + } + + res, err := secrets.Rekey(secrets.RekeyOptions{ + Layout: layout, + OutDir: c.OutDir, + Force: flags.Force, + Backend: backendInfo.Value, + OldPassword: oldPassword, + OldPasswordSet: oldSet, + NewPassword: newPassword, + NewPasswordSet: newSet, + GOOS: openOptions.GOOS, + DBusAddress: openOptions.DBusAddress, + SkipUnreadable: c.SkipUnreadable, + }) + if err != nil { + if len(res.Replaced) > 0 { + _, _ = fmt.Fprintf(stderrWriter(ctx), "Removed previous output entries in %s: %s. Live keyring untouched; output was not verified.\n", res.OutDir, strings.Join(res.Replaced, ", ")) + } + return err + } + + return writeRekeyResult(ctx, u, res) +} + +// rekeyPromptSecret reads a password without trimming it. A keyring password may +// legitimately begin or end with whitespace, and an environment-supplied value is +// used verbatim, so trimming only the prompted side would rotate the keyring to a +// password the user never set. +func rekeyPromptSecret(ctx context.Context, prompt string) (string, error) { + _, _ = fmt.Fprint(stderrWriter(ctx), prompt) + + secret, err := readSecret(stdinReader(ctx)) + defer clear(secret) + _, _ = fmt.Fprintln(stderrWriter(ctx)) + + if err != nil { + return "", err + } + + return string(secret), nil +} + +// rekeyReadPassword resolves a password from the environment, falling back to a +// no-echo terminal prompt. Passwords never come from argv, where they would be +// visible to every process on the box. +func rekeyReadPassword(ctx context.Context, env, prompt string, noInput bool) (string, bool, error) { + if value, ok := os.LookupEnv(env); ok { + return value, true, nil + } + + if noInput || !stdinIsTerminal(ctx) { + return "", false, nil + } + + value, err := rekeyPromptSecret(ctx, prompt) + if err != nil { + return "", false, fmt.Errorf("read %s: %w", env, err) + } + + return value, true, nil +} + +// rekeyReadNewPassword asks twice when prompting interactively: a typo here +// would encrypt the output with a password the user never intended. +func rekeyReadNewPassword(ctx context.Context, noInput bool) (string, bool, error) { + if value, ok := os.LookupEnv(rekeyNewPasswordEnv); ok { + return value, true, nil + } + + if noInput || !stdinIsTerminal(ctx) { + return "", false, nil + } + + first, err := rekeyPromptSecret(ctx, "New keyring password: ") + if err != nil { + return "", false, fmt.Errorf("read new keyring password: %w", err) + } + if first == "" { + return "", false, usagef("new keyring password cannot be empty; set %s= to force one", rekeyNewPasswordEnv) + } + + second, err := rekeyPromptSecret(ctx, "Repeat new keyring password: ") + if err != nil { + return "", false, fmt.Errorf("read new keyring password: %w", err) + } + if first != second { + return "", false, usagef("new keyring passwords do not match") + } + + return first, true, nil +} + +func writeRekeyResult(ctx context.Context, u *ui.UI, res secrets.RekeyResult) error { + next := "Inspect the output, stop running gog processes before installing, and keep " + res.RetainedDir + " until the new keyring is proven. Update GOG_KEYRING_PASSWORD only after installation." + if res.Items == 0 { + next = "Empty output: no password was changed or established. " + next + } + if len(res.Unreadable) > 0 { + next = "Output omits unreadable keys; inspect these before installing. " + next + } + if outfmt.IsJSON(ctx) { + return outfmt.WriteJSON(ctx, stdoutWriter(ctx), map[string]any{ + "keyring_dir": res.Dir, "output_dir": res.OutDir, "items": res.Items, + "keys": res.Keys, "unreadable": res.Unreadable, "replaced": res.Replaced, + "password_changed": false, "move_command": res.MoveCommand, "next_step": next, + "retained_dir": res.RetainedDir, + }) + } + if u == nil { + return fmt.Errorf("cannot report rekey output without a UI") + } + if outfmt.IsPlain(ctx) { + u.Out().Linef("keyring_dir\t%s", res.Dir) + u.Out().Linef("output_dir\t%s", res.OutDir) + u.Out().Linef("retained_dir\t%s", res.RetainedDir) + u.Out().Linef("items\t%d", res.Items) + u.Out().Linef("keys\t%s", strings.Join(res.Keys, ",")) + u.Out().Linef("password_changed\tfalse") + u.Out().Linef("replaced\t%s", strings.Join(res.Replaced, ",")) + u.Out().Linef("unreadable\t%s", strings.Join(res.Unreadable, ",")) + u.Out().Linef("move_command\t%s", res.MoveCommand) + u.Out().Linef("next_step\t%s", next) + return nil + } + u.Out().Linef("Wrote and verified %d item(s) in %s. Live keyring untouched: %s", res.Items, res.OutDir, res.Dir) + u.Out().Linef("Keys: %s", strings.Join(res.Keys, ", ")) + if len(res.Replaced) > 0 { + u.Out().Linef("Replaced output entries in %s: %s", res.OutDir, strings.Join(res.Replaced, ", ")) + } + if len(res.Unreadable) > 0 { + u.Err().Linef("Omitted from output, cannot be decrypted: %s", strings.Join(res.Unreadable, ", ")) + } + u.Out().Println(next) + u.Out().Linef("Install with: %s", res.MoveCommand) + return nil +} diff --git a/internal/cmd/auth_rekey_test.go b/internal/cmd/auth_rekey_test.go new file mode 100644 index 000000000..9f7ee804a --- /dev/null +++ b/internal/cmd/auth_rekey_test.go @@ -0,0 +1,410 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/alecthomas/kong" + + "github.com/openclaw/gogcli/internal/app" + "github.com/openclaw/gogcli/internal/config" + "github.com/openclaw/gogcli/internal/outfmt" + "github.com/openclaw/gogcli/internal/secrets" +) + +const ( + rekeyTestOldPassword = "old-password" + rekeyTestNewPassword = "new-password" + rekeyTestPayload = "private-refresh-token-must-not-appear" +) + +// rekeyTestContext gives each test an isolated HOME/XDG layout so the keyring +// under test is never the ambient one. +func rekeyTestContext(t *testing.T) (context.Context, *bytes.Buffer) { + t.Helper() + + ctx, stdout, _ := rekeyTestContextIO(t) + + return ctx, stdout +} + +// rekeyTestContextIO is rekeyTestContext plus the stderr buffer, for tests that +// assert on what the command must *not* print. +func rekeyTestContextIO(t *testing.T) (context.Context, *bytes.Buffer, *bytes.Buffer) { + t.Helper() + + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("APPDATA", filepath.Join(home, "appdata")) + for _, name := range []string{"GOG_CONFIG_DIR", "GOG_DATA_DIR", "GOG_STATE_DIR", "GOG_CACHE_DIR"} { + t.Setenv(name, "") + } + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "xdg-config")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, "xdg-data")) + t.Setenv("GOG_HOME", "") + t.Setenv("GOG_KEYRING_BACKEND", "file") + + var stdout, stderr bytes.Buffer + + // newCmdRuntimeIOContext wires the runtime's IO to these buffers, which is + // what stdoutWriter reads — the ui alone is not enough. + ctx := newCmdRuntimeIOContext(t, strings.NewReader(""), &stdout, &stderr) + + return ctx, &stdout, &stderr +} + +// unsetEnv removes a variable for the duration of the test, restoring the +// original value on cleanup. t.Setenv alone cannot express "unset", because an +// empty value still counts as present. +func unsetEnv(t *testing.T, name string) { + t.Helper() + + original, had := os.LookupEnv(name) + t.Cleanup(func() { + if had { + _ = os.Setenv(name, original) + + return + } + _ = os.Unsetenv(name) + }) + + if err := os.Unsetenv(name); err != nil { + t.Fatalf("unset %s: %v", name, err) + } +} + +// seedRekeyKeyring writes one token into the keyring the command will rekey. +func seedRekeyKeyring(t *testing.T, ctx context.Context) { + t.Helper() + + layout, err := commandLayout(ctx, config.PathKindConfig, config.PathKindData) + if err != nil { + t.Fatalf("layout: %v", err) + } + + store, err := secrets.Open(secrets.OpenOptions{ + Layout: layout, + Backend: "file", + Password: rekeyTestOldPassword, + PasswordSet: true, + GOOS: runtime.GOOS, + }) + if err != nil { + t.Fatalf("open keyring: %v", err) + } + + if err := store.SetToken("default", "a@example.com", secrets.Token{ + Client: "default", + Email: "a@example.com", + RefreshToken: rekeyTestPayload, + }); err != nil { + t.Fatalf("seed token: %v", err) + } +} + +// keyringReadable reports whether the isolated keyring can be opened and read +// with the given password. +func keyringReadable(t *testing.T, ctx context.Context, password string) bool { + t.Helper() + + layout, err := commandLayout(ctx, config.PathKindConfig, config.PathKindData) + if err != nil { + t.Fatalf("layout: %v", err) + } + + store, err := secrets.Open(secrets.OpenOptions{ + Layout: layout, + Backend: "file", + Password: password, + PasswordSet: true, + GOOS: runtime.GOOS, + }) + if err != nil { + return false + } + + tokens, err := store.ListTokens() + + return err == nil && len(tokens) > 0 +} + +func TestAuthRekey_OutputAndNextStep(t *testing.T) { + for _, mode := range []string{"human", "plain", "json"} { + t.Run(mode, func(t *testing.T) { + ctx, stdout, stderr := rekeyTestContextIO(t) + seedRekeyKeyring(t, ctx) + t.Setenv(rekeyPasswordEnv, rekeyTestOldPassword) + t.Setenv(rekeyNewPasswordEnv, rekeyTestNewPassword) + if mode == "json" { + ctx = outfmt.WithMode(ctx, outfmt.Mode{JSON: true}) + } + if mode == "plain" { + ctx = outfmt.WithMode(ctx, outfmt.Mode{Plain: true}) + } + out := filepath.Join(t.TempDir(), "output") + if err := runKong(t, &AuthRekeyCmd{}, []string{out}, ctx, &RootFlags{NoInput: true}); err != nil { + t.Fatal(err) + } + resolvedOut, err := filepath.EvalSymlinks(out) + if err != nil { + t.Fatal(err) + } + layout, err := commandLayout(ctx, config.PathKindData) + if err != nil { + t.Fatal(err) + } + live, err := filepath.EvalSymlinks(layout.KeyringDir()) + if err != nil { + t.Fatal(err) + } + quote := func(path string) string { + if runtime.GOOS == "windows" { + return "'" + strings.ReplaceAll(path, "'", "''") + "'" + } + return "'" + strings.ReplaceAll(path, "'", `'\''`) + "'" + } + move := "mv -- " + quote(live) + " " + quote(live+".old") + " && mv -- " + quote(resolvedOut) + " " + quote(live) + if runtime.GOOS == "windows" { + move = "Move-Item -LiteralPath " + quote(live) + " -Destination " + quote(live+".old") + " -ErrorAction Stop; Move-Item -LiteralPath " + quote(resolvedOut) + " -Destination " + quote(live) + " -ErrorAction Stop" + } + combined := stdout.String() + stderr.String() + requiredText := []string{".old", "proven", "GOG_KEYRING_PASSWORD", "token:default:a@example.com", "token:a@example.com"} + if mode != "json" { + requiredText = append(requiredText, resolvedOut, move) + } + for _, required := range requiredText { + if !strings.Contains(combined, required) { + t.Fatalf("missing %q in %s", required, combined) + } + } + for _, secret := range []string{rekeyTestOldPassword, rekeyTestNewPassword, rekeyTestPayload} { + if strings.Contains(combined, secret) { + t.Fatalf("output disclosed secret %q", secret) + } + } + if !keyringReadable(t, ctx, rekeyTestOldPassword) || keyringReadable(t, ctx, rekeyTestNewPassword) { + t.Fatal("command changed live password") + } + switch mode { + case "json": + var payload map[string]any + if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload["password_changed"] != false || payload["items"] != float64(2) || payload["output_dir"] != resolvedOut || payload["move_command"] == "" { + t.Fatalf("dishonest result: %v", payload) + } + if command, ok := payload["move_command"].(string); !ok || !strings.Contains(command, move) { + t.Fatal("JSON omitted the exact move command") + } + case "plain": + for _, required := range []string{"password_changed\tfalse", "items\t2", "move_command\t"} { + if !strings.Contains(stdout.String(), required) { + t.Fatalf("plain output missing %q", required) + } + } + default: + if !strings.Contains(stdout.String(), "Live keyring untouched") || !strings.Contains(stdout.String(), "Install with:") { + t.Fatal("human output omitted live status or installation command") + } + } + }) + } +} + +func TestAuthRekey_PromptPreservesWhitespace(t *testing.T) { + var stdout, stderr bytes.Buffer + ctx := newCmdRuntimeIOContext(t, strings.NewReader(" private password \n"), &stdout, &stderr) + password, err := rekeyPromptSecret(ctx, "Password: ") + if err != nil || password != " private password " { + t.Fatalf("prompt changed the password: %v", err) + } + if stdout.Len() != 0 || stderr.String() != "Password: \n" { + t.Fatal("prompt printed a password or wrote to stdout") + } +} + +func TestAuthRekey_RejectsBackendBeforePasswords(t *testing.T) { + ctx, stdout, stderr := rekeyTestContextIO(t) + t.Setenv("GOG_KEYRING_BACKEND", "keychain") + // The test runtime normally overrides backend selection with "file". + ctx = withTestRuntime(ctx, func(runtime *app.Runtime) { + runtime.KeyringOptions.Backend = "keychain" + }) + unsetEnv(t, rekeyPasswordEnv) + unsetEnv(t, rekeyNewPasswordEnv) + layout, err := commandLayout(ctx, config.PathKindData) + if err != nil { + t.Fatal(err) + } + out := filepath.Join(t.TempDir(), "out") + err = runKong(t, &AuthRekeyCmd{}, []string{out}, ctx, &RootFlags{NoInput: true}) + if !errors.Is(err, secrets.ErrRekeyNotFileBackend) { + t.Fatalf("backend guard did not run first: %v", err) + } + if stdout.Len() != 0 || stderr.Len() != 0 { + t.Fatal("backend rejection prompted or reported success") + } + for _, path := range []string{layout.KeyringDir(), out} { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatal("backend rejection created a directory") + } + } +} + +func TestAuthRekey_Guards(t *testing.T) { + for _, scenario := range []string{"missing-output", "missing-old", "missing-new", "wrong", "nonempty"} { + t.Run(scenario, func(t *testing.T) { + ctx, stdout := rekeyTestContext(t) + seedRekeyKeyring(t, ctx) + t.Setenv(rekeyPasswordEnv, rekeyTestOldPassword) + t.Setenv(rekeyNewPasswordEnv, rekeyTestNewPassword) + out := filepath.Join(t.TempDir(), "output") + args := make([]string, 0, 2) + wantText := "outdir" + if scenario != "missing-output" { + args = append(args, out) + } + switch scenario { + case "missing-old": + unsetEnv(t, rekeyPasswordEnv) + wantText = "no current password:" + case "missing-new": + unsetEnv(t, rekeyNewPasswordEnv) + wantText = "no new password:" + case "wrong": + t.Setenv(rekeyPasswordEnv, "wrong") + args = append(args, "--skip-unreadable") + wantText = "does not open any keyring item" + case "nonempty": + wantText = "output directory is not empty" + if err := os.Mkdir(out, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(out, "keep"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := runKong(t, &AuthRekeyCmd{}, args, ctx, &RootFlags{NoInput: true}); err == nil || !strings.Contains(err.Error(), wantText) { + t.Fatalf("want %q error, got %v", wantText, err) + } + if stdout.Len() != 0 { + t.Fatal("failure printed success") + } + if !keyringReadable(t, ctx, rekeyTestOldPassword) { + t.Fatal("guard changed live keyring") + } + }) + } +} + +func TestAuthRekey_PositionalRequired(t *testing.T) { + for _, args := range [][]string{nil, {"--outdir", "output"}, {"output"}} { + command := &AuthRekeyCmd{} + parser, err := kong.New(command) + if err != nil { + t.Fatal(err) + } + _, err = parser.Parse(args) + if len(args) == 1 { + if err != nil || command.OutDir != "output" { + t.Fatalf("required positional not accepted: %v", err) + } + } else if err == nil { + t.Fatalf("accepted invalid positional interface: %v", args) + } + } +} + +func TestAuthRekey_PasswordEnvironment(t *testing.T) { + for _, value := range []string{"", " whitespace matters "} { + ctx, _, stderr := rekeyTestContextIO(t) + t.Setenv(rekeyPasswordEnv, value) + t.Setenv(rekeyNewPasswordEnv, value) + old, oldSet, err := rekeyReadPassword(ctx, rekeyPasswordEnv, "Current: ", true) + if err != nil || !oldSet || old != value { + t.Fatalf("old password changed or lost: %v", err) + } + newPassword, newSet, err := rekeyReadNewPassword(ctx, true) + if err != nil || !newSet || newPassword != value { + t.Fatalf("new password changed or lost: %v", err) + } + if stderr.Len() != 0 { + t.Fatal("environment passwords prompted or were printed") + } + } +} + +func TestAuthRekey_ForceReportsReplacement(t *testing.T) { + ctx, stdout := rekeyTestContext(t) + seedRekeyKeyring(t, ctx) + t.Setenv(rekeyPasswordEnv, rekeyTestOldPassword) + t.Setenv(rekeyNewPasswordEnv, rekeyTestNewPassword) + out := t.TempDir() + if err := os.WriteFile(filepath.Join(out, "stale"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + err := runKong(t, &AuthRekeyCmd{}, []string{out}, ctx, &RootFlags{Force: true}) + if runtime.GOOS == "windows" { + if err == nil || !strings.Contains(err.Error(), "fresh output directory") { + t.Fatalf("expected safe refusal: %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + if !strings.Contains(stdout.String(), "Replaced") || !strings.Contains(stdout.String(), "stale") { + t.Fatal("replacement not reported") + } +} + +func TestAuthRekey_EmptyHonest(t *testing.T) { + ctx, stdout, stderr := rekeyTestContextIO(t) + layout, err := commandLayout(ctx, config.PathKindData, config.PathKindConfig) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(layout.KeyringDir(), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv(rekeyPasswordEnv, rekeyTestOldPassword) + t.Setenv(rekeyNewPasswordEnv, rekeyTestNewPassword) + if err := runKong(t, &AuthRekeyCmd{}, []string{filepath.Join(t.TempDir(), "out")}, ctx, &RootFlags{}); err != nil { + t.Fatal(err) + } + if !strings.Contains(stdout.String()+stderr.String(), "no password was changed or established") { + t.Fatal("empty keyring claimed password rotation") + } +} + +func TestAuthRekey_DryRunChangesNothing(t *testing.T) { + ctx, _ := rekeyTestContext(t) + // No passwords or source directory; dry-run must not try to open anything. + unsetEnv(t, rekeyPasswordEnv) + unsetEnv(t, rekeyNewPasswordEnv) + layout, err := commandLayout(ctx, config.PathKindData, config.PathKindConfig) + if err != nil { + t.Fatal(err) + } + out := filepath.Join(t.TempDir(), "output") + err = runKong(t, &AuthRekeyCmd{}, []string{out}, ctx, &RootFlags{DryRun: true}) + var exit *ExitError + if !errors.As(err, &exit) || exit.Code != 0 { + t.Fatalf("dry run: %v", err) + } + for _, path := range []string{layout.KeyringDir(), out} { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("dry run created %s", path) + } + } +} diff --git a/internal/secrets/backend.go b/internal/secrets/backend.go index 3a402724b..5c5593e6d 100644 --- a/internal/secrets/backend.go +++ b/internal/secrets/backend.go @@ -319,11 +319,22 @@ func prepareKeyring( keychainTrustApplication bool, options OpenOptions, ) keyring.Keyring { - if wrapFileKeys || isFileKeyring(ring) { - ring = newFileSafeKeyring(ring) + fileBacked := isFileKeyring(ring) + + if wrapFileKeys || fileBacked { + dir := "" + if fileBacked { + dir = options.Layout.KeyringDir() + } + + ring = newFileSafeKeyringIn(ring, dir) } - if shouldUseKeyringOperationTimeout(options.GOOS, backendInfo, options.DBusAddress) { + // Not for a real file backend: the timeout runs the operation in a goroutine + // that cannot be stopped, so a timed-out write continues after its caller has + // returned — and after the lock it held is released, allowing concurrent + // operations on the same entry. + if !fileBacked && shouldUseKeyringOperationTimeout(options.GOOS, backendInfo, options.DBusAddress) { timeout := options.OpenTimeout if timeout <= 0 { timeout = defaultKeyringOpenTimeout(options.GOOS) diff --git a/internal/secrets/file_keyring_safe.go b/internal/secrets/file_keyring_safe.go index 63e891788..0142de8f2 100644 --- a/internal/secrets/file_keyring_safe.go +++ b/internal/secrets/file_keyring_safe.go @@ -5,24 +5,39 @@ import ( "errors" "fmt" "io/fs" + "os" + "path/filepath" "sort" "strings" "github.com/99designs/keyring" ) -const fileKeyPrefix = "_gogcli_key_v1_" +const ( + fileKeyPrefix = "_gogcli_key_v1_" + // keyringVerifierKey names bookkeeping written by the abandoned in-place + // rekey. Output-only rekey never writes or consults a verifier, but a live + // keyring may still carry one from an older release, so reads skip it. + keyringVerifierKey = ".gogcli-password-verifier" +) var isInvalidFileKeyError = defaultIsInvalidFileKeyError type fileSafeKeyring struct { inner keyring.Keyring + // dir is where the file backend stores entries, when the caller knows it. + // It lets Keys omit directories from the upstream file listing. + dir string } func newFileSafeKeyring(inner keyring.Keyring) keyring.Keyring { return &fileSafeKeyring{inner: inner} } +func newFileSafeKeyringIn(inner keyring.Keyring, dir string) keyring.Keyring { + return &fileSafeKeyring{inner: inner, dir: dir} +} + func fileKeyringBackendOnly(backends []keyring.BackendType) bool { return len(backends) == 1 && backends[0] == keyring.FileBackend } @@ -142,6 +157,20 @@ func (k *fileSafeKeyring) Keys() ([]string, error) { seen := make(map[string]struct{}, len(keys)) for _, key := range keys { decoded := decodeFileSafeKey(key) + if isInternalKeyringKey(decoded) { + // Bookkeeping the keyring owns, not one of the user's credentials. + continue + } + + // The library lists every directory entry, so a subdirectory is reported + // here as though it were a stored item. Rekey would then call it an + // undecryptable credential and suggest skipping it. + if k.dir != "" { + if info, statErr := os.Lstat(filepath.Join(k.dir, key)); statErr == nil && info.IsDir() { + continue + } + } + if _, ok := seen[decoded]; ok { continue } diff --git a/internal/secrets/rekey.go b/internal/secrets/rekey.go new file mode 100644 index 000000000..9223e5c40 --- /dev/null +++ b/internal/secrets/rekey.go @@ -0,0 +1,520 @@ +package secrets + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "slices" + "strings" + + "github.com/99designs/keyring" + jose "github.com/dvsekhvalnov/jose2go" + "github.com/mtibben/percent" + + "github.com/openclaw/gogcli/internal/config" +) + +const keyringBackendFile = "file" + +var ( + ErrRekeyNotFileBackend = errors.New("rekey requires the file keyring backend") + ErrRekeySamePassword = errors.New("new password must differ from the current password") + ErrRekeyNoOldPassword = errors.New("no current keyring password provided; set GOG_KEYRING_PASSWORD or run on a TTY") + ErrRekeyNoNewPassword = errors.New("no new password provided; set GOG_KEYRING_NEW_PASSWORD or run on a TTY") + errRekeyUnreadableItems = errors.New("keyring items cannot be decrypted with the current password") + errRekeyNoReadableItems = errors.New("the current password does not open any keyring item") + errRekeyContentMismatch = errors.New("keyring content mismatch") + errRekeyUnsafeOutput = errors.New("output directory overlaps the live keyring") + errRekeyOutputNotEmpty = errors.New("output directory is not empty; use --force to replace it") + errRekeyNoOutput = errors.New("output directory is required; pass it as the positional argument") +) + +// RekeyOptions describes an output-only keyring password change. +type RekeyOptions struct { + Layout config.Layout + Backend string + OldPassword string + OldPasswordSet bool + NewPassword string + NewPasswordSet bool + GOOS string + DBusAddress string + // OutDir is the required output directory, passed positionally on the + // command line. Force permits replacing its contents. + OutDir string + Force bool + SkipUnreadable bool + // openOutput is a test seam for write and independent read-back failures. + openOutput func(dir, password string) (keyring.Keyring, error) +} + +// RekeyResult reports what was written, never a change to the live keyring. +type RekeyResult struct { + Dir string + OutDir string + Items int + Keys []string + Unreadable []string + Replaced []string + MoveCommand string + // RetainedDir is where the printed installation command would keep the old + // directory. Rekey itself never creates or moves anything there. + RetainedDir string + // Deprecated: the live password never changes and no backup is made. + BackupDir string + PasswordChanged bool +} + +// Rekey opens the live keyring read-only and writes re-encrypted entries only to +// OutDir. Nothing the live directory holds is ever modified, so no crash, +// interruption or bug in output writing can lose or corrupt live credentials. +// Re-running with --force rewrites the output directory from the live store. +func Rekey(opts RekeyOptions) (RekeyResult, error) { + if !opts.OldPasswordSet { + return RekeyResult{}, ErrRekeyNoOldPassword + } + + if !opts.NewPasswordSet { + return RekeyResult{}, ErrRekeyNoNewPassword + } + + if opts.OldPassword == opts.NewPassword { + return RekeyResult{}, ErrRekeySamePassword + } + + if err := CheckRekeyBackend(opts.Backend, opts.GOOS, opts.DBusAddress); err != nil { + return RekeyResult{}, err + } + + if opts.OutDir == "" { + return RekeyResult{}, errRekeyNoOutput + } + + dir, err := filepath.EvalSymlinks(opts.Layout.KeyringDir()) + if err != nil { + return RekeyResult{}, fmt.Errorf("resolve live keyring: %w", err) + } + + dir, err = filepath.Abs(dir) + if err != nil { + return RekeyResult{}, fmt.Errorf("resolve live keyring path: %w", err) + } + + out, err := rekeyOutputPath(dir, opts.OutDir) + if err != nil { + return RekeyResult{}, err + } + + lock := sharedKeyringLock(filepath.Join(dir, keyringLockFilename), parseKeyringLockTimeout(os.Getenv(keyringLockTimeoutEnv))) + var res RekeyResult + err = lock.withReadLock(func() error { + var rekeyErr error + res, rekeyErr = rekeyLocked(opts, dir, out) + return rekeyErr + }) + return res, err +} + +func rekeyLocked(opts RekeyOptions, dir, out string) (RekeyResult, error) { + info, err := os.Stat(dir) + if err != nil { + return RekeyResult{}, fmt.Errorf("stat live keyring: %w", err) + } + + items, unreadable, err := readRekeyItems(dir, opts.OldPassword, opts.SkipUnreadable) + if err != nil { + return RekeyResult{}, err + } + + defer clearRekeyItems(items) + + mode := info.Mode() & (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky) + res := RekeyResult{Dir: dir, OutDir: out, Unreadable: unreadable} + entries, err := os.ReadDir(out) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return res, fmt.Errorf("read output directory: %w", err) + } + if len(entries) > 0 && !opts.Force { + return res, errRekeyOutputNotEmpty + } + if err := os.MkdirAll(filepath.Dir(out), 0o700); err != nil { + return res, fmt.Errorf("create output parent: %w", err) + } + stage, err := os.MkdirTemp(filepath.Dir(out), ".gog-rekey-*") + if err != nil { + return res, fmt.Errorf("create staging directory: %w", err) + } + cleanupStage := true + defer func() { + if cleanupStage { + _ = os.RemoveAll(stage) + } + }() + if err := os.Chmod(stage, mode); err != nil { + return res, fmt.Errorf("set output permissions: %w", err) + } + + open := opts.openOutput + if open == nil { + open = openRekeyOutput + } + + dst, err := open(stage, opts.NewPassword) + if err != nil { + return res, fmt.Errorf("open output keyring: %w", err) + } + + if err = writeRekeyItems(dst, items); err != nil { + return res, err + } + // Reopen independently with the NEW password. Comparing the whole item also + // protects metadata, not just the credential data. Never print decoded data. + keys, err := verifyRekeyOutput(open, stage, opts.NewPassword, items) + if err != nil { + return res, err + } + if err := syncRekeyOutput(stage); err != nil { + return res, err + } + if err := publishRekeyOutput(stage, out); err != nil { + var recovery *rekeyRecoveryError + cleanupStage = !errors.As(err, &recovery) + return res, err + } + for _, entry := range entries { + res.Replaced = append(res.Replaced, entry.Name()) + } + res.Keys = keys + res.Items = len(items) + res.RetainedDir = rekeyRetainedDir(dir, out) + res.MoveCommand = rekeyMoveCommand(dir, out) + + return res, nil +} + +func writeRekeyItems(dst keyring.Keyring, items []keyring.Item) error { + for _, item := range items { + if err := dst.Set(item); err != nil { + return fmt.Errorf("write output item %q: %w", item.Key, err) + } + } + + return nil +} + +func verifyRekeyOutput(open func(string, string) (keyring.Keyring, error), out, password string, items []keyring.Item) ([]string, error) { + verify, err := open(out, password) + if err != nil { + return nil, fmt.Errorf("open output for verification: %w", err) + } + + keys := make([]string, 0, len(items)) + for _, item := range items { + got, getErr := verify.Get(item.Key) + matches := reflect.DeepEqual(got, item) + clear(got.Data) + if getErr != nil || !matches { + return nil, fmt.Errorf("%w: output item %q failed verification", errRekeyContentMismatch, item.Key) + } + + keys = append(keys, item.Key) + } + + listed, err := verify.Keys() + if err != nil { + return nil, fmt.Errorf("list output for verification: %w", err) + } + + slices.Sort(listed) + + if !slices.Equal(listed, keys) { + return nil, fmt.Errorf("%w: output keys differ", errRekeyContentMismatch) + } + + return keys, nil +} + +// readRekeyItems reads credential files without opening a writable backend. +// The caller holds the store lock for the complete snapshot and publication. +func readRekeyItems(dir, password string, skip bool) ([]keyring.Item, []string, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, nil, fmt.Errorf("read live keyring directory: %w", err) + } + items := make(map[string]keyring.Item) + transferred := false + defer func() { + if !transferred { + for _, item := range items { + clear(item.Data) + } + } + }() + var unreadable []string + + for _, entry := range entries { + key := decodeFileSafeKey(percent.Decode(entry.Name())) + if entry.IsDir() || isInternalKeyringKey(key) || entry.Name() == ".DS_Store" { + continue + } + + info, statErr := os.Lstat(filepath.Join(dir, entry.Name())) + if statErr != nil { + return nil, nil, fmt.Errorf("stat live item %q: %w", key, statErr) + } + + if !info.Mode().IsRegular() { + return nil, nil, fmt.Errorf("%w: nonregular live item %q", errRekeyUnreadableItems, key) + } + + data, readErr := os.ReadFile(filepath.Join(dir, entry.Name())) //nolint:gosec // name from ReadDir, source read-only + if readErr != nil { + return nil, nil, fmt.Errorf("read live item %q: %w", key, readErr) + } + payload, _, decodeErr := jose.Decode(string(data), password) + + var item keyring.Item + decoded := []byte(payload) + unmarshalErr := json.Unmarshal(decoded, &item) + clear(decoded) + payload = "" + if decodeErr != nil || unmarshalErr != nil { + clear(item.Data) + unreadable = append(unreadable, key) + continue + } + + item.Key = key + if previous, ok := items[key]; ok { + if !reflect.DeepEqual(previous, item) { + clear(item.Data) + return nil, nil, fmt.Errorf("%w: conflicting live copies of %q", errRekeyContentMismatch, key) + } + clear(previous.Data) + } + items[key] = item + } + + slices.Sort(unreadable) + + if len(unreadable) > 0 { + if len(items) == 0 { + return nil, unreadable, fmt.Errorf("%w: %s", errRekeyNoReadableItems, strings.Join(unreadable, ", ")) + } + + if !skip { + return nil, unreadable, fmt.Errorf("%w: %s", errRekeyUnreadableItems, strings.Join(unreadable, ", ")) + } + } + + result := make([]keyring.Item, 0, len(items)) + for _, item := range items { + result = append(result, item) + } + + slices.SortFunc(result, func(a, b keyring.Item) int { return strings.Compare(a.Key, b.Key) }) + + transferred = true + return result, unreadable, nil +} + +// Resolve existing parents too, so aliases and paths through symlinks cannot +// point output into the source. Reject ancestors as well: --force on one would +// remove the live directory. A final symlink is never an output directory. +func rekeyOutputPath(dir, out string) (string, error) { + absolute, err := filepath.Abs(out) + if err != nil { + return "", fmt.Errorf("resolve output path: %w", err) + } + + if info, statErr := os.Lstat(absolute); statErr == nil && info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("%w: output is a symlink: %s", errRekeyUnsafeOutput, absolute) + } + + resolved, err := resolveRekeyParents(absolute) + if err != nil { + return "", err + } + + if rekeyPathContains(dir, resolved) || rekeyPathContains(resolved, dir) { + return "", fmt.Errorf("%w: %s and %s", errRekeyUnsafeOutput, dir, resolved) + } + + return resolved, nil +} + +func resolveRekeyParents(path string) (string, error) { + resolved, err := filepath.EvalSymlinks(path) + if err == nil { + return resolved, nil + } + + if !errors.Is(err, os.ErrNotExist) { + return "", fmt.Errorf("resolve output directory: %w", err) + } + + parent := filepath.Dir(path) + if parent == path { + return "", fmt.Errorf("resolve output parent: %w", err) + } + + resolved, err = resolveRekeyParents(parent) + if err != nil { + return "", err + } + + return filepath.Join(resolved, filepath.Base(path)), nil +} + +func rekeyPathContains(parent, child string) bool { + // Lexical checks alone miss case aliases on macOS's usual filesystem and + // Windows short names. Compare directory identities along existing parents + // as well, including when the requested output does not exist yet. + parentInfo, statErr := os.Stat(parent) + if statErr == nil { + for path := child; ; path = filepath.Dir(path) { + if info, err := os.Stat(path); err == nil && os.SameFile(parentInfo, info) { + return true + } + + if filepath.Dir(path) == path { + break + } + } + } + + if runtime.GOOS == "windows" { + parent, child = strings.ToLower(parent), strings.ToLower(child) + } + rel, err := filepath.Rel(parent, child) + + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +func clearRekeyItems(items []keyring.Item) { + for i := range items { + clear(items[i].Data) + } +} + +// Flush every ciphertext file before making the verified directory visible. +func syncRekeyOutput(dir string) error { + entries, err := os.ReadDir(dir) + if err != nil { + return fmt.Errorf("read staged output: %w", err) + } + for _, entry := range entries { + file, err := os.OpenFile(filepath.Join(dir, entry.Name()), os.O_RDWR, 0) + if err != nil { + return fmt.Errorf("open staged item: %w", err) + } + syncErr := file.Sync() + closeErr := file.Close() + if err := errors.Join(syncErr, closeErr); err != nil { + return fmt.Errorf("sync staged item: %w", err) + } + } + return syncRekeyDir(dir) +} + +// Existing output is exchanged as a whole; stage then holds the previous output. +// A failed durability barrier exchanges it back before the caller cleans stage. +func publishRekeyOutput(stage, out string) error { + return publishRekeyOutputWith(stage, out, exchangeRekeyDirs, syncRekeyDir) +} + +func publishRekeyOutputWith(stage, out string, exchange func(string, string) error, syncDir func(string) error) error { + _, err := os.Lstat(out) + existed := err == nil + if err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("stat output: %w", err) + } + if existed { + if err := exchange(stage, out); err != nil { + return fmt.Errorf("exchange output: %w", err) + } + } else if err := renameRekeyDir(stage, out); err != nil { + return fmt.Errorf("publish output: %w", err) + } + if err := syncDir(filepath.Dir(out)); err != nil { + var rollbackErr error + if existed { + rollbackErr = exchange(stage, out) + } else { + rollbackErr = renameRekeyDir(out, stage) + } + if rollbackErr != nil { + return &rekeyRecoveryError{err: fmt.Errorf("sync output: %w; rollback: %w; recovery required: inspect output %s and retained staging %s", err, rollbackErr, out, stage)} + } + return fmt.Errorf("sync output (rolled back): %w", errors.Join(err, syncDir(filepath.Dir(out)))) + } + return nil +} + +type rekeyRecoveryError struct{ err error } + +func (e *rekeyRecoveryError) Error() string { return e.err.Error() } +func (e *rekeyRecoveryError) Unwrap() error { return e.err } + +func openRekeyOutput(dir, password string) (keyring.Keyring, error) { + ring, err := keyring.Open(keyring.Config{ + ServiceName: config.AppName, + AllowedBackends: []keyring.BackendType{keyring.FileBackend}, + FileDir: dir, + FilePasswordFunc: keyring.FixedStringPrompt(password), + }) + if err != nil { + return nil, fmt.Errorf("open file keyring: %w", err) + } + + return newFileSafeKeyringIn(ring, dir), nil +} + +func shellQuote(path string) string { return "'" + strings.ReplaceAll(path, "'", `'\''`) + "'" } + +func rekeyMoveCommand(dir, out string) string { + old := rekeyRetainedDir(dir, out) + + if runtime.GOOS == "windows" { + quote := func(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" } + return "if (Get-Item -Force -LiteralPath " + quote(old) + " -ErrorAction SilentlyContinue) { throw 'Old directory already exists' }; Move-Item -LiteralPath " + quote(dir) + " -Destination " + quote(old) + " -ErrorAction Stop; Move-Item -LiteralPath " + quote(out) + " -Destination " + quote(dir) + " -ErrorAction Stop" + } + + return "test ! -e " + shellQuote(old) + " && test ! -L " + shellQuote(old) + " && mv -- " + shellQuote(dir) + " " + shellQuote(old) + " && mv -- " + shellQuote(out) + " " + shellQuote(dir) +} + +func rekeyRetainedDir(dir, out string) string { + old := dir + ".old" + for suffix := 1; rekeyPathContains(old, out) || rekeyPathContains(out, old); suffix++ { + old = fmt.Sprintf("%s.old-%d", dir, suffix) + } + + return old +} + +// CheckRekeyBackend rejects OS keychains without opening or creating any store. +// auto qualifies only for the headless Linux configuration that forces file. +func CheckRekeyBackend(backend, goos, dbusAddress string) error { + if rekeyUsesFileBackend(RekeyOptions{Backend: backend, GOOS: goos, DBusAddress: dbusAddress}) { + return nil + } + + return fmt.Errorf("%w (current backend: %s)", ErrRekeyNotFileBackend, rekeyBackendLabel(backend)) +} + +func rekeyUsesFileBackend(opts RekeyOptions) bool { + value := strings.ToLower(strings.TrimSpace(opts.Backend)) + return value == keyringBackendFile || shouldForceFileBackend(opts.GOOS, KeyringBackendInfo{Value: value}, opts.DBusAddress) +} + +func rekeyBackendLabel(backend string) string { + if label := strings.TrimSpace(backend); label != "" { + return label + } + + return "unresolved" +} diff --git a/internal/secrets/rekey_exchange_darwin.go b/internal/secrets/rekey_exchange_darwin.go new file mode 100644 index 000000000..3982e0be4 --- /dev/null +++ b/internal/secrets/rekey_exchange_darwin.go @@ -0,0 +1,7 @@ +package secrets + +import "golang.org/x/sys/unix" + +func exchangeRekeyDirs(a, b string) error { + return unix.RenamexNp(a, b, unix.RENAME_SWAP) +} diff --git a/internal/secrets/rekey_exchange_linux.go b/internal/secrets/rekey_exchange_linux.go new file mode 100644 index 000000000..4947e8205 --- /dev/null +++ b/internal/secrets/rekey_exchange_linux.go @@ -0,0 +1,7 @@ +package secrets + +import "golang.org/x/sys/unix" + +func exchangeRekeyDirs(a, b string) error { + return unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE) +} diff --git a/internal/secrets/rekey_exchange_other.go b/internal/secrets/rekey_exchange_other.go new file mode 100644 index 000000000..e33a25503 --- /dev/null +++ b/internal/secrets/rekey_exchange_other.go @@ -0,0 +1,9 @@ +//go:build !linux && !darwin + +package secrets + +import "errors" + +func exchangeRekeyDirs(_, _ string) error { + return errors.New("atomic replacement is unavailable on this platform; choose a fresh output directory") +} diff --git a/internal/secrets/rekey_lock_test.go b/internal/secrets/rekey_lock_test.go new file mode 100644 index 000000000..1f737a2e8 --- /dev/null +++ b/internal/secrets/rekey_lock_test.go @@ -0,0 +1,186 @@ +package secrets + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/99designs/keyring" +) + +func TestRekey_TakesLiveLock(t *testing.T) { + opts, dir := rekeyFixture(t) + t.Setenv(keyringLockTimeoutEnv, "30ms") + holder, err := os.OpenFile(filepath.Join(dir, keyringLockFilename), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + defer holder.Close() + if err := lockKeyringFile(holder, true); err != nil { + t.Fatal(err) + } + defer func() { + if err := unlockKeyringFile(holder); err != nil { + t.Error(err) + } + }() + if _, err := Rekey(opts); !errors.Is(err, errKeyringTimeout) { + t.Fatalf("expected lock timeout, got %v", err) + } +} + +func TestRekey_HoldsLiveLockThroughVerification(t *testing.T) { + opts, dir := rekeyFixture(t) + opens := 0 + opts.openOutput = func(path, password string) (keyring.Keyring, error) { + opens++ + if opens == 2 { + lock := &keyringLock{path: filepath.Join(dir, keyringLockFilename), timeout: 30 * time.Millisecond, mu: &sync.RWMutex{}} + if err := lock.withWriteLock(func() error { return nil }); !errors.Is(err, errKeyringTimeout) { + t.Fatalf("writer was not blocked: %v", err) + } + } + return openRekeyOutput(path, password) + } + if _, err := Rekey(opts); err != nil { + t.Fatal(err) + } +} + +func TestRekey_FailedWritePreservesOutput(t *testing.T) { + opts, _ := rekeyFixture(t) + opts.OutDir, opts.Force = t.TempDir(), true + if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("previous output"), 0o600); err != nil { + t.Fatal(err) + } + before := snapshotRekeyDir(t, opts.OutDir) + opts.openOutput = func(string, string) (keyring.Keyring, error) { return nil, errRekeyTestWrite } + if _, err := Rekey(opts); !errors.Is(err, errRekeyTestWrite) { + t.Fatal(err) + } + if !reflect.DeepEqual(before, snapshotRekeyDir(t, opts.OutDir)) { + t.Fatal("failed rekey destroyed previous output") + } +} + +func TestRekey_PublishRollback(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("directory exchange is unavailable") + } + for _, existing := range []bool{false, true} { + t.Run(fmt.Sprint(existing), func(t *testing.T) { + parent := t.TempDir() + stage, out := filepath.Join(parent, "stage"), filepath.Join(parent, "output") + if err := os.Mkdir(stage, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(stage, "new"), []byte("new ciphertext"), 0o600); err != nil { + t.Fatal(err) + } + if existing { + if err := os.Mkdir(out, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(out, "old"), []byte("old ciphertext"), 0o600); err != nil { + t.Fatal(err) + } + } + calls := 0 + err := publishRekeyOutputWith(stage, out, exchangeRekeyDirs, func(string) error { + calls++ + if calls == 1 { + return errRekeyTestWrite + } + return nil + }) + if !errors.Is(err, errRekeyTestWrite) || calls != 2 { + t.Fatalf("rollback not synced: %v (%d syncs)", err, calls) + } + if existing { + data, err := os.ReadFile(filepath.Join(out, "old")) + if err != nil || string(data) != "old ciphertext" { + t.Fatal("previous output not restored") + } + if _, err := os.Stat(filepath.Join(out, "new")); !errors.Is(err, os.ErrNotExist) { + t.Fatal("new output survived rollback") + } + } else if _, err := os.Stat(out); !errors.Is(err, os.ErrNotExist) { + t.Fatal("failed output was published") + } + }) + } +} + +func TestRekey_ExistingOutputUnsupported(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("Windows-only safety refusal") + } + opts, _ := rekeyFixture(t) + opts.OutDir, opts.Force = t.TempDir(), true + if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("old ciphertext"), 0o600); err != nil { + t.Fatal(err) + } + before := snapshotRekeyDir(t, opts.OutDir) + if _, err := Rekey(opts); err == nil || !strings.Contains(err.Error(), "fresh output directory") { + t.Fatalf("expected safe refusal: %v", err) + } + if !reflect.DeepEqual(before, snapshotRekeyDir(t, opts.OutDir)) { + t.Fatal("unsupported exchange modified output") + } +} + +func TestRekey_PublishesOnlyAfterVerification(t *testing.T) { + opts, _ := rekeyFixture(t) + opens := 0 + opts.openOutput = func(path, password string) (keyring.Keyring, error) { + opens++ + if _, err := os.Stat(opts.OutDir); !errors.Is(err, os.ErrNotExist) { + t.Fatal("output visible before verification") + } + return openRekeyOutput(path, password) + } + if _, err := Rekey(opts); err != nil { + t.Fatal(err) + } + if opens != 2 { + t.Fatal("independent verification missing") + } +} + +func TestRekey_PublishRollbackFailureRetainsPreviousOutput(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("directory exchange is unavailable") + } + parent := t.TempDir() + stage, out := filepath.Join(parent, "stage"), filepath.Join(parent, "output") + for _, path := range []string{stage, out} { + if err := os.Mkdir(path, 0o700); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(out, "old"), []byte("old ciphertext"), 0o600); err != nil { + t.Fatal(err) + } + calls := 0 + err := publishRekeyOutputWith(stage, out, func(a, b string) error { + calls++ + if calls == 2 { + return errRekeyTestWrite + } + return exchangeRekeyDirs(a, b) + }, func(string) error { return errRekeyTestWrite }) + var recovery *rekeyRecoveryError + if !errors.As(err, &recovery) || !strings.Contains(err.Error(), stage) { + t.Fatalf("missing recovery path: %v", err) + } + if data, err := os.ReadFile(filepath.Join(stage, "old")); err != nil || string(data) != "old ciphertext" { + t.Fatal("previous output lost after rollback failure") + } +} diff --git a/internal/secrets/rekey_sync_unix.go b/internal/secrets/rekey_sync_unix.go new file mode 100644 index 000000000..baec2f1fd --- /dev/null +++ b/internal/secrets/rekey_sync_unix.go @@ -0,0 +1,19 @@ +//go:build !windows + +package secrets + +import ( + "errors" + "fmt" + "os" +) + +func syncRekeyDir(path string) error { + dir, err := os.Open(path) + if err != nil { + return fmt.Errorf("open output directory for sync: %w", err) + } + return errors.Join(dir.Sync(), dir.Close()) +} + +func renameRekeyDir(from, to string) error { return os.Rename(from, to) } diff --git a/internal/secrets/rekey_sync_windows.go b/internal/secrets/rekey_sync_windows.go new file mode 100644 index 000000000..a4f85569f --- /dev/null +++ b/internal/secrets/rekey_sync_windows.go @@ -0,0 +1,19 @@ +package secrets + +import "golang.org/x/sys/windows" + +// Windows has no directory fsync. Publication uses a write-through rename; +// ciphertext files are individually flushed before it. +func syncRekeyDir(string) error { return nil } + +func renameRekeyDir(from, to string) error { + source, err := windows.UTF16PtrFromString(from) + if err != nil { + return err + } + target, err := windows.UTF16PtrFromString(to) + if err != nil { + return err + } + return windows.MoveFileEx(source, target, windows.MOVEFILE_WRITE_THROUGH) +} diff --git a/internal/secrets/rekey_test.go b/internal/secrets/rekey_test.go new file mode 100644 index 000000000..778f0c00d --- /dev/null +++ b/internal/secrets/rekey_test.go @@ -0,0 +1,993 @@ +package secrets + +import ( + "bufio" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + "time" + + "github.com/99designs/keyring" + + "github.com/openclaw/gogcli/internal/config" +) + +func newRekeyTestLayout(tb testing.TB) (config.Layout, string) { + tb.Helper() + + layout := config.Layout{DataDir: tb.TempDir(), ExplicitData: true} + + dir := layout.KeyringDir() + if err := os.MkdirAll(dir, 0o700); err != nil { + tb.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(dir, keyringLockFilename), nil, 0o600); err != nil { + tb.Fatal(err) + } + return layout, dir +} + +func openFileRing(tb testing.TB, dir, password string) keyring.Keyring { + tb.Helper() + + ring, err := openRekeyOutput(dir, password) + if err != nil { + tb.Fatal(err) + } + + return ring +} + +func rekeyFixture(t *testing.T) (RekeyOptions, string) { + t.Helper() + layout, dir := newRekeyTestLayout(t) + + item := keyring.Item{Key: "credential/one", Data: []byte("private-payload"), Label: "label", Description: "description"} + if err := openFileRing(t, dir, "old").Set(item); err != nil { + t.Fatal(err) + } + + return RekeyOptions{Layout: layout, Backend: "file", GOOS: runtime.GOOS, OldPassword: "old", OldPasswordSet: true, NewPassword: "new", NewPasswordSet: true, OutDir: filepath.Join(t.TempDir(), "output")}, dir +} + +type rekeySnapshotEntry struct { + Mode os.FileMode + Data string +} + +// Snapshot all files, nested directories, symlink targets and modes, including +// bookkeeping. Absence of any newly-created lock or verifier is part of equality. +func snapshotRekeyDir(tb testing.TB, dir string) map[string]rekeySnapshotEntry { + tb.Helper() + + result := make(map[string]rekeySnapshotEntry) + + err := filepath.WalkDir(dir, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return fmt.Errorf("walk %q: %w", path, err) + } + + info, err := entry.Info() + if err != nil { + return fmt.Errorf("info %q: %w", path, err) + } + + rel, err := filepath.Rel(dir, path) + if err != nil { + return fmt.Errorf("rel %q: %w", path, err) + } + + var data []byte + if info.Mode().IsRegular() { + data, err = os.ReadFile(path) + } + + if info.Mode()&os.ModeSymlink != 0 { + var target string + target, err = os.Readlink(path) + data = []byte(target) + } + + if err != nil { + return fmt.Errorf("read %q: %w", path, err) + } + + result[rel] = rekeySnapshotEntry{Mode: info.Mode(), Data: string(data)} + + return nil + }) + if err != nil { + tb.Fatal(err) + } + + return result +} + +func TestRekey_LiveByteIdentical(t *testing.T) { + for _, scenario := range []string{"success", "wrong-password", "write-failure", "verify-failure", "nonempty", "unsafe"} { + t.Run(scenario, func(t *testing.T) { + opts, dir := rekeyFixture(t) + if err := os.Mkdir(filepath.Join(dir, "nested"), 0o700); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(dir, "nested", "note"), []byte("untouched"), 0o600); err != nil { + t.Fatal(err) + } + + switch scenario { + case "wrong-password": + opts.OldPassword = "wrong" + case "write-failure": + opts.openOutput = func(dir, password string) (keyring.Keyring, error) { + return &rekeyFaultRing{Keyring: openFileRing(t, dir, password), failSet: true}, nil + } + case "verify-failure": + opts.openOutput = func(dir, password string) (keyring.Keyring, error) { + return &rekeyFaultRing{Keyring: openFileRing(t, dir, password), corruptGet: true}, nil + } + case "nonempty": + opts.OutDir = t.TempDir() + if err := os.WriteFile(filepath.Join(opts.OutDir, "sentinel"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + case "unsafe": + opts.OutDir = dir + opts.Force = true + } + before := snapshotRekeyDir(t, dir) + + _, err := Rekey(opts) + if (err == nil) != (scenario == "success") { + t.Fatalf("unexpected result: %v", err) + } + + if after := snapshotRekeyDir(t, dir); !reflect.DeepEqual(before, after) { + t.Fatal("live directory changed") + } + }) + } +} + +func TestRekey_InterruptedLiveByteIdentical(t *testing.T) { + const childEnv = "GOG_REKEY_INTERRUPTION_TEST_DIR" + if dir := os.Getenv(childEnv); dir != "" { + opts := RekeyOptions{ + Layout: config.Layout{DataDir: dir, ExplicitData: true}, + Backend: "file", GOOS: runtime.GOOS, + OldPassword: "old", OldPasswordSet: true, + NewPassword: "new", NewPasswordSet: true, + OutDir: filepath.Join(dir, "output"), + } + opens := 0 + + opts.openOutput = func(dir, password string) (keyring.Keyring, error) { + opens++ + if opens == 2 { + // Output has been written, but verification has not begun. + fmt.Println("output written") + + for { + time.Sleep(time.Hour) + } + } + + return openRekeyOutput(dir, password) + } + if _, err := Rekey(opts); err != nil { + t.Fatal(err) + } + + t.Fatal("child returned without interruption") + } + + opts, dir := rekeyFixture(t) + before := snapshotRekeyDir(t, dir) + + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + child := exec.CommandContext(ctx, executable, "-test.run=^TestRekey_InterruptedLiveByteIdentical$") + + child.Env = append(os.Environ(), childEnv+"="+opts.Layout.DataDir) + + stdout, err := child.StdoutPipe() + if err != nil { + t.Fatal(err) + } + + if err := child.Start(); err != nil { + t.Fatal(err) + } + defer func() { + _ = child.Process.Kill() + _ = child.Wait() + }() + + if line, err := bufio.NewReader(stdout).ReadString('\n'); err != nil || line != "output written\n" { + t.Fatalf("child did not reach interruption point: %q %v", line, err) + } + + if err := child.Process.Kill(); err != nil { + t.Fatal(err) + } + + if err := child.Wait(); err == nil { + t.Fatal("interrupted process reported success") + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("interruption changed live directory") + } +} + +func TestRekey_OutputRoundTrip(t *testing.T) { + opts, dir := rekeyFixture(t) + // Every kind of key, including names illegal as raw Windows filenames, is + // stored encoded. This creates no invalid filenames on any platform. + src := openFileRing(t, dir, "old") + for _, key := range []string{"token:default:a@example.com", "default-account", ".credential", ".DS_Store"} { + if err := src.Set(keyring.Item{Key: key, Data: []byte(key), Label: "metadata"}); err != nil { + t.Fatal(err) + } + } + + res, err := Rekey(opts) + if err != nil { + t.Fatal(err) + } + + wantKeys := []string{".DS_Store", ".credential", "credential/one", "default-account", "token:default:a@example.com"} + // Do not trust the returned keys as the round-trip inputs: the legacy + // fallback can read an encoded filename as though it were a raw key, masking + // a missing decode step and a second layer of encoding in the output. + if res.Items != len(wantKeys) || !reflect.DeepEqual(res.Keys, wantKeys) || res.PasswordChanged || res.BackupDir != "" { + t.Fatalf("incorrect result: %+v", res) + } + + for _, key := range wantKeys { + want, wantErr := src.Get(key) + if wantErr != nil { + t.Fatal(wantErr) + } + + got, gotErr := openFileRing(t, opts.OutDir, "new").Get(key) + if gotErr != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("item %q failed round trip: %v", key, gotErr) + } + + if _, oldErr := openFileRing(t, opts.OutDir, "old").Get(key); oldErr == nil { + t.Fatal("output accepts old password") + } + } + + entries, err := os.ReadDir(opts.OutDir) + if err != nil { + t.Fatal(err) + } + + if len(entries) != 5 { + t.Fatalf("unexpected output entries: %d", len(entries)) + } +} + +func TestRekey_Guards(t *testing.T) { + for _, scenario := range []string{"missing-old", "missing-new", "same", "backend", "missing-output", "nonempty", "same-dir", "inside", "ancestor", "wrong", "all-skipped"} { + t.Run(scenario, func(t *testing.T) { + opts, dir := rekeyFixture(t) + want := ErrRekeyNoOldPassword + + switch scenario { + case "missing-old": + opts.OldPasswordSet = false + case "missing-new": + opts.NewPasswordSet = false + want = ErrRekeyNoNewPassword + case "same": + opts.NewPassword = opts.OldPassword + want = ErrRekeySamePassword + case "backend": + opts.Backend = "keychain" + want = ErrRekeyNotFileBackend + case "missing-output": + opts.OutDir = "" + // Removing the required-output guard must reach a fresh empty + // directory, rather than fail on unrelated files in the checkout. + t.Chdir(t.TempDir()) + want = errRekeyNoOutput + case "nonempty": + opts.OutDir = t.TempDir() + if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + want = errRekeyOutputNotEmpty + case "same-dir": + opts.OutDir = dir + opts.Force = true + want = errRekeyUnsafeOutput + case "inside": + opts.OutDir = filepath.Join(dir, "output") + opts.Force = true + want = errRekeyUnsafeOutput + case "ancestor": + opts.OutDir = filepath.Dir(dir) + opts.Force = true + want = errRekeyUnsafeOutput + case "wrong": + opts.OldPassword = "wrong" + want = errRekeyNoReadableItems + case "all-skipped": + opts.OldPassword = "wrong" + opts.SkipUnreadable = true + want = errRekeyNoReadableItems + } + before := snapshotRekeyDir(t, dir) + + _, err := Rekey(opts) + if !errors.Is(err, want) { + t.Fatalf("want %v, got %v", want, err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("guard changed source") + } + + if scenario == "nonempty" { + data, err := os.ReadFile(filepath.Join(opts.OutDir, "keep")) + if err != nil || string(data) != "keep" { + t.Fatal("guard replaced output") + } + } + }) + } +} + +func TestRekey_ForceReplacesAndRestarts(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("atomic directory exchange unsupported; tested by TestRekey_ExistingOutputUnsupported") + } + opts, dir := rekeyFixture(t) + before := snapshotRekeyDir(t, dir) + + opts.OutDir = t.TempDir() + if err := os.Mkdir(filepath.Join(opts.OutDir, "stale"), 0o700); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(opts.OutDir, "stale", "file"), []byte("stale"), 0o600); err != nil { + t.Fatal(err) + } + opts.Force = true + + res, err := Rekey(opts) + if err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(res.Replaced, []string{"stale"}) { + t.Fatal("replacement not reported") + } + + if _, statErr := os.Stat(filepath.Join(opts.OutDir, "stale")); !errors.Is(statErr, os.ErrNotExist) { + t.Fatal("stale output merged") + } + + res, err = Rekey(opts) + if err != nil || res.Items != 1 || len(res.Replaced) != 1 { + t.Fatalf("restart failed: %v", err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("forced restart modified live directory") + } +} + +func TestRekey_EmptyClaimsNoChange(t *testing.T) { + opts, dir := rekeyFixture(t) + if err := openFileRing(t, dir, "old").Remove("credential/one"); err != nil { + t.Fatal(err) + } + before := snapshotRekeyDir(t, dir) + + res, err := Rekey(opts) + if err != nil || res.Items != 0 || res.PasswordChanged || res.BackupDir != "" { + t.Fatalf("empty claimed change: %+v %v", res, err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("empty source modified") + } + + entries, err := os.ReadDir(opts.OutDir) + if err != nil || len(entries) != 0 { + t.Fatal("empty output contains a verifier or credential") + } + // With no claimed rotation there is no stale-password guard to bypass by + // removing credentials. Both Set and Remove on the live store still work. + ring := openFileRing(t, dir, "old") + if err := ring.Set(keyringItem("later", []byte("value"))); err != nil { + t.Fatal(err) + } + + if err := ring.Remove("later"); err != nil { + t.Fatal(err) + } +} + +func TestRekey_Unreadable(t *testing.T) { + opts, dir := rekeyFixture(t) + if err := openFileRing(t, dir, "other").Set(keyringItem("unreadable", []byte("private-other"))); err != nil { + t.Fatal(err) + } + before := snapshotRekeyDir(t, dir) + opts.OutDir = t.TempDir() + + opts.Force = true + if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + outputBefore := snapshotRekeyDir(t, opts.OutDir) + + _, err := Rekey(opts) + if !errors.Is(err, errRekeyUnreadableItems) { + t.Fatalf("want unreadable error, got %v", err) + } + + if !reflect.DeepEqual(outputBefore, snapshotRekeyDir(t, opts.OutDir)) { + t.Fatal("unreadable input replaced output") + } + opts.SkipUnreadable = true + + res, err := Rekey(opts) + if err != nil || res.Items != 1 || !reflect.DeepEqual(res.Unreadable, []string{"unreadable"}) { + t.Fatalf("skip: %+v %v", res, err) + } + + if _, err := openFileRing(t, opts.OutDir, "new").Get("unreadable"); !errors.Is(err, keyring.ErrKeyNotFound) { + t.Fatal("skipped credential present in output") + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("unreadable source changed") + } +} + +var errRekeyTestWrite = errors.New("injected output write failure") + +type rekeyFaultRing struct { + keyring.Keyring + failSet, corruptGet, corruptMetadata, extraKey, failKeys bool + targetKey string +} + +func (r *rekeyFaultRing) Set(item keyring.Item) error { + if r.failSet && (r.targetKey == "" || item.Key == r.targetKey) { + return errRekeyTestWrite + } + + if err := r.Keyring.Set(item); err != nil { + return fmt.Errorf("fault ring set: %w", err) + } + + return nil +} + +func (r *rekeyFaultRing) Get(key string) (keyring.Item, error) { + item, err := r.Keyring.Get(key) + if r.corruptGet && (r.targetKey == "" || key == r.targetKey) { + item.Data = []byte("mismatch") + } + + if r.corruptMetadata && (r.targetKey == "" || key == r.targetKey) { + item.Label = "changed metadata" + } + + if err != nil { + return item, fmt.Errorf("fault ring get: %w", err) + } + + return item, nil +} + +func (r *rekeyFaultRing) Keys() ([]string, error) { + if r.failKeys { + return nil, errRekeyTestWrite + } + + keys, err := r.Keyring.Keys() + if r.extraKey { + keys = append(keys, "unexpected") + } + + if err != nil { + return keys, fmt.Errorf("fault ring keys: %w", err) + } + + return keys, nil +} + +func TestRekey_VerifiesIndependentOutput(t *testing.T) { + for _, scenario := range []string{"write", "mismatch", "metadata", "missing", "extra", "open", "list", "wrong-password"} { + t.Run(scenario, func(t *testing.T) { + opts, dir := rekeyFixture(t) + // The first item is sound. Faults in a later item must still fail, + // otherwise checking just one credential could pass this test. + if err := openFileRing(t, dir, opts.OldPassword).Set(keyringItem("credential/two", []byte("second-private-payload"))); err != nil { + t.Fatal(err) + } + before := snapshotRekeyDir(t, dir) + opens := 0 + opts.openOutput = func(dir, password string) (keyring.Keyring, error) { + opens++ + + if password != opts.NewPassword { + t.Fatal("output not opened with the new password") + } + + if opens == 2 && scenario == "open" { + return nil, errRekeyTestWrite + } + + if opens == 2 && scenario == "wrong-password" { + password = opts.OldPassword + } + + ring := openFileRing(t, dir, password) + if opens == 1 && scenario == "write" { + return &rekeyFaultRing{Keyring: ring, failSet: true, targetKey: "credential/two"}, nil + } + + if opens == 2 && scenario == "missing" { + if err := ring.Remove("credential/two"); err != nil { + t.Fatal(err) + } + } + + return &rekeyFaultRing{ + Keyring: ring, + corruptGet: opens == 2 && scenario == "mismatch", + corruptMetadata: opens == 2 && scenario == "metadata", + extraKey: opens == 2 && scenario == "extra", + failKeys: opens == 2 && scenario == "list", + targetKey: "credential/two", + }, nil + } + + res, err := Rekey(opts) + if err == nil || res.Items != 0 || res.PasswordChanged || res.MoveCommand != "" { + t.Fatalf("failed output reported success: %+v %v", res, err) + } + + if scenario != "write" && opens != 2 { + t.Fatal("verification did not independently reopen output") + } + + want := errRekeyContentMismatch + if scenario == "write" || scenario == "open" || scenario == "list" { + want = errRekeyTestWrite + } + + if !errors.Is(err, want) { + t.Fatalf("want %v, got %v", want, err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("failed output modified live directory") + } + + for _, secret := range []string{"private-payload", "second-private-payload", "changed metadata"} { + if strings.Contains(err.Error(), secret) { + t.Fatal("verification failure disclosed item content") + } + } + }) + } +} + +func TestRekey_Permissions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows mode bits do not represent Unix directory permissions; ACL equivalence is not exercised") + } + + for _, existing := range []bool{false, true} { + t.Run(fmt.Sprintf("existing=%t", existing), func(t *testing.T) { + opts, dir := rekeyFixture(t) + + mode := os.FileMode(0o750) | os.ModeSetgid | os.ModeSticky + if err := os.Chmod(dir, mode); err != nil { + t.Fatal(err) + } + // Existing empty output must also receive the source's permissions. + if existing { + opts.OutDir = t.TempDir() + if err := os.Chmod(opts.OutDir, 0o700); err != nil { + t.Fatal(err) + } + } + + if _, err := Rekey(opts); err != nil { + t.Fatal(err) + } + + info, err := os.Stat(opts.OutDir) + if err != nil || info.Mode()&(os.ModePerm|os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != mode { + t.Fatalf("permissions differ: %v", err) + } + }) + } +} + +func TestRekey_SymlinkOverlap(t *testing.T) { + opts, dir := rekeyFixture(t) + + link := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(dir, link); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlink creation requires Windows privilege/developer mode: %v", err) + } + + t.Fatal(err) + } + + // A final symlink is refused even when it points away from the live keyring, + // so --force can never remove or write a directory reached through a link. + // Without this case the test passes on the overlap guard alone and the + // symlink branch could be deleted unnoticed. + benign := filepath.Join(t.TempDir(), "benign-alias") + if err := os.Symlink(t.TempDir(), benign); err != nil { + t.Fatalf("symlink: %v", err) + } + + for _, output := range []string{link, filepath.Join(link, "child", "missing"), benign} { + opts.OutDir = output + + opts.Force = true + if _, err := Rekey(opts); !errors.Is(err, errRekeyUnsafeOutput) { + t.Fatalf("accepted symlink output %s: %v", output, err) + } + } +} + +func TestRekey_PathIdentity(t *testing.T) { + _, dir := rekeyFixture(t) + + link := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(dir, link); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("directory aliases require symlink privilege/developer mode: %v", err) + } + + t.Fatal(err) + } + // Exercise the identity comparison on every OS, even on a case-sensitive + // filesystem. Neither spelling is lexically contained in the other. + if !rekeyPathContains(dir, filepath.Join(link, "not-created")) || !rekeyPathContains(link, dir) { + t.Fatal("directory identities were not compared") + } +} + +func TestRekey_CaseAliasOverlap(t *testing.T) { + opts, dir := rekeyFixture(t) + alias := filepath.Join(filepath.Dir(dir), strings.ToUpper(filepath.Base(dir))) + + info, err := os.Stat(alias) + if errors.Is(err, os.ErrNotExist) { + t.Skip("temporary filesystem is case-sensitive; case aliases cannot be exercised") + } + + if err != nil { + t.Fatal(err) + } + + original, err := os.Stat(dir) + if err != nil || !os.SameFile(original, info) { + t.Fatalf("case alias fixture is not the live directory: %v", err) + } + + for _, output := range []string{alias, filepath.Join(alias, "new", "output")} { + opts.OutDir, opts.Force = output, true + if _, err := Rekey(opts); !errors.Is(err, errRekeyUnsafeOutput) { + t.Fatalf("accepted case alias: %v", err) + } + } +} + +func TestRekey_ReadFailures(t *testing.T) { + for _, scenario := range []string{"missing", "file", "output-file", "nonregular"} { + t.Run(scenario, func(t *testing.T) { + opts, dir := rekeyFixture(t) + + switch scenario { + case "missing": + if err := os.RemoveAll(dir); err != nil { + t.Fatal(err) + } + case "file": + if err := os.RemoveAll(dir); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(dir, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + case "output-file": + if err := os.WriteFile(opts.OutDir, []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + case "nonregular": + if err := os.Symlink(filepath.Join(dir, fileSafeKey("credential/one")), filepath.Join(dir, "link")); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlink privilege unavailable: %v", err) + } + + t.Fatal(err) + } + } + + if _, err := Rekey(opts); err == nil { + t.Fatal("filesystem failure reported success") + } + + if scenario == "missing" { + if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) { + t.Fatal("source directory was created") + } + } + }) + } +} + +func TestRekey_LegacyAndConflicts(t *testing.T) { + opts, dir := rekeyFixture(t) + + raw, err := keyring.Open(keyring.Config{AllowedBackends: []keyring.BackendType{keyring.FileBackend}, FileDir: dir, FilePasswordFunc: keyring.FixedStringPrompt("old")}) + if err != nil { + t.Fatal(err) + } + // Raw filename is portable; slash and colon keys are tested encoded above. + if setErr := raw.Set(keyringItem("legacy", []byte("legacy-data"))); setErr != nil { + t.Fatal(setErr) + } + before := snapshotRekeyDir(t, dir) + + res, err := Rekey(opts) + if err != nil || res.Items != 2 { + t.Fatalf("legacy rekey: %v", err) + } + + item, err := openFileRing(t, opts.OutDir, "new").Get("legacy") + if err != nil || string(item.Data) != "legacy-data" { + t.Fatal("legacy output missing") + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("legacy source modified") + } + + if err := openFileRing(t, dir, "old").Set(keyringItem("legacy", []byte("different"))); err != nil { + t.Fatal(err) + } + + opts.Force = true + if _, err := Rekey(opts); !errors.Is(err, errRekeyContentMismatch) { + t.Fatalf("conflicting copies silently lost: %v", err) + } +} + +func TestRekey_LiveCommandsRemainUsable(t *testing.T) { + opts, dir := rekeyFixture(t) + // Historical markers and verifiers must have no influence on live writes. + if err := os.WriteFile(dir+".rekey-in-progress", []byte("obsolete"), 0o600); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(dir, fileSafeKey(keyringVerifierKey)), []byte("obsolete"), 0o600); err != nil { + t.Fatal(err) + } + + if _, err := Rekey(opts); err != nil { + t.Fatal(err) + } + + ring := openFileRing(t, dir, "old") + if _, err := ring.Get("credential/one"); err != nil { + t.Fatalf("live credential cannot be read after rekey: %v", err) + } + + if err := ring.Set(keyringItem("later", []byte("still-old"))); err != nil { + t.Fatal(err) + } + + if err := ring.Remove("credential/one"); err != nil { + t.Fatal(err) + } + + item, err := ring.Get("later") + if err != nil || string(item.Data) != "still-old" { + t.Fatal("live writes blocked or lost") + } +} + +func TestRekey_MoveCommand(t *testing.T) { + for _, location := range []string{"separate", "old", "inside-old"} { + t.Run(location, func(t *testing.T) { + opts, dir := rekeyFixture(t) + opts.OutDir = filepath.Join(t.TempDir(), "output ' $literal") + + switch location { + case "old": + opts.OutDir = dir + ".old" + case "inside-old": + opts.OutDir = filepath.Join(dir+".old", "output") + } + + res, err := Rekey(opts) + if err != nil { + t.Fatal(err) + } + + if runtime.GOOS != "windows" && !strings.Contains(res.MoveCommand, "mv --") { + t.Fatal("missing exact move command") + } + // Execute the printed command against temp storage, then prove both copies. + if output, runErr := rekeyMoveProcess(t, res.MoveCommand).CombinedOutput(); runErr != nil { + t.Fatalf("move: %v %s", runErr, output) + } + + if _, err := openFileRing(t, dir, "new").Get("credential/one"); err != nil { + t.Fatal(err) + } + + if _, err := openFileRing(t, res.RetainedDir, "old").Get("credential/one"); err != nil { + t.Fatal(err) + } + }) + } +} + +func rekeyMoveProcess(t *testing.T, command string) *exec.Cmd { + t.Helper() + + if runtime.GOOS == "windows" { + for _, shell := range []string{"pwsh", "powershell"} { + if path, err := exec.LookPath(shell); err == nil { + return exec.CommandContext(context.Background(), path, "-NoProfile", "-NonInteractive", "-Command", "$ErrorActionPreference = 'Stop'; "+command) + } + } + + t.Skip("PowerShell is unavailable; cannot execute the Windows installation command") + } + + return exec.CommandContext(context.Background(), "sh", "-c", command) +} + +func TestRekey_MoveCommandProtectsOld(t *testing.T) { + for _, kind := range []string{"directory", "dangling-symlink"} { + t.Run(kind, func(t *testing.T) { + opts, dir := rekeyFixture(t) + + res, err := Rekey(opts) + if err != nil { + t.Fatal(err) + } + + old := dir + ".old" + if kind == "directory" { + if err := os.Mkdir(old, 0o700); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile(filepath.Join(old, "keep"), []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + } else if err := os.Symlink(filepath.Join(t.TempDir(), "missing"), old); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("dangling symlink creation requires privilege/developer mode: %v", err) + } + + t.Fatal(err) + } + // Keep both source operands present so failure must be the .old + // guard, and snapshot all three paths to catch partial moves too. + liveBefore := snapshotRekeyDir(t, dir) + outBefore := snapshotRekeyDir(t, opts.OutDir) + + oldBefore := snapshotRekeyDir(t, old) + // A dangling destination can make mv fail independently of our + // guard. Record attempted moves so that removing the guard cannot + // pass this test merely because the platform's mv also refuses it. + probe := filepath.Join(t.TempDir(), "attempted-move") + + command := "rekey_probe_move() { printf 'called\\n' >> " + shellQuote(probe) + "; mv \"$@\"; }; " + strings.ReplaceAll(res.MoveCommand, "mv --", "rekey_probe_move --") + if runtime.GOOS == "windows" { + quote := "'" + strings.ReplaceAll(probe, "'", "''") + "'" + command = "function Rekey-ProbeMove { [CmdletBinding()] param([string]$LiteralPath, [string]$Destination) Add-Content -LiteralPath " + quote + " -Value 'called'; Microsoft.PowerShell.Management\\Move-Item @PSBoundParameters }; " + strings.ReplaceAll(res.MoveCommand, "Move-Item", "Rekey-ProbeMove") + } + + if output, err := rekeyMoveProcess(t, command).CombinedOutput(); err == nil { + t.Fatalf("installation accepted existing .old: %s", output) + } + + if _, err := os.Stat(probe); !errors.Is(err, os.ErrNotExist) { + t.Fatal("installation attempted a move despite existing .old") + } + + if !reflect.DeepEqual(liveBefore, snapshotRekeyDir(t, dir)) || + !reflect.DeepEqual(outBefore, snapshotRekeyDir(t, opts.OutDir)) || + !reflect.DeepEqual(oldBefore, snapshotRekeyDir(t, old)) { + t.Fatal("refused installation changed directories") + } + }) + } +} + +func TestRekey_FailureReportsReplacement(t *testing.T) { + opts, dir := rekeyFixture(t) + + opts.OutDir, opts.Force = t.TempDir(), true + if err := os.WriteFile(filepath.Join(opts.OutDir, "stale"), []byte("stale"), 0o600); err != nil { + t.Fatal(err) + } + opts.openOutput = func(string, string) (keyring.Keyring, error) { return nil, errRekeyTestWrite } + before := snapshotRekeyDir(t, dir) + + res, err := Rekey(opts) + if !errors.Is(err, errRekeyTestWrite) || len(res.Replaced) != 0 || res.MoveCommand != "" || res.Items != 0 { + t.Fatalf("failed run lost replacement information: %+v %v", res, err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("failed replacement modified live directory") + } +} + +func TestRekey_BookkeepingIsReadOnly(t *testing.T) { + opts, dir := rekeyFixture(t) + for _, name := range []string{keyringLockFilename, keyringVerifierKey, fileSafeKey(keyringVerifierKey), ".DS_Store"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte("not-a-credential"), 0o600); err != nil { + t.Fatal(err) + } + } + before := snapshotRekeyDir(t, dir) + + res, err := Rekey(opts) + if err != nil || res.Items != 1 || len(res.Unreadable) != 0 { + t.Fatalf("bookkeeping treated as credentials: %+v %v", res, err) + } + + if !reflect.DeepEqual(before, snapshotRekeyDir(t, dir)) { + t.Fatal("bookkeeping changed") + } +} + +func TestCheckRekeyBackend(t *testing.T) { + for _, tc := range []struct { + backend, goos, dbus string + allowed bool + }{ + {"file", "windows", "", true}, + {"file", "darwin", "", true}, + {"auto", "linux", "", true}, + {"auto", "linux", "session", false}, + {"auto", "darwin", "", false}, + {"auto", "windows", "", false}, + {"keychain", "linux", "", false}, + } { + err := CheckRekeyBackend(tc.backend, tc.goos, tc.dbus) + if (err == nil) != tc.allowed { + t.Fatalf("backend %s/%s/%s: %v", tc.backend, tc.goos, tc.dbus, err) + } + } +} diff --git a/internal/secrets/store.go b/internal/secrets/store.go index b5ba5609f..18ef5b5e1 100644 --- a/internal/secrets/store.go +++ b/internal/secrets/store.go @@ -79,7 +79,7 @@ func (s *KeyringStore) keysNoLock() ([]string, error) { func withoutInternalKeyringKeys(keys []string) []string { out := keys[:0] for _, key := range keys { - if key == keyringLockFilename { + if isInternalKeyringKey(key) { continue } out = append(out, key) @@ -88,6 +88,12 @@ func withoutInternalKeyringKeys(keys []string) []string { return out } +// isInternalKeyringKey reports whether key is bookkeeping the keyring owns +// rather than a credential the user asked for. +func isInternalKeyringKey(key string) bool { + return key == keyringLockFilename || key == keyringVerifierKey +} + func (s *KeyringStore) withReadLock(fn func() error) error { if s.lock == nil { return fn() From a3c88bcf42f2dbfbd45af6ec39992f87760f48ad Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Tue, 20 Oct 2026 11:05:34 -0700 Subject: [PATCH 2/4] fix(auth): validate rekey transaction helpers --- internal/secrets/keyring_lock.go | 2 +- internal/secrets/rekey.go | 35 ++++++++++++++++++++--- internal/secrets/rekey_exchange_darwin.go | 12 ++++++-- internal/secrets/rekey_exchange_linux.go | 12 ++++++-- internal/secrets/rekey_exchange_other.go | 4 ++- internal/secrets/rekey_lock_test.go | 30 +++++++++++++++++++ internal/secrets/rekey_sync_unix.go | 11 +++++-- internal/secrets/rekey_sync_windows.go | 17 ++++++++--- internal/secrets/rekey_test.go | 1 + 9 files changed, 108 insertions(+), 16 deletions(-) diff --git a/internal/secrets/keyring_lock.go b/internal/secrets/keyring_lock.go index 523e0a2b2..a54410e0d 100644 --- a/internal/secrets/keyring_lock.go +++ b/internal/secrets/keyring_lock.go @@ -107,7 +107,7 @@ func (l *keyringLock) withWriteLock(fn func() error) error { } func (l *keyringLock) withFileLock(exclusive bool, fn func() error) error { - file, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0o600) + file, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0o600) //nolint:gosec // lock path is inside the user-selected keyring directory if err != nil { return fmt.Errorf("open keyring lock: %w", err) } diff --git a/internal/secrets/rekey.go b/internal/secrets/rekey.go index 9223e5c40..cda96e18c 100644 --- a/internal/secrets/rekey.go +++ b/internal/secrets/rekey.go @@ -114,8 +114,10 @@ func Rekey(opts RekeyOptions) (RekeyResult, error) { err = lock.withReadLock(func() error { var rekeyErr error res, rekeyErr = rekeyLocked(opts, dir, out) + return rekeyErr }) + return res, err } @@ -134,27 +136,33 @@ func rekeyLocked(opts RekeyOptions, dir, out string) (RekeyResult, error) { mode := info.Mode() & (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky) res := RekeyResult{Dir: dir, OutDir: out, Unreadable: unreadable} + entries, err := os.ReadDir(out) if err != nil && !errors.Is(err, os.ErrNotExist) { return res, fmt.Errorf("read output directory: %w", err) } + if len(entries) > 0 && !opts.Force { return res, errRekeyOutputNotEmpty } - if err := os.MkdirAll(filepath.Dir(out), 0o700); err != nil { + + if err = os.MkdirAll(filepath.Dir(out), 0o700); err != nil { return res, fmt.Errorf("create output parent: %w", err) } + stage, err := os.MkdirTemp(filepath.Dir(out), ".gog-rekey-*") if err != nil { return res, fmt.Errorf("create staging directory: %w", err) } + cleanupStage := true defer func() { if cleanupStage { _ = os.RemoveAll(stage) } }() - if err := os.Chmod(stage, mode); err != nil { + + if err = os.Chmod(stage, mode); err != nil { return res, fmt.Errorf("set output permissions: %w", err) } @@ -177,14 +185,18 @@ func rekeyLocked(opts RekeyOptions, dir, out string) (RekeyResult, error) { if err != nil { return res, err } + if err := syncRekeyOutput(stage); err != nil { return res, err } + if err := publishRekeyOutput(stage, out); err != nil { var recovery *rekeyRecoveryError cleanupStage = !errors.As(err, &recovery) + return res, err } + for _, entry := range entries { res.Replaced = append(res.Replaced, entry.Name()) } @@ -217,6 +229,7 @@ func verifyRekeyOutput(open func(string, string) (keyring.Keyring, error), out, got, getErr := verify.Get(item.Key) matches := reflect.DeepEqual(got, item) clear(got.Data) + if getErr != nil || !matches { return nil, fmt.Errorf("%w: output item %q failed verification", errRekeyContentMismatch, item.Key) } @@ -246,6 +259,7 @@ func readRekeyItems(dir, password string, skip bool) ([]keyring.Item, []string, return nil, nil, fmt.Errorf("read live keyring directory: %w", err) } items := make(map[string]keyring.Item) + transferred := false defer func() { if !transferred { @@ -281,10 +295,12 @@ func readRekeyItems(dir, password string, skip bool) ([]keyring.Item, []string, decoded := []byte(payload) unmarshalErr := json.Unmarshal(decoded, &item) clear(decoded) - payload = "" + if decodeErr != nil || unmarshalErr != nil { clear(item.Data) + unreadable = append(unreadable, key) + continue } @@ -294,6 +310,7 @@ func readRekeyItems(dir, password string, skip bool) ([]keyring.Item, []string, clear(item.Data) return nil, nil, fmt.Errorf("%w: conflicting live copies of %q", errRekeyContentMismatch, key) } + clear(previous.Data) } items[key] = item @@ -319,6 +336,7 @@ func readRekeyItems(dir, password string, skip bool) ([]keyring.Item, []string, slices.SortFunc(result, func(a, b keyring.Item) int { return strings.Compare(a.Key, b.Key) }) transferred = true + return result, unreadable, nil } @@ -407,17 +425,20 @@ func syncRekeyOutput(dir string) error { if err != nil { return fmt.Errorf("read staged output: %w", err) } + for _, entry := range entries { - file, err := os.OpenFile(filepath.Join(dir, entry.Name()), os.O_RDWR, 0) + file, err := os.OpenFile(filepath.Join(dir, entry.Name()), os.O_RDWR, 0) //nolint:gosec // private staged directory and name from ReadDir if err != nil { return fmt.Errorf("open staged item: %w", err) } syncErr := file.Sync() + closeErr := file.Close() if err := errors.Join(syncErr, closeErr); err != nil { return fmt.Errorf("sync staged item: %w", err) } } + return syncRekeyDir(dir) } @@ -429,10 +450,12 @@ func publishRekeyOutput(stage, out string) error { func publishRekeyOutputWith(stage, out string, exchange func(string, string) error, syncDir func(string) error) error { _, err := os.Lstat(out) + existed := err == nil if err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("stat output: %w", err) } + if existed { if err := exchange(stage, out); err != nil { return fmt.Errorf("exchange output: %w", err) @@ -440,6 +463,7 @@ func publishRekeyOutputWith(stage, out string, exchange func(string, string) err } else if err := renameRekeyDir(stage, out); err != nil { return fmt.Errorf("publish output: %w", err) } + if err := syncDir(filepath.Dir(out)); err != nil { var rollbackErr error if existed { @@ -447,11 +471,14 @@ func publishRekeyOutputWith(stage, out string, exchange func(string, string) err } else { rollbackErr = renameRekeyDir(out, stage) } + if rollbackErr != nil { return &rekeyRecoveryError{err: fmt.Errorf("sync output: %w; rollback: %w; recovery required: inspect output %s and retained staging %s", err, rollbackErr, out, stage)} } + return fmt.Errorf("sync output (rolled back): %w", errors.Join(err, syncDir(filepath.Dir(out)))) } + return nil } diff --git a/internal/secrets/rekey_exchange_darwin.go b/internal/secrets/rekey_exchange_darwin.go index 3982e0be4..1260c18f2 100644 --- a/internal/secrets/rekey_exchange_darwin.go +++ b/internal/secrets/rekey_exchange_darwin.go @@ -1,7 +1,15 @@ package secrets -import "golang.org/x/sys/unix" +import ( + "fmt" + + "golang.org/x/sys/unix" +) func exchangeRekeyDirs(a, b string) error { - return unix.RenamexNp(a, b, unix.RENAME_SWAP) + if err := unix.RenamexNp(a, b, unix.RENAME_SWAP); err != nil { + return fmt.Errorf("exchange keyring directories: %w", err) + } + + return nil } diff --git a/internal/secrets/rekey_exchange_linux.go b/internal/secrets/rekey_exchange_linux.go index 4947e8205..4a43c4200 100644 --- a/internal/secrets/rekey_exchange_linux.go +++ b/internal/secrets/rekey_exchange_linux.go @@ -1,7 +1,15 @@ package secrets -import "golang.org/x/sys/unix" +import ( + "fmt" + + "golang.org/x/sys/unix" +) func exchangeRekeyDirs(a, b string) error { - return unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE) + if err := unix.Renameat2(unix.AT_FDCWD, a, unix.AT_FDCWD, b, unix.RENAME_EXCHANGE); err != nil { + return fmt.Errorf("exchange keyring directories: %w", err) + } + + return nil } diff --git a/internal/secrets/rekey_exchange_other.go b/internal/secrets/rekey_exchange_other.go index e33a25503..fc08d792e 100644 --- a/internal/secrets/rekey_exchange_other.go +++ b/internal/secrets/rekey_exchange_other.go @@ -4,6 +4,8 @@ package secrets import "errors" +var errRekeyExchangeUnavailable = errors.New("atomic replacement is unavailable on this platform; choose a fresh output directory") + func exchangeRekeyDirs(_, _ string) error { - return errors.New("atomic replacement is unavailable on this platform; choose a fresh output directory") + return errRekeyExchangeUnavailable } diff --git a/internal/secrets/rekey_lock_test.go b/internal/secrets/rekey_lock_test.go index 1f737a2e8..6473d216a 100644 --- a/internal/secrets/rekey_lock_test.go +++ b/internal/secrets/rekey_lock_test.go @@ -18,11 +18,14 @@ import ( func TestRekey_TakesLiveLock(t *testing.T) { opts, dir := rekeyFixture(t) t.Setenv(keyringLockTimeoutEnv, "30ms") + holder, err := os.OpenFile(filepath.Join(dir, keyringLockFilename), os.O_CREATE|os.O_RDWR, 0o600) if err != nil { t.Fatal(err) } + defer holder.Close() + if err := lockKeyringFile(holder, true); err != nil { t.Fatal(err) } @@ -31,6 +34,7 @@ func TestRekey_TakesLiveLock(t *testing.T) { t.Error(err) } }() + if _, err := Rekey(opts); !errors.Is(err, errKeyringTimeout) { t.Fatalf("expected lock timeout, got %v", err) } @@ -39,6 +43,7 @@ func TestRekey_TakesLiveLock(t *testing.T) { func TestRekey_HoldsLiveLockThroughVerification(t *testing.T) { opts, dir := rekeyFixture(t) opens := 0 + opts.openOutput = func(path, password string) (keyring.Keyring, error) { opens++ if opens == 2 { @@ -47,6 +52,7 @@ func TestRekey_HoldsLiveLockThroughVerification(t *testing.T) { t.Fatalf("writer was not blocked: %v", err) } } + return openRekeyOutput(path, password) } if _, err := Rekey(opts); err != nil { @@ -56,15 +62,18 @@ func TestRekey_HoldsLiveLockThroughVerification(t *testing.T) { func TestRekey_FailedWritePreservesOutput(t *testing.T) { opts, _ := rekeyFixture(t) + opts.OutDir, opts.Force = t.TempDir(), true if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("previous output"), 0o600); err != nil { t.Fatal(err) } before := snapshotRekeyDir(t, opts.OutDir) + opts.openOutput = func(string, string) (keyring.Keyring, error) { return nil, errRekeyTestWrite } if _, err := Rekey(opts); !errors.Is(err, errRekeyTestWrite) { t.Fatal(err) } + if !reflect.DeepEqual(before, snapshotRekeyDir(t, opts.OutDir)) { t.Fatal("failed rekey destroyed previous output") } @@ -74,40 +83,49 @@ func TestRekey_PublishRollback(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("directory exchange is unavailable") } + for _, existing := range []bool{false, true} { t.Run(fmt.Sprint(existing), func(t *testing.T) { parent := t.TempDir() + stage, out := filepath.Join(parent, "stage"), filepath.Join(parent, "output") if err := os.Mkdir(stage, 0o700); err != nil { t.Fatal(err) } + if err := os.WriteFile(filepath.Join(stage, "new"), []byte("new ciphertext"), 0o600); err != nil { t.Fatal(err) } + if existing { if err := os.Mkdir(out, 0o700); err != nil { t.Fatal(err) } + if err := os.WriteFile(filepath.Join(out, "old"), []byte("old ciphertext"), 0o600); err != nil { t.Fatal(err) } } calls := 0 + err := publishRekeyOutputWith(stage, out, exchangeRekeyDirs, func(string) error { calls++ if calls == 1 { return errRekeyTestWrite } + return nil }) if !errors.Is(err, errRekeyTestWrite) || calls != 2 { t.Fatalf("rollback not synced: %v (%d syncs)", err, calls) } + if existing { data, err := os.ReadFile(filepath.Join(out, "old")) if err != nil || string(data) != "old ciphertext" { t.Fatal("previous output not restored") } + if _, err := os.Stat(filepath.Join(out, "new")); !errors.Is(err, os.ErrNotExist) { t.Fatal("new output survived rollback") } @@ -123,14 +141,17 @@ func TestRekey_ExistingOutputUnsupported(t *testing.T) { t.Skip("Windows-only safety refusal") } opts, _ := rekeyFixture(t) + opts.OutDir, opts.Force = t.TempDir(), true if err := os.WriteFile(filepath.Join(opts.OutDir, "keep"), []byte("old ciphertext"), 0o600); err != nil { t.Fatal(err) } + before := snapshotRekeyDir(t, opts.OutDir) if _, err := Rekey(opts); err == nil || !strings.Contains(err.Error(), "fresh output directory") { t.Fatalf("expected safe refusal: %v", err) } + if !reflect.DeepEqual(before, snapshotRekeyDir(t, opts.OutDir)) { t.Fatal("unsupported exchange modified output") } @@ -139,16 +160,20 @@ func TestRekey_ExistingOutputUnsupported(t *testing.T) { func TestRekey_PublishesOnlyAfterVerification(t *testing.T) { opts, _ := rekeyFixture(t) opens := 0 + opts.openOutput = func(path, password string) (keyring.Keyring, error) { opens++ + if _, err := os.Stat(opts.OutDir); !errors.Is(err, os.ErrNotExist) { t.Fatal("output visible before verification") } + return openRekeyOutput(path, password) } if _, err := Rekey(opts); err != nil { t.Fatal(err) } + if opens != 2 { t.Fatal("independent verification missing") } @@ -159,12 +184,14 @@ func TestRekey_PublishRollbackFailureRetainsPreviousOutput(t *testing.T) { t.Skip("directory exchange is unavailable") } parent := t.TempDir() + stage, out := filepath.Join(parent, "stage"), filepath.Join(parent, "output") for _, path := range []string{stage, out} { if err := os.Mkdir(path, 0o700); err != nil { t.Fatal(err) } } + if err := os.WriteFile(filepath.Join(out, "old"), []byte("old ciphertext"), 0o600); err != nil { t.Fatal(err) } @@ -174,12 +201,15 @@ func TestRekey_PublishRollbackFailureRetainsPreviousOutput(t *testing.T) { if calls == 2 { return errRekeyTestWrite } + return exchangeRekeyDirs(a, b) }, func(string) error { return errRekeyTestWrite }) + var recovery *rekeyRecoveryError if !errors.As(err, &recovery) || !strings.Contains(err.Error(), stage) { t.Fatalf("missing recovery path: %v", err) } + if data, err := os.ReadFile(filepath.Join(stage, "old")); err != nil || string(data) != "old ciphertext" { t.Fatal("previous output lost after rollback failure") } diff --git a/internal/secrets/rekey_sync_unix.go b/internal/secrets/rekey_sync_unix.go index baec2f1fd..fb891d762 100644 --- a/internal/secrets/rekey_sync_unix.go +++ b/internal/secrets/rekey_sync_unix.go @@ -9,11 +9,18 @@ import ( ) func syncRekeyDir(path string) error { - dir, err := os.Open(path) + dir, err := os.Open(path) //nolint:gosec // deliberately sync the selected output directory if err != nil { return fmt.Errorf("open output directory for sync: %w", err) } + return errors.Join(dir.Sync(), dir.Close()) } -func renameRekeyDir(from, to string) error { return os.Rename(from, to) } +func renameRekeyDir(from, to string) error { + if err := os.Rename(from, to); err != nil { + return fmt.Errorf("rename keyring directory: %w", err) + } + + return nil +} diff --git a/internal/secrets/rekey_sync_windows.go b/internal/secrets/rekey_sync_windows.go index a4f85569f..4fd9f605c 100644 --- a/internal/secrets/rekey_sync_windows.go +++ b/internal/secrets/rekey_sync_windows.go @@ -1,6 +1,10 @@ package secrets -import "golang.org/x/sys/windows" +import ( + "fmt" + + "golang.org/x/sys/windows" +) // Windows has no directory fsync. Publication uses a write-through rename; // ciphertext files are individually flushed before it. @@ -9,11 +13,16 @@ func syncRekeyDir(string) error { return nil } func renameRekeyDir(from, to string) error { source, err := windows.UTF16PtrFromString(from) if err != nil { - return err + return fmt.Errorf("encode keyring path: %w", err) } target, err := windows.UTF16PtrFromString(to) if err != nil { - return err + return fmt.Errorf("encode keyring path: %w", err) + } + + if err = windows.MoveFileEx(source, target, windows.MOVEFILE_WRITE_THROUGH); err != nil { + return fmt.Errorf("rename keyring directory: %w", err) } - return windows.MoveFileEx(source, target, windows.MOVEFILE_WRITE_THROUGH) + + return nil } diff --git a/internal/secrets/rekey_test.go b/internal/secrets/rekey_test.go index 778f0c00d..241c24d6b 100644 --- a/internal/secrets/rekey_test.go +++ b/internal/secrets/rekey_test.go @@ -32,6 +32,7 @@ func newRekeyTestLayout(tb testing.TB) (config.Layout, string) { if err := os.WriteFile(filepath.Join(dir, keyringLockFilename), nil, 0o600); err != nil { tb.Fatal(err) } + return layout, dir } From 6a4d5520612bff0ebd30758b07afa9fb9b671e68 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Tue, 20 Oct 2026 11:16:19 -0700 Subject: [PATCH 3/4] test(auth): use fresh output for unreadable rekey test --- internal/secrets/rekey_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/secrets/rekey_test.go b/internal/secrets/rekey_test.go index 241c24d6b..003318567 100644 --- a/internal/secrets/rekey_test.go +++ b/internal/secrets/rekey_test.go @@ -450,6 +450,7 @@ func TestRekey_Unreadable(t *testing.T) { t.Fatal("unreadable input replaced output") } opts.SkipUnreadable = true + opts.OutDir = filepath.Join(t.TempDir(), "output") res, err := Rekey(opts) if err != nil || res.Items != 1 || !reflect.DeepEqual(res.Unreadable, []string{"unreadable"}) { From dbfb6bb5fe78029c62654d1f6d873a58d881efb4 Mon Sep 17 00:00:00 2001 From: Peter Steinberger Date: Tue, 20 Oct 2026 11:26:16 -0700 Subject: [PATCH 4/4] style(auth): satisfy Windows rekey helper lint --- internal/secrets/rekey_sync_windows.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/secrets/rekey_sync_windows.go b/internal/secrets/rekey_sync_windows.go index 4fd9f605c..4a9d78a14 100644 --- a/internal/secrets/rekey_sync_windows.go +++ b/internal/secrets/rekey_sync_windows.go @@ -15,6 +15,7 @@ func renameRekeyDir(from, to string) error { if err != nil { return fmt.Errorf("encode keyring path: %w", err) } + target, err := windows.UTF16PtrFromString(to) if err != nil { return fmt.Errorf("encode keyring path: %w", err)