forked from basecamp/kamal-proxy
-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(cert-store): certificate store export/import for disaster recovery #95
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5949de4
feat(cert-store): export/import of the certificate estate for disaste…
mhenrixon 9b705e6
fix(cert-store): harden export/restore per review findings
mhenrixon 6e479f1
fix(cert-store): second review round — deadlock, unsafe identifiers, …
mhenrixon 8bc16b5
fix(cert-store): third review round — write-path identity, metadata c…
mhenrixon 8e2d367
fix(cert-store): fourth review round — pinned write directory, full-s…
mhenrixon fad9ce7
fix(cert-store): fifth review round — subdirectory containment, bound…
mhenrixon e22de8c
fix(cert-store): sixth review round — pinned-tree containment, strict…
mhenrixon bd05e74
fix(cert-store): seventh review round — fail-closed containment walk,…
mhenrixon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/rpc" | ||
| "path/filepath" | ||
| "strings" | ||
|
|
||
| "github.com/spf13/cobra" | ||
|
|
||
| "github.com/basecamp/kamal-proxy/internal/server" | ||
| ) | ||
|
|
||
| type exportCommand struct { | ||
| cmd *cobra.Command | ||
| } | ||
|
|
||
| func newExportCommand() *exportCommand { | ||
| exportCommand := &exportCommand{} | ||
| exportCommand.cmd = &cobra.Command{ | ||
| Use: "export", | ||
| Short: "Export proxy state for backup", | ||
| } | ||
|
|
||
| exportCommand.cmd.AddCommand(newExportCertsCommand().cmd) | ||
|
|
||
| return exportCommand | ||
| } | ||
|
|
||
| // exportCertsCommand archives the certificate store for disaster recovery. | ||
| // Against a running proxy it exports over the RPC socket, under the same lock | ||
| // the certificate managers use for writes, so a backup taken mid-renewal is | ||
| // never torn. Without a reachable proxy it falls back to reading the data | ||
| // directory offline -- only safe when the proxy is actually stopped. | ||
| type exportCertsCommand struct { | ||
| cmd *cobra.Command | ||
| } | ||
|
|
||
| func newExportCertsCommand() *exportCertsCommand { | ||
| exportCertsCommand := &exportCertsCommand{} | ||
| exportCertsCommand.cmd = &cobra.Command{ | ||
| Use: "certs <output-path>", | ||
| Short: "Export the certificate store to an archive for disaster recovery", | ||
| Long: "Export the certificate store -- ACME account key, issued certificates,\n" + | ||
| "domain mappings, and dynamic domain state -- to a gzipped tar archive.\n\n" + | ||
| "With the proxy running, the snapshot is taken through the proxy under its\n" + | ||
| "certificate write lock. With no proxy reachable on the socket, the data\n" + | ||
| "directory is read directly; only do that with the proxy stopped.\n\n" + | ||
| "The archive contains PRIVATE KEYS (certificate keys and the ACME account\n" + | ||
| "key). It is written with mode 0600; store and transfer it accordingly.", | ||
| RunE: exportCertsCommand.run, | ||
| Args: cobra.ExactArgs(1), | ||
| } | ||
|
|
||
| exportCertsCommand.cmd.Flags().StringVar(&globalConfig.AlternateConfigDir, "data-dir", getEnvString("DATA_DIR", ""), "Directory for state and certificate storage (default $HOME/.config/kamal-proxy)") | ||
|
|
||
| return exportCertsCommand | ||
| } | ||
|
|
||
| func (c *exportCertsCommand) run(cmd *cobra.Command, args []string) error { | ||
| outputPath, err := filepath.Abs(args[0]) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to resolve the output path: %w", err) | ||
| } | ||
|
|
||
| summary, err := c.export(cmd, outputPath) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| for _, warning := range summary.Warnings { | ||
| fmt.Fprintf(cmd.ErrOrStderr(), "WARN %s\n", warning) | ||
| } | ||
|
|
||
| fmt.Fprintf(cmd.OutOrStdout(), "Exported %d certificates (%d domains) to %s\n", | ||
| summary.Certificates, summary.Domains, outputPath) | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // export snapshots through the running proxy when the socket answers, and | ||
| // falls back to reading the data directory offline when it does not. | ||
| func (c *exportCertsCommand) export(cmd *cobra.Command, outputPath string) (server.CertsExportSummary, error) { | ||
| var summary server.CertsExportSummary | ||
|
|
||
| client, dialErr := rpc.Dial("unix", globalConfig.SocketPath()) | ||
| if dialErr == nil { | ||
| defer client.Close() | ||
| err := client.Call("kamal-proxy.CertsExport", server.CertsExportArgs{Path: outputPath}, &summary) | ||
| if err != nil && strings.HasPrefix(err.Error(), "rpc: can't find method kamal-proxy.CertsExport") { | ||
| // A proxy is answering the socket but predates this command. Do | ||
| // NOT fall back to reading the data dir -- that proxy is live and | ||
| // writing, which is exactly the torn-snapshot case the RPC path | ||
| // exists to prevent. | ||
| return summary, fmt.Errorf("the running proxy does not support certificate export; upgrade it, or stop it and re-run for an offline export: %w", err) | ||
| } | ||
| return summary, err | ||
| } | ||
|
|
||
| fmt.Fprintln(cmd.ErrOrStderr(), "Proxy is not running; exporting offline from the data directory") | ||
| return server.ExportCertificateStore(globalConfig.CertStorePaths(), outputPath) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/basecamp/kamal-proxy/internal/server" | ||
| ) | ||
|
|
||
| // runExportCerts executes `export certs` with the given args and returns the | ||
| // combined output. The socket is pointed at nowhere so the command always | ||
| // falls back to the offline path. | ||
| func runExportCerts(t *testing.T, args ...string) (string, error) { | ||
| t.Helper() | ||
|
|
||
| t.Setenv("KAMAL_PROXY_SOCKET", filepath.Join(t.TempDir(), "no-proxy.sock")) | ||
|
|
||
| previousConfig := globalConfig | ||
| t.Cleanup(func() { | ||
| globalConfig = previousConfig | ||
| }) | ||
| globalConfig = server.Config{} | ||
| cmd := newExportCommand().cmd | ||
|
|
||
| out := &bytes.Buffer{} | ||
| cmd.SetOut(out) | ||
| cmd.SetErr(out) | ||
| cmd.SetArgs(append([]string{"certs"}, args...)) | ||
|
|
||
| err := cmd.Execute() | ||
| return out.String(), err | ||
| } | ||
|
|
||
| // seedCertStore writes a minimal but valid store into dir. | ||
| func seedCertStore(t *testing.T, dir string) { | ||
| t.Helper() | ||
|
|
||
| require.NoError(t, os.WriteFile(filepath.Join(dir, "acme.state"), | ||
| []byte(`{"certificates":{},"domain_map":{},"saved_at":"2026-08-09T00:00:00Z"}`), 0600)) | ||
| } | ||
|
|
||
| func TestExportCertsCommand_RequiresAnOutputPath(t *testing.T) { | ||
| _, err := runExportCerts(t) | ||
| require.Error(t, err) | ||
| } | ||
|
|
||
| func TestExportCertsCommand_ExportsOffline(t *testing.T) { | ||
| dir := t.TempDir() | ||
| seedCertStore(t, dir) | ||
|
|
||
| archivePath := filepath.Join(t.TempDir(), "backup.tar.gz") | ||
| out, err := runExportCerts(t, archivePath, "--data-dir", dir) | ||
| require.NoError(t, err) | ||
|
|
||
| assert.Contains(t, out, "offline") | ||
| assert.Contains(t, out, "Exported 0 certificates (0 domains)") | ||
| assert.FileExists(t, archivePath) | ||
| } | ||
|
|
||
| func TestExportCertsCommand_EmptyStoreFails(t *testing.T) { | ||
| _, err := runExportCerts(t, filepath.Join(t.TempDir(), "backup.tar.gz"), "--data-dir", t.TempDir()) | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), "empty") | ||
| } | ||
|
|
||
| func TestImportCertsCommand_ArchiveRestoreRoundTrip(t *testing.T) { | ||
| source := t.TempDir() | ||
| seedCertStore(t, source) | ||
|
|
||
| archivePath := filepath.Join(t.TempDir(), "backup.tar.gz") | ||
| _, err := runExportCerts(t, archivePath, "--data-dir", source) | ||
| require.NoError(t, err) | ||
|
|
||
| // Restore into an empty data dir. | ||
| target := t.TempDir() | ||
| out, err := runImportCerts(t, "--archive", archivePath, "--data-dir", target) | ||
| require.NoError(t, err) | ||
| assert.Contains(t, out, "Restored 0 certificates (0 domains)") | ||
| assert.FileExists(t, filepath.Join(target, "acme.state")) | ||
|
|
||
| // A second restore refuses the now non-empty store... | ||
| _, err = runImportCerts(t, "--archive", archivePath, "--data-dir", target) | ||
| require.ErrorIs(t, err, server.ErrCertStoreNotEmpty) | ||
|
|
||
| // ...unless forced. | ||
| _, err = runImportCerts(t, "--archive", archivePath, "--data-dir", target, "--force") | ||
| require.NoError(t, err) | ||
| } | ||
|
|
||
| func TestImportCertsCommand_VerifyReportsWithoutWriting(t *testing.T) { | ||
| source := t.TempDir() | ||
| seedCertStore(t, source) | ||
|
|
||
| archivePath := filepath.Join(t.TempDir(), "backup.tar.gz") | ||
| _, err := runExportCerts(t, archivePath, "--data-dir", source) | ||
| require.NoError(t, err) | ||
|
|
||
| target := t.TempDir() | ||
| out, err := runImportCerts(t, "--archive", archivePath, "--verify", "--data-dir", target) | ||
| require.NoError(t, err) | ||
|
|
||
| assert.Contains(t, out, "Certificates: 0") | ||
| assert.NoFileExists(t, filepath.Join(target, "acme.state"), | ||
| "--verify must not touch the store") | ||
| } | ||
|
|
||
| func TestImportCertsCommand_FlagValidation(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| args []string | ||
| }{ | ||
| {name: "archive and traefik-acme are exclusive", args: []string{"--archive", "a.tar.gz", "--traefik-acme", "acme.json"}}, | ||
| {name: "resolver applies only to traefik", args: []string{"--archive", "a.tar.gz", "--resolver", "le"}}, | ||
| {name: "verify requires archive", args: []string{"--traefik-acme", "acme.json", "--verify"}}, | ||
| {name: "verify and force are exclusive", args: []string{"--archive", "a.tar.gz", "--verify", "--force"}}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| _, err := runImportCerts(t, tt.args...) | ||
| require.Error(t, err) | ||
| }) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.