Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 762bf6f9b8 | |||
| aa8b74dcf0 | |||
| 027f1453d7 | |||
| 6e7073a830 | |||
| 612874a0c7 | |||
| d2e9e42e20 | |||
| 9a36da3174 | |||
| 70fe2858d0 | |||
| 3fc5fcd9a8 | |||
| 430a360177 |
+6
-5
@@ -47,11 +47,12 @@ nfpms:
|
||||
dst: /usr/bin/encapic-enc
|
||||
file_info:
|
||||
mode: 0755
|
||||
# noreplace: puppet manages this file's contents (hiera-driven URL), so an
|
||||
# upgrade must not overwrite it.
|
||||
- src: packaging/encapic.conf
|
||||
dst: /etc/encapic/encapic.conf
|
||||
type: "config|noreplace"
|
||||
- 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
|
||||
|
||||
|
||||
@@ -75,6 +75,13 @@ steps:
|
||||
- |
|
||||
HOST="https://artifactapi.k8s.syd1.au.unkin.net"
|
||||
REPO="rpm-internal"
|
||||
set -o pipefail
|
||||
VAULT="https://vault.service.consul:8200"
|
||||
AUTH=$$(mktemp)
|
||||
VT=$$(jq -n --rawfile jwt /var/run/secrets/kubernetes.io/serviceaccount/token '{role:"woodpecker_artifactapi_writer",jwt:$$jwt}' \
|
||||
| curl -sf -d @- "$$VAULT/v1/auth/k8s/au/syd1/login" | jq -er .auth.client_token) || exit 1
|
||||
printf 'X-Vault-Token: %s\n' "$$VT" | curl -sf -H @- "$$VAULT/v1/identity/oidc/token/artifactapi-writer" \
|
||||
| jq -er '"Authorization: Bearer " + .data.token' > "$$AUTH" || exit 1
|
||||
for rpm in dist/*.rpm; do
|
||||
FILE=$$(basename "$$rpm")
|
||||
# artifactapi has no HEAD route (returns 405); probe with GET against
|
||||
@@ -87,7 +94,7 @@ steps:
|
||||
echo "Uploading $$FILE to $$REPO (existence probe returned $$code)"
|
||||
curl -f -X PUT \
|
||||
"$$HOST/api/v2/remotes/$$REPO/files/$$FILE" \
|
||||
-H "Content-Type: application/x-rpm" \
|
||||
-H "Content-Type: application/x-rpm" -H @"$$AUTH" \
|
||||
--data-binary @"$$rpm"
|
||||
done
|
||||
depends_on: [goreleaser]
|
||||
|
||||
@@ -25,10 +25,34 @@ 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. 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 +72,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:
|
||||
@@ -107,14 +142,11 @@ 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`
|
||||
invokes `external_nodes` with a certname and no environment, so the shim
|
||||
sources the URL before exec'ing the binary. Point `external_nodes` at this,
|
||||
not at `/usr/bin/encapic`;
|
||||
- `/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.
|
||||
sources the puppet-managed `/etc/encapi/encapic.conf` before exec'ing the
|
||||
binary. Point `external_nodes` at this, not at `/usr/bin/encapic`;
|
||||
- bash and zsh completion scripts.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,155 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const initDefaultURL = "https://encapi.k8s.syd1.au.unkin.net"
|
||||
|
||||
var systemConfPath = "/etc/encapi/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 []string{userConfPath(), systemConfPath} {
|
||||
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)
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
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)
|
||||
}
|
||||
systemConfPath = ""
|
||||
_ = 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")
|
||||
old := systemConfPath
|
||||
systemConfPath = system
|
||||
t.Cleanup(func() { systemConfPath = 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, 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)
|
||||
}
|
||||
}
|
||||
@@ -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 <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
|
||||
encapic -v | --version show the version
|
||||
|
||||
ENCAPI_URL is read from the environment, then ~/.config/encapi/encapic.conf,
|
||||
/etc/encapi/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 <certname> | %s set-testing <certname>", 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 {
|
||||
|
||||
@@ -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{"<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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunVersion(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
if err := run([]string{"encapic", "--version"}, &out); err != nil {
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
# 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
|
||||
if [ -r /etc/encapi/encapic.conf ]; then
|
||||
. /etc/encapi/encapic.conf
|
||||
fi
|
||||
if [ -n "${ENCAPI_URL:-}" ]; then
|
||||
export ENCAPI_URL
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Base URL of the encapi service, read by /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
|
||||
+40
-17
@@ -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<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 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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user