21 Commits

Author SHA1 Message Date
benvin 762bf6f9b8 Merge pull request 'fix: drop legacy /etc/encapic/encapic.conf' (#8) from benvin/drop-legacy-conf into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #8
2026-11-09 22:26:09 +11:00
unkin-agent aa8b74dcf0 fix: drop legacy /etc/encapic/encapic.conf
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-11-09 07:17:49 +11:00
benvin 027f1453d7 Merge pull request 'feat: add help, init, completion and conf-file URL resolution' (#6) from benvin/encapic-init-help into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #6
2026-11-08 17:54:06 +11:00
benvin 6e7073a830 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
2026-11-08 17:37:58 +11:00
unkin-agent 612874a0c7 fix: default init URL to the encapi FQDN the cert covers
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-11-08 17:34:55 +11:00
unkin-agent d2e9e42e20 feat: add unset-testing to restore a node's pre-testing environment
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-11-08 17:27:04 +11:00
unkin-agent 9a36da3174 fix: keep rpm conf at /etc/encapic and test silent no-config hint
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-11-08 17:22:35 +11:00
unkin-agent 70fe2858d0 feat: add help, init, completion and conf-file URL resolution
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was canceled
2026-11-08 17:19:35 +11:00
benvin 3fc5fcd9a8 Merge pull request 'ci: authenticate artifactapi rpm upload with a vault token' (#5) from benvin/artifactapi-upload-token into main
Reviewed-on: #5
2026-10-25 23:01:52 +11:00
unkin-agent 430a360177 ci: authenticate artifactapi rpm upload with a vault token
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-10-25 20:35:28 +11:00
benvin 2a63b3560e Merge pull request 'feat: add set-testing subcommand' (#4) from benvin/set-testing into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #4
2026-10-23 21:45:56 +11:00
unkin-agent b664d2f12f fix: require https VAULT_ADDR and never follow redirects in set-testing
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-10-23 21:38:43 +11:00
unkin-agent df0221bcbf fix: refuse non-https encapi URL in set-testing; cover vault CA and token errors
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
2026-10-23 21:36:38 +11:00
unkin-agent 7877f1eab6 feat: add set-testing subcommand to pin a node to testing
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was canceled
2026-10-23 21:34:07 +11:00
benvin 2800eca378 Merge pull request 'ci: switch Go steps to gobuilder, enable S3 build cache' (#3) from benvin/gocache into main
Reviewed-on: #3
2026-10-03 00:25:03 +10:00
unkin-agent b4d1b3594a ci: bump gobuilder to 0.1.3-alma9
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
0.1.2-alma9 left $GOPATH/bin off PATH, so the package step's
`go install goreleaser` succeeded but `goreleaser` exited 127.
0.1.3-alma9 sets GOPATH=/go and PATH=/go/bin:$PATH.
2026-10-03 00:18:13 +10:00
unkin-agent 5c5a069d57 ci: switch Go steps to gobuilder, enable S3 build cache
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline failed
golang:1.25/1.26 and the stale almalinux9-gobuilder pin are replaced by
gobuilder:0.1.2-alma9 on every step that invokes the Go toolchain, with
GOCACHEPROG wired to the baked-in go-cache-plugin against the shared
S3 cache bucket.

- build.yaml/test.yaml/release.yaml: build+test+goreleaser steps use
  gobuilder, cache env added
- pre-commit.yaml: switch pin, add cache (hooks run go-fmt/go-vet/go-unit-tests)
- lint step (test.yaml) and upload-rpm step left untouched
2026-10-02 23:47:35 +10:00
benvin fe44518287 Merge pull request 'Package encapic as an RPM for the VM puppet masters' (#2) from benvin/rpm-packaging into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #2
2026-09-19 18:40:41 +10:00
unkin-agent 2241ea3d72 Stop nested class parameters being parsed as classes
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
encapi's cobbler-wire document keys class parameters under the role name, and
the line-based parser treats every indented line as a class, so a node with
class params is classified with the parameter keys as extra classes.

- track the indentation of the classes block and skip deeper lines
- cover the nested form real cobbler-imported nodes return
2026-09-19 18:12:47 +10:00
unkin-agent 1e48c06bfe Package encapic as an RPM published to rpm-internal
The VM puppet masters are dnf-managed hosts moving off cobbler onto encapi,
and encapic ships only as a release binary the k8s compilers curl.

- drive the release with goreleaser, keeping the encapic_linux_amd64 asset
  and its .sha256 byte-compatible with the compiler initContainer
- build encapic-<version>-1.x86_64.rpm and PUT it to artifactapi rpm-internal
- install /usr/bin/encapic, the /usr/bin/encapic-enc ENC entrypoint and
  /etc/encapic/encapic.conf as %config(noreplace)
- add make rpm/rpm-package/pre-commit and a PR packaging check
2026-09-19 18:12:47 +10:00
benvin 75ed5e5cdf Merge pull request 'Add encapic ENC client' (#1) from benvin/initial into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #1
2026-07-25 10:18:40 +10:00
21 changed files with 1448 additions and 55 deletions
+80
View File
@@ -0,0 +1,80 @@
version: 2
project_name: encapic
builds:
- id: encapic
main: .
binary: encapic
env:
- CGO_ENABLED=0
goos:
- linux
goarch:
- amd64
flags:
- -trimpath
ldflags:
- -s -w -X main.version={{ .Version }}
archives:
# Raw binary, not an archive: the puppetserver-compiler initContainer fetches
# this exact asset name by URL and sha256-verifies it before installing it.
- id: binaries
ids: [encapic]
formats: [binary]
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}"
nfpms:
- id: encapic
ids: [encapic]
package_name: encapic
# encapic-<version>-1.x86_64.rpm
file_name_template: "{{ .ConventionalFileName }}"
vendor: unkin
homepage: https://git.unkin.net/unkin/encapic
maintainer: Ben Vincent <ben@unkin.net>
description: Puppet exec ENC client for encapi
license: MIT
formats:
- rpm
release: "1"
bindir: /usr/bin
contents:
# Puppet's exec node_terminus passes a certname and no environment, so
# external_nodes points at this shim, which sources the URL first.
- src: packaging/encapic-enc
dst: /usr/bin/encapic-enc
file_info:
mode: 0755
- 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 <artifact>.sha256 per file rather than a single checksums.txt: the
# compiler initContainer fetches encapic_linux_amd64.sha256 next to the binary.
split: true
name_template: "{{ .ArtifactName }}.sha256"
release:
gitea:
owner: unkin
name: encapic
gitea_urls:
api: https://git.unkin.net/api/v1
download: https://git.unkin.net
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
- "^chore:"
+45 -1
View File
@@ -3,7 +3,18 @@ when:
steps:
- name: build
image: golang:1.25
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- make build
backend_options:
@@ -16,3 +27,36 @@ steps:
limits:
memory: 2Gi
cpu: 2
# The release itself only runs on a tag, so validate the packaging config and
# build the artifacts (binary + RPM) here without publishing anything.
- name: package
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- git fetch --tags --force
- go install github.com/goreleaser/goreleaser/v2@v2.17.1
- goreleaser check
- goreleaser release --snapshot --clean
- ls -l dist/*.rpm dist/*.sha256
depends_on: [build]
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+12 -1
View File
@@ -3,7 +3,18 @@ when:
steps:
- name: pre-commit
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- uvx pre-commit run --all-files
backend_options:
+69 -30
View File
@@ -4,7 +4,18 @@ when:
steps:
- name: test
image: golang:1.25
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- go test -race ./...
backend_options:
@@ -18,13 +29,31 @@ steps:
memory: 2Gi
cpu: 2
# Build the static linux/amd64 binary and its checksum, both attached to the
# Gitea release. The binary is what the puppet compilers pull at pod start.
- name: build
image: golang:1.25
# goreleaser is the single driver for the release: it builds the static
# binary, builds the RPM (nfpm is built in) and creates the Gitea release
# with the binary, RPM and per-artifact sha256 files attached. The binary
# asset name is unchanged — the puppet compilers pull it at pod start.
- name: goreleaser
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GITEA_TOKEN:
from_secret: RELEASER_TOKEN
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.version=${CI_COMMIT_TAG}" -o encapic_linux_amd64 .
- sha256sum encapic_linux_amd64 > encapic_linux_amd64.sha256
# goreleaser reads the tag history for the changelog; Woodpecker's clone
# can be shallow.
- git fetch --tags --force
- go install github.com/goreleaser/goreleaser/v2@v2.17.1
- goreleaser release --clean
depends_on: [test]
backend_options:
kubernetes:
@@ -37,35 +66,45 @@ steps:
memory: 2Gi
cpu: 2
# Cut a Gitea release with the binary + checksum attached.
- name: release
# goreleaser cannot PUT to artifactapi, so the RPM it built into dist/ is
# published to the local rpm repo here (a real yum repo; repodata
# regenerates automatically).
- name: upload-rpm
image: git.unkin.net/unkin/almalinux9-base:20260606
environment:
RELEASER_TOKEN:
from_secret: RELEASER_TOKEN
commands:
- |
curl --output /usr/local/bin/tea https://artifactapi.k8s.syd1.au.unkin.net/api/v1/remote/gitea-dl/tea/0.12.0/tea-0.12.0-linux-amd64 && chmod +x /usr/local/bin/tea
tea logins add --name gitea --url https://git.unkin.net --token "$${RELEASER_TOKEN}" --no-version-check
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
if [ -n "$PREV_TAG" ]; then
NOTES=$(git log "${PREV_TAG}..${CI_COMMIT_TAG}" --pretty=format:"- %s")
else
NOTES=$(git log --pretty=format:"- %s")
fi
tea releases create --tag "${CI_COMMIT_TAG}" --title "${CI_COMMIT_TAG}" --note "${NOTES}" --login gitea --repo "${CI_REPO}"
tea releases assets create "${CI_COMMIT_TAG}" \
encapic_linux_amd64 \
encapic_linux_amd64.sha256 \
--login gitea --repo "${CI_REPO}"
depends_on: [build]
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
# the served path (RPMs are stored under Packages/) to avoid re-upload.
code=$$(curl -s -o /dev/null -w '%{http_code}' "$$HOST/api/v2/remotes/$$REPO/files/Packages/$$FILE" || true)
if [ "$$code" = "200" ]; then
echo "$$FILE already exists in $$REPO (HTTP $$code); skipping upload"
continue
fi
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 @"$$AUTH" \
--data-binary @"$$rpm"
done
depends_on: [goreleaser]
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 128Mi
cpu: 100m
limits:
memory: 512Mi
cpu: 500m
cpu: 1
limits:
memory: 2Gi
cpu: 2
+12 -1
View File
@@ -18,7 +18,18 @@ steps:
cpu: 2
- name: test
image: golang:1.25
image: "artifactapi.k8s.syd1.au.unkin.net/docker-internal/gobuilder:0.1.3-alma9"
environment:
GOCACHE_S3_BUCKET: gocache
GOCACHE_S3_REGION: us-east-1
GOCACHE_S3_ENDPOINT_URL: "https://s3.ceph.unkin.net"
GOCACHE_S3_PATH_STYLE: "true"
GOCACHE_KEY_PREFIX: ci-encapic
GOCACHEPROG: go-cache-plugin --cache-dir=/tmp/gocache
AWS_ACCESS_KEY_ID:
from_secret: GOCACHE_AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY:
from_secret: GOCACHE_AWS_SECRET_ACCESS_KEY
commands:
- go test -v -race ./...
backend_options:
+13 -1
View File
@@ -5,7 +5,7 @@ GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)"
OS ?= $(shell go env GOOS)
ARCH ?= $(shell go env GOARCH)
.PHONY: all build test lint fmt clean install patch minor major _tag
.PHONY: all build test lint fmt pre-commit clean install rpm rpm-package patch minor major _tag
all: build
@@ -22,12 +22,24 @@ lint:
fmt:
gofmt -w .
pre-commit:
uvx pre-commit run --all-files
clean:
rm -rf $(DIST) $(BINARY)
install:
go install $(GOFLAGS) .
# Build every release artifact locally without publishing: the raw binary the
# puppet compilers fetch, and the RPM the VM masters install.
rpm: rpm-package
# goreleaser drives the build and the nfpm packaging in one pass, so packaging
# an already-built binary is not a separate step.
rpm-package:
goreleaser release --snapshot --clean
# Bump helpers — read the latest semver tag and create the next one.
# If no tag exists yet, start from v0.0.0.
_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1)
+80 -4
View File
@@ -25,10 +25,64 @@ 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`
```
encapic set-testing <certname>
```
Sets the node's environment to `testing` in encapi (requires the encapi
oidc-auth release). A `testing` node's ENC omits `environment`, so any
`puppet agent --environment X` is honoured; the host stays in `testing` until
the next terragrunt-enc apply resets it.
It mints a JWT from `${VAULT_ADDR}/v1/identity/oidc/token/${ENCAPI_OIDC_ROLE}`
(defaults `https://vault.service.consul:8200`, `encapi-testing`) using
`VAULT_TOKEN` or `~/.vault-token`, trusting `VAULT_CACERT` when set, then
`PUT`s `{"environment":"testing"}` to
`${ENCAPI_URL}/api/v1/nodes/<certname>/environment`. `ENCAPI_URL` and
`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:
@@ -69,8 +123,30 @@ make build # static binary into dist/
make test # go test -v -race ./...
make lint # golangci-lint
make fmt # gofmt -w .
make rpm # binary + RPM into dist/ via goreleaser, publishing nothing
```
Release: `make minor` (etc.) tags `vX.Y.Z` and pushes it; the `release`
Woodpecker pipeline builds `encapic_linux_amd64` (+ `.sha256`) and attaches
them to a Gitea release.
Woodpecker pipeline runs goreleaser, which attaches `encapic_linux_amd64`
(+ `.sha256`) and the RPM to a Gitea release, and then publishes the RPM to the
artifactapi `rpm-internal` yum repo.
## Installation
The kubernetes compilers fetch `encapic_linux_amd64` from the Gitea release in
an initContainer and install it to `/opt/bin/encapic`.
The VM puppet masters install the RPM from `rpm-internal`:
```
dnf install encapic
```
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 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.
+65
View File
@@ -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
}
+73
View File
@@ -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)
}
}
+15
View File
@@ -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
+11
View File
@@ -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
+155
View File
@@ -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
View File
@@ -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)
}
}
+37 -11
View File
@@ -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,19 +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 {
return fmt.Errorf("usage: %s <certname>", args[0])
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) == 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 {
+21
View File
@@ -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 {
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Puppet's exec node_terminus invokes external_nodes with a certname and no
# environment, so the encapi URL cannot be inherited; source it here instead.
set -eu
if [ -r /etc/encapi/encapic.conf ]; then
. /etc/encapi/encapic.conf
fi
if [ -n "${ENCAPI_URL:-}" ]; then
export ENCAPI_URL
fi
exec /usr/bin/encapic "$@"
+15 -6
View File
@@ -81,6 +81,10 @@ func parseClasses(lines []string, i int, inline string) ([]string, int, error) {
}
var classes []string
// Entries of the block sit at one indentation level. A class's value may
// itself be a nested block (class parameters, which encapi emits keyed by
// role name), whose deeper lines are values, not class names.
entryIndent := -1
j := i + 1
for ; j < len(lines); j++ {
line := lines[j]
@@ -88,18 +92,23 @@ func parseClasses(lines []string, i int, inline string) ([]string, int, error) {
continue
}
trimmed := strings.TrimSpace(line)
indent := len(line) - len(strings.TrimLeft(line, " \t"))
// An unindented, non-list line is the next top-level key, so stop.
if indent == 0 && !strings.HasPrefix(trimmed, "-") {
break
}
if entryIndent < 0 {
entryIndent = indent
}
if indent > entryIndent {
continue
}
if strings.HasPrefix(trimmed, "- ") || trimmed == "-" {
// Block list form, at either the parent indent ("- roles::base",
// as yaml.dump emits) or nested (" - roles::base").
classes = append(classes, unquote(strings.TrimSpace(trimmed[1:])))
continue
}
// An indented, non-list line is a nested map entry belonging to
// classes (" roles::base: {}"). An unindented, non-list line is the
// next top-level key, so stop.
if line[0] != ' ' && line[0] != '\t' {
break
}
name, _, ok := splitKV(trimmed)
if !ok {
return nil, 0, fmt.Errorf("unexpected classes entry: %q", line)
+53
View File
@@ -0,0 +1,53 @@
package main
import "testing"
// Nodes imported from cobbler carry class parameters, which encapi emits as a
// nested block under the role name. ausyd1nxvm2020/2021/2022 carry the role
// name as its own class parameter, so a line-based parser that treats every
// indented line as a class name emits the role twice.
func TestParseClassesNestedBlockIsOneClass(t *testing.T) {
body := []byte("classes:\n" +
" roles::infra::proxy::jumphost:\n" +
" roles::infra::proxy::jumphost: '~'\n" +
"environment: develop\n" +
"parameters: {}\n")
doc, err := parseCobbler(body)
if err != nil {
t.Fatalf("parseCobbler returned error: %v", err)
}
want := []string{"roles::infra::proxy::jumphost"}
if len(doc.classes) != len(want) || doc.classes[0] != want[0] {
t.Errorf("classes = %q, want %q", doc.classes, want)
}
if doc.environment != "develop" {
t.Errorf("environment = %q, want develop", doc.environment)
}
}
// The same shape with ordinary class parameters: the parameter keys are values
// of the class, never classes themselves.
func TestParseClassesNestedParamsAreNotClasses(t *testing.T) {
body := []byte("classes:\n" +
" roles::base:\n" +
" listen_port: 8140\n" +
" tls: true\n" +
" roles::infra::dns::master: {}\n" +
"environment: production\n" +
"parameters: {}\n")
doc, err := parseCobbler(body)
if err != nil {
t.Fatalf("parseCobbler returned error: %v", err)
}
want := []string{"roles::base", "roles::infra::dns::master"}
if len(doc.classes) != len(want) {
t.Fatalf("classes = %q, want %q", doc.classes, want)
}
for i := range want {
if doc.classes[i] != want[i] {
t.Errorf("classes[%d] = %q, want %q", i, doc.classes[i], want[i])
}
}
}
+180
View File
@@ -0,0 +1,180 @@
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
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 nil, err
}
client, err := vaultClient()
if err != nil {
return nil, err
}
jwt, err := mintToken(client)
if err != nil {
return nil, err
}
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 nil, err
}
req.Header.Set("Authorization", "Bearer "+jwt)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
return do(client, req)
}
func mintToken(client *http.Client) (string, error) {
addr := os.Getenv("VAULT_ADDR")
if addr == "" {
addr = defaultVaultAddr
}
if err := requireHTTPS("VAULT_ADDR", addr); err != nil {
return "", err
}
role := os.Getenv("ENCAPI_OIDC_ROLE")
if role == "" {
role = "encapi-testing"
}
vaultToken, err := readVaultToken()
if err != nil {
return "", err
}
req, err := http.NewRequest(http.MethodGet, strings.TrimRight(addr, "/")+"/v1/identity/oidc/token/"+url.PathEscape(role), nil)
if err != nil {
return "", err
}
req.Header.Set("X-Vault-Token", vaultToken)
body, err := do(client, req)
if err != nil {
return "", err
}
var resp struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
if err := json.Unmarshal(body, &resp); err != nil {
return "", fmt.Errorf("decode vault token response: %w", err)
}
if resp.Data.Token == "" {
return "", errors.New("vault returned no OIDC token")
}
return resp.Data.Token, nil
}
func requireHTTPS(name, raw string) error {
if parsed, err := url.Parse(raw); err != nil || parsed.Scheme != "https" {
return fmt.Errorf("encapic requires an https %s, got %q", name, raw)
}
return nil
}
func readVaultToken() (string, error) {
if t := os.Getenv("VAULT_TOKEN"); t != "" {
return t, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
b, err := os.ReadFile(filepath.Join(home, ".vault-token"))
if err != nil {
return "", fmt.Errorf("no VAULT_TOKEN and cannot read ~/.vault-token: %w", err)
}
return strings.TrimSpace(string(b)), nil
}
func vaultClient() (*http.Client, error) {
client := &http.Client{
Timeout: httpTimeout,
// Never follow redirects: they would re-send the vault token or JWT.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
caFile := os.Getenv("VAULT_CACERT")
if caFile == "" {
return client, nil
}
pem, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read VAULT_CACERT: %w", err)
}
pool, err := x509.SystemCertPool()
if err != nil {
pool = x509.NewCertPool()
}
if !pool.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("no certificates in VAULT_CACERT %s", caFile)
}
client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12},
}
return client, nil
}
func do(client *http.Client, req *http.Request) ([]byte, error) {
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", req.Method, req.URL, err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response from %s: %w", req.URL, err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s returned HTTP %d: %s",
req.Method, req.URL, resp.StatusCode, strings.TrimSpace(string(body)))
}
return body, nil
}
+258
View File
@@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/pem"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func fakeVault(t *testing.T, status int, body string) *httptest.Server {
t.Helper()
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/v1/identity/oidc/token/encapi-testing" {
http.NotFound(w, r)
return
}
if r.Header.Get("X-Vault-Token") != "vt" {
http.Error(w, `{"errors":["permission denied"]}`, http.StatusForbidden)
return
}
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}))
t.Cleanup(srv.Close)
trustServer(t, srv)
return srv
}
type seenPut struct{ path, auth, body string }
func fakeEncapi(t *testing.T, status int, seen *seenPut) *httptest.Server {
t.Helper()
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if r.Method == http.MethodPut {
*seen = seenPut{r.URL.Path, r.Header.Get("Authorization"), string(b)}
}
w.WriteHeader(status)
_, _ = io.WriteString(w, `{"error":"forbidden"}`)
}))
t.Cleanup(srv.Close)
trustServer(t, srv)
return srv
}
// trustServer points VAULT_CACERT at the TLS server's certificate; all
// httptest TLS servers share one certificate, so this trusts both fakes.
func trustServer(t *testing.T, srv *httptest.Server) {
t.Helper()
path := filepath.Join(t.TempDir(), "ca.pem")
b := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw})
if err := os.WriteFile(path, b, 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("VAULT_CACERT", path)
}
func TestSetTestingSuccess(t *testing.T) {
var seen seenPut
t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL)
t.Setenv("VAULT_TOKEN", "vt")
t.Setenv("ENCAPI_URL", fakeEncapi(t, 200, &seen).URL)
var out bytes.Buffer
if err := run([]string{"encapic", "set-testing", "host.example"}, &out); err != nil {
t.Fatalf("run: %v", err)
}
want := seenPut{"/api/v1/nodes/host.example/environment", "Bearer jwt123", `{"environment":"testing"}`}
if seen != want {
t.Errorf("PUT = %+v, want %+v", seen, want)
}
}
func TestSetTestingVaultTokenFile(t *testing.T) {
var seen seenPut
home := t.TempDir()
if err := os.WriteFile(filepath.Join(home, ".vault-token"), []byte("vt\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", home)
t.Setenv("VAULT_TOKEN", "")
t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL)
t.Setenv("ENCAPI_URL", fakeEncapi(t, 204, &seen).URL)
if err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard); err != nil {
t.Fatalf("run: %v", err)
}
if seen.auth != "Bearer jwt123" {
t.Errorf("auth = %q", seen.auth)
}
}
func TestSetTestingVaultError(t *testing.T) {
var seen seenPut
t.Setenv("VAULT_ADDR", fakeVault(t, 400, `{"errors":["role not found"]}`).URL)
t.Setenv("VAULT_TOKEN", "vt")
t.Setenv("ENCAPI_URL", fakeEncapi(t, 200, &seen).URL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "HTTP 400") || !strings.Contains(err.Error(), "role not found") {
t.Fatalf("err = %v, want HTTP 400 with body", err)
}
if seen.path != "" {
t.Errorf("encapi called despite vault failure: %+v", seen)
}
}
func TestSetTestingEncapiForbidden(t *testing.T) {
var seen seenPut
t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL)
t.Setenv("VAULT_TOKEN", "vt")
t.Setenv("ENCAPI_URL", fakeEncapi(t, 403, &seen).URL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "HTTP 403") || !strings.Contains(err.Error(), "forbidden") {
t.Fatalf("err = %v, want HTTP 403 with body", err)
}
}
func TestSetTestingRefusesPlainHTTP(t *testing.T) {
vaultHit := false
vault := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { vaultHit = true }))
t.Cleanup(vault.Close)
t.Setenv("VAULT_ADDR", vault.URL)
t.Setenv("VAULT_TOKEN", "vt")
for _, encapiURL := range []string{"http://encapi.example", "", "encapi.example", "://bad"} {
t.Setenv("ENCAPI_URL", encapiURL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "requires an https ENCAPI_URL") {
t.Errorf("ENCAPI_URL=%q: err = %v, want https refusal", encapiURL, err)
}
}
if vaultHit {
t.Error("vault called despite non-https ENCAPI_URL")
}
}
func TestSetTestingRefusesPlainHTTPVault(t *testing.T) {
vaultHit := false
vault := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { vaultHit = true }))
t.Cleanup(vault.Close)
var seen seenPut
t.Setenv("ENCAPI_URL", fakeEncapi(t, 200, &seen).URL)
t.Setenv("VAULT_TOKEN", "vt")
for _, addr := range []string{vault.URL, "vault.example:8200", "://bad"} {
t.Setenv("VAULT_ADDR", addr)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "requires an https VAULT_ADDR") {
t.Errorf("VAULT_ADDR=%q: err = %v, want https refusal", addr, err)
}
}
if vaultHit || seen.path != "" {
t.Errorf("request sent despite non-https VAULT_ADDR: vault=%v encapi=%+v", vaultHit, seen)
}
}
func TestSetTestingDoesNotFollowRedirect(t *testing.T) {
var hits []string
encapi := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits = append(hits, r.URL.Path+" "+r.Header.Get("Authorization"))
http.Redirect(w, r, "/elsewhere", http.StatusTemporaryRedirect)
}))
t.Cleanup(encapi.Close)
t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL)
t.Setenv("VAULT_TOKEN", "vt")
t.Setenv("ENCAPI_URL", encapi.URL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "HTTP 307") {
t.Fatalf("err = %v, want HTTP 307", err)
}
if len(hits) != 1 {
t.Errorf("encapi requests = %v, want exactly one", hits)
}
}
func TestSetTestingVaultNoToken(t *testing.T) {
for _, body := range []string{`{"data":{"token":""}}`, `{"data":{}}`, `{}`} {
var seen seenPut
t.Setenv("VAULT_ADDR", fakeVault(t, 200, body).URL)
t.Setenv("VAULT_TOKEN", "vt")
t.Setenv("ENCAPI_URL", fakeEncapi(t, 200, &seen).URL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "no OIDC token") {
t.Errorf("body %s: err = %v, want no OIDC token", body, err)
}
if seen.path != "" {
t.Errorf("body %s: encapi called: %+v", body, seen)
}
}
}
func TestSetTestingNoVaultToken(t *testing.T) {
var seen seenPut
t.Setenv("HOME", t.TempDir())
t.Setenv("VAULT_TOKEN", "")
t.Setenv("VAULT_ADDR", fakeVault(t, 200, `{"data":{"token":"jwt123"}}`).URL)
t.Setenv("ENCAPI_URL", fakeEncapi(t, 200, &seen).URL)
err := run([]string{"encapic", "set-testing", "host.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "no VAULT_TOKEN and cannot read ~/.vault-token") {
t.Fatalf("err = %v, want missing vault token", err)
}
if seen.path != "" {
t.Errorf("encapi called: %+v", seen)
}
}
func TestVaultClientCACertUnreadable(t *testing.T) {
t.Setenv("VAULT_CACERT", filepath.Join(t.TempDir(), "missing.pem"))
if _, err := vaultClient(); err == nil || !strings.Contains(err.Error(), "read VAULT_CACERT") {
t.Fatalf("err = %v, want read VAULT_CACERT", err)
}
}
func TestVaultClientCACertNoPEM(t *testing.T) {
path := filepath.Join(t.TempDir(), "ca.pem")
if err := os.WriteFile(path, []byte("not a certificate\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("VAULT_CACERT", path)
if _, err := vaultClient(); err == nil || !strings.Contains(err.Error(), "no certificates in VAULT_CACERT") {
t.Fatalf("err = %v, want no certificates", err)
}
}
func TestVaultClientCACertTrustsServer(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
t.Cleanup(srv.Close)
t.Setenv("VAULT_CACERT", "")
plain, err := vaultClient()
if err != nil {
t.Fatal(err)
}
if _, err := plain.Get(srv.URL); err == nil {
t.Fatal("untrusted TLS server accepted without VAULT_CACERT")
}
trustServer(t, srv)
client, err := vaultClient()
if err != nil {
t.Fatalf("vaultClient: %v", err)
}
resp, err := client.Get(srv.URL)
if err != nil {
t.Fatalf("GET with VAULT_CACERT: %v", err)
}
_ = resp.Body.Close()
}
+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)
}
}