diff --git a/README.md b/README.md index 67cd2df..4d37a52 100644 --- a/README.md +++ b/README.md @@ -73,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: diff --git a/completion_test.go b/completion_test.go index f138c9d..a6ba435 100644 --- a/completion_test.go +++ b/completion_test.go @@ -17,7 +17,7 @@ func TestCompletionPrint(t *testing.T) { if !strings.Contains(out.String(), marker) { t.Errorf("%s script missing %q", shell, marker) } - for _, word := range []string{"init", "set-testing", "completion", "bash zsh", "--install"} { + 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) } diff --git a/completions/_encapic b/completions/_encapic index 4627e0c..8c49222 100644 --- a/completions/_encapic +++ b/completions/_encapic @@ -2,7 +2,7 @@ _encapic() { case $CURRENT in - 2) compadd -- init set-testing completion help --help --version ;; + 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 diff --git a/completions/encapic.bash b/completions/encapic.bash index f391660..4019d25 100644 --- a/completions/encapic.bash +++ b/completions/encapic.bash @@ -2,7 +2,7 @@ _encapic() { local cur=${COMP_WORDS[COMP_CWORD]} words="" case $COMP_CWORD in - 1) words="init set-testing completion help --help --version" ;; + 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 diff --git a/main.go b/main.go index 1131f79..060fadd 100644 --- a/main.go +++ b/main.go @@ -47,6 +47,7 @@ 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 @@ -84,6 +85,9 @@ func run(args []string, out io.Writer) error { if len(args) == 3 && args[1] == "set-testing" { return setTesting(args[2], out) } + 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")) } diff --git a/main_test.go b/main_test.go index f6239c4..5d853ba 100644 --- a/main_test.go +++ b/main_test.go @@ -120,7 +120,7 @@ func TestRunHelp(t *testing.T) { if err := run([]string{"encapic", arg}, &out); err != nil { t.Fatalf("%s: %v", arg, err) } - for _, want := range []string{"", "set-testing", "init", "completion bash|zsh [--install]", "--version", "ENCAPI_URL"} { + 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) } diff --git a/settesting.go b/settesting.go index 75672f7..8a0f5b0 100644 --- a/settesting.go +++ b/settesting.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "crypto/tls" "crypto/x509" "encoding/json" @@ -20,31 +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 { + 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 err + 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) { @@ -88,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) + } +}