Compare commits
11 Commits
benvin/initial
...
v0.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 2a63b3560e | |||
| b664d2f12f | |||
| df0221bcbf | |||
| 7877f1eab6 | |||
| 2800eca378 | |||
| b4d1b3594a | |||
| 5c5a069d57 | |||
| fe44518287 | |||
| 2241ea3d72 | |||
| 1e48c06bfe | |||
| 75ed5e5cdf |
@@ -0,0 +1,79 @@
|
||||
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
|
||||
# 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"
|
||||
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
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
+62
-30
@@ -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,38 @@ 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"
|
||||
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: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 512Mi
|
||||
cpu: 500m
|
||||
cpu: 1
|
||||
limits:
|
||||
memory: 2Gi
|
||||
cpu: 2
|
||||
|
||||
+12
-1
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -29,6 +29,25 @@ exec `node_terminus` fails safe rather than compiling an empty catalog.
|
||||
`http://encapi.encapi.svc.cluster.local` (the in-cluster service).
|
||||
- The HTTP request has a 10s timeout.
|
||||
|
||||
### 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.
|
||||
|
||||
## Behaviour (drop-in for the python ENC)
|
||||
|
||||
encapic reproduces the previous python script byte-for-byte:
|
||||
@@ -69,8 +88,33 @@ 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 three paths:
|
||||
|
||||
- `/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.
|
||||
|
||||
@@ -58,8 +58,11 @@ func run(args []string, out io.Writer) error {
|
||||
_, err := fmt.Fprintf(out, "encapic %s\n", version)
|
||||
return err
|
||||
}
|
||||
if len(args) == 3 && args[1] == "set-testing" {
|
||||
return setTesting(args[2], out)
|
||||
}
|
||||
if len(args) != 2 {
|
||||
return fmt.Errorf("usage: %s <certname>", args[0])
|
||||
return fmt.Errorf("usage: %s <certname> | %s set-testing <certname>", args[0], args[0])
|
||||
}
|
||||
certname := args[1]
|
||||
|
||||
|
||||
Executable
+13
@@ -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/encapic/encapic.conf ]; then
|
||||
. /etc/encapic/encapic.conf
|
||||
fi
|
||||
if [ -n "${ENCAPI_URL:-}" ]; then
|
||||
export ENCAPI_URL
|
||||
fi
|
||||
|
||||
exec /usr/bin/encapic "$@"
|
||||
@@ -0,0 +1,4 @@
|
||||
# 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
|
||||
@@ -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)
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"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 {
|
||||
baseURL := os.Getenv("ENCAPI_URL")
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBaseURL
|
||||
}
|
||||
if err := requireHTTPS("ENCAPI_URL", baseURL); err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := vaultClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
jwt, err := mintToken(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u := strings.TrimRight(baseURL, "/") + "/api/v1/nodes/" + url.PathEscape(certname) + "/environment"
|
||||
req, err := http.NewRequest(http.MethodPut, u, bytes.NewBufferString(`{"environment":"testing"}`))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+jwt)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if _, err := do(client, req); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintf(out, "%s set to testing\n", certname)
|
||||
return err
|
||||
}
|
||||
|
||||
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("set-testing 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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user