Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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

6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
129 changes: 129 additions & 0 deletions docs/local-environment.md
Original file line number Diff line number Diff line change
@@ -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/<name>.json`; commit the updated
`models.go` (if any) together with the refreshed fixtures.
Comment thread
Copilot marked this conversation as resolved.
Resolved

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`.

3 changes: 3 additions & 0 deletions local/kind/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# The kubeconfig exported by `kind export kubeconfig` is machine-local and
# contains cluster credentials β€” never commit it.
kubeconfig
12 changes: 12 additions & 0 deletions local/kind/cluster.yaml
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion scanner/keppel/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
76 changes: 76 additions & 0 deletions scanner/keppel/mock/fixtures.go
Original file line number Diff line number Diff line change
@@ -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/<name>.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"))
}
71 changes: 71 additions & 0 deletions scanner/keppel/mock/fixtures_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading
Loading