14 Commits

Author SHA1 Message Date
benvin 7da4d453a1 Merge pull request 'Add GitHub Actions CI and GoReleaser release' (#9) from benvin/github-actions into main
ci / pre-commit (push) Has been cancelled
ci / lint (push) Has been cancelled
ci / test (push) Has been cancelled
ci / build (push) Has been cancelled
Reviewed-on: #9
2026-11-20 23:11:40 +11:00
unkin-agent 69c0894184 Skip signing in Woodpecker snapshot build
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci / pre-commit (pull_request) Has been cancelled
ci / lint (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
ci / build (pull_request) Has been cancelled
2026-11-20 22:16:01 +11:00
unkin-agent 9b3b9f0330 Update release notes in README
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline failed
ci / pre-commit (pull_request) Has been cancelled
ci / lint (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
ci / build (pull_request) Has been cancelled
2026-11-20 22:13:18 +11:00
unkin-agent c4990259c8 Add GitHub Actions CI and GoReleaser release
ci/woodpecker/pr/pre-commit Pipeline was successful
ci / pre-commit (pull_request) Has been cancelled
ci / lint (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled
ci / build (pull_request) Has been cancelled
ci/woodpecker/pr/build Pipeline was canceled
ci/woodpecker/pr/test Pipeline was canceled
2026-11-20 22:12:30 +11:00
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
21 changed files with 828 additions and 165 deletions
+1
View File
@@ -0,0 +1 @@
* @IUCLabs/maintainers
+66
View File
@@ -0,0 +1,66 @@
name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
pre-commit:
runs-on: iuclabs-k8s
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: go.mod
- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
- run: uvx pre-commit run --all-files --show-diff-on-failure
lint:
runs-on: iuclabs-k8s
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: go.mod
- uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v9.3.0
with:
version: v2.15.0
test:
runs-on: iuclabs-k8s
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: go.mod
# runner image has no C toolchain, so no -race
- run: go test -count=1 ./...
build:
runs-on: iuclabs-k8s
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: go.mod
- run: go build -trimpath -ldflags="-s -w" ./...
- uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0
with:
distribution: goreleaser
version: v2.20.2
args: check
- uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0
with:
distribution: goreleaser
version: v2.20.2
args: release --snapshot --clean --skip=sign,publish
+38
View File
@@ -0,0 +1,38 @@
name: release
on:
push:
tags: ["v*"]
permissions:
contents: write
id-token: write
env:
VAULT_ADDR: https://vault.service.consul:8200
jobs:
release:
runs-on: iuclabs-release
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
- uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
with:
go-version-file: go.mod
- uses: hashicorp/vault-action@892a26828f195e65540a40b4768ae4571f51ebfc # v4.0.0
with:
url: ${{ env.VAULT_ADDR }}
method: jwt
path: jwt/github/iuclabs
role: release
jwtGithubAudience: ${{ env.VAULT_ADDR }}
exportToken: true
- uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0
with:
distribution: goreleaser
version: v2.20.2
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+10 -13
View File
@@ -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
@@ -61,14 +62,10 @@ checksum:
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
signs:
- artifacts: checksum
cmd: scripts/sign.sh
args: ["${artifact}", "${signature}"]
changelog:
sort: asc
+1 -1
View File
@@ -47,7 +47,7 @@ steps:
- git fetch --tags --force
- go install github.com/goreleaser/goreleaser/v2@v2.17.1
- goreleaser check
- goreleaser release --snapshot --clean
- goreleaser release --snapshot --clean --skip=sign
- ls -l dist/*.rpm dist/*.sha256
depends_on: [build]
backend_options:
-103
View File
@@ -1,103 +0,0 @@
when:
- event: tag
ref: refs/tags/v*
steps:
- name: test
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:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
# 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:
# 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:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
# 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
commands:
- |
HOST="https://artifactapi.k8s.syd1.au.unkin.net"
REPO="rpm-internal"
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" \
--data-binary @"$$rpm"
done
depends_on: [goreleaser]
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+1 -1
View File
@@ -38,7 +38,7 @@ 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
GOTOOLCHAIN=auto go run github.com/goreleaser/goreleaser/v2@v2.20.2 release --snapshot --clean --skip=sign
# Bump helpers — read the latest semver tag and create the next one.
# If no tag exists yet, start from v0.0.0.
+45 -13
View File
@@ -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:
@@ -91,10 +126,10 @@ 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 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.
Release: `make minor` (etc.) tags `vX.Y.Z` and pushes it; the tag mirrors to
GitHub, where the `release` workflow runs goreleaser, which attaches
`encapic_linux_amd64` and the RPM (each with a signed `.sha256`) to the GitHub
release.
## Installation
@@ -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.
+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)
}
}
+34 -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,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 {
+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 {
+2 -2
View File
@@ -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
-4
View File
@@ -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
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Detached binary signature of $1 into $2 via the Vault gpg engine.
set -euo pipefail
b=$(base64 -w0 "$1")
jq -n --arg input "$b" '{input: $input, format: "base64"}' \
| curl -sSf --cacert "${VAULT_CACERT:-/etc/vault-ca/ca.crt}" \
-H "X-Vault-Token: ${VAULT_TOKEN}" -d @- \
"${VAULT_ADDR}/v1/gpg/sign/iuclabs-release" \
| jq -er .data.signature | base64 -d > "$2"
+40 -17
View File
@@ -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
}
+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)
}
}