Merge pull request 'feat: add unset-testing subcommand' (#7) from benvin/encapic-unset-testing into benvin/encapic-init-help
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

Reviewed-on: #7
This commit was merged in pull request #7.
This commit is contained in:
2026-11-08 17:37:58 +11:00
8 changed files with 133 additions and 17 deletions
+11
View File
@@ -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 <certname>
```
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/<certname>/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:
+1 -1
View File
@@ -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)
}
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+4
View File
@@ -47,6 +47,7 @@ const httpTimeout = 10 * time.Second
const usage = `usage:
encapic <certname> print the Puppet ENC YAML for certname
encapic set-testing <certname> pin certname to the testing environment
encapic unset-testing <certname> 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"))
}
+1 -1
View File
@@ -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{"<certname>", "set-testing", "init", "completion bash|zsh [--install]", "--version", "ENCAPI_URL"} {
for _, want := range []string{"<certname>", "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)
}
+39 -13
View File
@@ -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<suffix> 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
}
+75
View File
@@ -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)
}
}