From 8e6c8e594be0fb7e28f25a19895279609625639b Mon Sep 17 00:00:00 2001 From: Kanstantsin Buklis Date: Wed, 28 Oct 2026 14:12:39 +0100 Subject: [PATCH] test: Create Local Infrastructure for Scanner Testing Signed-off-by: Kanstantsin Buklis --- Makefile | 71 +++++++ README.md | 6 + docs/local-environment.md | 129 +++++++++++++ go.sum | 4 +- local/kind/.gitignore | 3 + local/kind/cluster.yaml | 12 ++ scanner/keppel/go.mod | 2 +- scanner/keppel/mock/fixtures.go | 76 ++++++++ scanner/keppel/mock/fixtures_test.go | 71 +++++++ scanner/keppel/mock/keppel.go | 179 ++++++++++++++++++ scanner/keppel/mock/keystone.go | 70 +++++++ scanner/keppel/mock/main.go | 57 ++++++ scanner/keppel/mock/record.go | 125 ++++++++++++ scanner/keppel/mock/serve.go | 37 ++++ .../keppel/mock/testdata/fixtures/.gitkeep | 3 + scanner/keppel/mock/tlscert.go | 55 ++++++ scanner/keppel/models/models.go | 28 ++- .../templates/serviceaccount.yaml | 2 +- 18 files changed, 919 insertions(+), 11 deletions(-) create mode 100644 docs/local-environment.md create mode 100644 local/kind/.gitignore create mode 100644 local/kind/cluster.yaml create mode 100644 scanner/keppel/mock/fixtures.go create mode 100644 scanner/keppel/mock/fixtures_test.go create mode 100644 scanner/keppel/mock/keppel.go create mode 100644 scanner/keppel/mock/keystone.go create mode 100644 scanner/keppel/mock/main.go create mode 100644 scanner/keppel/mock/record.go create mode 100644 scanner/keppel/mock/serve.go create mode 100644 scanner/keppel/mock/testdata/fixtures/.gitkeep create mode 100644 scanner/keppel/mock/tlscert.go diff --git a/Makefile b/Makefile index c6081a2de..00a3cd362 100644 --- a/Makefile +++ b/Makefile @@ -188,3 +188,74 @@ openfga-up: openfga-down: $(DOCKER_COMPOSE) --profile openfga down + +# --------------------------------------------------------------------------- +# Local scanner development environment (kind + keppel mock). +# See docs/local-environment.md for the full workflow. +# --------------------------------------------------------------------------- +KIND_CLUSTER := heureka-local +KIND_CONTEXT := kind-$(KIND_CLUSTER) +KIND_CONFIG := local/kind/cluster.yaml +KIND_KUBECONFIG := $(CURDIR)/local/kind/kubeconfig +PLAYGROUND_CHART := ./scanner/playground/k8s-playground + +.PHONY: kind-up kind-down playground-up playground-down scan-k8s-assets-local keppel-mock-up keppel-mock-record scan-keppel-local local-up local-down + +# Create the kind cluster and export its kubeconfig to a fixed, git-ignored path. +kind-up: + kind create cluster --config $(KIND_CONFIG) + kind export kubeconfig --name $(KIND_CLUSTER) --kubeconfig $(KIND_KUBECONFIG) + +kind-down: + kind delete cluster --name $(KIND_CLUSTER) + +# Install the sample namespaces/pods the k8s-assets scanner scans. +playground-up: + helm upgrade --install k8s-playground $(PLAYGROUND_CHART) --kube-context $(KIND_CONTEXT) + +playground-down: + helm uninstall k8s-playground --kube-context $(KIND_CONTEXT) + +# Run the k8s-assets scanner on the host against the kind cluster, reporting to +# the docker-compose heureka backend. Requires: kind-up, playground-up, compose-up. +scan-k8s-assets-local: + cd scanner/k8s-assets && \ + KUBE_CONFIG_TYPE=default \ + KUBE_CONFIG_PATH=$(KIND_KUBECONFIG) \ + HEUREKA_URL=http://localhost/query \ + HEUREKA_CLUSTER_NAME=local-kind \ + HEUREKA_CLUSTER_REGION=local \ + DEFAULT_KEPPEL_REGISTRY=keppel.example.com \ + LOG_LEVEL=debug \ + go run . + +# Start the keppel mock (Keystone on :8080 HTTP, Keppel on :8443 HTTPS). +# Runs in the foreground; use a separate terminal. +keppel-mock-up: + cd scanner/keppel/mock && go run . + +# Refresh the mock's fixtures from a real Keppel. Requires real KEPPEL_* creds +# plus RECORD_IDENTITY_UPSTREAM and RECORD_KEPPEL_UPSTREAM in the environment. +keppel-mock-record: + cd scanner/keppel/mock && KEPPEL_RECORD=1 go run . + +# Run the keppel scanner on the host against the local mock, reporting to the +# docker-compose heureka backend. Requires: keppel-mock-up, compose-up, and +# image-shaped components in heureka (run scan-k8s-assets-local first). +scan-keppel-local: + cd scanner/keppel && \ + KEPPEL_FQDN=localhost:8443 \ + KEPPEL_FQDN_ALIASES=docker.io \ + IDENTITY_ENDPOINT=http://localhost:8080/v3 \ + KEPPEL_USERNAME=dummy KEPPEL_PASSWORD=dummy KEPPEL_USER_DOMAIN=dummy \ + KEPPEL_DOMAIN=dummy KEPPEL_PROJECT=dummy \ + HEUREKA_URL=http://localhost/query \ + LOG_LEVEL=debug \ + go run . + +# Bring the whole local environment up (backend + cluster + sample workloads). +local-up: compose-prepare compose-up kind-up playground-up + +# Tear it down WITHOUT deleting the DB (deliberately not `make stop`/`clean`). +local-down: playground-down kind-down compose-down + diff --git a/README.md b/README.md index f773f7749..e448241ed 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,12 @@ The application can be started by using the provided Makefile: make start-all-heureka ``` +### Local scanner environment + +To run and test the `k8s-assets` and `keppel` scanners locally against a +[kind](https://kind.sigs.k8s.io/) cluster and an in-repo keppel mock (no remote cluster or +registry needed), see [docs/local-environment.md](./docs/local-environment.md). + ### Devcontainers Devcontainers is a new standard for development environments based on (docker) diff --git a/docs/local-environment.md b/docs/local-environment.md new file mode 100644 index 000000000..307895306 --- /dev/null +++ b/docs/local-environment.md @@ -0,0 +1,129 @@ +# Local environment for running & testing scanners + +This guide lets you run the **k8s-assets** and **keppel** scanners end-to-end on your +laptop — no remote cluster or registry required. Both scanners report into a local +heureka backend running in docker-compose. + +- **k8s-assets** scans a Kubernetes cluster. Locally we use a [kind](https://kind.sigs.k8s.io/) + cluster seeded with sample workloads from the existing `scanner/playground` Helm chart. +- **keppel** is *not* a Kubernetes scanner — it is an HTTP client for a Keppel image + registry fronted by OpenStack Keystone. Locally we point it at an in-repo **mock** + (`scanner/keppel/mock`) that emulates Keystone v3 auth and the Keppel endpoints. + +## Prerequisites + +- Docker, [`kind`](https://kind.sigs.k8s.io/), [`helm`](https://helm.sh/), `go` (version per + the scanner modules), and a free set of ports: `:80` (heureka), `:3306` (MariaDB), + `:6379` (valkey), `:8080`/`:8443` (keppel mock). + +## 1. Start the backend + cluster + +```bash +make local-up +``` + +This runs `compose-prepare` + `compose-up` (heureka + MariaDB + valkey, GraphQL at +`http://localhost/query`, playground at `http://localhost/playground`), then `kind-up` +(creates the `heureka-local` cluster and exports its kubeconfig to +`local/kind/kubeconfig`) and `playground-up` (installs the sample namespaces/pods). + +> There is **no auth locally** — the compose backend sets no `AUTH_TOKEN_SECRET`, and the +> scanners never send an API token. `HEUREKA_API_TOKEN` is a no-op here. + +## 2. Run the k8s-assets scanner + +```bash +make scan-k8s-assets-local +``` + +Runs the scanner on the host (`KUBE_CONFIG_TYPE=default`) against the kind kubeconfig and +reports to local heureka. Image pulls into kind are **not** required — the scan reads pod +specs even if pods are in `ImagePullBackOff`. + +Verify in the GraphQL playground (`http://localhost/playground`): a completed +`scannerRuns` entry tagged `k8s-assets-local-kind`, and `services` / `componentInstances` +/ `components` populated from the playground pods (nginx, mariadb, mongo, redis, nats, httpd). + +## 3. Run the keppel scanner + +The keppel scanner only looks at **components that already exist in heureka**, so run +k8s-assets first (step 2) to create image-shaped components. + +In one terminal, start the mock: + +```bash +make keppel-mock-up # Keystone :8080 (http), Keppel :8443 (https, self-signed) +``` + +In another terminal, run the scanner against it: + +```bash +make scan-keppel-local +``` + +Verify: a completed `scannerRuns` entry tagged `Keppel`, and `componentVersions` / +`issueMatches` carrying the mock's CVEs (e.g. `CVE-2021-44228`). + +## 4. Tear down + +```bash +make local-down # preserves the local DB +``` + +Use `local-down` (or `compose-down`) — **not** `make stop` or `make clean`, which delete +`./.db/data` / compose volumes and wipe your scanned data. + +## How the keppel mock stays in sync with the real API + +The mock is a Go program **inside the keppel module** (`scanner/keppel/mock`), so it imports +the scanner's own response structs from `scanner/keppel/models`. Three layers keep it honest: + +1. **Compile-time coupling.** Responses are built from `models` structs and the upstream + trivy types — a breaking change to those types is a compile error in the mock. +2. **CI drift guard.** `fixtures_test.go` asserts the built-in responses round-trip and that + any committed override fixture still unmarshals into its model type. Run with + `cd scanner/keppel && go test ./mock/...`. +3. **Record mode.** When the real API changes and you have staging credentials, refresh the + fixtures from reality: + + ```bash + cd scanner/keppel/mock + KEPPEL_RECORD=1 \ + RECORD_IDENTITY_UPSTREAM=https://identity.staging.example.com \ + RECORD_KEPPEL_UPSTREAM=https://keppel.staging.example.com \ + KEPPEL_USERNAME=... KEPPEL_PASSWORD=... KEPPEL_USER_DOMAIN=... \ + KEPPEL_DOMAIN=... KEPPEL_PROJECT=... \ + go run . # (or: make keppel-mock-record with the same env) + ``` + + Then point the keppel scanner at the mock and run it once (step 3). Each Keppel response + is written to `scanner/keppel/mock/testdata/fixtures/.json`; commit the updated + `models.go` (if any) together with the refreshed fixtures. + + Update workflow: edit `models.go` if the shape changed → `go test ./mock/...` (fails on + drift) → `make keppel-mock-record` (or hand-edit fixtures) → re-run the test → commit. + +When no override fixture is present, the mock serves a built-in default; an override file +takes precedence. Manifest response headers (`X-Keppel-Vulnerability-Status`, +`Docker-Content-Digest`) are set statically in serve mode. + +## Notes & gotchas + +- **TLS asymmetry**: Keystone (`IDENTITY_ENDPOINT`) is plain HTTP because gophercloud + verifies TLS there; Keppel (`https://$KEPPEL_FQDN`) is HTTPS self-signed because the + scanner skips verification only for its own Keppel client. +- The keppel Helm chart's CronJob has a placeholder `args` (`date; echo Hello…`) that + overrides the real command, so you can't fall back to in-cluster Jobs without fixing it — + host `go run` (the flow above) avoids this. +- `KUBE_CONFIG_CONTEXT` is ignored with `KUBE_CONFIG_TYPE=default`; the kind kubeconfig's + current-context (set by `kind export kubeconfig`) is what matters. +- **Rebuild the backend after pulling GraphQL schema changes**: the compose `heureka-app` + image bakes in the generated schema, so after a rebase that adds fields (e.g. + `ComponentVersion.latestVersion`) run `make compose-build && make compose-restart` or the + scanner's mutations will fail against the stale running server. (Restart re-seeds the DB + when `SEED_MODE=true`, so re-run the scanners afterwards.) +- **`scan-keppel-local` sets `KEPPEL_FQDN_ALIASES=docker.io`** so the scanner's `OwnsRegistry` + check passes for the `docker.io/*` components created by k8s-assets — that's what exercises + the available-version-update feature (`ListTags` → highest semver). The mock's `_manifests` + listing returns tags `1.0.0 / 2.0.5 / 2.3.1 / latest`, so `latestVersion` becomes `2.3.1`. + diff --git a/go.sum b/go.sum index ad2f41b74..9e4f1904e 100644 --- a/go.sum +++ b/go.sum @@ -376,8 +376,8 @@ google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1: google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= -google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/local/kind/.gitignore b/local/kind/.gitignore new file mode 100644 index 000000000..5d669f4b0 --- /dev/null +++ b/local/kind/.gitignore @@ -0,0 +1,3 @@ +# The kubeconfig exported by `kind export kubeconfig` is machine-local and +# contains cluster credentials — never commit it. +kubeconfig diff --git a/local/kind/cluster.yaml b/local/kind/cluster.yaml new file mode 100644 index 000000000..8d53cb017 --- /dev/null +++ b/local/kind/cluster.yaml @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +# SPDX-License-Identifier: Apache-2.0 + +# kind cluster for local scanner development. +# Create with: kind create cluster --config local/kind/cluster.yaml +# A single control-plane node is enough: the k8s-assets scanner only lists +# namespaces and pods, it does not schedule real workloads. +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +name: heureka-local +nodes: + - role: control-plane diff --git a/scanner/keppel/go.mod b/scanner/keppel/go.mod index 19051753e..8419119d2 100644 --- a/scanner/keppel/go.mod +++ b/scanner/keppel/go.mod @@ -5,6 +5,7 @@ go 1.26.3 require ( github.com/Khan/genqlient v0.8.1 github.com/aquasecurity/trivy v0.72.0 + github.com/aquasecurity/trivy-db v0.0.0-20260629102122-a0049d7ad12f github.com/cloudoperators/heureka v1.54.2 github.com/google/uuid v1.6.0 github.com/gophercloud/gophercloud v1.14.1 @@ -20,7 +21,6 @@ require ( github.com/agnivade/levenshtein v1.2.1 // indirect github.com/alexflint/go-arg v1.5.1 // indirect github.com/alexflint/go-scalar v1.2.0 // indirect - github.com/aquasecurity/trivy-db v0.0.0-20260629102122-a0049d7ad12f // indirect github.com/bmatcuk/doublestar/v4 v4.10.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect diff --git a/scanner/keppel/mock/fixtures.go b/scanner/keppel/mock/fixtures.go new file mode 100644 index 000000000..520813a3b --- /dev/null +++ b/scanner/keppel/mock/fixtures.go @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "errors" + "fmt" + "log" + "os" + "path/filepath" +) + +// fixturesDir holds optional JSON overrides for the built-in responses. It is +// resolved relative to the working directory; the Makefile targets `cd` into +// this package before running, and record mode writes here. +const fixturesDir = "testdata/fixtures" + +// loadOverride reads fixturesDir/.json into v when the file exists. +// Returns (false, nil) if there is no override. A file that does not fit v's +// type is a hard error — that is the fixture drift guard, also asserted in +// fixtures_test.go. +func loadOverride(name string, v any) (bool, error) { + path := filepath.Join(fixturesDir, name+".json") + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + if err := json.Unmarshal(b, v); err != nil { + return false, fmt.Errorf("fixture %s does not fit its model type (regenerate it with `make keppel-mock-record`): %w", path, err) + } + return true, nil +} + +func mustOverride(name string, v any) { + used, err := loadOverride(name, v) + if err != nil { + log.Fatalf("keppel mock: %v", err) + } + if used { + log.Printf("keppel mock: serving %s from %s/%s.json", name, fixturesDir, name) + } +} + +func writeFixture(name string, b []byte) error { + if err := os.MkdirAll(fixturesDir, 0o755); err != nil { + return err + } + + tmp, err := os.CreateTemp(fixturesDir, name+".*.tmp") + if err != nil { + return err + } + + tmpName := tmp.Name() + defer os.Remove(tmpName) + + if _, err := tmp.Write(b); err != nil { + tmp.Close() + return err + } + + if err := tmp.Close(); err != nil { + return err + } + + if err := os.Chmod(tmpName, 0o644); err != nil { + return err + } + + return os.Rename(tmpName, filepath.Join(fixturesDir, name+".json")) +} diff --git a/scanner/keppel/mock/fixtures_test.go b/scanner/keppel/mock/fixtures_test.go new file mode 100644 index 000000000..8d000f6cd --- /dev/null +++ b/scanner/keppel/mock/fixtures_test.go @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/cloudoperators/heureka/scanners/keppel/models" +) + +// TestDefaultsRoundTrip ensures the built-in responses marshal and unmarshal +// cleanly against the scanner's model types — the compile-time coupling is +// backed up by a JSON round-trip check. +func TestDefaultsRoundTrip(t *testing.T) { + cases := map[string]any{ + "accounts": accountsResponse(), + "repositories": repositoriesResponse(), + "manifest": manifestResponse(), + "trivy_report": trivyResponse(), + } + for name, v := range cases { + b, err := json.Marshal(v) + if err != nil { + t.Fatalf("%s: marshal: %v", name, err) + } + if !json.Valid(b) { + t.Fatalf("%s: produced invalid JSON", name) + } + } + + // The default Trivy report must carry at least one CVE so the scanner has + // something to report. + report := defaultTrivyReport() + var cves int + for _, r := range report.Results { + cves += len(r.Vulnerabilities) + } + if cves == 0 { + t.Fatal("defaultTrivyReport has no vulnerabilities") + } +} + +// TestFixturesFitModels is the drift guard: every committed override fixture +// must still unmarshal into the model type the scanner expects. If a fixture +// no longer fits (e.g. models.go changed), this fails and the fixture must be +// regenerated with `make keppel-mock-record`. +func TestFixturesFitModels(t *testing.T) { + targets := map[string]func([]byte) error{ + "accounts": func(b []byte) error { return json.Unmarshal(b, &models.AccountResponse{}) }, + "repositories": func(b []byte) error { return json.Unmarshal(b, &models.RepositoryResponse{}) }, + "manifest": func(b []byte) error { return json.Unmarshal(b, &models.ManifestResponse{}) }, + "trivy_report": func(b []byte) error { return json.Unmarshal(b, &models.TrivyReport{}) }, + } + for name, fit := range targets { + path := filepath.Join(fixturesDir, name+".json") + b, err := os.ReadFile(path) + if os.IsNotExist(err) { + continue // no override committed; the Go default is used + } + if err != nil { + t.Fatalf("%s: %v", path, err) + } + if err := fit(b); err != nil { + t.Errorf("%s does not fit its model type: %v", path, err) + } + } +} diff --git a/scanner/keppel/mock/keppel.go b/scanner/keppel/mock/keppel.go new file mode 100644 index 000000000..828c4acc9 --- /dev/null +++ b/scanner/keppel/mock/keppel.go @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "log" + "net/http" + "strings" + "time" + + dbtypes "github.com/aquasecurity/trivy-db/pkg/types" + "github.com/aquasecurity/trivy/pkg/types" + "github.com/cloudoperators/heureka/scanners/keppel/models" +) + +// keppelHandler serves the four Keppel endpoints the scanner calls. Repository +// names can contain slashes (organization/repo), which net/http path wildcards +// don't match, so we route by inspecting the path instead of registering +// patterns. +// +// All response bodies are built from the scanner's own structs in +// scanner/keppel/models (and the upstream trivy types), so a change to those +// types is a compile error here — that is the primary drift guard. A committed +// fixture under testdata/fixtures/.json, if present, overrides the +// built-in default (see fixtures.go). +func keppelHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case path == "/keppel/v1/accounts": + writeJSON(w, http.StatusOK, accountsResponse()) + case strings.HasPrefix(path, "/keppel/v1/accounts/") && strings.HasSuffix(path, "/repositories"): + writeJSON(w, http.StatusOK, repositoriesResponse()) + case strings.HasPrefix(path, "/keppel/v1/accounts/") && strings.HasSuffix(path, "/trivy_report"): + writeJSON(w, http.StatusOK, trivyResponse()) + case strings.HasPrefix(path, "/keppel/v1/accounts/") && strings.HasSuffix(path, "/_manifests"): + // Tag listing used by the scanner's ListTags (available-version-update + // feature). Returns one non-truncated page of manifests carrying tags. + writeJSON(w, http.StatusOK, manifestListResponse()) + case strings.HasPrefix(path, "/v2/") && strings.Contains(path, "/manifests/"): + digest := path[strings.LastIndex(path, "/manifests/")+len("/manifests/"):] + writeManifest(w, digest) + default: + http.NotFound(w, r) + } + }) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(v); err != nil { + log.Printf("keppel: encode response: %v", err) + } +} + +// writeManifest returns a single-arch manifest (no children) so the scanner +// proceeds to fetch a Trivy report. The scanner reads the vulnerability status +// and digest from response headers, not the body. +func writeManifest(w http.ResponseWriter, digest string) { + w.Header().Set("Content-Type", "application/json") + // "Low" is a valid (non-skipped) status, so the scanner fetches the report. + w.Header().Set("X-Keppel-Vulnerability-Status", "Low") + if digest != "" { + w.Header().Set("Docker-Content-Digest", digest) + } + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode(manifestResponse()); err != nil { + log.Printf("keppel: encode manifest: %v", err) + } +} + +func accountsResponse() models.AccountResponse { + v := models.AccountResponse{ + Accounts: []models.Account{{Name: "mock-account", AuthTenantID: "mock-tenant"}}, + } + mustOverride("accounts", &v) + return v +} + +func repositoriesResponse() models.RepositoryResponse { + v := models.RepositoryResponse{ + Repositories: []models.Repository{{Name: "mock-repo", ManifestCount: 1, TagCount: 1}}, + } + mustOverride("repositories", &v) + return v +} + +// manifestResponse carries the children list only (empty = single-arch image). +func manifestResponse() models.ManifestResponse { + v := models.ManifestResponse{Manifests: []models.Manifest{}} + mustOverride("manifest", &v) + return v +} + +// manifestListResponse answers the paginated _manifests listing used by +// ListTags. It returns one non-truncated page of manifests whose Tags include +// several semantic versions (plus a floating "latest" that HighestSemverTag +// ignores), so the scanner records 2.3.1 as the available latest version. +func manifestListResponse() models.ManifestResponse { + v := models.ManifestResponse{ + Truncated: false, + Manifests: []models.Manifest{ + { + Digest: "sha256:aaaa000000000000000000000000000000000000000000000000000000000001", + Tags: []models.Tag{ + {Name: "1.0.0"}, + {Name: "2.3.1"}, + {Name: "2.0.5"}, + {Name: "latest"}, + }, + }, + }, + } + mustOverride("manifest_list", &v) + return v +} + +func trivyResponse() models.TrivyReport { + v := defaultTrivyReport() + mustOverride("trivy_report", &v) + return v +} + +// defaultTrivyReport is built from the upstream trivy structs so that any +// breaking change to those types fails to compile here. +func defaultTrivyReport() models.TrivyReport { + return models.TrivyReport{ + SchemaVersion: 2, + CreatedAt: time.Now().UTC(), + ArtifactName: "mock-account/mock-repo", + ArtifactType: "container_image", + Results: []types.Result{ + { + Target: "mock-account/mock-repo (debian 12)", + Vulnerabilities: []types.DetectedVulnerability{ + { + VulnerabilityID: "CVE-2021-44228", + PkgName: "log4j", + InstalledVersion: "2.14.1", + FixedVersion: "2.17.0", + PrimaryURL: "https://nvd.nist.gov/vuln/detail/CVE-2021-44228", + Vulnerability: dbtypes.Vulnerability{ + Title: "Log4Shell", + Description: "Mock critical vulnerability (Log4Shell) for local scanner testing.", + Severity: "CRITICAL", + CVSS: dbtypes.VendorCVSS{ + "nvd": dbtypes.CVSS{ + V3Vector: "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H", + V3Score: 10.0, + }, + }, + }, + }, + { + VulnerabilityID: "CVE-2023-38545", + PkgName: "curl", + InstalledVersion: "7.88.0", + FixedVersion: "8.4.0", + PrimaryURL: "https://nvd.nist.gov/vuln/detail/CVE-2023-38545", + Vulnerability: dbtypes.Vulnerability{ + Title: "curl SOCKS5 heap buffer overflow", + Description: "Mock high severity vulnerability for local scanner testing.", + Severity: "HIGH", + CVSS: dbtypes.VendorCVSS{ + "nvd": dbtypes.CVSS{ + V3Vector: "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", + V3Score: 8.1, + }, + }, + }, + }, + }, + }, + }, + } +} diff --git a/scanner/keppel/mock/keystone.go b/scanner/keppel/mock/keystone.go new file mode 100644 index 000000000..698a044d7 --- /dev/null +++ b/scanner/keppel/mock/keystone.go @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "encoding/json" + "log" + "net/http" + "time" +) + +// keystoneHandler emulates the small slice of the OpenStack Keystone v3 API +// that gophercloud's AuthenticateV3 exercises. +// +// gophercloud (v1.14.1) POSTs to {IDENTITY_ENDPOINT}/auth/tokens and then: +// - reads the issued token id from the X-Subject-Token response header +// (this is what scanner.CreateAuthToken returns via iClient.Token()), and +// - unmarshals the body, requiring a well-formed token.expires_at and a +// token.catalog (which may be empty — the scanner never uses it). +func keystoneHandler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /v3/auth/tokens", handleToken) + // Version discovery is defensive: v1.14.1 posts directly, but some code + // paths probe the unversioned/base endpoint first. + mux.HandleFunc("GET /v3", handleVersion) + mux.HandleFunc("GET /", handleVersion) + return mux +} + +func handleToken(w http.ResponseWriter, r *http.Request) { + now := time.Now().UTC() + body := map[string]any{ + "token": map[string]any{ + "issued_at": now.Format(time.RFC3339), + "expires_at": now.Add(24 * time.Hour).Format(time.RFC3339), + "methods": []string{"password"}, + "user": map[string]any{ + "id": "mock-user", + "name": "mock", + }, + // Empty catalog is accepted: the scanner builds the Keppel URL from + // KEPPEL_FQDN and never consults the service catalog. + "catalog": []any{}, + }, + } + w.Header().Set("X-Subject-Token", "mock-subject-token") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + if err := json.NewEncoder(w).Encode(body); err != nil { + log.Printf("keystone: encode token response: %v", err) + } +} + +func handleVersion(w http.ResponseWriter, r *http.Request) { + body := map[string]any{ + "version": map[string]any{ + "id": "v3.14", + "status": "stable", + "links": []map[string]string{ + {"rel": "self", "href": "http://" + r.Host + "/v3"}, + }, + }, + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode(body); err != nil { + log.Printf("keystone: encode version response: %v", err) + } +} diff --git a/scanner/keppel/mock/main.go b/scanner/keppel/mock/main.go new file mode 100644 index 000000000..6bd8c1d69 --- /dev/null +++ b/scanner/keppel/mock/main.go @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +// Command mock is a local stand-in for a Keppel image registry plus its +// OpenStack Keystone identity endpoint, so the keppel scanner can be run +// end-to-end on a developer laptop without access to a real registry. +// +// It starts two listeners: +// +// - Keystone on plain HTTP (default :8080). gophercloud verifies TLS on the +// identity endpoint and the scanner's InsecureSkipVerify does NOT apply to +// it, so this one must be HTTP. +// - Keppel on HTTPS with a self-signed cert (default :8443). The scanner's +// Keppel base URL is hardcoded to https:// and it skips TLS verification, +// so a self-signed cert is fine. +// +// Run it (from this directory): +// +// go run . +// +// then point the scanner at it: +// +// KEPPEL_FQDN=localhost:8443 +// IDENTITY_ENDPOINT=http://localhost:8080/v3 +// +// See ../../../docs/local-environment.md for the full workflow. +package main + +import ( + "flag" + "log" + "os" +) + +func main() { + keystoneAddr := flag.String("keystone-addr", envOr("MOCK_KEYSTONE_ADDR", ":8080"), "Keystone (HTTP) listen address") + keppelAddr := flag.String("keppel-addr", envOr("MOCK_KEPPEL_ADDR", ":8443"), "Keppel (HTTPS) listen address") + record := flag.Bool("record", os.Getenv("KEPPEL_RECORD") == "1", "record mode: proxy to the real upstreams (RECORD_IDENTITY_UPSTREAM/RECORD_KEPPEL_UPSTREAM) and write fixtures") + flag.Parse() + + if *record { + if err := runRecord(*keystoneAddr, *keppelAddr); err != nil { + log.Fatalf("record mode failed: %v", err) + } + return + } + if err := runServe(*keystoneAddr, *keppelAddr); err != nil { + log.Fatalf("serve mode failed: %v", err) + } +} + +func envOr(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} diff --git a/scanner/keppel/mock/record.go b/scanner/keppel/mock/record.go new file mode 100644 index 000000000..6915002ac --- /dev/null +++ b/scanner/keppel/mock/record.go @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "strings" +) + +// runRecord runs the mock as a transparent recording proxy in front of a real +// Keppel + Keystone. Point the scanner at the mock as usual (KEPPEL_FQDN and +// IDENTITY_ENDPOINT), set the real upstreams via RECORD_KEPPEL_UPSTREAM and +// RECORD_IDENTITY_UPSTREAM, provide real KEPPEL_* credentials, and run the +// scanner once. Every Keppel response the scanner fetches is written to +// testdata/fixtures/.json, so the committed fixtures can be refreshed +// from reality when the real API changes. +func runRecord(keystoneAddr, keppelAddr string) error { + idUp := mustURL("RECORD_IDENTITY_UPSTREAM") + kpUp := mustURL("RECORD_KEPPEL_UPSTREAM") + + // Keystone is a stable protocol; proxy it (so gophercloud can authenticate) + // but don't record it. + keystone := &http.Server{Addr: keystoneAddr, Handler: recordingProxy(idUp, false)} + go func() { + log.Printf("[record] keystone proxy %s -> %s", keystoneAddr, idUp) + if err := keystone.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("keystone proxy: %v", err) + } + }() + + cert, err := selfSignedCert() + if err != nil { + return err + } + keppel := &http.Server{ + Addr: keppelAddr, + Handler: recordingProxy(kpUp, true), + TLSConfig: &tls.Config{Certificates: []tls.Certificate{*cert}}, + } + log.Printf("[record] keppel proxy %s -> %s (writing fixtures to %s)", keppelAddr, kpUp, fixturesDir) + if err := keppel.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed { + return err + } + return nil +} + +func mustURL(key string) *url.URL { + raw := envOr(key, "") + if raw == "" { + log.Fatalf("record mode requires %s", key) + } + u, err := url.Parse(raw) + if err != nil { + log.Fatalf("invalid %s=%q: %v", key, raw, err) + } + return u +} + +// recordingProxy forwards requests to upstream (preserving the incoming path), +// skipping TLS verification. When record is true, each JSON response body is +// classified and written to a fixture file. +func recordingProxy(upstream *url.URL, record bool) http.Handler { + proxy := &httputil.ReverseProxy{ + Director: func(req *http.Request) { + req.URL.Scheme = upstream.Scheme + req.URL.Host = upstream.Host + req.Host = upstream.Host + }, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec // recording against staging only + }, + } + if record { + proxy.ModifyResponse = func(resp *http.Response) error { + name := fixtureName(resp.Request.URL.Path) + body, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return err + } + resp.Body = io.NopCloser(bytes.NewReader(body)) + if name != "" && resp.StatusCode >= 200 && resp.StatusCode < 300 { + var pretty bytes.Buffer + if json.Indent(&pretty, body, "", " ") == nil { + if err := writeFixture(name, pretty.Bytes()); err != nil { + log.Printf("[record] write %s: %v", name, err) + } else { + log.Printf("[record] saved %s (%d bytes) from %s", name, pretty.Len(), resp.Request.URL.Path) + if name == "manifest" { + log.Printf("[record] manifest headers: X-Keppel-Vulnerability-Status=%q Docker-Content-Digest=%q", + resp.Header.Get("X-Keppel-Vulnerability-Status"), resp.Header.Get("Docker-Content-Digest")) + } + } + } + } + return nil + } + } + return proxy +} + +// fixtureName maps a Keppel request path to the fixture it should update, or "" +// to skip recording. +func fixtureName(path string) string { + switch { + case path == "/keppel/v1/accounts": + return "accounts" + case strings.HasSuffix(path, "/repositories"): + return "repositories" + case strings.HasSuffix(path, "/trivy_report"): + return "trivy_report" + case strings.HasPrefix(path, "/v2/") && strings.Contains(path, "/manifests/"): + return "manifest" + default: + return "" + } +} diff --git a/scanner/keppel/mock/serve.go b/scanner/keppel/mock/serve.go new file mode 100644 index 000000000..09eff4166 --- /dev/null +++ b/scanner/keppel/mock/serve.go @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "crypto/tls" + "log" + "net/http" +) + +// runServe starts the canned Keystone (HTTP) and Keppel (HTTPS) listeners. +func runServe(keystoneAddr, keppelAddr string) error { + keystone := &http.Server{Addr: keystoneAddr, Handler: keystoneHandler()} + go func() { + log.Printf("keystone (http) listening on %s", keystoneAddr) + if err := keystone.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("keystone listener: %v", err) + } + }() + + cert, err := selfSignedCert() + if err != nil { + return err + } + keppel := &http.Server{ + Addr: keppelAddr, + Handler: keppelHandler(), + TLSConfig: &tls.Config{Certificates: []tls.Certificate{*cert}}, + } + log.Printf("keppel (https) listening on %s", keppelAddr) + // ListenAndServeTLS with empty cert/key files uses TLSConfig.Certificates. + if err := keppel.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed { + return err + } + return nil +} diff --git a/scanner/keppel/mock/testdata/fixtures/.gitkeep b/scanner/keppel/mock/testdata/fixtures/.gitkeep new file mode 100644 index 000000000..c8a8a4303 --- /dev/null +++ b/scanner/keppel/mock/testdata/fixtures/.gitkeep @@ -0,0 +1,3 @@ +# Optional override fixtures for the keppel mock live here as .json +# (accounts, repositories, manifest, trivy_report). When absent, the mock serves +# defaults built in Go. Refresh them from a real Keppel with `make keppel-mock-record`. diff --git a/scanner/keppel/mock/tlscert.go b/scanner/keppel/mock/tlscert.go new file mode 100644 index 000000000..fb68ebadc --- /dev/null +++ b/scanner/keppel/mock/tlscert.go @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "time" +) + +// selfSignedCert generates an ephemeral self-signed certificate for the Keppel +// HTTPS listener. The scanner skips TLS verification (SetInsecureSkipVerify) so +// the cert does not need to be trusted; it only needs to exist and cover +// localhost / 127.0.0.1. +func selfSignedCert() (*tls.Certificate, error) { + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, err + } + + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + return nil, err + } + + template := x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: "keppel-mock.local"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: []string{"localhost", "keppel-mock.local"}, + IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback}, + } + + der, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) + if err != nil { + return nil, err + } + + cert := tls.Certificate{ + Certificate: [][]byte{der}, + PrivateKey: priv, + } + return &cert, nil +} diff --git a/scanner/keppel/models/models.go b/scanner/keppel/models/models.go index a782b6ae7..dd4f950ad 100644 --- a/scanner/keppel/models/models.go +++ b/scanner/keppel/models/models.go @@ -37,13 +37,14 @@ type Repository struct { } type Manifest struct { - Digest string - MediaType string `json:"media_type"` - SizeBytes uint64 `json:"size_bytes"` - PushedAt uint64 `json:"pushed_at"` - LastPulledAt uint64 `json:"last_pulled_at"` - VulnerabilityStatus string `json:"vulnerability_status"` + Digest string `json:"digest"` + MediaType string `json:"media_type"` + SizeBytes uint64 `json:"size_bytes"` + PushedAt uint64 `json:"pushed_at"` + LastPulledAt uint64 `json:"last_pulled_at"` + VulnerabilityStatus string `json:"vulnerability_status"` Labels Labels + Tags []Tag `json:"tags"` Children []Manifest `json:"manifests"` MaxLayerCreatedAt int64 `json:"max_layer_created_at"` MinLayerCreatedAt int64 `json:"min_layer_created_at"` @@ -55,8 +56,21 @@ type Platform struct { OS string `json:"os"` } +// ManifestResponse is the paginated response body of the Keppel +// GET /keppel/v1/accounts/{account}/repositories/{repo}/_manifests endpoint. +// When Truncated is true the caller must resend with marker set to the digest +// of the last manifest to retrieve the next page. type ManifestResponse struct { - Manifests []Manifest + Manifests []Manifest `json:"manifests"` + Truncated bool `json:"truncated"` +} + +// Tag represents a single tag entry nested within a Keppel manifest listing +// response (GET /keppel/v1/accounts/{account}/repositories/{repo}/_manifests). +type Tag struct { + Name string `json:"name"` + PushedAt int64 `json:"pushed_at"` + LastPulledAt int64 `json:"last_pulled_at"` } type Labels struct { diff --git a/scanner/playground/k8s-playground/templates/serviceaccount.yaml b/scanner/playground/k8s-playground/templates/serviceaccount.yaml index fe12f41e6..9c27293cd 100644 --- a/scanner/playground/k8s-playground/templates/serviceaccount.yaml +++ b/scanner/playground/k8s-playground/templates/serviceaccount.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors # SPDX-License-Identifier: Apache-2.0 -{{- if .Values.serviceAccount.create -}} +{{- if .Values.serviceAccount.create }} apiVersion: v1 kind: ServiceAccount metadata: