diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 21567d9..471e899 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -54,6 +54,14 @@ nfpms: type: "config|noreplace" file_info: mode: 0644 + - src: completions/encapic.bash + dst: /usr/share/bash-completion/completions/encapic + file_info: + mode: 0644 + - src: completions/_encapic + dst: /usr/share/zsh/site-functions/_encapic + file_info: + mode: 0644 checksum: # One .sha256 per file rather than a single checksums.txt: the diff --git a/README.md b/README.md index a4d108c..4d37a52 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,35 @@ reshapes it, and prints the resulting ENC YAML to stdout. It exits non-zero on any HTTP or parse failure — including a 404 for an unknown node — so the puppet exec `node_terminus` fails safe rather than compiling an empty catalog. -- `ENCAPI_URL` overrides the encapi base URL. The compiled-in default is - `http://encapi.encapi.svc.cluster.local` (the in-cluster service). - The HTTP request has a 10s timeout. +`encapic --help` lists every command. + +### Configuration + +The encapi base URL comes from the first of: + +1. the `ENCAPI_URL` environment variable; +2. `${XDG_CONFIG_HOME:-~/.config}/encapi/encapic.conf`; +3. `/etc/encapi/encapic.conf`; +4. `/etc/encapic/encapic.conf` (legacy, shipped by the RPM); +5. the compiled-in default `http://encapi.encapi.svc.cluster.local`. + +Conf files are shell-sourceable `KEY=VALUE` (`ENCAPI_URL=https://...`). +`encapic init` prompts for the URL (default +`https://encapi.k8s.syd1.au.unkin.net`), writes the user conf and offers to +install shell completion. With no config found, an interactive run prints a hint to +stderr; non-TTY runs (the puppet exec ENC) stay silent. + +### Shell completion + +``` +encapic completion bash|zsh # print the script +encapic completion bash|zsh --install # install under ${XDG_DATA_HOME:-~/.local/share} +``` + +The RPM also installs both scripts system-wide. + ### Pinning a host to `testing` ``` @@ -48,6 +73,17 @@ It mints a JWT from `${VAULT_ADDR}/v1/identity/oidc/token/${ENCAPI_OIDC_ROLE}` `VAULT_ADDR` must be `https` and redirects are never followed, so neither the Vault token nor the JWT is sent over plain http or to another host. +### Restoring a host from `testing` + +``` +encapic unset-testing +``` + +Restores the environment the node had before `set-testing` and prints it +(requires the encapi testing-restore endpoint). It authenticates like +`set-testing` and sends `DELETE ${ENCAPI_URL}/api/v1/nodes//environment/testing`; +a node that is not in `testing` fails with encapi's error message. + ## Behaviour (drop-in for the python ENC) encapic reproduces the previous python script byte-for-byte: @@ -107,7 +143,7 @@ The VM puppet masters install the RPM from `rpm-internal`: dnf install encapic ``` -It ships three paths: +It ships: - `/usr/bin/encapic` — the binary; - `/usr/bin/encapic-enc` — the ENC entrypoint. Puppet's exec `node_terminus` @@ -117,4 +153,6 @@ It ships three paths: - `/etc/encapic/encapic.conf` — `ENCAPI_URL=...`, defaulting to the external address `https://encapi.k8s.syd1.au.unkin.net` because a VM cannot resolve the in-cluster default. Shipped `%config(noreplace)` so puppet may own its - contents without an upgrade reverting them. + contents without an upgrade reverting them. A `/etc/encapi/encapic.conf`, when + present, takes precedence in both the shim and the binary; +- bash and zsh completion scripts. diff --git a/completion.go b/completion.go new file mode 100644 index 0000000..fc43a05 --- /dev/null +++ b/completion.go @@ -0,0 +1,65 @@ +package main + +import ( + _ "embed" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +//go:embed completions/encapic.bash +var bashCompletion string + +//go:embed completions/_encapic +var zshCompletion string + +var completionScripts = map[string]string{"bash": bashCompletion, "zsh": zshCompletion} + +func completionPath(shell string) (string, error) { + d := xdgDir("XDG_DATA_HOME", filepath.Join(".local", "share")) + if d == "" { + return "", fmt.Errorf("cannot determine user data directory") + } + if shell == "zsh" { + return filepath.Join(d, "zsh", "site-functions", "_encapic"), nil + } + return filepath.Join(d, "bash-completion", "completions", "encapic"), nil +} + +func installCompletion(shell string, out io.Writer) error { + path, err := completionPath(shell) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + if err := os.WriteFile(path, []byte(completionScripts[shell]), 0o644); err != nil { + return err + } + if _, err := fmt.Fprintf(out, "installed %s completion to %s\n", shell, path); err != nil { + return err + } + dir := filepath.Dir(path) + if shell == "zsh" && !strings.Contains(":"+os.Getenv("FPATH")+":", ":"+dir+":") { + _, err = fmt.Fprintf(out, "hint: add to ~/.zshrc before compinit: fpath=(%s $fpath)\n", dir) + } + return err +} + +func completion(args []string, out io.Writer) error { + if len(args) < 1 || len(args) > 2 || (len(args) == 2 && args[1] != "--install") { + return fmt.Errorf("usage: encapic completion bash|zsh [--install]") + } + script, ok := completionScripts[args[0]] + if !ok { + return fmt.Errorf("unsupported shell %q: want bash or zsh", args[0]) + } + if len(args) == 2 { + return installCompletion(args[0], out) + } + _, err := io.WriteString(out, script) + return err +} diff --git a/completion_test.go b/completion_test.go new file mode 100644 index 0000000..a6ba435 --- /dev/null +++ b/completion_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCompletionPrint(t *testing.T) { + for shell, marker := range map[string]string{"bash": "complete -F _encapic encapic", "zsh": "#compdef encapic"} { + var out bytes.Buffer + if err := run([]string{"encapic", "completion", shell}, &out); err != nil { + t.Fatalf("%s: %v", shell, err) + } + if !strings.Contains(out.String(), marker) { + t.Errorf("%s script missing %q", shell, marker) + } + for _, word := range []string{"init", "set-testing", "unset-testing", "completion", "bash zsh", "--install"} { + if !strings.Contains(out.String(), word) { + t.Errorf("%s script does not complete %q", shell, word) + } + } + } +} + +func TestCompletionErrors(t *testing.T) { + for _, args := range [][]string{{}, {"fish"}, {"bash", "--bogus"}, {"bash", "--install", "x"}} { + if err := completion(args, &bytes.Buffer{}); err == nil { + t.Errorf("completion(%q) succeeded, want error", args) + } + } +} + +func TestCompletionInstall(t *testing.T) { + data := t.TempDir() + t.Setenv("XDG_DATA_HOME", data) + zshDir := filepath.Join(data, "zsh", "site-functions") + + cases := []struct { + shell, path, fpath string + hint bool + }{ + {"bash", filepath.Join(data, "bash-completion", "completions", "encapic"), "", false}, + {"zsh", filepath.Join(zshDir, "_encapic"), "/usr/share/zsh/site-functions", true}, + {"zsh", filepath.Join(zshDir, "_encapic"), "/a:" + zshDir + ":/b", false}, + } + for _, tc := range cases { + t.Setenv("FPATH", tc.fpath) + var out bytes.Buffer + if err := run([]string{"encapic", "completion", tc.shell, "--install"}, &out); err != nil { + t.Fatalf("%s install: %v", tc.shell, err) + } + b, err := os.ReadFile(tc.path) + if err != nil || string(b) != completionScripts[tc.shell] { + t.Errorf("%s: script not at %s: %v", tc.shell, tc.path, err) + } + if got := strings.Contains(out.String(), "fpath=("+zshDir); got != tc.hint { + t.Errorf("%s FPATH=%q: hint = %v, want %v (%q)", tc.shell, tc.fpath, got, tc.hint, out.String()) + } + } +} + +func TestCompletionInstallDefaultsToLocalShare(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_DATA_HOME", "") + path, err := completionPath("bash") + if err != nil || path != filepath.Join(home, ".local", "share", "bash-completion", "completions", "encapic") { + t.Errorf("completionPath = %q, %v", path, err) + } +} diff --git a/completions/_encapic b/completions/_encapic new file mode 100644 index 0000000..8c49222 --- /dev/null +++ b/completions/_encapic @@ -0,0 +1,15 @@ +#compdef encapic + +_encapic() { + case $CURRENT in + 2) compadd -- init set-testing unset-testing completion help --help --version ;; + 3) [[ $words[2] == completion ]] && compadd -- bash zsh ;; + 4) [[ $words[2] == completion ]] && compadd -- --install ;; + esac +} + +if [[ $funcstack[1] == _encapic ]]; then + _encapic "$@" +else + compdef _encapic encapic +fi diff --git a/completions/encapic.bash b/completions/encapic.bash new file mode 100644 index 0000000..4019d25 --- /dev/null +++ b/completions/encapic.bash @@ -0,0 +1,11 @@ +# bash completion for encapic +_encapic() { + local cur=${COMP_WORDS[COMP_CWORD]} words="" + case $COMP_CWORD in + 1) words="init set-testing unset-testing completion help --help --version" ;; + 2) [[ ${COMP_WORDS[1]} == completion ]] && words="bash zsh" ;; + 3) [[ ${COMP_WORDS[1]} == completion ]] && words="--install" ;; + esac + mapfile -t COMPREPLY < <(compgen -W "$words" -- "$cur") +} +complete -F _encapic encapic diff --git a/config.go b/config.go new file mode 100644 index 0000000..5b6d37c --- /dev/null +++ b/config.go @@ -0,0 +1,157 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" +) + +const initDefaultURL = "https://encapi.k8s.syd1.au.unkin.net" + +// systemConfPaths follow the user conf in precedence; the legacy path is a +// read-only fallback for hosts whose puppet still manages it. +var systemConfPaths = []string{"/etc/encapi/encapic.conf", "/etc/encapic/encapic.conf"} + +func xdgDir(env, fallback string) string { + if d := os.Getenv(env); d != "" { + return d + } + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, fallback) +} + +func userConfPath() string { + d := xdgDir("XDG_CONFIG_HOME", ".config") + if d == "" { + return "" + } + return filepath.Join(d, "encapi", "encapic.conf") +} + +// resolveBaseURL returns the encapi URL and whether it came from env or a conf +// file rather than the compiled default. +func resolveBaseURL() (string, bool) { + if u := os.Getenv("ENCAPI_URL"); u != "" { + return u, true + } + for _, p := range append([]string{userConfPath()}, systemConfPaths...) { + if u := readConfURL(p); u != "" { + return u, true + } + } + return defaultBaseURL, false +} + +func baseURL() string { + u, found := resolveBaseURL() + if !found { + noConfigHint(os.Stderr) + } + return u +} + +func noConfigHint(f *os.File) { + if fi, err := f.Stat(); err == nil && fi.Mode()&os.ModeCharDevice != 0 { + _, _ = fmt.Fprintln(f, "hint: no config found, run 'encapic init'") + } +} + +func readConfURL(path string) string { + if path == "" { + return "" + } + b, err := os.ReadFile(path) + if err != nil { + return "" + } + u := "" + for _, line := range strings.Split(string(b), "\n") { + k, v, ok := strings.Cut(strings.TrimSpace(line), "=") + if ok && strings.TrimSpace(strings.TrimPrefix(k, "export ")) == "ENCAPI_URL" { + u = strings.Trim(strings.TrimSpace(v), `"'`) + } + } + return u +} + +func validURL(raw string) error { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return fmt.Errorf("invalid encapi URL %q: want http(s)://host", raw) + } + return nil +} + +func prompt(r *bufio.Reader, out io.Writer, q string) (string, error) { + if _, err := fmt.Fprint(out, q); err != nil { + return "", err + } + line, err := r.ReadString('\n') + if err != nil && !errors.Is(err, io.EOF) { + return "", err + } + return strings.TrimSpace(line), nil +} + +func initConfig(in io.Reader, out io.Writer) error { + path := userConfPath() + if path == "" { + return errors.New("cannot determine user config directory") + } + r := bufio.NewReader(in) + u, err := prompt(r, out, fmt.Sprintf("encapi URL [%s]: ", initDefaultURL)) + if err != nil { + return err + } + if u == "" { + u = initDefaultURL + } + if err := validURL(u); err != nil { + return err + } + + write, verb := true, "wrote" + if _, err := os.Stat(path); err == nil { + ans, err := prompt(r, out, path+" exists, overwrite? [y/N] ") + if err != nil { + return err + } + write = strings.EqualFold(ans, "y") || strings.EqualFold(ans, "yes") + if !write { + verb = "kept" + } + } + if write { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + if err := os.WriteFile(path, []byte("ENCAPI_URL="+u+"\n"), 0o644); err != nil { + return err + } + } + if _, err := fmt.Fprintf(out, "%s %s\n", verb, path); err != nil { + return err + } + + ans, err := prompt(r, out, "Install shell completion? [Y/n] ") + if err != nil { + return err + } + if ans != "" && !strings.EqualFold(ans, "y") && !strings.EqualFold(ans, "yes") { + return nil + } + shell := filepath.Base(os.Getenv("SHELL")) + if _, ok := completionScripts[shell]; !ok { + _, err := fmt.Fprintf(out, "skipping completion: unsupported shell %q (bash|zsh)\n", shell) + return err + } + return installCompletion(shell, out) +} diff --git a/config_test.go b/config_test.go new file mode 100644 index 0000000..b943f7c --- /dev/null +++ b/config_test.go @@ -0,0 +1,169 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "encapic-test") + if err != nil { + panic(err) + } + systemConfPaths = nil + _ = os.Unsetenv("ENCAPI_URL") + _ = os.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) + _ = os.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data")) + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} + +func writeConf(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestResolveBaseURLPrecedence(t *testing.T) { + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "user")) + user := filepath.Join(dir, "user", "encapi", "encapic.conf") + system := filepath.Join(dir, "etc", "encapi", "encapic.conf") + legacy := filepath.Join(dir, "etc", "encapic", "encapic.conf") + old := systemConfPaths + systemConfPaths = []string{system, legacy} + t.Cleanup(func() { systemConfPaths = old }) + + check := func(want string, wantFound bool) { + t.Helper() + got, found := resolveBaseURL() + if got != want || found != wantFound { + t.Errorf("resolveBaseURL() = %q, %v; want %q, %v", got, found, want, wantFound) + } + } + + t.Setenv("ENCAPI_URL", "") + check(defaultBaseURL, false) + writeConf(t, legacy, "ENCAPI_URL=https://legacy\n") + check("https://legacy", true) + writeConf(t, system, "# comment\nENCAPI_URL=\"https://system\"\n") + check("https://system", true) + writeConf(t, user, "OTHER=x\nexport ENCAPI_URL='https://user'\n") + check("https://user", true) + t.Setenv("ENCAPI_URL", "https://env") + check("https://env", true) + + t.Setenv("ENCAPI_URL", "") + writeConf(t, user, "OTHER=x\n") + check("https://system", true) +} + +func TestInitConfig(t *testing.T) { + cases := []struct { + name, input, want string + wantErr bool + }{ + {"default", "\nn\n", "ENCAPI_URL=https://encapi.k8s.syd1.au.unkin.net\n", false}, + {"custom", "http://encapi.example:8080\nn\n", "ENCAPI_URL=http://encapi.example:8080\n", false}, + {"invalid", "ftp://nope\n", "", true}, + {"no host", "encapi.example\n", "", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + var out bytes.Buffer + err := initConfig(strings.NewReader(tc.input), &out) + if (err != nil) != tc.wantErr { + t.Fatalf("err = %v, wantErr %v", err, tc.wantErr) + } + b, rerr := os.ReadFile(userConfPath()) + if tc.wantErr { + if rerr == nil { + t.Errorf("conf written despite invalid URL: %q", b) + } + return + } + if string(b) != tc.want { + t.Errorf("conf = %q, want %q", b, tc.want) + } + if !strings.Contains(out.String(), "encapi URL [https://encapi.k8s.syd1.au.unkin.net]: ") { + t.Errorf("missing URL prompt in %q", out.String()) + } + fi, err := os.Stat(filepath.Dir(userConfPath())) + if err != nil || fi.Mode().Perm() != 0o700 { + t.Errorf("conf dir mode = %v, %v; want 0700", fi.Mode().Perm(), err) + } + t.Setenv("ENCAPI_URL", "") + if got, found := resolveBaseURL(); !found || got+"\n" != strings.TrimPrefix(tc.want, "ENCAPI_URL=") { + t.Errorf("resolveBaseURL after init = %q", got) + } + }) + } +} + +func TestInitConfigOverwrite(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + writeConf(t, userConfPath(), "ENCAPI_URL=https://keep\n") + + var out bytes.Buffer + if err := initConfig(strings.NewReader("https://new\n\nn\n"), &out); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(userConfPath()); string(b) != "ENCAPI_URL=https://keep\n" { + t.Errorf("conf overwritten without consent: %q", b) + } + if !strings.Contains(out.String(), "overwrite? [y/N]") { + t.Errorf("no overwrite prompt in %q", out.String()) + } + + if err := initConfig(strings.NewReader("https://new\ny\nn\n"), &out); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(userConfPath()); string(b) != "ENCAPI_URL=https://new\n" { + t.Errorf("conf not overwritten after yes: %q", b) + } +} + +func TestInitInstallsCompletion(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_DATA_HOME", t.TempDir()) + + t.Setenv("SHELL", "/bin/bash") + var out bytes.Buffer + if err := initConfig(strings.NewReader("\n\n"), &out); err != nil { + t.Fatal(err) + } + path, _ := completionPath("bash") + if b, err := os.ReadFile(path); err != nil || string(b) != bashCompletion { + t.Errorf("bash completion not installed at %s: %v", path, err) + } + + t.Setenv("SHELL", "/usr/bin/fish") + out.Reset() + if err := initConfig(strings.NewReader("\ny\n"), &out); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), `unsupported shell "fish"`) { + t.Errorf("no skip note for fish in %q", out.String()) + } +} + +func TestNoConfigHintSilentWithoutTTY(t *testing.T) { + f, err := os.CreateTemp(t.TempDir(), "stderr") + if err != nil { + t.Fatal(err) + } + defer func() { _ = f.Close() }() + noConfigHint(f) + if fi, err := f.Stat(); err != nil || fi.Size() != 0 { + t.Errorf("hint written to non-TTY stderr (size %d, %v)", fi.Size(), err) + } +} diff --git a/main.go b/main.go index 80c02c7..060fadd 100644 --- a/main.go +++ b/main.go @@ -38,12 +38,25 @@ import ( var version = "dev" // defaultBaseURL is compiled in and points at the in-cluster encapi service. It -// is overridden by the ENCAPI_URL environment variable when set. +// is overridden by ENCAPI_URL from the environment or a conf file. const defaultBaseURL = "http://encapi.encapi.svc.cluster.local" // httpTimeout bounds the whole request; the puppet exec ENC must not hang. const httpTimeout = 10 * time.Second +const usage = `usage: + encapic print the Puppet ENC YAML for certname + encapic set-testing pin certname to the testing environment + encapic unset-testing restore certname's pre-testing environment + encapic init write ~/.config/encapi/encapic.conf + encapic completion bash|zsh [--install] print or install shell completion + encapic -h | --help | help show this help + encapic -v | --version show the version + +ENCAPI_URL is read from the environment, then ~/.config/encapi/encapic.conf, +/etc/encapi/encapic.conf, /etc/encapic/encapic.conf, else the in-cluster default. +` + func main() { if err := run(os.Args, os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) @@ -54,22 +67,32 @@ func main() { // run is the testable entry point. It writes the ENC YAML to out and returns a // non-nil error on any failure. func run(args []string, out io.Writer) error { - if len(args) == 2 && (args[1] == "-v" || args[1] == "--version") { - _, err := fmt.Fprintf(out, "encapic %s\n", version) - return err + if len(args) == 2 { + switch args[1] { + case "-v", "--version": + _, err := fmt.Fprintf(out, "encapic %s\n", version) + return err + case "-h", "--help", "help": + _, err := io.WriteString(out, usage) + return err + case "init": + return initConfig(os.Stdin, out) + } + } + if len(args) >= 2 && args[1] == "completion" { + return completion(args[2:], out) } if len(args) == 3 && args[1] == "set-testing" { return setTesting(args[2], out) } - if len(args) != 2 { - return fmt.Errorf("usage: %s | %s set-testing ", args[0], args[0]) + if len(args) == 3 && args[1] == "unset-testing" { + return unsetTesting(args[2], out) + } + if len(args) != 2 || strings.HasPrefix(args[1], "-") { + return fmt.Errorf("invalid arguments %q\n%s", args[1:], strings.TrimSuffix(usage, "\n")) } certname := args[1] - - baseURL := os.Getenv("ENCAPI_URL") - if baseURL == "" { - baseURL = defaultBaseURL - } + baseURL := baseURL() body, err := fetch(baseURL, certname) if err != nil { diff --git a/main_test.go b/main_test.go index 90adc0f..5d853ba 100644 --- a/main_test.go +++ b/main_test.go @@ -107,6 +107,27 @@ func TestRunUsage(t *testing.T) { } } +func TestRunUnknownFlag(t *testing.T) { + err := run([]string{"encapic", "--bogus"}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "usage:") { + t.Fatalf("err = %v, want usage error", err) + } +} + +func TestRunHelp(t *testing.T) { + for _, arg := range []string{"-h", "--help", "help"} { + var out bytes.Buffer + if err := run([]string{"encapic", arg}, &out); err != nil { + t.Fatalf("%s: %v", arg, err) + } + for _, want := range []string{"", "set-testing", "unset-testing", "init", "completion bash|zsh [--install]", "--version", "ENCAPI_URL"} { + if !strings.Contains(out.String(), want) { + t.Errorf("%s output missing %q", arg, want) + } + } + } +} + func TestRunVersion(t *testing.T) { var out bytes.Buffer if err := run([]string{"encapic", "--version"}, &out); err != nil { diff --git a/packaging/encapic-enc b/packaging/encapic-enc index 88fbd22..81e1b68 100755 --- a/packaging/encapic-enc +++ b/packaging/encapic-enc @@ -3,9 +3,11 @@ # environment, so the encapi URL cannot be inherited; source it here instead. set -eu -if [ -r /etc/encapic/encapic.conf ]; then - . /etc/encapic/encapic.conf -fi +for conf in /etc/encapic/encapic.conf /etc/encapi/encapic.conf; do + if [ -r "$conf" ]; then + . "$conf" + fi +done if [ -n "${ENCAPI_URL:-}" ]; then export ENCAPI_URL fi diff --git a/packaging/encapic.conf b/packaging/encapic.conf index 481e61d..1dd2ac7 100644 --- a/packaging/encapic.conf +++ b/packaging/encapic.conf @@ -1,4 +1,4 @@ -# Base URL of the encapi service, read by /usr/bin/encapic-enc. +# Base URL of the encapi service, read by encapic and /usr/bin/encapic-enc. # The binary's compiled-in default is the in-cluster address, which VM puppet # masters cannot resolve. ENCAPI_URL=https://encapi.k8s.syd1.au.unkin.net diff --git a/settesting.go b/settesting.go index 46218bd..8a0f5b0 100644 --- a/settesting.go +++ b/settesting.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "crypto/tls" "crypto/x509" "encoding/json" @@ -20,34 +19,58 @@ const defaultVaultAddr = "https://vault.service.consul:8200" // setTesting pins certname to the testing environment via encapi, using a // Vault identity OIDC token for the encapi-testing role. func setTesting(certname string, out io.Writer) error { - baseURL := os.Getenv("ENCAPI_URL") - if baseURL == "" { - baseURL = defaultBaseURL - } - if err := requireHTTPS("ENCAPI_URL", baseURL); err != nil { + if _, err := encapiEnvironment(http.MethodPut, certname, "", `{"environment":"testing"}`); err != nil { return err } + _, err := fmt.Fprintf(out, "%s set to testing\n", certname) + return err +} + +// unsetTesting restores certname to the environment it had before set-testing. +func unsetTesting(certname string, out io.Writer) error { + body, err := encapiEnvironment(http.MethodDelete, certname, "/testing", "") + if err != nil { + return err + } + var node struct { + Environment string `json:"environment"` + } + if err := json.Unmarshal(body, &node); err != nil { + return fmt.Errorf("decode encapi node response: %w", err) + } + if node.Environment == "" { + return errors.New("encapi returned no environment") + } + _, err = fmt.Fprintf(out, "%s restored to %s\n", certname, node.Environment) + return err +} + +// encapiEnvironment sends an authenticated request to the node's +// /environment endpoint and returns the response body. +func encapiEnvironment(method, certname, suffix, body string) ([]byte, error) { + baseURL := baseURL() + if err := requireHTTPS("ENCAPI_URL", baseURL); err != nil { + return nil, err + } client, err := vaultClient() if err != nil { - return err + return nil, err } jwt, err := mintToken(client) if err != nil { - return err + return nil, err } - u := strings.TrimRight(baseURL, "/") + "/api/v1/nodes/" + url.PathEscape(certname) + "/environment" - req, err := http.NewRequest(http.MethodPut, u, bytes.NewBufferString(`{"environment":"testing"}`)) + u := strings.TrimRight(baseURL, "/") + "/api/v1/nodes/" + url.PathEscape(certname) + "/environment" + suffix + req, err := http.NewRequest(method, u, strings.NewReader(body)) if err != nil { - return err + return nil, err } req.Header.Set("Authorization", "Bearer "+jwt) - req.Header.Set("Content-Type", "application/json") - if _, err := do(client, req); err != nil { - return err + if body != "" { + req.Header.Set("Content-Type", "application/json") } - _, err = fmt.Fprintf(out, "%s set to testing\n", certname) - return err + return do(client, req) } func mintToken(client *http.Client) (string, error) { @@ -91,7 +114,7 @@ func mintToken(client *http.Client) (string, error) { func requireHTTPS(name, raw string) error { if parsed, err := url.Parse(raw); err != nil || parsed.Scheme != "https" { - return fmt.Errorf("set-testing requires an https %s, got %q", name, raw) + return fmt.Errorf("encapic requires an https %s, got %q", name, raw) } return nil } diff --git a/unsettesting_test.go b/unsettesting_test.go new file mode 100644 index 0000000..59f6ae9 --- /dev/null +++ b/unsettesting_test.go @@ -0,0 +1,75 @@ +package main + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func fakeEncapiDelete(t *testing.T, status int, body string, seen *seenPut) *httptest.Server { + t.Helper() + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *seen = seenPut{r.Method + " " + r.URL.Path, r.Header.Get("Authorization"), ""} + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + trustServer(t, srv) + return srv +} + +func runUnset(t *testing.T, status int, body string) (string, seenPut, error) { + t.Helper() + var seen seenPut + t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL) + t.Setenv("VAULT_TOKEN", "vt") + t.Setenv("ENCAPI_URL", fakeEncapiDelete(t, status, body, &seen).URL) + var out bytes.Buffer + err := run([]string{"encapic", "unset-testing", "host.example"}, &out) + return out.String(), seen, err +} + +func TestUnsetTestingSuccess(t *testing.T) { + out, seen, err := runUnset(t, 200, `{"certname":"host.example","environment":"production"}`) + if err != nil { + t.Fatalf("run: %v", err) + } + want := seenPut{"DELETE /api/v1/nodes/host.example/environment/testing", "Bearer jwt123", ""} + if seen != want { + t.Errorf("request = %+v, want %+v", seen, want) + } + if out != "host.example restored to production\n" { + t.Errorf("out = %q", out) + } +} + +func TestUnsetTestingErrors(t *testing.T) { + for _, tc := range []struct { + status int + body, want string + }{ + {409, `{"error":"node is not in testing"}`, "HTTP 409: {\"error\":\"node is not in testing\"}"}, + {404, `{"error":"node not found"}`, "HTTP 404"}, + {200, `{"certname":"host.example"}`, "no environment"}, + {200, `not json`, "decode encapi node response"}, + } { + out, _, err := runUnset(t, tc.status, tc.body) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%d %s: err = %v, want %q", tc.status, tc.body, err, tc.want) + } + if out != "" { + t.Errorf("%d %s: out = %q, want none", tc.status, tc.body, out) + } + } +} + +func TestUnsetTestingRefusesPlainHTTP(t *testing.T) { + t.Setenv("ENCAPI_URL", "http://encapi.example") + err := run([]string{"encapic", "unset-testing", "host.example"}, io.Discard) + if err == nil || !strings.Contains(err.Error(), "requires an https ENCAPI_URL") { + t.Fatalf("err = %v, want https refusal", err) + } +}