Repository navigation
test: Create Local Infrastructure for Scanner Testing #1329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
MR2011
merged 3 commits into
main
from
kanstantsinbuklis-sap/issue-1302/create-local-infrastructure-for-scanner-testing
Nov 18, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
8e6c8e5
test: Create Local Infrastructure for Scanner Testing
kanstantsinbuklis-sap e70bd7a
Merge branch 'main' into kanstantsinbuklis-sap/issue-1302/create-locaβ¦
kanstantsinbuklis-sap e181e9e
Merge branch 'main' into kanstantsinbuklis-sap/issue-1302/create-locaβ¦
MR2011 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
| 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`. | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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")) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.