diff --git a/AGENTS.md b/AGENTS.md index aa5c61b..4473700 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,13 +18,18 @@ internal/cli/ cat.go # "cat" subcommand — print resolved config as YAML version.go # "version" subcommand + Version/Commit/Date vars pkg/config/ - config.go # Config/RepoDefaults/RepoConfig/Pattern structs; RepoConfig embeds RepoDefaults inline; Load(), Validate(), validateRepo(), validateAuth(); PartialValidateError for partial-validate tolerance; per-repo-subdir (//config.yaml) directory discovery — strict fail-fast on load + config.go # Config/RepoDefaults/RepoConfig/OpenBaoConfig/Pattern structs; RepoConfig embeds RepoDefaults inline; OpenBaoConfig embeds secrets.OpenBaoConfig with Enabled flag; Load(), Validate(), validateRepo(), validateAuth(), validateOpenBaoConfig(), validateKVPath(); PartialValidateError for partial-validate tolerance; per-repo-subdir (//config.yaml) directory discovery — strict fail-fast on load duration.go # ParseDuration() — support for s, m, h, d url.go # CheckHTTPSAccessible() helper config_test.go # Config unit tests +pkg/secrets/ + store.go # Store — concurrent-safe secret reader: cache per openbao config and path handing out copies, with a generation per path (the first of two concurrent reads of a path to finish caches, a slower one never overwrites it); Refetch (replaces a cached key only when it changed), Invalidate (evicts a path under every config); one client per openbao config, built on first use and kept; sentinels ErrNotFound/ErrForbidden/ErrUnavailable/ErrRejected/ErrInvalidSecret/ErrClientConfig (a client that cannot be built from the config); a failed read, client build included, is counted on the secret fetch failure metric + openbao.go # OpenBao KV v2 client — lazy kubernetes-auth login, background renewal from 2/3 lease (reads keep the current token; a failed renewal is retried at most once per policyDenialWindow; only a missing or expired token makes a read wait for a login: one login runs at a time on its own context without the mutex, every read needing it waits on it until its own ctx ends, and a failed one is answered from memory for loginFailureBackoff instead of retried per read), 403 backstop re-login through that same shared login rate-limited to reloginCooldown (a third of the lease when that is shorter, token age taken at the 403), error mapping to sentinels (an unreadable service-account token file is ErrUnavailable) + store_test.go # httptest-based tests for login, shared login and its failure backoff, read, cache-first, invalidation, background token renewal, concurrency, metrics pkg/gsync/ - auth.go # resolveAuth() — SSH key or nil (HTTPS); preferredHostKeyAlgorithms + mergeAlgorithms (OpenSSH-style dynamic per-host promotion); sshHostPort() + auth.go # resolveAuth() — SSH key from file, OpenBao secret, or nil (HTTPS); sshAuth (file), openBaoAuth = parseSSHKey + withKnownHosts (in-memory PEM, from Read or the bytes Refetch returned; the endpoint is parsed before the OpenBao read); preferredHostKeyAlgorithms + mergeAlgorithms (OpenSSH-style dynamic per-host promotion); sshHostPort() auth_test.go # SSH auth and host key algorithm tests + errors.go # Classify(): maps sync errors to stable FailureCodes; secret errors are typed at resolveAuth known_hosts.go # buildKnownHostsAuth() — host key callback + per-host algorithms via gitssh.NewKnownHostsDb syncer.go # Syncer, SyncAll(), SyncRepo(), syncBranches(), syncTagsWrapper(), handleCheckout(), ensureCloned() refs.go # resolveBranches/resolveTags/default branch + staleness and branch discovery helpers @@ -34,8 +39,9 @@ pkg/gsync/ openvox.go # OpenVox sync flow and per-ref directory sync/prune logic syncer_test.go # Integration tests using in-process bare repos pkg/telemetry/ - telemetry.go # Prometheus metrics definitions and registration (sync metrics + config reload metrics) + telemetry.go # Prometheus metrics definitions and registration (sync metrics + config reload metrics + secret fetch metrics) pkg/daemon/ + constants.go # failure code table: HTTP status + message per code scheduler.go # Scheduler — gocron-backed periodic syncing; atomic config pointer + Reload() (cancel all jobs / swap config / reschedule with delayed first-fire) scheduler_test.go # Scheduler + Reload diff tests server.go # HTTP server: /health, /metrics, /sync, /sync/{repo}, POST /reload @@ -64,6 +70,8 @@ renovate.json # Renovate config (gomod, dockerfile, github-actio - **Directory-mode layout**: `loadDir` discovers per-repo configs at `//config.yaml` via `filepath.Glob`. `/global.yaml` at the root carries shared defaults. - **Pruning in daemon mode**: daemon passes `SyncOptions{}` to `SyncRepo`, which then promotes `repo.Prune`, `repo.PruneStale`, and `repo.StaleAge` from the repo config into the options. Set `prune: true` or `prune_stale: true` in config to enable pruning per-repo in daemon mode. `--prune` and `--dry-run` CLI flags remain exclusive to the `sync` subcommand. - **SSH HostKeyAlgorithms**: `gitssh.NewKnownHostsDb` produces both the host-key callback and the list of algorithms our known_hosts has entries for at the dialed `host:port`. `mergeAlgorithms` puts those first, then appends the OpenSSH 9.x default order (Ed25519/ECDSA/RSA-SHA2 plus their cert variants) — mimicking OpenSSH's dynamic per-host HostKeyAlgorithms promotion so negotiation lands on a key type we can verify. Plain `ssh-rsa` (SHA-1) and `ssh-dss` are intentionally omitted. +- **Cache-first SSH key fetch**: when `openbao.enabled: true`, the SSH private key is fetched from OpenBao KV v2 on first use and cached in memory per path. On reload only the key paths of repos added, removed or re-keyed are evicted (`InvalidateSecrets`), except a path an unchanged repo still reads; the OpenBao client and token survive, and a key rotated in place is picked up by the ssh-auth refetch. Each openbao config has its own client and cache entries, so after a reload that changes the block, syncs still running on the old one and syncs on the new one do not evict each other's client or cache. An SSH auth failure at the first network op (listRemoteRefs / loadResolverRepoAndRefs; `ensureCloned` is local only, so this holds on a fresh clone too) refetches the key, replaces the cached one only if it changed, and retries once with the key the refetch returned if it differs (self-heals a missed reload); the sync then carries on, object-store repair included, with the refetched key. A key that does not parse is evicted (it never reaches the network, so no auth failure would refetch it), so a value fixed in OpenBao is read on the next sync. There is no stale-key fallback: if OpenBao is down on a cache miss, the sync fails. +- **HTTP error contract**: `/sync`, `/sync/{repo}` and `/reload` failures return a status per failure class (503 secret backend unavailable / git host unreachable / shutting down, 422 git host rejection, missing, invalid, denied or rejected secret, or invalid config, 409 sync in progress, 404 unknown repo, 500 otherwise, including an OpenBao client that cannot be built from the config, `secret_config_invalid`). `error` keeps the raw error chain; `code` (one table in `pkg/daemon/constants.go`) and `message` are the stable surface callers should match on. An OpenBao request timeout or an unreadable service-account token file is `secret_unavailable`; a policy denial (`secret_forbidden`) or a request OpenBao rejects (`secret_rejected`) does not clear on a retry, so it is 422; a request the caller cancelled is `internal`; a git-host dial failure or timeout, or an SSH handshake the host closes early (EOF), is `git_unreachable`, 503 since it is transient; a repo URL that does not parse is `internal`, not `git_unreachable`, even though its url.Error satisfies net.Error. - **Package Naming**: `pkg/gsync` is used for git sync logic to avoid conflict with the standard `sync` package. `pkg/telemetry` is used for metrics. - **Concurrent OpenVox Sync**: When `openvox: true` is set, branches and tags are synced in parallel using a worker pool (default 5 workers). A mutex protects the shared resolver repo (`.gfetch-meta`) from concurrent access conflicts. - **Index auto-repair**: `checkoutRefContext` automatically detects corrupted, truncated, or unknown `.git/index` files (including `unexpected EOF`, `EOF`, and `index.ErrMalformedSignature`) and deletes/rebuilds them on the fly. @@ -107,7 +115,7 @@ For AI coding agents: after making code changes, run `go fix ./...` before tests - **Go version**: 1.27 (see `go.mod`) - **Module path**: `github.com/obmondo/gfetch` -- **Logging**: `log/slog` with text handler to stderr. Logger is passed through structs (e.g., `Syncer.logger`), not globals. Use `.With("key", value)` for structured fields. +- **Logging**: `log/slog` with text handler to stderr. Per-repo code builds a `log *slog.Logger` with `slog.With("repo", …)` and passes it down as a parameter (e.g. `runStandardSync`, `refreshAuthAfterSSHFailure`, the openvox workers); a type that owns its logging holds a struct logger (e.g. `secrets.Store`); package-level code without a per-repo context (e.g. config loading, the scheduler) logs via the slog default. Use `.With("key", value)` for structured fields. - **CLI framework**: `github.com/spf13/cobra`. Commands are defined in `internal/cli/` with `newXxxCmd()` factory functions. Flags use package-level vars. - **Config parsing**: `gopkg.in/yaml.v3`. Config validation is manual in `Config.Validate()` — no struct validation tags. - **Git operations**: `github.com/go-git/go-git/v5`. All git work is done through the go-git library, not by shelling out to git. @@ -190,9 +198,10 @@ Commits should be logically atomic — one concern per commit. When a session to - `prune` (bool) enables obsolete-ref pruning (branches/tags no longer matching any pattern); defaults to false - `prune_stale` (bool) and `stale_age` (duration) enable inactivity-based pruning; `prune_stale` only has effect when `prune: true` is also set (a warning is logged otherwise) - Regex patterns (wrapped in `/`) are compiled and validated -- SSH URLs require `ssh_key_path` pointing to an existing file +- SSH URLs require `ssh_key_path`. When `openbao.enabled: true`, it is shape-checked as a KV path (charset `[A-Za-z0-9._/-]`, no leading `/`, no `..` or empty segments, no `data/` prefix); otherwise it must point to an existing file - HTTPS URLs must be publicly accessible (HEAD request returns 200) - `checkout` (if set) must match at least one branch or tag pattern +- `openbao` block with `enabled: true` must have a valid `addr` (http/https URL with host), `role`, and `service_account_token_path`. An invalid block is a hard config error (not per-repo). Defaults: `kv_mount=kv`, `field=private_key`. The `openbao` block in a per-repo `*/config.yaml` is ignored; only honored in `global.yaml` or at the single-file top level. ## Pattern System @@ -206,7 +215,8 @@ Patterns appear in `branches` and `tags` YAML lists: ## Auth System -- **SSH**: any non-HTTPS URL. Uses `go-git/go-git/v5/plumbing/transport/ssh.NewPublicKeysFromFile("git", keyPath, "")`. No passphrase support. +- **SSH**: any non-HTTPS URL. When `openbao.enabled: true`, the key is fetched from OpenBao KV v2 and parsed in memory via `parseSSHKey` + `withKnownHosts` (cache-first; see decision above); otherwise uses `go-git/go-git/v5/plumbing/transport/ssh.NewPublicKeysFromFile("git", keyPath, "")`. No passphrase support. SSH auth failure with an OpenBao key triggers one refetch-retry cycle (the retry uses the key the refetch returned and is skipped when it is unchanged); file-based keys are not retried. +- **Validation**: KV paths reject `.` and `..` segments; a per-repo `openbao` block in directory mode is ignored with a warning. - **HTTPS**: URLs starting with `https://` or `http://`. Auth is `nil` (anonymous). Only public repos are supported. ## Known future work diff --git a/README.md b/README.md index 356b198..9881c35 100644 --- a/README.md +++ b/README.md @@ -114,11 +114,11 @@ docker build --build-arg VERSION=1.0.0 \ ## Configuration -gfetch reads a YAML config file (default: `config.yaml` in the current directory). Use a `defaults:` key to share settings across multiple repositories. +gfetch reads a YAML config file (default: `config.yaml` in the current directory). Use a `defaults:` key to share settings across multiple repositories. An optional `openbao:` block enables fetching SSH keys from an OpenBao KV v2 secret backend instead of the filesystem (see [OpenBao Secret Backend](docs/configuration.md#openbao-secret-backend)). ```yaml defaults: - ssh_key_path: /home/gfetch/.ssh/id_rsa + ssh_key_path: /home/gfetch/.ssh/id_rsa # or a KV path when openbao.enabled poll_interval: 10m prune: true # remove branches/tags no longer matching any pattern prune_stale: true # remove branches with no commits in 6 months (requires prune: true) @@ -213,6 +213,16 @@ The daemon exposes the following HTTP endpoints on the listen address (default ` To pick up a config change before syncing, call `POST /reload` (or send `SIGHUP`) first, then `POST /sync`. +Error responses carry a stable `code` and `message` next to `error`, which holds the raw error chain (on `/sync` per repo result). The status follows the failure class; on `POST /sync` only failed repos count, and failures with different statuses return `500`. `git_unreachable` covers a git host that cannot be dialled or closes the SSH handshake early; a repo URL that does not parse is `internal`. + +| Status | Codes | +| :--- | :--- | +| `503` | `secret_unavailable`, `git_unreachable`, `shutting_down` | +| `422` | `secret_not_found`, `secret_invalid`, `secret_forbidden`, `secret_rejected`, `git_auth_failed`, `git_repo_not_found`, `git_host_key_mismatch`, `config_invalid` | +| `409` | `sync_in_progress` | +| `404` | `repo_not_found` | +| `500` | `internal`, `secret_config_invalid`, `config_load_failed`, `config_apply_failed` | + ### `gfetch validate-config` Validate the config file and exit. diff --git a/config.example.yaml b/config.example.yaml index 997147f..565bc44 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -1,6 +1,22 @@ +# --- OpenBao secret backend (optional) --- +# When enabled, per-repo ssh_key_path values are KV secret paths instead of +# filesystem paths. The SSH key is fetched from OpenBao on first use and +# cached in memory per path. A successful config reload evicts only the keys +# of repos it added, removed or re-keyed, and never a key an unchanged repo +# still reads. An openbao block in a per-repo config.yaml (directory mode) is +# ignored; use global.yaml instead. +# +# openbao: +# enabled: true +# addr: http://openbao.openbao:8200 +# role: gfetch +# service_account_token_path: /var/run/secrets/openbao/token +# kv_mount: kv # default: kv +# field: private_key # default: private_key + # --- Shared defaults --- defaults: - ssh_key_path: /home/gfetch/.ssh/id_rsa + ssh_key_path: /home/gfetch/.ssh/id_rsa # or a KV path when openbao.enabled poll_interval: 10m local_path: /var/repos branches: diff --git a/docs/configuration.md b/docs/configuration.md index 2c7db63..e628143 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -56,7 +56,7 @@ Validation, however, tolerates per-repo failures: a repo that fails `Validate` ( | ------- | ------ | ---------- | ------------- | | (key) | string | Yes | The repository name. Max 64 characters. Allowed characters: `a-z`, `A-Z`, `0-9`, `.`, `_`, `-`. | | `url` | string | Yes | Remote repository URL. Prefix `https://` for HTTPS; anything else for SSH. | -| `ssh_key_path` | string | Only for SSH | Absolute path to a private SSH key file. | +| `ssh_key_path` | string | Only for SSH | Filesystem path to a private SSH key file. When `openbao.enabled: true`, this is the KV secret path instead (e.g. `ssh-keys/acme/kubeaid`). Inheritable from `defaults`/`global.yaml`. | | `ssh_known_hosts` | string | No | Extra SSH host key entries. Merged with built-in keys for GitHub, GitLab, Bitbucket, and Azure DevOps. | | `local_path` | string | Yes | Local directory where the repo will be cloned and synced. | | `poll_interval` | duration | Yes | How often the daemon polls this repo. Supports `30s`, `5m`, `1h`, `30d`. Minimum: `10s`. | @@ -226,11 +226,62 @@ The delimiters are stripped before compilation. The regex is matched against the A pattern of `//` (empty regex) is treated as a literal string, not a regex. +## OpenBao Secret Backend + +gfetch can fetch SSH private keys from an [OpenBao](https://openbao.org/) KV v2 secret backend instead of reading them from the filesystem. This is controlled by a global `openbao` block. + +### Configuration + +```yaml +openbao: + enabled: true + addr: http://openbao.openbao:8200 + role: gfetch + service_account_token_path: /var/run/secrets/openbao/token + kv_mount: kv # default: kv + field: private_key # default: private_key +``` + +| Field | Required | Default | Description | +| --- | --- | --- | --- | +| `enabled` | Yes | `false` | Enable OpenBao for SSH key retrieval. | +| `addr` | Yes (when enabled) | — | OpenBao server URL (`http://` or `https://`). | +| `role` | Yes (when enabled) | — | Kubernetes auth role for login. | +| `service_account_token_path` | Yes (when enabled) | — | Path to the Kubernetes service account JWT file. | +| `kv_mount` | No | `kv` | KV v2 mount path. | +| `field` | No | `private_key` | Field name within the KV secret that holds the PEM-encoded private key. | + +The `openbao` block is allowed at the top level of a single-file config and in `global.yaml` in directory mode. An `openbao` block in a per-repo `*/config.yaml` is ignored. + +When `enabled: true`, per-repo `ssh_key_path` values are interpreted as KV secret paths instead of filesystem paths. The key is cached in memory per path after first fetch; on a successful config reload (SIGHUP or POST /reload) only the key paths of repos the reload added, removed or re-keyed are evicted, except a path an unchanged repo still reads, and the OpenBao client and token survive. A changed openbao block gets its own client and cached keys, while syncs still running on the old block keep theirs until they finish. Deleting a key removes its repo config, and the next verify re-adds it, so a regenerated key at the same path is refetched. An SSH auth failure with an OpenBao key refetches the key, replaces the cached one only if it changed, and retries the network operation once if the refetched key differs (self-heals a missed reload). A key that does not parse is evicted, so once the value is fixed in OpenBao the next sync reads it. When two reads of one path race, the first to finish is cached and a slower one does not overwrite it. There is no stale-key fallback: if OpenBao is down on a cache miss, the sync fails. The key is never written to disk. + +Token management: from 2/3 of the token lease the token is renewed in the background, so reads keep using the current token and never wait on that login; a failed renewal keeps the token and is retried at most once per minute, or per third of the lease when that is shorter. Only a missing or expired token makes a read wait for a login. One login runs at a time and every read that needs it shares it, each waiting no longer than its own deadline; a failed login is answered from memory for 5 seconds instead of being retried by every read. A 403 backstop re-login uses that same shared login and is rate-limited the same way. The token's age is taken when the 403 arrives, so a slow request on an expiring token still gets its re-login. Recommend setting a short `token_ttl` on the Kubernetes auth role. + +When `openbao.enabled` is set, `ssh_key_path` must be a KV path; an inherited `defaults.ssh_key_path` file path makes SSH repos fail validation (the path is validated as a KV path and dropped per repo). + +When `enabled: false` or absent, `ssh_key_path` is a filesystem path as before, with no behavior change. + +### Validation + +An invalid `openbao` block (missing role, bad addr, etc.) is a **hard** config-level error. The reload is rejected and the previous config keeps running. + +When enabled, per-repo `ssh_key_path` is shape-checked as a KV path: + +- Must not be empty. +- Allowed characters: `A-Z`, `a-z`, `0-9`, `.`, `_`, `-`, `/`. +- Must not start with `/`. +- Must not contain empty segments (`//`), `.` segments, or `..` segments. +- Must not start with `data/` (the KV v2 API prefix is added automatically). + +These shape failures are per-repo (the failing repo is dropped via `PartialValidateError`, other repos survive). + ## Auth Methods ### SSH (private and public repos) -Use an SSH-style URL (e.g. `git@github.com:user/repo.git`) and provide `ssh_key_path` pointing to a private key file. The username is always `git`. Passphrase-protected keys are not supported. +Use an SSH-style URL (e.g. `git@github.com:user/repo.git`) and provide `ssh_key_path`. When the `openbao` block is enabled, `ssh_key_path` is the KV secret path; otherwise it is the filesystem path to a private key file. The username is always `git`. Passphrase-protected keys are not supported. + +The SSH key is fetched from OpenBao on first use and cached in memory per path. A config reload evicts only the keys of repos it added, removed or re-keyed, and never a key an unchanged repo still reads. An SSH auth failure with an OpenBao key refetches the key, replaces the cached one only if it changed, and retries once if the refetched key differs. The key is never written to disk. Host key verification is always enabled using built-in keys. To add extra host keys (e.g. for a self-hosted Git server), use `ssh_known_hosts`: @@ -272,11 +323,12 @@ The config is validated when loaded. The following rules are enforced: - At least one of `branches` or `tags` must be non-empty, unless `default_branch_only: true` is set. - `default_branch_only: true` is rejected alongside `branches`, `tags`, `checkout` or `openvox`. Each of those names the refs to sync, so they contradict the option rather than refine it — the config fails instead of silently ignoring what you wrote. - All regex patterns must be valid Go regular expressions. -- If `url` is an SSH URL, `ssh_key_path` must be set and the file must exist. +- If `url` is an SSH URL, `ssh_key_path` must be set. When `openbao.enabled: true`, it is shape-checked as a KV path; otherwise the file must exist on disk. - If `url` is an HTTPS URL, the repo must be publicly accessible (HTTP 200 on HEAD request). - If `checkout` is set, it must match at least one configured branch or tag pattern (not enforced when `openvox` is enabled). - If both `openvox` and `checkout` are set, a warning is logged and `checkout` is ignored. - `prune_stale: true` requires `prune: true` to take effect. If `prune_stale` is set without `prune`, a warning is logged and stale pruning is skipped. +- An `openbao` block with `enabled: true` must have a valid `addr` (http/https URL with host), `role`, and `service_account_token_path`. An invalid block is a hard config error. Run `gfetch validate-config` to check your config file without performing any sync. @@ -337,6 +389,8 @@ In addition to the per-sync metrics, the daemon exposes the following config-rel | `gfetch_config_repo_validate_failures_total` | counter | `repo` | Per-repo validation failures (the repo is dropped from the running config). | | `gfetch_config_last_reload_timestamp` | gauge | — | Unix timestamp of the last successful reload. | | `gfetch_config_managed_repos` | gauge | — | Number of repos currently managed by the daemon. | +| `gfetch_secret_fetch_failures_total` | counter | `repo`, `reason` (`not_found`, `forbidden`, `unavailable`, `invalid`, `rejected`, `config_invalid`) | Secret fetch failures per repo and reason, an OpenBao client that cannot be built from the config included. | +| `gfetch_secret_auth_refetch_total` | counter | `repo` | Times a secret key was refetched after an SSH authentication failure. | ## Complete Example diff --git a/go.mod b/go.mod index c950240..4780d21 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/go-co-op/gocron/v2 v2.22.0 github.com/go-git/go-git/v5 v5.19.2 github.com/google/uuid v1.6.0 + github.com/openbao/openbao/api/v2 v2.7.1 github.com/prometheus/client_golang v1.24.1 github.com/spf13/cobra v1.10.2 golang.org/x/crypto v0.55.0 @@ -17,31 +18,46 @@ require ( github.com/Microsoft/go-winio v0.6.2 // indirect github.com/ProtonMail/go-crypto v1.1.6 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudflare/circl v1.6.3 // indirect github.com/cyphar/filepath-securejoin v0.6.1 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/go-git/go-billy/v5 v5.9.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-retryablehttp v0.7.8 // indirect + github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect + github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect + github.com/hashicorp/go-sockaddr v1.0.7 // indirect + github.com/hashicorp/hcl v1.0.1-vault-7 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect github.com/jonboulle/clockwork v0.5.0 // indirect github.com/kevinburke/ssh_config v1.2.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/kylelemons/godebug v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pjbgf/sha1cd v0.6.0 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/procfs v0.21.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect + github.com/ryanuber/go-glob v1.0.0 // indirect github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect github.com/skeema/knownhosts v1.3.1 // indirect github.com/spf13/pflag v1.0.9 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect - golang.org/x/net v0.57.0 // indirect + golang.org/x/net v0.58.0 // indirect golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + golang.org/x/time v0.15.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index 85bba20..e4b3685 100644 --- a/go.sum +++ b/go.sum @@ -11,6 +11,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= @@ -19,12 +21,15 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE= github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o= github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= +github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c= github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU= github.com/go-co-op/gocron/v2 v2.22.0 h1:uEuH2F7k7VoESb1BYSaffuuV+T0kkpzsC0aXk7/z79I= @@ -37,12 +42,37 @@ github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMj github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII= github.com/go-git/go-git/v5 v5.19.2 h1:wkfn7vOlUBu8ivAWKBWisTiwJK4jYHzTF8Ndv1LyGqY= github.com/go-git/go-git/v5 v5.19.2/go.mod h1:QqCBE1EFN5ddFmrliLQ3/ntRCUjZU3EJuwuB/jWEHjk= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U= +github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= +github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= +github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 h1:U+kC2dOhMFQctRfhK0gRctKAPTloZdMU5ZJxaesJ/VM= +github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0/go.mod h1:Ll013mhdmsVDuoIXVfBtvgGJsXDYkTw1kooNcoCXuE0= +github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 h1:kes8mmyCpxJsI7FTwtzRqEy9CdjCtrXrXGuOpxEA7Ts= +github.com/hashicorp/go-secure-stdlib/strutil v0.1.2/go.mod h1:Gou2R9+il93BqX25LAKCLuM+y9U2T4hlwvT1yprcna4= +github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw= +github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw= +github.com/hashicorp/hcl v1.0.1-vault-7 h1:ag5OxFVy3QYTFTJODRzTKVZ6xvdfLLCA1cy/Y6xGI0I= +github.com/hashicorp/hcl v1.0.1-vault-7/go.mod h1:XYhtn6ijBSAj6n4YqAaf7RBPS4I06AItNorpy+MoQNM= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= @@ -64,15 +94,22 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k= github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY= +github.com/openbao/openbao/api/v2 v2.7.1 h1:moqdSJdKr4Bpb5c/qsUY5ZuA/TIQChVigu0qHgo8GXo= +github.com/openbao/openbao/api/v2 v2.7.1/go.mod h1:uXbMoyH2pjSvNyTepinUvLde8pOJB82EuhUCfOKnKbo= github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU= github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= @@ -87,6 +124,8 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= +github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 h1:n661drycOFuPLCN3Uc8sB6B/s6Z4t2xvBgU1htSHuq8= github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -99,8 +138,8 @@ github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -108,14 +147,16 @@ go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= -golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -130,6 +171,8 @@ golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/pkg/config/config.go b/pkg/config/config.go index d075e82..b189c38 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "log/slog" + "net/url" "os" "path/filepath" "regexp" @@ -12,6 +13,7 @@ import ( "gopkg.in/yaml.v3" + "github.com/obmondo/gfetch/pkg/secrets" "github.com/obmondo/gfetch/pkg/telemetry" ) @@ -25,10 +27,23 @@ const ( maxRepoNameLen = 64 ) +// OpenBaoConfig holds the top-level OpenBao settings. When Enabled is true, +// per-repo ssh_key_path values are interpreted as KV secret paths instead of +// filesystem paths. +type OpenBaoConfig struct { + Enabled bool `yaml:"enabled"` + secrets.OpenBaoConfig `yaml:",inline"` +} + +// kvPathRegex allows alphanumeric, dots, underscores, hyphens, and forward +// slashes in KV secret paths. +var kvPathRegex = regexp.MustCompile(`^[A-Za-z0-9._/\-]+$`) + // Config is the top-level configuration. type Config struct { Defaults *RepoDefaults `yaml:"defaults,omitempty"` Repos map[string]RepoConfig `yaml:"repos"` + OpenBao *OpenBaoConfig `yaml:"openbao,omitempty"` } // PartialValidateError is returned by Config.Validate when one or more repos @@ -92,9 +107,10 @@ type RepoDefaults struct { // Shared fields are inherited from RepoDefaults via embedding. type RepoConfig struct { RepoDefaults `yaml:",inline"` - Name string `yaml:"-"` - URL string `yaml:"url"` - Checkout string `yaml:"checkout"` + Name string `yaml:"-"` + URL string `yaml:"url"` + Checkout string `yaml:"checkout"` + OpenBao *secrets.OpenBaoConfig `yaml:"-"` } // Pattern represents a matching pattern, either literal or regex. @@ -235,6 +251,7 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { var aux struct { Defaults *RepoDefaults `yaml:"defaults,omitempty"` Repos map[string]RepoConfig `yaml:"repos"` + OpenBao *OpenBaoConfig `yaml:"openbao,omitempty"` } if err := value.Decode(&aux); err != nil { @@ -243,6 +260,7 @@ func (c *Config) UnmarshalYAML(value *yaml.Node) error { c.Defaults = aux.Defaults c.Repos = aux.Repos + c.OpenBao = aux.OpenBao if c.Repos == nil { return nil @@ -288,7 +306,7 @@ func loadFile(path string) (*Config, error) { // loadDir loads configuration from a directory structure. func loadDir(dir string) (*Config, error) { - defaults, err := readGlobalDefaults(filepath.Join(dir, "global.yaml")) + defaults, obCfg, err := readGlobalDefaults(filepath.Join(dir, "global.yaml")) if err != nil { return nil, err } @@ -302,6 +320,7 @@ func loadDir(dir string) (*Config, error) { cfg := &Config{ Repos: make(map[string]RepoConfig), Defaults: defaults, + OpenBao: obCfg, } for _, match := range matches { @@ -313,6 +332,9 @@ func loadDir(dir string) (*Config, error) { if err := yaml.Unmarshal(data, &sub); err != nil { return nil, fmt.Errorf("parsing %s: %w", match, err) } + if sub.OpenBao != nil { + slog.Warn("openbao block in per-repo config is ignored; set it in global.yaml", "file", match) + } for name, repo := range sub.Repos { if _, exists := cfg.Repos[name]; exists { return nil, fmt.Errorf("duplicate repo name %q across config files", name) @@ -334,20 +356,23 @@ func loadDir(dir string) (*Config, error) { return cfg, nil } -func readGlobalDefaults(path string) (*RepoDefaults, error) { +func readGlobalDefaults(path string) (*RepoDefaults, *OpenBaoConfig, error) { data, err := os.ReadFile(path) if err != nil { if os.IsNotExist(err) { - return nil, nil + return nil, nil, nil } - return nil, fmt.Errorf("reading global.yaml: %w", err) + return nil, nil, fmt.Errorf("reading global.yaml: %w", err) } - var defaults RepoDefaults - if err := yaml.Unmarshal(data, &defaults); err != nil { - return nil, fmt.Errorf("parsing global.yaml: %w", err) + var parsed struct { + RepoDefaults `yaml:",inline"` + OpenBao *OpenBaoConfig `yaml:"openbao,omitempty"` + } + if err := yaml.Unmarshal(data, &parsed); err != nil { + return nil, nil, fmt.Errorf("parsing global.yaml: %w", err) } - return &defaults, nil + return &parsed.RepoDefaults, parsed.OpenBao, nil } // applyDefaults fills empty repo fields from global defaults. @@ -416,9 +441,20 @@ func (c *Config) Validate() error { return fmt.Errorf("no repos configured") } + // Validate and default the global OpenBao block before per-repo validation. + // An invalid block is a hard config-level error because it is a global + // setting; the reload is rejected and the previous config keeps running. + var obSnapshot *secrets.OpenBaoConfig + if c.OpenBao != nil && c.OpenBao.Enabled { + if err := validateOpenBaoConfig(c.OpenBao); err != nil { + return err + } + obSnapshot = &c.OpenBao.OpenBaoConfig + } + failures := map[string]error{} for name, r := range c.Repos { - if err := c.validateRepo(&r); err != nil { + if err := c.validateRepo(&r, obSnapshot); err != nil { slog.Warn("repo failed validation, dropping", "repo", name, "error", err) telemetry.ConfigRepoValidateFailuresTotal.WithLabelValues(name).Inc() failures[name] = err @@ -434,7 +470,7 @@ func (c *Config) Validate() error { return &PartialValidateError{Failures: failures} } -func (c *Config) validateRepo(r *RepoConfig) error { +func (c *Config) validateRepo(r *RepoConfig, obSnapshot *secrets.OpenBaoConfig) error { if r.Name == "" { return fmt.Errorf("repo name is required") } @@ -442,7 +478,7 @@ func (c *Config) validateRepo(r *RepoConfig) error { if r.URL == "" { return fmt.Errorf("repo %s: url is required", r.Name) } - if err := c.validateAuth(r); err != nil { + if err := c.validateAuth(r, obSnapshot); err != nil { return err } @@ -586,15 +622,75 @@ func compilePatterns(r *RepoConfig) error { return nil } -func (*Config) validateAuth(r *RepoConfig) error { +func (*Config) validateAuth(r *RepoConfig, obSnapshot *secrets.OpenBaoConfig) error { if r.IsHTTPS() { return CheckHTTPSAccessible(r.Name, r.URL) } + if r.SSHKeyPath == "" { return fmt.Errorf("repo %s: ssh_key_path is required", r.Name) } + + // When OpenBao is enabled, ssh_key_path is a KV secret path. + if obSnapshot != nil { + if err := validateKVPath(r.Name, r.SSHKeyPath); err != nil { + return err + } + r.OpenBao = obSnapshot + return nil + } + if _, err := os.Stat(r.SSHKeyPath); err != nil { return fmt.Errorf("repo %s: ssh key not found at %s: %w", r.Name, r.SSHKeyPath, err) } return nil } + +// validateOpenBaoConfig validates the global OpenBao block. Defaults for +// kv_mount and field are applied idempotently. +func validateOpenBaoConfig(ob *OpenBaoConfig) error { + if ob.Addr == "" { + return fmt.Errorf("openbao: addr is required") + } + u, err := url.Parse(ob.Addr) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return fmt.Errorf("openbao: addr must be a valid http or https URL with a host") + } + + if ob.Role == "" { + return fmt.Errorf("openbao: role is required") + } + if ob.ServiceAccountTokenPath == "" { + return fmt.Errorf("openbao: service_account_token_path is required") + } + + if ob.KVMount == "" { + ob.KVMount = "kv" + } + if ob.Field == "" { + ob.Field = "private_key" + } + return nil +} + +// validateKVPath checks that path is a valid KV secret path. +func validateKVPath(repoName, path string) error { + if !kvPathRegex.MatchString(path) { + return fmt.Errorf("repo %s: ssh_key_path %q contains invalid characters for a KV path", repoName, path) + } + if strings.HasPrefix(path, "/") { + return fmt.Errorf("repo %s: ssh_key_path %q must not start with '/'", repoName, path) + } + if strings.HasPrefix(path, "data/") { + return fmt.Errorf("repo %s: ssh_key_path %q must not start with 'data/'", repoName, path) + } + for seg := range strings.SplitSeq(path, "/") { + if seg == "" { + return fmt.Errorf("repo %s: ssh_key_path %q must not contain empty segments", repoName, path) + } + if seg == "." || seg == ".." { + return fmt.Errorf("repo %s: ssh_key_path %q must not contain '.' or '..' segments", repoName, path) + } + } + return nil +} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index e5b08b5..982e29f 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -2,12 +2,15 @@ package config import ( "errors" + "log/slog" "os" "path/filepath" + "strings" "testing" "time" "github.com/prometheus/client_golang/prometheus/testutil" + "gopkg.in/yaml.v3" "github.com/obmondo/gfetch/pkg/telemetry" ) @@ -18,6 +21,7 @@ const ( testRepoName = "test" testLocalPath = "/tmp/test" testRepoURL = "git@github.com:test/repo.git" + goodRepoName = "good" ) func TestPattern_IsRegex(t *testing.T) { @@ -362,14 +366,14 @@ func TestValidate_DropsInvalidRepoAndKeepsRest(t *testing.T) { } cfg := &Config{Repos: map[string]RepoConfig{ - "good": { + goodRepoName: { RepoDefaults: RepoDefaults{ SSHKeyPath: keyFile, LocalPath: "/tmp/good", PollInterval: Duration(30 * time.Second), Branches: []Pattern{{Raw: branchMain}}, }, - Name: "good", + Name: goodRepoName, URL: "git@github.com:test/good.git", }, "bad-missing-url": { @@ -398,7 +402,7 @@ func TestValidate_DropsInvalidRepoAndKeepsRest(t *testing.T) { if _, ok := cfg.Repos["bad-missing-url"]; ok { t.Error("expected bad-missing-url to be dropped from cfg.Repos") } - if _, ok := cfg.Repos["good"]; !ok { + if _, ok := cfg.Repos[goodRepoName]; !ok { t.Error("expected good repo to remain after partial validate") } if got := testutil.ToFloat64(telemetry.ConfigRepoValidateFailuresTotal.WithLabelValues("bad-missing-url")); got != before+1 { @@ -880,3 +884,439 @@ func TestLoadDir_DefaultBranchOnlyRejectsExplicitBranches(t *testing.T) { t.Fatal("expected repo1 to be dropped for setting branches alongside default_branch_only") } } + +// --- OpenBao config tests --- + +func validOpenBao() *OpenBaoConfig { + return &OpenBaoConfig{ + Enabled: true, + Addr: "http://openbao.openbao:8200", + Role: "gfetch", + ServiceAccountTokenPath: "/var/run/secrets/openbao/token", + } +} + +// openBaoTestConfig builds a Config with one SSH repo and the given OpenBao +// block. Use it to avoid repeating the ~10-line literal in every test. +func openBaoTestConfig(ob *OpenBaoConfig, sshKeyPath string) *Config { + return &Config{ + OpenBao: ob, + Repos: map[string]RepoConfig{testRepoName: { + RepoDefaults: RepoDefaults{ + SSHKeyPath: sshKeyPath, + LocalPath: testLocalPath, + PollInterval: Duration(30 * time.Second), + Branches: []Pattern{{Raw: branchMain}}, + }, + Name: testRepoName, + URL: testRepoURL, + }}, + } +} + +func TestValidate_OpenBaoEnabled_ValidRepoGetsOpenBaoCopy(t *testing.T) { + ob := validOpenBao() + cfg := openBaoTestConfig(ob, "ssh-keys/acme/kubeaid") + + if err := cfg.Validate(); err != nil { + t.Fatalf("expected valid config, got: %v", err) + } + + repo := cfg.Repos[testRepoName] + if repo.OpenBao == nil { + t.Fatal("expected repo.OpenBao to be set") + } + if repo.OpenBao.Addr != ob.Addr { + t.Errorf("addr = %q, want %q", repo.OpenBao.Addr, ob.Addr) + } + if repo.OpenBao.KVMount != "kv" { + t.Errorf("kv_mount = %q, want %q (default)", repo.OpenBao.KVMount, "kv") + } + if repo.OpenBao.Field != "private_key" { + t.Errorf("field = %q, want %q (default)", repo.OpenBao.Field, "private_key") + } +} + +func TestValidate_OpenBaoOff_FilePathUnchanged(t *testing.T) { + keyFile := filepath.Join(t.TempDir(), "key") + if err := os.WriteFile(keyFile, []byte("fake"), 0600); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + openbao *OpenBaoConfig + }{ + {"disabled", &OpenBaoConfig{Enabled: false}}, + {"absent", nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := openBaoTestConfig(tt.openbao, keyFile) + if err := cfg.Validate(); err != nil { + t.Fatalf("expected valid config, got: %v", err) + } + repo := cfg.Repos[testRepoName] + if repo.OpenBao != nil { + t.Errorf("expected repo.OpenBao to be nil when openbao is %s", tt.name) + } + }) + } +} + +func TestValidate_OpenBaoInvalidBlock_HardError(t *testing.T) { + tests := []struct { + name string + mutate func(ob *OpenBaoConfig) + }{ + {"empty addr", func(ob *OpenBaoConfig) { ob.Addr = "" }}, + {"no scheme", func(ob *OpenBaoConfig) { ob.Addr = "openbao:8200" }}, + {"ftp scheme", func(ob *OpenBaoConfig) { ob.Addr = "ftp://openbao:8200" }}, + {"no host", func(ob *OpenBaoConfig) { ob.Addr = "http://" }}, + {"empty role", func(ob *OpenBaoConfig) { ob.Role = "" }}, + {"empty service_account_token_path", func(ob *OpenBaoConfig) { ob.ServiceAccountTokenPath = "" }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ob := validOpenBao() + tt.mutate(ob) + cfg := openBaoTestConfig(ob, "ssh-keys/acme") + err := cfg.Validate() + if err == nil { + t.Fatal("expected hard error") + } + if _, ok := errors.AsType[*PartialValidateError](err); ok { + t.Fatal("expected hard error, got PartialValidateError") + } + }) + } +} + +func TestValidate_OpenBaoBadKVPath_PerRepoFailure(t *testing.T) { + tests := []struct { + name string + path string + }{ + {"leading slash", "/ssh-keys/acme"}, + {"double dot", "ssh-keys/../acme"}, + {"single dot segment", "a/./b"}, + {"just dot", "."}, + {"empty segment", "ssh-keys//acme"}, + {"bad charset", "ssh-keys/acme@host"}, + {"data prefix", "data/ssh-keys/acme"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ob := validOpenBao() + cfg := &Config{ + OpenBao: ob, + Repos: map[string]RepoConfig{ + "bad": { + RepoDefaults: RepoDefaults{ + SSHKeyPath: tt.path, + LocalPath: testLocalPath, + PollInterval: Duration(30 * time.Second), + Branches: []Pattern{{Raw: branchMain}}, + }, + Name: "bad", + URL: testRepoURL, + }, + goodRepoName: { + RepoDefaults: RepoDefaults{ + SSHKeyPath: "ssh-keys/valid", + LocalPath: "/tmp/good", + PollInterval: Duration(30 * time.Second), + Branches: []Pattern{{Raw: branchMain}}, + }, + Name: goodRepoName, + URL: testRepoURL, + }, + }, + } + + before := testutil.ToFloat64(telemetry.ConfigRepoValidateFailuresTotal.WithLabelValues("bad")) + + err := cfg.Validate() + var partial *PartialValidateError + if !errors.As(err, &partial) { + t.Fatalf("expected PartialValidateError, got %T: %v", err, err) + } + if _, ok := partial.Failures["bad"]; !ok { + t.Error("expected failure for 'bad' repo") + } + if _, ok := cfg.Repos[goodRepoName]; !ok { + t.Error("expected 'good' repo to survive") + } + + after := testutil.ToFloat64(telemetry.ConfigRepoValidateFailuresTotal.WithLabelValues("bad")) + if after != before+1 { + t.Errorf("metric: got %v, want %v", after, before+1) + } + }) + } +} + +func TestValidate_OpenBaoEnabled_SSHRepoMissingKeyPath_PerRepoFailure(t *testing.T) { + cfg := openBaoTestConfig(validOpenBao(), "") + // Empty ssh_key_path to trigger the "is required" error. + r := cfg.Repos[testRepoName] + r.SSHKeyPath = "" + cfg.Repos[testRepoName] = r + + err := cfg.Validate() + if err == nil { + t.Fatal("expected error for missing ssh_key_path") + } +} + +func TestValidate_OpenBaoEnabled_HTTPSRepoUnaffected(t *testing.T) { + ob := validOpenBao() + cfg := &Config{ + OpenBao: ob, + Repos: map[string]RepoConfig{"public": { + RepoDefaults: RepoDefaults{ + LocalPath: testLocalPath, + PollInterval: Duration(30 * time.Second), + Branches: []Pattern{{Raw: branchMain}}, + }, + Name: "public", + URL: "https://github.com/git/git.git", + }}, + } + + if err := cfg.Validate(); err != nil { + t.Fatalf("expected HTTPS repo to pass with openbao enabled, got: %v", err) + } + repo := cfg.Repos["public"] + if repo.OpenBao != nil { + t.Error("HTTPS repo should not get OpenBao config") + } +} + +func TestLoad_SingleFile_OpenBaoFlowsToRepo(t *testing.T) { + content := `openbao: + enabled: true + addr: http://openbao:8200 + role: gfetch + service_account_token_path: /var/run/secrets/token +repos: + test-repo: + url: git@github.com:test/repo.git + ssh_key_path: ssh-keys/test + local_path: /tmp/test + poll_interval: 1m + branches: + - main +` + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(cfgPath, []byte(content), 0644); err != nil { + t.Fatal(err) + } + + cfg, err := Load(cfgPath) + if err != nil { + t.Fatal(err) + } + if cfg.OpenBao == nil { + t.Fatal("expected OpenBao to be loaded") + } + + if err := cfg.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + + repo := cfg.Repos["test-repo"] + if repo.OpenBao == nil { + t.Fatal("expected repo.OpenBao to be set after validate") + } + if repo.OpenBao.KVMount != "kv" { + t.Errorf("kv_mount default = %q, want %q", repo.OpenBao.KVMount, "kv") + } + if repo.OpenBao.Field != "private_key" { + t.Errorf("field default = %q, want %q", repo.OpenBao.Field, "private_key") + } +} + +func TestLoadDir_GlobalYAMLOpenBaoHonored(t *testing.T) { + dir := t.TempDir() + + if err := os.WriteFile(filepath.Join(dir, "global.yaml"), []byte(`ssh_key_path: ssh-keys/default +local_path: /tmp/repos +poll_interval: 5m +branches: + - "*" +openbao: + enabled: true + addr: http://openbao:8200 + role: gfetch + service_account_token_path: /var/run/secrets/token +`), 0644); err != nil { + t.Fatal(err) + } + + repoDir := filepath.Join(dir, "repo1") + if err := os.MkdirAll(repoDir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repoDir, "config.yaml"), []byte(`repos: + repo1: + url: git@github.com:test/repo1.git + ssh_key_path: ssh-keys/repo1 + branches: + - main +`), 0644); err != nil { + t.Fatal(err) + } + + cfg, err := Load(dir) + if err != nil { + t.Fatal(err) + } + if cfg.OpenBao == nil { + t.Fatal("expected OpenBao from global.yaml") + } + if !cfg.OpenBao.Enabled { + t.Fatal("expected OpenBao.Enabled = true") + } + + if err := cfg.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + repo := cfg.Repos["repo1"] + if repo.OpenBao == nil { + t.Fatal("expected repo.OpenBao to be set") + } +} + +func TestLoadDir_PerRepoOpenBaoIgnored(t *testing.T) { + dir := t.TempDir() + + repoDir := filepath.Join(dir, "repo1") + if err := os.MkdirAll(repoDir, 0755); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(repoDir, "config.yaml") + // Per-repo config has an openbao block, which should be ignored. + if err := os.WriteFile(configPath, []byte(`openbao: + enabled: true + addr: http://openbao:8200 + role: gfetch + service_account_token_path: /var/run/secrets/token +repos: + repo1: + url: git@github.com:test/repo1.git + ssh_key_path: /tmp/key + local_path: /tmp/repo1 + poll_interval: 1m + branches: + - main +`), 0644); err != nil { + t.Fatal(err) + } + + // Write the key file so file-path validation passes. + if err := os.WriteFile("/tmp/key", []byte("fake"), 0600); err != nil { + // Can't write to /tmp/key; use a temp dir instead. + t.Skip("cannot write test key file") + } + t.Cleanup(func() { _ = os.Remove("/tmp/key") }) + + // Capture slog output to verify the warning. + var buf strings.Builder + logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})) + old := slog.Default() + slog.SetDefault(logger) + t.Cleanup(func() { slog.SetDefault(old) }) + + cfg, err := Load(dir) + if err != nil { + t.Fatal(err) + } + // The per-repo openbao is ignored; cfg.OpenBao remains nil because there's + // no global.yaml. + if cfg.OpenBao != nil { + t.Fatal("per-repo openbao should be ignored") + } + + logged := buf.String() + if !strings.Contains(logged, configPath) { + t.Errorf("expected warning to mention per-repo config path %q, got: %s", configPath, logged) + } + + if err := cfg.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + repo := cfg.Repos["repo1"] + if repo.OpenBao != nil { + t.Error("repo should not have OpenBao when per-repo block is ignored") + } +} + +func TestValidate_OpenBaoEnabled_SSHKeyPathInheritedFromDefaults(t *testing.T) { + cfg := openBaoTestConfig(validOpenBao(), "") + cfg.Defaults = &RepoDefaults{SSHKeyPath: "ssh-keys/default"} + + // Clear the repo's ssh_key_path so it inherits from defaults. + r := cfg.Repos[testRepoName] + r.SSHKeyPath = "" + cfg.Repos[testRepoName] = r + + // Apply defaults as loadFile would. + for name, repo := range cfg.Repos { + applyDefaults(&repo, cfg.Defaults) + cfg.Repos[name] = repo + } + + if err := cfg.Validate(); err != nil { + t.Fatalf("expected valid config, got: %v", err) + } + repo := cfg.Repos[testRepoName] + if repo.SSHKeyPath != "ssh-keys/default" { + t.Errorf("ssh_key_path = %q, want %q", repo.SSHKeyPath, "ssh-keys/default") + } + if repo.OpenBao == nil { + t.Fatal("expected repo.OpenBao to be set") + } +} + +func TestMarshal_OpenBaoBlockPresent_RepoOpenBaoAbsent(t *testing.T) { + cfg := openBaoTestConfig(validOpenBao(), "ssh-keys/test") + + if err := cfg.Validate(); err != nil { + t.Fatalf("validate: %v", err) + } + + out, err := yaml.Marshal(cfg) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + s := string(out) + if !strings.Contains(s, "openbao:") { + t.Error("expected openbao block in marshaled output") + } + if !strings.Contains(s, "ssh_key_path: ssh-keys/test") { + t.Error("expected ssh_key_path in marshaled output") + } + // The per-repo OpenBao (yaml:"-") should not appear as a nested openbao + // block under the repo. We check by parsing the output and inspecting the + // repos section: no repo should have an "openbao" key. + var parsed map[string]any + if err := yaml.Unmarshal(out, &parsed); err != nil { + t.Fatalf("unmarshal output: %v", err) + } + repos, ok := parsed["repos"].(map[string]any) + if !ok { + t.Fatal("expected repos map in marshaled output") + } + for name, raw := range repos { + repoMap, ok := raw.(map[string]any) + if !ok { + continue + } + if _, has := repoMap["openbao"]; has { + t.Errorf("repo %q has an openbao key in marshaled output (yaml:\"-\" should suppress it)", name) + } + } +} diff --git a/pkg/daemon/constants.go b/pkg/daemon/constants.go new file mode 100644 index 0000000..37219ab --- /dev/null +++ b/pkg/daemon/constants.go @@ -0,0 +1,57 @@ +package daemon + +import ( + "net/http" + + "github.com/obmondo/gfetch/pkg/gsync" +) + +// Daemon-only failure codes, alongside the gsync.Classify codes in the HTTP +// error contract. +const ( + codeShuttingDown gsync.FailureCode = "shutting_down" + codeSyncInProgress gsync.FailureCode = "sync_in_progress" + codeRepoNotFound gsync.FailureCode = "repo_not_found" + codeConfigLoadFailed gsync.FailureCode = "config_load_failed" + codeConfigInvalid gsync.FailureCode = "config_invalid" + codeConfigApplyFailed gsync.FailureCode = "config_apply_failed" +) + +type failureSpec struct { + status int + message string +} + +// failureSpecs is the single source of each code's HTTP status and message. +var failureSpecs = map[gsync.FailureCode]failureSpec{ + gsync.CodeSecretUnavailable: {http.StatusServiceUnavailable, "secret fetch failed: openbao unavailable"}, + gsync.CodeSecretForbidden: {http.StatusUnprocessableEntity, "secret fetch failed: access denied"}, + gsync.CodeSecretNotFound: {http.StatusUnprocessableEntity, "secret fetch failed: secret not found"}, + gsync.CodeSecretInvalid: {http.StatusUnprocessableEntity, "secret fetch failed: invalid ssh key"}, + gsync.CodeSecretRejected: {http.StatusUnprocessableEntity, "secret fetch failed: request rejected"}, + gsync.CodeSecretConfigInvalid: {http.StatusInternalServerError, "secret fetch failed: openbao client config invalid"}, + gsync.CodeGitAuthFailed: {http.StatusUnprocessableEntity, "git clone failed: authentication rejected by git host"}, + gsync.CodeGitRepoNotFound: {http.StatusUnprocessableEntity, "git clone failed: repository not found or no access"}, + gsync.CodeGitHostKeyMismatch: {http.StatusUnprocessableEntity, "git clone failed: host key verification failed"}, + gsync.CodeGitUnreachable: {http.StatusServiceUnavailable, "git clone failed: git host unreachable"}, + gsync.CodeInternal: {http.StatusInternalServerError, "sync failed: internal error"}, + codeShuttingDown: {http.StatusServiceUnavailable, errDaemonShuttingDown.Error()}, + codeSyncInProgress: {http.StatusConflict, errSyncInProgress.Error()}, + codeRepoNotFound: {http.StatusNotFound, "repo not found"}, + codeConfigLoadFailed: {http.StatusInternalServerError, "config load failed"}, + codeConfigInvalid: {http.StatusUnprocessableEntity, "config invalid"}, + codeConfigApplyFailed: {http.StatusInternalServerError, "config apply failed"}, +} + +// specFor returns the code's table row; a missing code falls back to the +// internal row. +func specFor(c gsync.FailureCode) failureSpec { + if s, ok := failureSpecs[c]; ok { + return s + } + return failureSpecs[gsync.CodeInternal] +} + +func statusFor(c gsync.FailureCode) int { return specFor(c).status } + +func messageFor(c gsync.FailureCode) string { return specFor(c).message } diff --git a/pkg/daemon/scheduler.go b/pkg/daemon/scheduler.go index edd4341..e67dc2b 100644 --- a/pkg/daemon/scheduler.go +++ b/pkg/daemon/scheduler.go @@ -4,9 +4,11 @@ import ( "context" "fmt" "log/slog" + "maps" "net/http" "os" "os/signal" + "slices" "sort" "sync" "sync/atomic" @@ -168,7 +170,7 @@ func (s *Scheduler) runReloadOnSignal(ctx context.Context, hupCh <-chan os.Signa return case <-hupCh: slog.Info("received SIGHUP, reloading config") - if _, _, err := loadValidateAndReload(s); err != nil { + if _, err := loadValidateAndReload(s); err != nil { slog.Warn("SIGHUP reload failed", "error", err) } } @@ -198,10 +200,11 @@ func (s *Scheduler) applyInitial(cfg *config.Config) error { return nil } -// Reload cancels every running job, swaps in newCfg, and re-schedules every -// repo with a delayed first-fire (one full poll_interval out). The delay is -// deliberate: SIGHUP / POST /reload can flip many repos' configs at once -// (e.g. a defaults edit cascading to every tenant), and firing them all +// Reload cancels every running job, swaps in newCfg, evicts the cached keys of +// repos it added, removed or re-keyed, and re-schedules +// every repo with a delayed first-fire (one full poll_interval out). The +// delay is deliberate: SIGHUP / POST /reload can flip many repos' configs at +// once (e.g. a defaults edit cascading to every tenant), and firing them all // immediately would stampede the upstream git host. // // In-flight syncs are NOT interrupted. Cancelling a gocron job does not kill @@ -214,7 +217,7 @@ func (s *Scheduler) Reload(newCfg *config.Config) (ReloadResult, error) { defer s.applyMu.Unlock() if s.state.shuttingDown.Load() { - return ReloadResult{}, fmt.Errorf("daemon is shutting down") + return ReloadResult{}, errDaemonShuttingDown } for name, jobID := range s.jobs { @@ -226,8 +229,14 @@ func (s *Scheduler) Reload(newCfg *config.Config) (ReloadResult, error) { // Swap the live config so any concurrent fire/handler sees the new view. // In-flight syncs already hold their *RepoConfig and finish against it. + old := s.cfg.Load() s.cfg.Store(newCfg) + // Evict keys of repos added, removed or re-keyed; unchanged repos keep + // their cached key and the OpenBao token survives. A key rotated in place + // is caught by the ssh-auth refetch. + s.syncer.InvalidateSecrets(changedSecretPaths(old, newCfg)) + names := make([]string, 0, len(newCfg.Repos)) for name, repo := range newCfg.Repos { jobID, err := s.scheduleJob(name, time.Duration(repo.PollInterval), false) @@ -293,3 +302,57 @@ func (s *Scheduler) scheduleJob(name string, interval time.Duration, startNow bo } return job.ID(), nil } + +// changedSecretPaths returns the OpenBao key paths of repos that newCfg adds, +// removes, or re-keys (a different ssh_key_path or OpenBao config) relative to +// oldCfg. A path an unchanged repo still reads is left out: eviction is per +// path, so evicting it would drop that repo's cached key too. Repos without +// OpenBao are ignored. A nil oldCfg counts as empty. +func changedSecretPaths(oldCfg, newCfg *config.Config) []string { + var oldRepos, newRepos map[string]config.RepoConfig + if oldCfg != nil { + oldRepos = oldCfg.Repos + } + if newCfg != nil { + newRepos = newCfg.Repos + } + + paths := make(map[string]struct{}) + kept := make(map[string]struct{}) + add := func(r config.RepoConfig) { + if r.OpenBao != nil { + paths[r.SSHKeyPath] = struct{}{} + } + } + for name, o := range oldRepos { + n, ok := newRepos[name] + if ok && sameSecretSource(o, n) { + if o.OpenBao != nil { + kept[o.SSHKeyPath] = struct{}{} + } + continue + } + add(o) + if ok { + add(n) + } + } + for name, n := range newRepos { + if _, ok := oldRepos[name]; !ok { + add(n) + } + } + for p := range kept { + delete(paths, p) + } + return slices.Sorted(maps.Keys(paths)) +} + +// sameSecretSource reports whether two configs of one repo read the same key: +// neither uses OpenBao, or both use the same OpenBao config and key path. +func sameSecretSource(a, b config.RepoConfig) bool { + if a.OpenBao == nil || b.OpenBao == nil { + return a.OpenBao == nil && b.OpenBao == nil + } + return a.SSHKeyPath == b.SSHKeyPath && *a.OpenBao == *b.OpenBao +} diff --git a/pkg/daemon/scheduler_test.go b/pkg/daemon/scheduler_test.go index 51cfecd..f7d7c94 100644 --- a/pkg/daemon/scheduler_test.go +++ b/pkg/daemon/scheduler_test.go @@ -2,6 +2,7 @@ package daemon import ( "log/slog" + "slices" "testing" "time" @@ -9,6 +10,7 @@ import ( "github.com/obmondo/gfetch/pkg/config" "github.com/obmondo/gfetch/pkg/gsync" + "github.com/obmondo/gfetch/pkg/secrets" ) func TestNewScheduler(t *testing.T) { @@ -180,3 +182,126 @@ func assertEqualSlice(t *testing.T, label string, got, want []string) { } } } + +// TestSchedulerReload_InvalidatesSecrets verifies that a reload evicts only +// the key paths of OpenBao repos it adds, removes or re-keys, never a path an +// unchanged repo still reads, and that a refused (shutting-down) reload evicts +// nothing. +func TestSchedulerReload_InvalidatesSecrets(t *testing.T) { + const keyA = "keys/a" + + obRepo := func(name, keyPath string) config.RepoConfig { + r := testRepo(name, testMainBranch) + r.SSHKeyPath = keyPath + r.OpenBao = &secrets.OpenBaoConfig{Addr: testOpenBaoAddr, Role: "gfetch", KVMount: "kv", Field: "private_key"} + return r + } + fileRepo := func(name, keyPath string) config.RepoConfig { + r := testRepo(name, testMainBranch) + r.SSHKeyPath = keyPath + return r + } + + tests := []struct { + name string + old map[string]config.RepoConfig + new map[string]config.RepoConfig + shuttingDown bool + want []string + }{ + { + name: "unchanged", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + }, + { + name: "added", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": obRepo("a", keyA), "b": obRepo("b", "keys/b")}, + want: []string{"keys/b"}, + }, + { + name: "removed", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA), "b": obRepo("b", "keys/b")}, + new: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + want: []string{"keys/b"}, + }, + { + name: "removed repo shared its path with an unchanged one", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA), "b": obRepo("b", keyA)}, + new: map[string]config.RepoConfig{"b": obRepo("b", keyA)}, + }, + { + name: "re-keyed repo shared its old path with an unchanged one", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA), "b": obRepo("b", keyA)}, + new: map[string]config.RepoConfig{"a": obRepo("a", "keys/a2"), "b": obRepo("b", keyA)}, + want: []string{"keys/a2"}, + }, + { + name: "re-keyed", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": obRepo("a", "keys/a2")}, + want: []string{keyA, "keys/a2"}, + }, + { + name: "openbao config changed", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": func() config.RepoConfig { + r := obRepo("a", keyA) + r.OpenBao.Role = "gfetch-2" + return r + }()}, + want: []string{keyA}, + }, + { + name: "openbao to file key", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": fileRepo("a", "/keys/a")}, + want: []string{keyA}, + }, + { + name: "file key to openbao", + old: map[string]config.RepoConfig{"a": fileRepo("a", "/keys/a")}, + new: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + want: []string{keyA}, + }, + { + name: "file key", + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"a": obRepo("a", keyA), "f": testRepo("f", testMainBranch)}, + }, + { + name: testShuttingDownCaseName, + old: map[string]config.RepoConfig{"a": obRepo("a", keyA)}, + new: map[string]config.RepoConfig{"b": obRepo("b", "keys/b")}, + shuttingDown: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reader := &fakeSecretReaderForDaemonTests{} + sched := NewScheduler(gsync.New(gsync.WithSecretReader(reader)), ":0", "") + cron := newGocronForTest(t) + sched.cron = cron + t.Cleanup(func() { _ = cron.Shutdown() }) + + if err := sched.applyInitial(&config.Config{Repos: tt.old}); err != nil { + t.Fatalf("applyInitial: %v", err) + } + sched.state.shuttingDown.Store(tt.shuttingDown) + + _, err := sched.Reload(&config.Config{Repos: tt.new}) + if tt.shuttingDown != (err != nil) { + t.Fatalf("Reload error = %v, want error: %v", err, tt.shuttingDown) + } + + reader.mu.Lock() + got := slices.Sorted(slices.Values(reader.invalidated)) + reader.mu.Unlock() + if !slices.Equal(got, tt.want) { + t.Errorf("invalidated = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/pkg/daemon/server.go b/pkg/daemon/server.go index 393d792..549eddd 100644 --- a/pkg/daemon/server.go +++ b/pkg/daemon/server.go @@ -18,6 +18,15 @@ import ( var errSyncInProgress = errors.New("sync already in progress") var errDaemonShuttingDown = errors.New("daemon shutting down") +// reloadError is a fatal reload failure carrying its failure code. +type reloadError struct { + code gsync.FailureCode + err error +} + +func (e *reloadError) Error() string { return e.err.Error() } +func (e *reloadError) Unwrap() error { return e.err } + func newServer(sched *Scheduler) http.Handler { mux := http.NewServeMux() @@ -44,53 +53,27 @@ func newServer(sched *Scheduler) http.Handler { // quiescent dropped repo gets the terminal 404. This lets a caller // tearing the clone down wait instead of racing the live sync. if sched.state.guard.IsActive(repoName) { - http.Error(w, `{"error":"sync already in progress"}`, http.StatusConflict) + writeJSONError(w, codeSyncInProgress, errSyncInProgress.Error()) return } - http.Error(w, `{"error":"repo not found"}`, http.StatusNotFound) + writeJSONError(w, codeRepoNotFound, messageFor(codeRepoNotFound)) return } slog.Info("manual sync triggered", "repo", repoName) result := RunGuardedSync(r.Context(), sched.syncer, sched.state, &repo, "manual") - if errors.Is(result.Err, errDaemonShuttingDown) { - writeResultWithStatus(w, []gsync.Result{result}, http.StatusServiceUnavailable) - return - } - if errors.Is(result.Err, errSyncInProgress) { - writeResultWithStatus(w, []gsync.Result{result}, http.StatusConflict) - return - } - writeResult(w, []gsync.Result{result}) + writeResult(r.Context(), w, []gsync.Result{result}) }) mux.HandleFunc("POST /sync", func(w http.ResponseWriter, r *http.Request) { cfg := sched.Config() slog.Info("manual sync triggered for all repos") results := make([]gsync.Result, 0, len(cfg.Repos)) - hasShutdownErr := false - hasInProgressErr := false for name := range cfg.Repos { repo := cfg.Repos[name] - res := RunGuardedSync(r.Context(), sched.syncer, sched.state, &repo, "manual") - if errors.Is(res.Err, errDaemonShuttingDown) { - hasShutdownErr = true - } - if errors.Is(res.Err, errSyncInProgress) { - hasInProgressErr = true - } - results = append(results, res) - } - - if hasShutdownErr { - writeResultWithStatus(w, results, http.StatusServiceUnavailable) - return + results = append(results, RunGuardedSync(r.Context(), sched.syncer, sched.state, &repo, "manual")) } - if hasInProgressErr { - writeResultWithStatus(w, results, http.StatusConflict) - return - } - writeResult(w, results) + writeResult(r.Context(), w, results) }) return mux @@ -98,28 +81,39 @@ func newServer(sched *Scheduler) http.Handler { // handleReload services POST /reload directly. func handleReload(w http.ResponseWriter, _ *http.Request, sched *Scheduler) { - res, status, err := loadValidateAndReload(sched) - w.Header().Set("Content-Type", "application/json") + res, err := loadValidateAndReload(sched) if err != nil { - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) + code := codeConfigApplyFailed + if re, ok := errors.AsType[*reloadError](err); ok { + code = re.code + } + writeJSONError(w, code, err.Error()) return } + w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(res) } +// writeJSONError writes a JSON error body carrying the raw error text plus +// the stable code, with the status and message taken from the code's table +// row. +func writeJSONError(w http.ResponseWriter, code gsync.FailureCode, errText string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(statusFor(code)) + _ = json.NewEncoder(w).Encode(map[string]string{"error": errText, "code": string(code), "message": messageFor(code)}) +} + // loadValidateAndReload reads the config from disk, validates it, and applies // it via Scheduler.Reload. On fatal failure the old config keeps running and -// the returned status is the HTTP status the caller should write. Per-repo -// validate failures are surfaced as a *config.PartialValidateError and the -// reload proceeds with the remaining repos; an empty result after partial -// errors is treated as a 422. -func loadValidateAndReload(sched *Scheduler) (ReloadResult, int, error) { +// the returned error is a *reloadError carrying the failure code. Per-repo validate failures are surfaced as a +// *config.PartialValidateError and the reload proceeds with the remaining +// repos; an empty result after partial errors is treated as a 422. +func loadValidateAndReload(sched *Scheduler) (ReloadResult, error) { cfg, err := config.Load(sched.ConfigPath()) if err != nil { telemetry.ConfigReloadFailuresTotal.WithLabelValues("load").Inc() slog.Warn("config reload failed (load)", "error", err) - return ReloadResult{}, http.StatusInternalServerError, fmt.Errorf("load config: %w", err) + return ReloadResult{}, &reloadError{code: codeConfigLoadFailed, err: fmt.Errorf("load config: %w", err)} } var partialValidate *config.PartialValidateError @@ -130,23 +124,27 @@ func loadValidateAndReload(sched *Scheduler) (ReloadResult, int, error) { case err != nil: telemetry.ConfigReloadFailuresTotal.WithLabelValues("validate").Inc() slog.Warn("config reload failed (validate)", "error", err) - return ReloadResult{}, http.StatusUnprocessableEntity, fmt.Errorf("validate config: %w", err) + return ReloadResult{}, &reloadError{code: codeConfigInvalid, err: fmt.Errorf("validate config: %w", err)} } if len(cfg.Repos) == 0 { telemetry.ConfigReloadFailuresTotal.WithLabelValues("validate").Inc() slog.Warn("config reload aborted: no usable repos after load+validate, keeping previous config") - return ReloadResult{}, http.StatusUnprocessableEntity, fmt.Errorf("validate config: no usable repos after load+validate") + return ReloadResult{}, &reloadError{code: codeConfigInvalid, err: fmt.Errorf("validate config: no usable repos after load+validate")} } res, err := sched.Reload(cfg) if err != nil { telemetry.ConfigReloadFailuresTotal.WithLabelValues("apply").Inc() slog.Warn("config reload failed (apply)", "error", err) - return ReloadResult{}, http.StatusInternalServerError, fmt.Errorf("apply config: %w", err) + code := codeConfigApplyFailed + if errors.Is(err, errDaemonShuttingDown) { + code = codeShuttingDown + } + return ReloadResult{}, &reloadError{code: code, err: fmt.Errorf("apply config: %w", err)} } slog.Info("config reloaded", "repos", len(res.Repos)) - return res, http.StatusOK, nil + return res, nil } func RunGuardedSync(ctx context.Context, s *gsync.Syncer, state *SyncRuntimeState, repo *config.RepoConfig, source string) gsync.Result { @@ -171,21 +169,25 @@ func RunGuardedSync(ctx context.Context, s *gsync.Syncer, state *SyncRuntimeStat return s.SyncRepo(ctx, repo, gsync.SyncOptions{}) } -func writeResult(w http.ResponseWriter, results []gsync.Result) { - writeResultWithStatus(w, results, 0) +// resultCode returns the failure code for a sync result error. +func resultCode(ctx context.Context, err error) gsync.FailureCode { + switch { + case errors.Is(err, errDaemonShuttingDown): + return codeShuttingDown + case errors.Is(err, errSyncInProgress): + return codeSyncInProgress + case ctx.Err() != nil: + // The caller went away; nobody reads this reply. + return gsync.CodeInternal + } + return gsync.Classify(err) } -func writeResultWithStatus(w http.ResponseWriter, results []gsync.Result, status int) { +// writeResult writes the per-repo results. The status is the aggregated +// failure status, or 200 when no repo failed. +func writeResult(ctx context.Context, w http.ResponseWriter, results []gsync.Result) { w.Header().Set("Content-Type", "application/json") - hasErr := false - for _, r := range results { - if r.Err != nil { - hasErr = true - break - } - } - type jsonResult struct { RepoName string `json:"repo"` BranchesSynced []string `json:"branches_synced,omitempty"` @@ -194,9 +196,12 @@ func writeResultWithStatus(w http.ResponseWriter, results []gsync.Result, status TagsFetched []string `json:"tags_fetched,omitempty"` TagsUpToDate []string `json:"tags_up_to_date,omitempty"` Error string `json:"error,omitempty"` + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` } out := make([]jsonResult, len(results)) + failStatus := 0 for i, r := range results { out[i] = jsonResult{ RepoName: r.RepoName, @@ -208,15 +213,24 @@ func writeResultWithStatus(w http.ResponseWriter, results []gsync.Result, status } if r.Err != nil { out[i].Error = r.Err.Error() + code := resultCode(ctx, r.Err) + out[i].Code = string(code) + out[i].Message = messageFor(code) + // All failures sharing one status report it; mixed statuses + // fall back to 500. Successful repos don't count. + switch st := statusFor(code); failStatus { + case 0: + failStatus = st + case st: + default: + failStatus = http.StatusInternalServerError + } } } - if status != 0 { - w.WriteHeader(status) - } - - if status == 0 && hasErr { - w.WriteHeader(http.StatusInternalServerError) + if failStatus == 0 { + failStatus = http.StatusOK } + w.WriteHeader(failStatus) _ = json.NewEncoder(w).Encode(out) } diff --git a/pkg/daemon/server_test.go b/pkg/daemon/server_test.go index 502ac8a..915642a 100644 --- a/pkg/daemon/server_test.go +++ b/pkg/daemon/server_test.go @@ -1,17 +1,37 @@ package daemon import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" "encoding/json" + "encoding/pem" + "fmt" "io" "log/slog" "net/http" "net/http/httptest" + "net/url" "os" "path/filepath" + "strings" + "sync" "testing" + "time" + + "github.com/go-git/go-git/v5" "github.com/obmondo/gfetch/pkg/config" "github.com/obmondo/gfetch/pkg/gsync" + "github.com/obmondo/gfetch/pkg/secrets" +) + +const ( + testExistingRepoName = "existing" + testMainBranch = "main" + testShuttingDownCaseName = "shutting down" + testOpenBaoAddr = "http://openbao:8200" ) func TestHealthEndpoint(t *testing.T) { @@ -41,64 +61,136 @@ func TestHealthEndpoint(t *testing.T) { } } -func TestReloadEndpoint_ValidConfig(t *testing.T) { - dir := t.TempDir() - keyFile := writeFakeSSHKey(t, dir) - writeSSHRepoConfig(t, dir, "repo1", keyFile) - - sched := newTestScheduler(t) - sched.configPath = dir - if err := sched.applyInitial(&config.Config{Repos: map[string]config.RepoConfig{}}); err != nil { - t.Fatalf("applyInitial: %v", err) +func TestReloadEndpoint_Status(t *testing.T) { + tests := []struct { + name string + initial map[string]config.RepoConfig + shuttingDown bool + wantStatus int + wantCode string + wantMessage string + wantRepo string + }{ + { + name: "valid config", + initial: map[string]config.RepoConfig{}, + wantStatus: http.StatusOK, + wantRepo: "repo1", + }, + { + name: testShuttingDownCaseName, + initial: map[string]config.RepoConfig{testExistingRepoName: testRepo(testExistingRepoName, testMainBranch)}, + shuttingDown: true, + wantStatus: http.StatusServiceUnavailable, + wantCode: string(codeShuttingDown), + wantMessage: "daemon shutting down", + wantRepo: testExistingRepoName, + }, } - h := newServer(sched) - req := httptest.NewRequest(http.MethodPost, "/reload", nil) - rr := httptest.NewRecorder() - h.ServeHTTP(rr, req) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + keyFile := writeFakeSSHKey(t, dir) + writeSSHRepoConfig(t, dir, "repo1", keyFile) - if rr.Code != http.StatusOK { - t.Fatalf("status = %d, want %d, body=%s", rr.Code, http.StatusOK, rr.Body.String()) + sched := newTestScheduler(t) + sched.configPath = dir + if err := sched.applyInitial(&config.Config{Repos: tt.initial}); err != nil { + t.Fatalf("applyInitial: %v", err) + } + if tt.shuttingDown { + sched.state.shuttingDown.Store(true) + } + + h := newServer(sched) + req := httptest.NewRequest(http.MethodPost, "/reload", nil) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + + if rr.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d, body=%s", rr.Code, tt.wantStatus, rr.Body.String()) + } + if tt.wantStatus == http.StatusOK { + assertReloadResultForTestReloadEndpointStatus(t, rr, tt.wantRepo) + } else { + body := decodeJSONErrorForDaemonEndpointTests(t, rr, tt.wantCode) + if body["message"] != tt.wantMessage { + t.Errorf("message = %q, want %q", body["message"], tt.wantMessage) + } + } + if _, ok := sched.Config().Repos[tt.wantRepo]; !ok { + t.Errorf("expected %s to be in scheduler config", tt.wantRepo) + } + }) } +} + +// assertReloadResultForTestReloadEndpointStatus asserts a successful +// reload response listing exactly wantRepo. +func assertReloadResultForTestReloadEndpointStatus(t *testing.T, rr *httptest.ResponseRecorder, wantRepo string) { + t.Helper() var res ReloadResult if err := json.NewDecoder(rr.Body).Decode(&res); err != nil { t.Fatalf("decode: %v", err) } - if len(res.Repos) != 1 || res.Repos[0] != "repo1" { - t.Errorf("expected [repo1], got %+v", res) - } - if _, ok := sched.Config().Repos["repo1"]; !ok { - t.Errorf("expected repo1 to be in scheduler config") + if len(res.Repos) != 1 || res.Repos[0] != wantRepo { + t.Errorf("expected [%s], got %+v", wantRepo, res) } } func TestReloadEndpoint_InvalidConfigKeepsOldConfig(t *testing.T) { - dir := t.TempDir() - brokenDir := filepath.Join(dir, "broken") - if err := os.MkdirAll(brokenDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(brokenDir, "config.yaml"), []byte(": :: bad yaml ::"), 0o644); err != nil { - t.Fatal(err) + tests := []struct { + name string + body string + wantStatus int + wantCode string + }{ + { + name: "malformed yaml", + body: ": :: bad yaml ::", + wantStatus: http.StatusInternalServerError, + wantCode: string(codeConfigLoadFailed), + }, + { + name: "no valid repos", + body: "repos:\n broken:\n poll_interval: 1m\n", + wantStatus: http.StatusUnprocessableEntity, + wantCode: string(codeConfigInvalid), + }, } - sched := newTestScheduler(t) - sched.configPath = dir - old := &config.Config{Repos: map[string]config.RepoConfig{"existing": testRepo("existing", "main")}} - if err := sched.applyInitial(old); err != nil { - t.Fatalf("applyInitial: %v", err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + brokenDir := filepath.Join(dir, "broken") + if err := os.MkdirAll(brokenDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(brokenDir, "config.yaml"), []byte(tt.body), 0o644); err != nil { + t.Fatal(err) + } - h := newServer(sched) - req := httptest.NewRequest(http.MethodPost, "/reload", nil) - rr := httptest.NewRecorder() - h.ServeHTTP(rr, req) + sched := newTestScheduler(t) + sched.configPath = dir + old := &config.Config{Repos: map[string]config.RepoConfig{testExistingRepoName: testRepo(testExistingRepoName, testMainBranch)}} + if err := sched.applyInitial(old); err != nil { + t.Fatalf("applyInitial: %v", err) + } - if rr.Code != http.StatusInternalServerError && rr.Code != http.StatusUnprocessableEntity { - t.Fatalf("status = %d, want 500 or 422, body=%s", rr.Code, rr.Body.String()) - } - if _, ok := sched.Config().Repos["existing"]; !ok { - t.Errorf("old config was lost after failed reload") + h := newServer(sched) + req := httptest.NewRequest(http.MethodPost, "/reload", nil) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + + if rr.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d, body=%s", rr.Code, tt.wantStatus, rr.Body.String()) + } + decodeJSONErrorForDaemonEndpointTests(t, rr, tt.wantCode) + if _, ok := sched.Config().Repos[testExistingRepoName]; !ok { + t.Errorf("old config was lost after failed reload") + } + }) } } @@ -120,6 +212,9 @@ func TestSyncEndpoint_DroppedRepoGuardGates(t *testing.T) { if rr.Code != http.StatusNotFound { t.Fatalf("quiescent: status = %d, want %d, body=%s", rr.Code, http.StatusNotFound, rr.Body.String()) } + if body := decodeJSONErrorForDaemonEndpointTests(t, rr, string(codeRepoNotFound)); body["error"] != "repo not found" { + t.Errorf("error = %q, want %q", body["error"], "repo not found") + } // Dropped from config but a sync still holds the guard: 409. if !sched.state.guard.TryStart(dropped) { @@ -130,6 +225,9 @@ func TestSyncEndpoint_DroppedRepoGuardGates(t *testing.T) { if rr.Code != http.StatusConflict { t.Fatalf("in-flight: status = %d, want %d, body=%s", rr.Code, http.StatusConflict, rr.Body.String()) } + if body := decodeJSONErrorForDaemonEndpointTests(t, rr, string(codeSyncInProgress)); body["error"] != "sync already in progress" { + t.Errorf("error = %q, want %q", body["error"], "sync already in progress") + } // Sync finished, guard cleared: back to terminal 404. sched.state.guard.Finish(dropped) @@ -138,6 +236,420 @@ func TestSyncEndpoint_DroppedRepoGuardGates(t *testing.T) { if rr.Code != http.StatusNotFound { t.Fatalf("after finish: status = %d, want %d, body=%s", rr.Code, http.StatusNotFound, rr.Body.String()) } + if body := decodeJSONErrorForDaemonEndpointTests(t, rr, string(codeRepoNotFound)); body["error"] != "repo not found" { + t.Errorf("error = %q, want %q", body["error"], "repo not found") + } +} + +// decodeJSONErrorForDaemonEndpointTests asserts a JSON error response with +// wantCode and non-empty message and error, and returns the body for any +// further checks. +func decodeJSONErrorForDaemonEndpointTests(t *testing.T, rr *httptest.ResponseRecorder, wantCode string) map[string]string { + t.Helper() + if got := rr.Header().Get("Content-Type"); got != "application/json" { + t.Errorf("content-type = %q, want %q", got, "application/json") + } + var body map[string]string + if err := json.NewDecoder(rr.Body).Decode(&body); err != nil { + t.Fatalf("decode body: %v", err) + } + if body["code"] != wantCode { + t.Errorf("code = %q, want %q", body["code"], wantCode) + } + if body["message"] == "" || body["error"] == "" { + t.Errorf("expected non-empty message and error, got %+v", body) + } + return body +} + +// TestFailureSpecs verifies every failure code has a non-empty, unique +// message and a status in the HTTP error contract. +func TestFailureSpecs(t *testing.T) { + allowed := map[int]bool{ + http.StatusNotFound: true, + http.StatusConflict: true, + http.StatusUnprocessableEntity: true, + http.StatusInternalServerError: true, + http.StatusServiceUnavailable: true, + } + seen := make(map[string]gsync.FailureCode, len(failureSpecs)) + for code, spec := range failureSpecs { + if spec.message == "" { + t.Errorf("%s: empty message", code) + } + if other, dup := seen[spec.message]; dup { + t.Errorf("%s: message %q duplicates %s", code, spec.message, other) + } + seen[spec.message] = code + if !allowed[spec.status] { + t.Errorf("%s: status %d is not in the contract", code, spec.status) + } + } +} + +// TestSyncEndpoint_FailureStatusAndCode verifies that a failed manual sync +// maps to the HTTP status of its failure class and carries the stable code +// and message while error keeps the detailed chain. +// syncEndpointFailureRow is one row of TestSyncEndpoint_FailureStatusAndCode. +type syncEndpointFailureRow struct { + name string + readErr error + // readKey makes the secret read return a valid key, so the sync dials. + readKey bool + cancelled bool + guardHeld bool + shuttingDown bool + repo func(t *testing.T, name string) config.RepoConfig + wantStatus int + wantCode string + wantErr string +} + +func TestSyncEndpoint_FailureStatusAndCode(t *testing.T) { + const repoName = "failing-repo" + + tests := []syncEndpointFailureRow{ + { + name: "secret unavailable", + readErr: secrets.ErrUnavailable, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusServiceUnavailable, + wantCode: string(gsync.CodeSecretUnavailable), + wantErr: secrets.ErrUnavailable.Error(), + }, + { + name: "secret forbidden", + readErr: fmt.Errorf("%w: denied", secrets.ErrForbidden), + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusUnprocessableEntity, + wantCode: string(gsync.CodeSecretForbidden), + wantErr: secrets.ErrForbidden.Error() + ": denied", + }, + { + name: "secret rejected", + readErr: fmt.Errorf("%w (status 400): bad request", secrets.ErrRejected), + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusUnprocessableEntity, + wantCode: string(gsync.CodeSecretRejected), + wantErr: secrets.ErrRejected.Error() + " (status 400): bad request", + }, + { + // A client that cannot be built is our config, not a backend + // outage: 500, so the caller does not retry it. + name: "secret client config invalid", + readErr: fmt.Errorf("%w: creating openbao client: bad address", secrets.ErrClientConfig), + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusInternalServerError, + wantCode: string(gsync.CodeSecretConfigInvalid), + wantErr: secrets.ErrClientConfig.Error(), + }, + { + name: "secret not found", + readErr: secrets.ErrNotFound, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusUnprocessableEntity, + wantCode: string(gsync.CodeSecretNotFound), + wantErr: secrets.ErrNotFound.Error(), + }, + { + // The repo's host refuses the dial: transient, so 503 like an + // OpenBao outage rather than a 422 about the request. + name: "git host unreachable", + readKey: true, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusServiceUnavailable, + wantCode: string(gsync.CodeGitUnreachable), + wantErr: "connection refused", + }, + { + name: "local repo not found", + repo: missingLocalRepoForSyncEndpointTests, + wantStatus: http.StatusUnprocessableEntity, + wantCode: string(gsync.CodeGitRepoNotFound), + wantErr: "repository not found", + }, + { + // Store.Read returns the caller's ctx error unwrapped: internal. + name: "caller cancelled", + cancelled: true, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusInternalServerError, + wantCode: string(gsync.CodeInternal), + wantErr: "context canceled", + }, + { + // An OpenBao request timeout is wrapped in ErrUnavailable: 503. + name: "openbao request timeout", + readErr: fmt.Errorf("%w: %w", secrets.ErrUnavailable, &url.Error{Op: "Put", URL: testOpenBaoAddr, Err: context.DeadlineExceeded}), + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusServiceUnavailable, + wantCode: string(gsync.CodeSecretUnavailable), + wantErr: secrets.ErrUnavailable.Error(), + }, + { + // The API's gfetch cleanup job keys on this 409 (utils/gfetch/client.go ErrSyncInProgress). + name: "sync in progress", + guardHeld: true, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusConflict, + wantCode: string(codeSyncInProgress), + wantErr: "sync already in progress", + }, + { + name: testShuttingDownCaseName, + shuttingDown: true, + repo: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusServiceUnavailable, + wantCode: string(codeShuttingDown), + wantErr: "daemon shutting down", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + runSyncEndpointFailureRow(t, repoName, tt) + }) + } +} + +// runSyncEndpointFailureRow syncs repoName through the HTTP endpoint with +// the row's secret reader and daemon state, and checks the status, code, +// message and error of the single result. +func runSyncEndpointFailureRow(t *testing.T, repoName string, tt syncEndpointFailureRow) { + t.Helper() + reader := &fakeSecretReaderForDaemonTests{err: tt.readErr} + if tt.readKey { + reader.key = ed25519PEMForSyncEndpointTests(t) + } + sched := NewScheduler(gsync.New(gsync.WithSecretReader(reader)), ":0", "") + sched.cfg.Store(&config.Config{Repos: map[string]config.RepoConfig{repoName: tt.repo(t, repoName)}}) + if tt.guardHeld { + if !sched.state.guard.TryStart(repoName) { + t.Fatalf("TryStart(%q) = false, want true", repoName) + } + t.Cleanup(func() { sched.state.guard.Finish(repoName) }) + } + if tt.shuttingDown { + sched.state.shuttingDown.Store(true) + } + h := newServer(sched) + + req := httptest.NewRequest(http.MethodPost, "/sync/"+repoName, nil) + if tt.cancelled { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + req = req.WithContext(ctx) + } + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + + if rr.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d, body=%s", rr.Code, tt.wantStatus, rr.Body.String()) + } + byRepo := decodeResultsByRepoForSyncEndpointTests(t, rr) + if len(byRepo) != 1 { + t.Fatalf("expected 1 result, got %d", len(byRepo)) + } + got := byRepo[repoName] + if got["code"] != tt.wantCode { + t.Errorf("code = %q, want %q", got["code"], tt.wantCode) + } + if got["message"] == "" { + t.Error("expected non-empty message") + } + if !strings.Contains(got["error"], tt.wantErr) { + t.Errorf("error = %q, want it to contain %q", got["error"], tt.wantErr) + } +} + +// TestSyncAllEndpoint_AggregatesStatus verifies that POST /sync reports the +// status shared by all failed repos, falls back to 500 for mixed statuses, +// and ignores successful repos. +func TestSyncAllEndpoint_AggregatesStatus(t *testing.T) { + tests := []struct { + name string + r1 func(t *testing.T, name string) config.RepoConfig + r2 func(t *testing.T, name string) config.RepoConfig + shuttingDown bool + wantStatus int + wantCodes map[string]string + }{ + { + name: "same", + r1: openBaoRepoForSyncEndpointTests, + r2: openBaoRepoForSyncEndpointTests, + wantStatus: http.StatusServiceUnavailable, + wantCodes: map[string]string{"r1": string(gsync.CodeSecretUnavailable), "r2": string(gsync.CodeSecretUnavailable)}, + }, + { + name: "mixed", + r1: openBaoRepoForSyncEndpointTests, + r2: missingLocalRepoForSyncEndpointTests, + wantStatus: http.StatusInternalServerError, + wantCodes: map[string]string{"r1": string(gsync.CodeSecretUnavailable), "r2": string(gsync.CodeGitRepoNotFound)}, + }, + { + name: testShuttingDownCaseName, + r1: openBaoRepoForSyncEndpointTests, + r2: openBaoRepoForSyncEndpointTests, + shuttingDown: true, + wantStatus: http.StatusServiceUnavailable, + wantCodes: map[string]string{"r1": string(codeShuttingDown), "r2": string(codeShuttingDown)}, + }, + { + name: "success+422", + r1: emptyBareRepoForSyncEndpointTests, + r2: missingLocalRepoForSyncEndpointTests, + wantStatus: http.StatusUnprocessableEntity, + wantCodes: map[string]string{"r1": "", "r2": string(gsync.CodeGitRepoNotFound)}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reader := &fakeSecretReaderForDaemonTests{err: secrets.ErrUnavailable} + sched := NewScheduler(gsync.New(gsync.WithSecretReader(reader)), ":0", "") + sched.cfg.Store(&config.Config{Repos: map[string]config.RepoConfig{ + "r1": tt.r1(t, "r1"), + "r2": tt.r2(t, "r2"), + }}) + if tt.shuttingDown { + sched.state.shuttingDown.Store(true) + } + h := newServer(sched) + + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/sync", nil)) + + if rr.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d, body=%s", rr.Code, tt.wantStatus, rr.Body.String()) + } + byRepo := decodeResultsByRepoForSyncEndpointTests(t, rr) + if len(byRepo) != len(tt.wantCodes) { + t.Fatalf("expected %d results, got %d: %+v", len(tt.wantCodes), len(byRepo), byRepo) + } + for repo, wantCode := range tt.wantCodes { + got, ok := byRepo[repo] + if !ok { + t.Errorf("missing result for %s", repo) + continue + } + if got["code"] != wantCode { + t.Errorf("%s: code = %q, want %q", repo, got["code"], wantCode) + } + } + }) + } +} + +// fakeSecretReaderForDaemonTests implements the secretReader interface. Read +// fails with the caller's context error when it is set (as Store.Read does), +// otherwise with err, and so does Refetch; Invalidate records the evicted +// paths. +type fakeSecretReaderForDaemonTests struct { + err error + // key is returned when err is nil, so the sync gets past resolveAuth. + key []byte + mu sync.Mutex + invalidated []string +} + +func (f *fakeSecretReaderForDaemonTests) Read(ctx context.Context, _ string, _ *secrets.OpenBaoConfig, _ string) ([]byte, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if f.err != nil { + return nil, f.err + } + return f.key, nil +} + +func (f *fakeSecretReaderForDaemonTests) Refetch(ctx context.Context, repoName string, obCfg *secrets.OpenBaoConfig, kvPath string) ([]byte, error) { + return f.Read(ctx, repoName, obCfg, kvPath) +} + +func (f *fakeSecretReaderForDaemonTests) Invalidate(path string) { + f.mu.Lock() + f.invalidated = append(f.invalidated, path) + f.mu.Unlock() +} + +// decodeResultsByRepoForSyncEndpointTests decodes a /sync response body and +// returns the per-repo results indexed by repo name. +func decodeResultsByRepoForSyncEndpointTests(t *testing.T, rr *httptest.ResponseRecorder) map[string]map[string]string { + t.Helper() + var body []map[string]string + if err := json.NewDecoder(rr.Body).Decode(&body); err != nil { + t.Fatalf("decode body: %v", err) + } + byRepo := make(map[string]map[string]string, len(body)) + for _, r := range body { + byRepo[r["repo"]] = r + } + return byRepo +} + +// ed25519PEMForSyncEndpointTests returns a fresh Ed25519 private key in +// PKCS#8 PEM form. +func ed25519PEMForSyncEndpointTests(t *testing.T) []byte { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate ed25519 key: %v", err) + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + t.Fatalf("marshal pkcs8: %v", err) + } + return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) +} + +// openBaoRepoForSyncEndpointTests returns an OpenBao-keyed repo whose host +// refuses connections (127.0.0.1:1). Without a key from the secret reader it +// fails in resolveAuth before any dial. +func openBaoRepoForSyncEndpointTests(t *testing.T, name string) config.RepoConfig { + t.Helper() + return config.RepoConfig{ + Name: name, + URL: "ssh://git@127.0.0.1:1/x.git", + SSHKeyPath: "ssh-keys/c/kubeaid", + OpenBao: &secrets.OpenBaoConfig{Addr: testOpenBaoAddr, Role: "gfetch", Field: "private_key"}, + LocalPath: t.TempDir(), + PollInterval: config.Duration(time.Minute), + Branches: []config.Pattern{{Raw: testMainBranch}}, + } +} + +// missingLocalRepoForSyncEndpointTests returns a repo whose URL is a local +// path with no repo: the test bypass in resolveAuth gives nil auth and +// go-git's file transport reports transport.ErrRepositoryNotFound. +func missingLocalRepoForSyncEndpointTests(t *testing.T, name string) config.RepoConfig { + t.Helper() + return config.RepoConfig{ + Name: name, + URL: filepath.Join(t.TempDir(), "missing"), + LocalPath: t.TempDir(), + PollInterval: config.Duration(time.Minute), + Branches: []config.Pattern{{Raw: testMainBranch}}, + } +} + +// emptyBareRepoForSyncEndpointTests returns a repo whose URL is an empty bare +// repo: listing its refs gives transport.ErrEmptyRemoteRepository, which the +// sync treats as a benign success. +func emptyBareRepoForSyncEndpointTests(t *testing.T, name string) config.RepoConfig { + t.Helper() + dir := t.TempDir() + if _, err := git.PlainInit(dir, true); err != nil { + t.Fatalf("init bare repo: %v", err) + } + return config.RepoConfig{ + Name: name, + URL: dir, + LocalPath: t.TempDir(), + PollInterval: config.Duration(time.Minute), + Branches: []config.Pattern{{Raw: testMainBranch}}, + } } // writeFakeSSHKey writes a placeholder SSH key file under dir and returns the path. diff --git a/pkg/gsync/auth.go b/pkg/gsync/auth.go index 15b1181..0f23395 100644 --- a/pkg/gsync/auth.go +++ b/pkg/gsync/auth.go @@ -1,8 +1,12 @@ package gsync import ( + "context" + "errors" "flag" "fmt" + "log/slog" + "os" "strconv" "strings" @@ -11,6 +15,8 @@ import ( "golang.org/x/crypto/ssh" "github.com/obmondo/gfetch/pkg/config" + "github.com/obmondo/gfetch/pkg/secrets" + "github.com/obmondo/gfetch/pkg/telemetry" ) // defaultSSHPort is used when transport.NewEndpoint reports Port == 0 (i.e. @@ -53,8 +59,9 @@ var preferredHostKeyAlgorithms = []string{ // resolveAuth returns the appropriate auth method for a repo. // HTTPS public repos use anonymous (nil) auth; SSH repos use key-based auth // with built-in host key verification (plus any extra entries from -// ssh_known_hosts). -func resolveAuth(repo *config.RepoConfig) (transport.AuthMethod, error) { +// ssh_known_hosts). When repo.OpenBao is set the key is fetched from the +// secret backend instead of the filesystem. +func (s *Syncer) resolveAuth(ctx context.Context, repo *config.RepoConfig) (transport.AuthMethod, error) { if repo.IsHTTPS() { return nil, nil } @@ -62,31 +69,89 @@ func resolveAuth(repo *config.RepoConfig) (transport.AuthMethod, error) { if strings.HasPrefix(repo.URL, "/") && flag.Lookup("test.v") != nil { return nil, nil } - hostPort, err := sshHostPort(repo.URL) + + // The URL is parsed first, so a malformed one fails before an OpenBao + // read or a cache entry is spent on it. + hostPort, err := repoHostPort(repo) if err != nil { - return nil, fmt.Errorf("parsing SSH endpoint %q: %w", repo.URL, err) + return nil, err + } + + if repo.OpenBao != nil { + pemBytes, readErr := s.secrets.Read(ctx, repo.Name, repo.OpenBao, repo.SSHKeyPath) + if readErr != nil { + return nil, newSecretError(repo.Name, readErr) + } + return s.openBaoAuth(repo, hostPort, pemBytes) } + return sshAuth(hostPort, repo.SSHKeyPath, repo.SSHKnownHosts) } +// errRepoURL marks a repo URL whose SSH endpoint does not parse. +var errRepoURL = errors.New("parsing SSH endpoint") + +// repoHostPort returns the host:port of repo's SSH endpoint. A URL that does +// not parse is an errRepoURL error. +func repoHostPort(repo *config.RepoConfig) (string, error) { + hostPort, err := sshHostPort(repo.URL) + if err != nil { + return "", fmt.Errorf("%w %q: %w", errRepoURL, repo.URL, err) + } + return hostPort, nil +} + +// openBaoAuth builds the SSH auth for repo from pemBytes, its key as read +// from OpenBao, with host key verification for hostPort. A key that does not +// parse is a secret error wrapping ErrInvalidSecret, and is evicted from the +// cache: it never reaches the network, so no auth failure would ever refetch +// it, and the next sync has to read OpenBao again for a fixed value to count. +func (s *Syncer) openBaoAuth(repo *config.RepoConfig, hostPort string, pemBytes []byte) (*gitssh.PublicKeys, error) { + auth, err := parseSSHKey("secret "+repo.SSHKeyPath, pemBytes) + if err != nil { + s.secrets.Invalidate(repo.SSHKeyPath) + return nil, newSecretError(repo.Name, fmt.Errorf("%w: %w", secrets.ErrInvalidSecret, err)) + } + return withKnownHosts(auth, hostPort, repo.SSHKnownHosts) +} + // sshAuth creates an SSH public key auth method from a key file. // Host key verification uses built-in known_hosts for major providers merged // with any extra user-provided entries; HostKeyAlgorithms is the OpenSSH // default order with the algorithms we have entries for at hostPort promoted // to the front (see preferredHostKeyAlgorithms and mergeAlgorithms). func sshAuth(hostPort, keyPath, extraKnownHosts string) (*gitssh.PublicKeys, error) { - auth, err := gitssh.NewPublicKeysFromFile("git", keyPath, "") + pem, err := os.ReadFile(keyPath) if err != nil { return nil, fmt.Errorf("loading SSH key %s: %w", keyPath, err) } + auth, err := parseSSHKey("file "+keyPath, pem) + if err != nil { + return nil, err + } + return withKnownHosts(auth, hostPort, extraKnownHosts) +} + +// parseSSHKey parses in-memory PEM bytes into an SSH public key auth method +// without host key verification. The PEM is never included in the error; +// source labels where it came from. +func parseSSHKey(source string, pemBytes []byte) (*gitssh.PublicKeys, error) { + auth, err := gitssh.NewPublicKeys("git", pemBytes, "") + if err != nil { + return nil, fmt.Errorf("parsing SSH key from %s: %w", source, err) + } + return auth, nil +} +// withKnownHosts sets host key verification on auth: the known_hosts callback +// for hostPort and the merged HostKeyAlgorithms preference. +func withKnownHosts(auth *gitssh.PublicKeys, hostPort, extraKnownHosts string) (*gitssh.PublicKeys, error) { callback, hostAlgos, err := buildKnownHostsAuth(extraKnownHosts, hostPort) if err != nil { return nil, fmt.Errorf("building known_hosts auth: %w", err) } auth.HostKeyCallback = callback auth.HostKeyAlgorithms = mergeAlgorithms(hostAlgos, preferredHostKeyAlgorithms) - return auth, nil } @@ -106,6 +171,71 @@ func sshHostPort(repoURL string) (string, error) { return ep.Host + ":" + strconv.Itoa(port), nil } +// isSSHAuthErr reports whether err is an SSH authentication failure. The +// x/crypto ssh package wraps the failure as a plain fmt.Errorf string, so +// substring matching is the only reliable detection. +func isSSHAuthErr(err error) bool { + return err != nil && strings.Contains(err.Error(), "ssh: unable to authenticate") +} + +// refreshAuthAfterSSHFailure checks whether err is an SSH auth failure for a +// repo using an OpenBao key. If so it refetches the key from OpenBao, which +// replaces the cached key only when it changed, and returns an auth method +// built from the refetched key for a single retry when it differs from auth. +// The key is the one the refetch returned, not read back from the cache, so an +// eviction in between neither costs a second OpenBao read nor turns a refetch +// that worked into a failure. Returns +// (nil, nil) when no retry should be attempted (not an SSH auth error, not an +// OpenBao key, or the refetched key is unchanged, so the caller keeps the +// original auth error), and (nil, error joining the ssh failure and the +// refetch failure) when the refetch itself fails; that failure is also logged +// and counted as a clone failure. +func (s *Syncer) refreshAuthAfterSSHFailure(ctx context.Context, log *slog.Logger, repo *config.RepoConfig, auth transport.AuthMethod, err error) (transport.AuthMethod, error) { + if !isSSHAuthErr(err) || repo.OpenBao == nil { + return nil, nil + } + + telemetry.SecretAuthRefetchTotal.WithLabelValues(repo.Name).Inc() + log.Warn("ssh auth failed with openbao key, refetching key") + + var newAuth *gitssh.PublicKeys + hostPort, rerr := repoHostPort(repo) + if rerr == nil { + pemBytes, fetchErr := s.secrets.Refetch(ctx, repo.Name, repo.OpenBao, repo.SSHKeyPath) + if fetchErr != nil { + rerr = newSecretError(repo.Name, fetchErr) + } else { + newAuth, rerr = s.openBaoAuth(repo, hostPort, pemBytes) + } + } + if rerr != nil { + joined := errors.Join(err, rerr) + log.Error("failed to refetch ssh key after auth failure", "error", joined) + telemetry.SyncFailuresTotal.WithLabelValues(repo.Name, "clone").Inc() + return nil, joined + } + if sameKey(auth, newAuth) { + log.Warn("ssh auth failed and the refetched openbao key is unchanged, not retrying") + return nil, nil + } + return newAuth, nil +} + +// sameKey reports whether a and b are SSH public key auths for the same key. +// It returns false when either is not a *gitssh.PublicKeys or has no signer, +// which keeps the retry. +func sameKey(a, b transport.AuthMethod) bool { + pa, ok := a.(*gitssh.PublicKeys) + if !ok || pa == nil || pa.Signer == nil { + return false + } + pb, ok := b.(*gitssh.PublicKeys) + if !ok || pb == nil || pb.Signer == nil { + return false + } + return ssh.FingerprintSHA256(pa.Signer.PublicKey()) == ssh.FingerprintSHA256(pb.Signer.PublicKey()) +} + // mergeAlgorithms returns hostAlgos concatenated with fallback, deduplicated, // preserving the order of first appearance. The "first appearance wins" // rule means an algorithm present in hostAlgos keeps its earlier position diff --git a/pkg/gsync/auth_test.go b/pkg/gsync/auth_test.go index 81ae1d7..3e477dc 100644 --- a/pkg/gsync/auth_test.go +++ b/pkg/gsync/auth_test.go @@ -1,16 +1,43 @@ package gsync import ( + "cmp" + "context" "crypto/ed25519" "crypto/rand" "crypto/x509" + "encoding/json" "encoding/pem" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" "os" "path/filepath" "slices" + "strings" + "sync" + "sync/atomic" "testing" "golang.org/x/crypto/ssh" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/prometheus/client_golang/prometheus/testutil" + + "github.com/obmondo/gfetch/pkg/config" + "github.com/obmondo/gfetch/pkg/secrets" + "github.com/obmondo/gfetch/pkg/telemetry" +) + +const ( + testAuthRepoName = "test-repo" + testAuthRepoURL = "git@github.com:test/repo.git" + testOpenBaoAddr = "http://openbao:8200" + testOpenBaoRole = "gfetch" + testOpenBaoSAToken = "/var/run/secrets/token" + testOpenBaoField = "private_key" ) // TestSSHAuth_FallsBackToOpenSSHDefaultsForUnknownHost verifies the @@ -224,3 +251,643 @@ func writeTempEd25519Key(t *testing.T) string { } return path } + +// generateEd25519PEM returns a freshly-generated Ed25519 private key in PKCS#8 +// PEM form as raw bytes. +func generateEd25519PEM(t *testing.T) []byte { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate ed25519 key: %v", err) + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + t.Fatalf("marshal pkcs8: %v", err) + } + return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) +} + +// fakeSecretReader is an inline test fake for the secretReader interface. +// Read returns (data, err), or readErrAfterRefetch once a refetch has run (the +// key was evicted and OpenBao then failed). Refetch returns refetchErr when +// set; otherwise it returns rotated (a key rotated in OpenBao), which later +// reads then return as Store.Refetch replaces the cached key, or data when +// rotated is nil. +type fakeSecretReader struct { + data []byte + err error + readErrAfterRefetch error + refetchErr error + rotated []byte + + mu sync.Mutex + reads int + refetches int + invalidated int +} + +func (f *fakeSecretReader) Read(_ context.Context, _ string, _ *secrets.OpenBaoConfig, _ string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.reads++ + if f.refetches > 0 && f.readErrAfterRefetch != nil { + return nil, f.readErrAfterRefetch + } + return f.data, f.err +} + +func (f *fakeSecretReader) Refetch(_ context.Context, _ string, _ *secrets.OpenBaoConfig, _ string) ([]byte, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.refetches++ + if f.refetchErr != nil { + return nil, f.refetchErr + } + if f.rotated != nil { + f.data = f.rotated + } + return f.data, nil +} + +func (f *fakeSecretReader) Invalidate(_ string) { + f.mu.Lock() + f.invalidated++ + f.mu.Unlock() +} + +// TestParseSSHKey_SameAlgorithmsAsFilePath verifies that an in-memory PEM +// auth (parseSSHKey + withKnownHosts, as resolveAuth builds it for OpenBao +// keys) produces the same HostKeyAlgorithms as a file-based auth for the same +// key and host. +func TestParseSSHKey_SameAlgorithmsAsFilePath(t *testing.T) { + keyPath := writeTempEd25519Key(t) + pemBytes, err := os.ReadFile(keyPath) + if err != nil { + t.Fatal(err) + } + + hostPort := "nonexistent.example.invalid:22" + + fileAuth, err := sshAuth(hostPort, keyPath, "") + if err != nil { + t.Fatalf("sshAuth: %v", err) + } + + parsed, err := parseSSHKey("test key", pemBytes) + if err != nil { + t.Fatalf("parseSSHKey: %v", err) + } + pemAuth, err := withKnownHosts(parsed, hostPort, "") + if err != nil { + t.Fatalf("withKnownHosts: %v", err) + } + + if !slices.Equal(fileAuth.HostKeyAlgorithms, pemAuth.HostKeyAlgorithms) { + t.Errorf("HostKeyAlgorithms mismatch.\n file: %v\n pem: %v", + fileAuth.HostKeyAlgorithms, pemAuth.HostKeyAlgorithms) + } +} + +// TestParseSSHKey_InvalidPEM_NoKeyInError verifies that a parse error for +// invalid PEM does not leak key bytes, and that the error names the source. +func TestParseSSHKey_InvalidPEM_NoKeyInError(t *testing.T) { + badPEM := []byte("not-a-real-key-SUPERSECRET") + + // PEM path: source label must appear, key bytes must not. + _, err := parseSSHKey("secret ssh-keys/acme/kubeaid", badPEM) + if err == nil { + t.Fatal("expected error for invalid PEM") + } + if strings.Contains(err.Error(), "SUPERSECRET") { + t.Errorf("error message contains key bytes: %v", err) + } + if !strings.Contains(err.Error(), "secret ssh-keys/acme/kubeaid") { + t.Errorf("error message does not contain the source label: %v", err) + } + + // File path: write the same garbage to a temp file and go through sshAuth. + tmpDir := t.TempDir() + badKeyFile := filepath.Join(tmpDir, "bad_key") + if werr := os.WriteFile(badKeyFile, badPEM, 0o600); werr != nil { + t.Fatalf("write temp key file: %v", werr) + } + _, err = sshAuth("host:22", badKeyFile, "") + if err == nil { + t.Fatal("expected error for invalid PEM via sshAuth") + } + if strings.Contains(err.Error(), "SUPERSECRET") { + t.Errorf("sshAuth error message contains key bytes: %v", err) + } + if !strings.Contains(err.Error(), badKeyFile) { + t.Errorf("sshAuth error message does not contain the file path: %v", err) + } +} + +// TestResolveAuth_SecretReader verifies that when repo.OpenBao is set, the +// Syncer uses s.secrets.Read to get the key PEM, and that reader errors +// propagate without leaking secret material. +func TestResolveAuth_SecretReader(t *testing.T) { + pemBytes := generateEd25519PEM(t) + + tests := []struct { + name string + reader *fakeSecretReader + // url overrides testAuthRepoURL. + url string + wantCode FailureCode + wantErr []error + // wantPlainErr is a substring of an error that is not a secret error. + wantPlainErr string + wantReads int + // wantInvalidated is how often the key path was evicted. + wantInvalidated int + }{ + { + name: "success", + reader: &fakeSecretReader{data: pemBytes}, + wantReads: 1, + }, + { + name: "malformed url fails before the read", + reader: &fakeSecretReader{data: pemBytes}, + url: "ssh://git@git.example.com:notaport/foo/bar.git", + wantPlainErr: "parsing SSH endpoint", + wantReads: 0, + }, + { + name: "reader error propagates", + reader: &fakeSecretReader{err: fmt.Errorf("backend unavailable")}, + wantCode: CodeSecretUnavailable, + wantReads: 1, + }, + { + // A key that does not parse is evicted, so a fixed value is read. + name: "invalid pem", + reader: &fakeSecretReader{data: []byte("not-a-real-key")}, + wantCode: CodeSecretInvalid, + wantErr: []error{secrets.ErrInvalidSecret}, + wantReads: 1, + wantInvalidated: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := New(WithSecretReader(tt.reader)) + + repo := &config.RepoConfig{ + SSHKeyPath: "ssh-keys/acme/kubeaid", + Name: testAuthRepoName, + URL: cmp.Or(tt.url, testAuthRepoURL), + OpenBao: &secrets.OpenBaoConfig{ + Addr: testOpenBaoAddr, + Role: testOpenBaoRole, + ServiceAccountTokenPath: testOpenBaoSAToken, + KVMount: "kv", + Field: testOpenBaoField, + }, + } + + auth, err := s.resolveAuth(context.Background(), repo) + if tt.reader.reads != tt.wantReads { + t.Errorf("secret reads = %d, want %d", tt.reader.reads, tt.wantReads) + } + if tt.reader.invalidated != tt.wantInvalidated { + t.Errorf("invalidations = %d, want %d", tt.reader.invalidated, tt.wantInvalidated) + } + if tt.wantPlainErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantPlainErr) { + t.Fatalf("error = %v, want it to contain %q", err, tt.wantPlainErr) + } + return + } + if tt.wantCode != "" { + assertSecretErrorForResolveAuthSecretReader(t, err, tt.wantCode, tt.wantErr) + return + } + if err != nil { + t.Fatalf("resolveAuth: %v", err) + } + if auth == nil { + t.Fatal("expected non-nil auth") + } + }) + } +} + +// TestResolveAuth_InvalidKeyFixedInOpenBao verifies, against a real Store and +// a fake OpenBao, that a key which does not parse is not served from the cache +// afterwards: once the value is fixed in OpenBao, the next resolveAuth reads it +// again and gets past parsing. +func TestResolveAuth_InvalidKeyFixedInOpenBao(t *testing.T) { + var ( + mu sync.Mutex + value = "not-a-real-key" + kvReads int + ) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + _, _ = w.Write([]byte(`{"auth":{"client_token":"tok","lease_duration":3600}}`)) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + mu.Lock() + kvReads++ + body, _ := json.Marshal(map[string]any{"data": map[string]any{"data": map[string]any{testOpenBaoField: value}}}) + mu.Unlock() + _, _ = w.Write(body) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(ts.Close) + + tokenFile := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(tokenFile, []byte("jwt"), 0o600); err != nil { + t.Fatal(err) + } + s := New(WithSecretReader(secrets.NewStore())) + repo := &config.RepoConfig{ + SSHKeyPath: "ssh-keys/acme/kubeaid", + Name: testAuthRepoName, + URL: testAuthRepoURL, + OpenBao: &secrets.OpenBaoConfig{ + Addr: ts.URL, + Role: testOpenBaoRole, + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testOpenBaoField, + }, + } + + _, err := s.resolveAuth(context.Background(), repo) + assertSecretErrorForResolveAuthSecretReader(t, err, CodeSecretInvalid, []error{secrets.ErrInvalidSecret}) + + mu.Lock() + value = string(generateEd25519PEM(t)) + mu.Unlock() + + if _, err := s.resolveAuth(context.Background(), repo); err != nil { + t.Fatalf("resolveAuth after the key was fixed: %v", err) + } + mu.Lock() + defer mu.Unlock() + if kvReads != 2 { + t.Errorf("OpenBao reads = %d, want 2: the unparseable key must not be served from the cache", kvReads) + } +} + +// assertSecretErrorForResolveAuthSecretReader checks that err is a +// *secretError with wantCode that wraps every error in wantErr. +func assertSecretErrorForResolveAuthSecretReader(t *testing.T, err error, wantCode FailureCode, wantErr []error) { + t.Helper() + var se *secretError + if !errors.As(err, &se) { + t.Fatalf("error %v is not a *secretError", err) + } + if se.code != wantCode { + t.Errorf("code = %q, want %q", se.code, wantCode) + } + for _, want := range wantErr { + if !errors.Is(err, want) { + t.Errorf("error %q is not %q", err, want) + } + } +} + +// TestResolveAuth_FilePathUnchanged verifies that when repo.OpenBao is nil, +// the file-based path is used. +func TestResolveAuth_FilePathUnchanged(t *testing.T) { + keyPath := writeTempEd25519Key(t) + s := New() + + repo := &config.RepoConfig{ + SSHKeyPath: keyPath, + Name: testAuthRepoName, + URL: testAuthRepoURL, + } + + auth, err := s.resolveAuth(context.Background(), repo) + if err != nil { + t.Fatalf("resolveAuth: %v", err) + } + if auth == nil { + t.Fatal("expected non-nil auth") + } +} + +// startRejectingSSHServer starts an in-process SSH server that rejects every +// public key authentication attempt. Returns the listener address, host +// public key and connection count. +func startRejectingSSHServer(t *testing.T) (addr string, hostPub ssh.PublicKey, conns *atomic.Int32) { + t.Helper() + + _, hostPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate host key: %v", err) + } + hostSigner, err := ssh.NewSignerFromKey(hostPriv) + if err != nil { + t.Fatalf("host signer: %v", err) + } + hostPub = hostSigner.PublicKey() + + sshCfg := &ssh.ServerConfig{ + PublicKeyCallback: func(_ ssh.ConnMetadata, _ ssh.PublicKey) (*ssh.Permissions, error) { + return nil, fmt.Errorf("rejected") + }, + } + sshCfg.AddHostKey(hostSigner) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + connCount := &atomic.Int32{} + go func() { + for { + conn, acceptErr := ln.Accept() + if acceptErr != nil { + return + } + connCount.Add(1) + go func(c net.Conn) { + defer func() { _ = c.Close() }() + _, _, _, _ = ssh.NewServerConn(c, sshCfg) + }(conn) + } + }() + + return ln.Addr().String(), hostPub, connCount +} + +// sshRepoConfig returns a repo config syncing main from the SSH server at addr. +func sshRepoConfig(t *testing.T, name, addr, knownHosts string) *config.RepoConfig { + t.Helper() + repo := &config.RepoConfig{ + Name: name, + URL: fmt.Sprintf("ssh://git@%s/r.git", addr), + SSHKeyPath: "ssh-keys/test", + SSHKnownHosts: knownHosts, + } + repo.LocalPath = t.TempDir() + repo.Branches = []config.Pattern{{Raw: "main"}} + repo.PollInterval = config.Duration(60_000_000_000) // 1m + return repo +} + +// TestSyncRepo_SSHAuthFailureRefetchesKeyOnce verifies that when SSH auth +// fails with an OpenBao key, the key is refetched without evicting the cached +// one, and one retry is attempted only when the refetched key differs. With a +// file-based key, nothing is refetched. +func TestSyncRepo_SSHAuthFailureRefetchesKeyOnce(t *testing.T) { + sshAddr, hostPub, sshConns := startRejectingSSHServer(t) + knownHosts := knownhosts.Line([]string{sshAddr}, hostPub) + keyPath := writeTempEd25519Key(t) + pemBytes := generateEd25519PEM(t) + rotatedPEM := generateEd25519PEM(t) + + testOBCfg := &secrets.OpenBaoConfig{ + Addr: testOpenBaoAddr, + Role: testOpenBaoRole, + ServiceAccountTokenPath: testOpenBaoSAToken, + KVMount: "kv", + Field: testOpenBaoField, + } + + tests := []struct { + name string + openvox bool + openBao *secrets.OpenBaoConfig + refetchErr error + rotated []byte + readErr error // what a Read after the refetch returns + wantReads int + wantRefetches int + wantConns int32 + wantRefetch float64 + wantCode FailureCode + }{ + { + name: "openbao unchanged key no retry", + openBao: testOBCfg, + wantReads: 1, + wantRefetches: 1, + wantConns: 1, + wantRefetch: 1, + wantCode: CodeGitAuthFailed, + }, + { + name: "openbao openvox unchanged key no retry", + openvox: true, + openBao: testOBCfg, + wantReads: 1, + wantRefetches: 1, + wantConns: 1, + wantRefetch: 1, + wantCode: CodeGitAuthFailed, + }, + { + name: "openbao rotated key retries", + openBao: testOBCfg, + rotated: rotatedPEM, + wantReads: 1, + wantRefetches: 1, + wantConns: 2, + wantRefetch: 1, + wantCode: CodeGitAuthFailed, + }, + { + name: "openbao openvox rotated key retries", + openvox: true, + openBao: testOBCfg, + rotated: rotatedPEM, + wantReads: 1, + wantRefetches: 1, + wantConns: 2, + wantRefetch: 1, + wantCode: CodeGitAuthFailed, + }, + { + // The key is evicted after the refetch and OpenBao then fails: the + // retry still uses the key the refetch returned. + name: "openbao rotated key retries without reading it back", + openBao: testOBCfg, + rotated: rotatedPEM, + readErr: secrets.ErrUnavailable, + wantReads: 1, + wantRefetches: 1, + wantConns: 2, + wantRefetch: 1, + wantCode: CodeGitAuthFailed, + }, + { + name: "file key no refetch", + wantReads: 0, // file path, no secret reader call + wantRefetches: 0, + wantConns: 1, + wantRefetch: 0, + wantCode: CodeGitAuthFailed, + }, + { + name: "openbao refetch fails", + openBao: testOBCfg, + refetchErr: secrets.ErrUnavailable, + wantReads: 1, + wantRefetches: 1, + wantConns: 1, + wantRefetch: 1, + wantCode: CodeSecretUnavailable, + }, + { + name: "openbao openvox refetch fails", + openvox: true, + openBao: testOBCfg, + refetchErr: secrets.ErrUnavailable, + wantReads: 1, + wantRefetches: 1, + wantConns: 1, + wantRefetch: 1, + wantCode: CodeSecretUnavailable, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sshConns.Store(0) + + reader := &fakeSecretReader{data: pemBytes, refetchErr: tt.refetchErr, rotated: tt.rotated, readErrAfterRefetch: tt.readErr} + s := New(WithSecretReader(reader)) + + repo := sshRepoConfig(t, "ssh-fail-"+tt.name, sshAddr, knownHosts) + repo.OpenBao = tt.openBao + repo.OpenVox = &tt.openvox + + if tt.openBao == nil { + repo.SSHKeyPath = keyPath + } + + before := testutil.ToFloat64(telemetry.SecretAuthRefetchTotal.WithLabelValues(repo.Name)) + + result := s.SyncRepo(context.Background(), repo, SyncOptions{}) + + if result.Err == nil { + t.Fatal("expected error (SSH auth should always fail against rejecting server)") + } + if got := Classify(result.Err); got != tt.wantCode { + t.Errorf("Classify(%q) = %q, want %q", result.Err, got, tt.wantCode) + } + if !strings.Contains(result.Err.Error(), "ssh: unable to authenticate") { + t.Errorf("error %q does not carry the ssh auth failure text", result.Err) + } + + reader.mu.Lock() + reads := reader.reads + refetches := reader.refetches + invalidated := reader.invalidated + reader.mu.Unlock() + + if reads != tt.wantReads { + t.Errorf("reads = %d, want %d", reads, tt.wantReads) + } + if refetches != tt.wantRefetches { + t.Errorf("refetches = %d, want %d", refetches, tt.wantRefetches) + } + if invalidated != 0 { + t.Errorf("invalidated = %d, want 0: a refetch must not evict the cached key", invalidated) + } + if got := sshConns.Load(); got != tt.wantConns { + t.Errorf("ssh conns = %d, want %d", got, tt.wantConns) + } + + after := testutil.ToFloat64(telemetry.SecretAuthRefetchTotal.WithLabelValues(repo.Name)) + if delta := after - before; delta != tt.wantRefetch { + t.Errorf("refetch counter delta = %v, want %v", delta, tt.wantRefetch) + } + }) + } +} + +// TestSyncRepo_HostKeyMismatchClassified verifies that a host key not matching +// the known_hosts entry for the dialed host:port classifies as a host key +// mismatch, for both the standard and the openvox flow. +// TestSyncRepo_ServerClosingHandshakeClassified verifies that a git host +// that accepts the connection and closes it before its SSH banner (sshd +// throttling, a load balancer without a backend) is classified unreachable. +func TestSyncRepo_ServerClosingHandshakeClassified(t *testing.T) { + ln, err := net.Listen(testNetTCP, "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, acceptErr := ln.Accept() + if acceptErr != nil { + return + } + _ = conn.Close() + } + }() + + _, hostPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate host key: %v", err) + } + hostSigner, err := ssh.NewSignerFromKey(hostPriv) + if err != nil { + t.Fatalf("host signer: %v", err) + } + addr := ln.Addr().String() + repo := sshRepoConfig(t, "handshake-eof", addr, knownhosts.Line([]string{addr}, hostSigner.PublicKey())) + repo.SSHKeyPath = writeTempEd25519Key(t) + + result := New().SyncRepo(context.Background(), repo, SyncOptions{}) + if result.Err == nil { + t.Fatal("expected error for a host closing the handshake") + } + if got := Classify(result.Err); got != CodeGitUnreachable { + t.Errorf("Classify(%q) = %q, want %q", result.Err, got, CodeGitUnreachable) + } +} + +func TestSyncRepo_HostKeyMismatchClassified(t *testing.T) { + sshAddr, _, _ := startRejectingSSHServer(t) + _, otherPriv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatalf("generate other host key: %v", err) + } + otherSigner, err := ssh.NewSignerFromKey(otherPriv) + if err != nil { + t.Fatalf("other host signer: %v", err) + } + knownHosts := knownhosts.Line([]string{sshAddr}, otherSigner.PublicKey()) + keyPath := writeTempEd25519Key(t) + + tests := []struct { + name string + openvox bool + }{ + {name: "standard"}, + {name: "openvox", openvox: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := New() + repo := sshRepoConfig(t, "host-key-mismatch-"+tt.name, sshAddr, knownHosts) + repo.SSHKeyPath = keyPath + repo.OpenVox = &tt.openvox + + result := s.SyncRepo(context.Background(), repo, SyncOptions{}) + if result.Err == nil { + t.Fatal("expected error for host key mismatch") + } + if got := Classify(result.Err); got != CodeGitHostKeyMismatch { + t.Errorf("Classify(%q) = %q, want %q", result.Err, got, CodeGitHostKeyMismatch) + } + }) + } +} diff --git a/pkg/gsync/constants.go b/pkg/gsync/constants.go index ee383d0..b31d430 100644 --- a/pkg/gsync/constants.go +++ b/pkg/gsync/constants.go @@ -13,3 +13,23 @@ const ( FeatureAuth = "feature-auth" OldBranch = "old-branch" ) + +// Failure codes returned by Classify. They are the stable, machine-readable +// error surface of the daemon HTTP API. +const ( + CodeSecretUnavailable FailureCode = "secret_unavailable" + CodeSecretForbidden FailureCode = "secret_forbidden" + CodeSecretNotFound FailureCode = "secret_not_found" + CodeSecretInvalid FailureCode = "secret_invalid" + CodeSecretRejected FailureCode = "secret_rejected" + CodeSecretConfigInvalid FailureCode = "secret_config_invalid" + CodeGitAuthFailed FailureCode = "git_auth_failed" + CodeGitRepoNotFound FailureCode = "git_repo_not_found" + CodeGitHostKeyMismatch FailureCode = "git_host_key_mismatch" + CodeGitUnreachable FailureCode = "git_unreachable" + CodeInternal FailureCode = "internal" +) + +// goGitTimeoutExceeded is the text of go-git's internal +// common.ErrTimeoutExceeded, which is not importable. +const goGitTimeoutExceeded = "timeout exceeded" diff --git a/pkg/gsync/errors.go b/pkg/gsync/errors.go new file mode 100644 index 0000000..03e0709 --- /dev/null +++ b/pkg/gsync/errors.go @@ -0,0 +1,124 @@ +package gsync + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "strings" + + "github.com/go-git/go-git/v5/plumbing/transport" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/obmondo/gfetch/pkg/secrets" +) + +// FailureCode is a stable, machine-readable classification of a sync error. +type FailureCode string + +// secretError is a failure to obtain a usable SSH key from the secret +// backend; code is fixed when it is created. +type secretError struct { + code FailureCode + err error +} + +func (e *secretError) Error() string { return e.err.Error() } +func (e *secretError) Unwrap() error { return e.err } + +func newSecretError(repoName string, err error) *secretError { + return &secretError{code: secretCode(err), err: fmt.Errorf("secret fetch failed for %s: %w", repoName, err)} +} + +// secretCodes maps secrets sentinels to codes, checked in order. +var secretCodes = []struct { + sentinel error + code FailureCode +}{ + {secrets.ErrNotFound, CodeSecretNotFound}, + {secrets.ErrForbidden, CodeSecretForbidden}, + {secrets.ErrUnavailable, CodeSecretUnavailable}, + {secrets.ErrInvalidSecret, CodeSecretInvalid}, + {secrets.ErrRejected, CodeSecretRejected}, + {secrets.ErrClientConfig, CodeSecretConfigInvalid}, +} + +// secretCode classifies a secret read error. A secrets sentinel wins, so an +// OpenBao request timeout is secret_unavailable and a client that cannot be +// built is secret_config_invalid. A bare caller-context error (Store.Read +// returns ctx.Err() unwrapped) is internal. Anything else is +// secret_unavailable. +func secretCode(err error) FailureCode { + for _, m := range secretCodes { + if errors.Is(err, m.sentinel) { + return m.code + } + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return CodeInternal + } + return CodeSecretUnavailable +} + +// Classify maps a sync error to a FailureCode. It returns "" for a nil error +// and CodeInternal for anything it does not recognise. +func Classify(err error) FailureCode { + // A secret error is checked first: a refetch failure joins it with the + // ssh auth error that triggered the refetch. + var se *secretError + switch { + case err == nil: + return "" + case errors.As(err, &se): + return se.code + // A URL that does not parse is a config problem: the url.Error it wraps + // satisfies net.Error, so it is caught before isNetErr would call it + // unreachable and have it retried forever. + case errors.Is(err, errRepoURL): + return CodeInternal + case errors.As(err, new(*knownhosts.KeyError)): + return CodeGitHostKeyMismatch + case errors.Is(err, transport.ErrRepositoryNotFound): + return CodeGitRepoNotFound + case isSSHAuthErr(err), + errors.Is(err, transport.ErrAuthenticationRequired), + errors.Is(err, transport.ErrAuthorizationFailed): + return CodeGitAuthFailed + case isNetErr(err), isGoGitTimeoutErr(err), isHandshakeEOF(err): + return CodeGitUnreachable + default: + return CodeInternal + } +} + +// isNetErr reports whether err carries a network error. The bare +// context.DeadlineExceeded sentinel implements net.Error but is not a network +// error: the openvox file-lock wait (withOpenVoxLockTimeout) returns it while +// the caller ctx is still alive, so it is excluded and stays internal. A +// *net.OpError wrapping it (a dial timeout) still matches. +func isNetErr(err error) bool { + var ne net.Error + if !errors.As(err, &ne) { + return false + } + bareDeadline := errors.Unwrap(ne) == nil && errors.Is(ne, context.DeadlineExceeded) + return !bareDeadline +} + +// isHandshakeEOF reports whether err is an SSH handshake the server closed +// early: before its version banner (sshd throttling new connections with +// MaxStartups, a load balancer with no healthy backend) or during the key +// exchange. x/crypto reports it as "ssh: handshake failed: EOF", which is not +// a net.Error, so it would otherwise read as internal. +func isHandshakeEOF(err error) bool { + return strings.Contains(err.Error(), "ssh: handshake failed") && + (errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)) +} + +// isGoGitTimeoutErr reports whether err is go-git's timeout-exceeded error. +// It lives in an internal go-git package (common.ErrTimeoutExceeded) that +// cannot be imported, so substring matching is the only reliable detection. +func isGoGitTimeoutErr(err error) bool { + return strings.Contains(err.Error(), goGitTimeoutExceeded) +} diff --git a/pkg/gsync/errors_test.go b/pkg/gsync/errors_test.go new file mode 100644 index 0000000..d4469a3 --- /dev/null +++ b/pkg/gsync/errors_test.go @@ -0,0 +1,77 @@ +package gsync + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/url" + "os" + "syscall" + "testing" + + "github.com/go-git/go-git/v5/plumbing/transport" + "golang.org/x/crypto/ssh/knownhosts" + + "github.com/obmondo/gfetch/pkg/config" + "github.com/obmondo/gfetch/pkg/secrets" +) + +const testNetTCP = "tcp" + +// repoHostPortErrForClassify returns the error repoHostPort gives for url. +func repoHostPortErrForClassify(url string) error { + _, err := repoHostPort(&config.RepoConfig{URL: url}) + return err +} + +func TestClassify(t *testing.T) { + secretFetch := func(err error) error { + return newSecretError("repo", err) + } + + tests := []struct { + name string + err error + want FailureCode + }{ + {name: "nil error", err: nil, want: ""}, + {name: "context canceled", err: context.Canceled, want: CodeInternal}, + {name: "secret fetch deadline exceeded", err: secretFetch(context.DeadlineExceeded), want: CodeInternal}, + {name: "secret unavailable", err: secretFetch(fmt.Errorf("%w (read status 503): boom", secrets.ErrUnavailable)), want: CodeSecretUnavailable}, + {name: "secret forbidden", err: secretFetch(fmt.Errorf("%w: denied after re-login for path %q", secrets.ErrForbidden, "p")), want: CodeSecretForbidden}, + {name: "secret not found", err: secretFetch(secrets.ErrNotFound), want: CodeSecretNotFound}, + {name: "secret invalid", err: secretFetch(fmt.Errorf("%w: field %q not present in secret at %q", secrets.ErrInvalidSecret, "f", "p")), want: CodeSecretInvalid}, + {name: "secret rejected", err: secretFetch(fmt.Errorf("%w (read status 400): boom", secrets.ErrRejected)), want: CodeSecretRejected}, + {name: "secret client config invalid", err: secretFetch(fmt.Errorf("%w: creating openbao client: bad address", secrets.ErrClientConfig)), want: CodeSecretConfigInvalid}, + {name: "host key unknown", err: fmt.Errorf("ssh: handshake failed: %w", &knownhosts.KeyError{}), want: CodeGitHostKeyMismatch}, + {name: "host key mismatch", err: fmt.Errorf("ssh: handshake failed: %w", &knownhosts.KeyError{Want: []knownhosts.KnownKey{{Filename: "known_hosts", Line: 1}}}), want: CodeGitHostKeyMismatch}, + {name: "repository not found", err: fmt.Errorf("listing remote refs: listing remote refs: %w", transport.ErrRepositoryNotFound), want: CodeGitRepoNotFound}, + {name: "ssh unable to authenticate", err: errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey]"), want: CodeGitAuthFailed}, + {name: "authentication required", err: transport.ErrAuthenticationRequired, want: CodeGitAuthFailed}, + {name: "connection refused", err: &net.OpError{Op: "dial", Net: testNetTCP, Err: syscall.ECONNREFUSED}, want: CodeGitUnreachable}, + {name: "openbao request timeout", err: secretFetch(fmt.Errorf("%w: %w", secrets.ErrUnavailable, &url.Error{Op: "Put", URL: "http://openbao:8200/v1/auth/kubernetes/login", Err: context.DeadlineExceeded})), want: CodeSecretUnavailable}, + {name: "git dial timeout", err: &net.OpError{Op: "dial", Net: testNetTCP, Err: context.DeadlineExceeded}, want: CodeGitUnreachable}, + {name: "git read deadline", err: &net.OpError{Op: "read", Net: testNetTCP, Err: os.ErrDeadlineExceeded}, want: CodeGitUnreachable}, + {name: "refetch failure joined with ssh auth error", err: errors.Join(errors.New("ssh: handshake failed: ssh: unable to authenticate"), secretFetch(secrets.ErrUnavailable)), want: CodeSecretUnavailable}, + {name: "openvox lock wait timeout", err: fmt.Errorf("waiting for file lock %s: %w", "/repo/.gfetch-meta/locks/main.lock", context.DeadlineExceeded), want: CodeInternal}, + {name: "server closed the ssh handshake before its banner", err: fmt.Errorf("listing remote refs: %w", fmt.Errorf("ssh: handshake failed: %w", io.EOF)), want: CodeGitUnreachable}, + {name: "server closed the ssh handshake mid key exchange", err: fmt.Errorf("ssh: handshake failed: %w", io.ErrUnexpectedEOF), want: CodeGitUnreachable}, + {name: "eof outside an ssh handshake", err: fmt.Errorf("reading pack: %w", io.EOF), want: CodeInternal}, + {name: "url with a port that does not parse", err: repoHostPortErrForClassify("ssh://git@host:badport/r.git"), want: CodeInternal}, + {name: "url with an unclosed ipv6 host", err: repoHostPortErrForClassify("ssh://git@[::1/r.git"), want: CodeInternal}, + {name: "other error", err: errors.New("checkout main: boom"), want: CodeInternal}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.want != "" && tt.err == nil { + t.Fatal("the row's error is nil") + } + if got := Classify(tt.err); got != tt.want { + t.Errorf("Classify(%v) = %q, want %q", tt.err, got, tt.want) + } + }) + } +} diff --git a/pkg/gsync/openvox.go b/pkg/gsync/openvox.go index fed4b0a..9c047e1 100644 --- a/pkg/gsync/openvox.go +++ b/pkg/gsync/openvox.go @@ -309,7 +309,7 @@ func (s *Syncer) syncRepoOpenVox(ctx context.Context, repo *config.RepoConfig, o defer s.recordOpenVoxMetrics(repo, start, &result) log := slog.With("repo", repo.Name, "mode", "openvox") - auth, err := resolveAuth(repo) + auth, err := s.resolveAuth(ctx, repo) if err != nil { telemetry.SyncFailuresTotal.WithLabelValues(repo.Name, "clone").Inc() result.Err = err @@ -324,6 +324,15 @@ func (s *Syncer) syncRepoOpenVox(ctx context.Context, repo *config.RepoConfig, o cachePath := filepath.Join(repo.LocalPath, metaDir, "cache.git") resolverPath := filepath.Join(repo.LocalPath, metaDir) resolverRepo, refs, err := loadResolverRepoAndRefs(ctx, repo.Name, resolverPath, cachePath, repo.URL, auth) + newAuth, rerr := s.refreshAuthAfterSSHFailure(ctx, log, repo, auth, err) + if rerr != nil { + result.Err = rerr + return result + } + if newAuth != nil { + auth = newAuth + resolverRepo, refs, err = loadResolverRepoAndRefs(ctx, repo.Name, resolverPath, cachePath, repo.URL, auth) + } if err != nil { if errors.Is(err, transport.ErrEmptyRemoteRepository) { log.Info("remote repository has no commits yet, nothing to sync") diff --git a/pkg/gsync/syncer.go b/pkg/gsync/syncer.go index 6fb9850..feace03 100644 --- a/pkg/gsync/syncer.go +++ b/pkg/gsync/syncer.go @@ -17,6 +17,7 @@ import ( "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability" "github.com/go-git/go-git/v5/plumbing/transport" "github.com/obmondo/gfetch/pkg/config" + "github.com/obmondo/gfetch/pkg/secrets" "github.com/obmondo/gfetch/pkg/telemetry" ) @@ -46,9 +47,28 @@ type Result struct { Err error } +// secretReader fetches an SSH private key from a secret backend. +type secretReader interface { + Read(ctx context.Context, repoName string, obCfg *secrets.OpenBaoConfig, kvPath string) ([]byte, error) + Refetch(ctx context.Context, repoName string, obCfg *secrets.OpenBaoConfig, kvPath string) ([]byte, error) + Invalidate(kvPath string) +} + +// Option configures a Syncer. +type Option func(*Syncer) + +// WithSecretReader sets the secret reader used for SSH keys stored in a +// secret backend. When nil (the default), a new secrets.Store is created. +func WithSecretReader(r secretReader) Option { + return func(s *Syncer) { + s.secrets = r + } +} + // Syncer performs git sync operations. type Syncer struct { - mu sync.Mutex + mu sync.Mutex + secrets secretReader } // New creates a new Syncer. @@ -72,11 +92,26 @@ type Syncer struct { // That global is gone in go-git v6, so this will not compile against it. // Upgrading is a rewrite rather than a bump - see "Known future work" in // AGENTS.md before attempting it. -func New() *Syncer { +func New(opts ...Option) *Syncer { transport.UnsupportedCapabilities = []capability.Capability{ capability.ThinPack, } - return &Syncer{} + s := &Syncer{} + for _, o := range opts { + o(s) + } + if s.secrets == nil { + s.secrets = secrets.NewStore() + } + return s +} + +// InvalidateSecrets evicts the cached keys at paths. Called by the daemon +// after a reload with the key paths of changed repos. +func (s *Syncer) InvalidateSecrets(paths []string) { + for _, p := range paths { + s.secrets.Invalidate(p) + } } // SyncAll syncs all repositories in the config. @@ -133,14 +168,16 @@ func (s *Syncer) SyncRepo(ctx context.Context, repo *config.RepoConfig, opts Syn return s.syncRepoOpenVox(ctx, repo, opts) } - auth, err := resolveAuth(repo) + auth, err := s.resolveAuth(ctx, repo) if err != nil { telemetry.SyncFailuresTotal.WithLabelValues(repo.Name, "clone").Inc() result.Err = err return result } - result, emptyRepo := s.runStandardSync(ctx, repo, auth, opts) + // runStandardSync returns the auth it ended with, which differs from auth + // when it refetched a rotated key, so the repair re-clones with that key. + result, auth, emptyRepo := s.runStandardSync(ctx, log, repo, auth, opts) if isObjectNotFoundErr(result.Err) { result, emptyRepo = s.repairIncompleteObjectStore(ctx, repo, auth, opts, log, result) } @@ -196,33 +233,44 @@ func (s *Syncer) repairIncompleteObjectStore(ctx context.Context, repo *config.R return failed, false } - return s.runStandardSync(ctx, repo, auth, opts) + result, _, emptyRepo := s.runStandardSync(ctx, log, repo, auth, opts) + return result, emptyRepo } // runStandardSync performs the clone/list/branch/tag/checkout flow for a single -// non-openvox repo. It returns the Result and whether the remote is empty (has -// no commits yet), which the caller records as a benign no-op success. It is -// safe to call twice (the caller wipes the local path and retries once on an -// incomplete local object store). -func (s *Syncer) runStandardSync(ctx context.Context, repo *config.RepoConfig, auth transport.AuthMethod, opts SyncOptions) (Result, bool) { +// non-openvox repo. It returns the Result, the auth it ended with (a refetched +// key's auth when the first one was rejected and the key had rotated), and +// whether the remote is empty (has no commits yet), which the caller records +// as a benign no-op success. It is safe to call twice (the caller wipes the +// local path and retries once on an incomplete local object store). +func (s *Syncer) runStandardSync(ctx context.Context, log *slog.Logger, repo *config.RepoConfig, auth transport.AuthMethod, opts SyncOptions) (Result, transport.AuthMethod, bool) { result := Result{RepoName: repo.Name} - r, err := ensureCloned(ctx, repo, auth) + r, err := ensureCloned(repo) if err != nil { telemetry.SyncFailuresTotal.WithLabelValues(repo.Name, "clone").Inc() result.Err = err - return result, false + return result, auth, false } refs, err := listRemoteRefs(ctx, r, auth, repo.Name, "standard") + newAuth, rerr := s.refreshAuthAfterSSHFailure(ctx, log, repo, auth, err) + if rerr != nil { + result.Err = rerr + return result, auth, false + } + if newAuth != nil { + auth = newAuth + refs, err = listRemoteRefs(ctx, r, auth, repo.Name, "standard") + } if err != nil { if errors.Is(err, transport.ErrEmptyRemoteRepository) { - return result, true + return result, auth, true } slog.Error("failed to list remote refs", "repo", repo.Name, "error", err) telemetry.SyncFailuresTotal.WithLabelValues(repo.Name, "clone").Inc() result.Err = fmt.Errorf("listing remote refs: %w", err) - return result, false + return result, auth, false } defaultBranch, _, matchedBranches, matchedTagRefs := extractRemoteRefState(refs, repo.Branches, repo.Tags, repo.ExcludeBranches, repo.ExcludeTags, repo.IsDefaultBranchOnly()) @@ -235,7 +283,7 @@ func (s *Syncer) runStandardSync(ctx context.Context, repo *config.RepoConfig, a s.syncTagsWrapper(ctx, r, repo, auth, opts, matchedTags, &result) s.handleCheckout(r, repo, defaultBranch, &result) - return result, false + return result, auth, false } func (s *Syncer) addBranchSynced(result *Result, branch string) { @@ -563,9 +611,11 @@ func (s *Syncer) handleCheckout(r *git.Repository, repo *config.RepoConfig, defa s.setCheckout(result, defaultBranch) } -// ensureCloned opens an existing repo or inits an empty one with the remote configured. +// ensureCloned opens an existing repo or inits an empty one with the remote +// configured. It is local only and never authenticates: the first network op, +// and so the first use of the key, is listRemoteRefs, on a fresh clone too. // Actual fetching is deferred to syncBranch/syncTags which use narrow refspecs. -func ensureCloned(_ context.Context, repo *config.RepoConfig, _ transport.AuthMethod) (*git.Repository, error) { +func ensureCloned(repo *config.RepoConfig) (*git.Repository, error) { // Stat .git, not the directory. A bare mkdir - the shared-PVC init container // makes these, and a failed earlier sync can leave one behind - satisfied the // old check, so PlainOpen ran against a path holding no repository and the diff --git a/pkg/secrets/openbao.go b/pkg/secrets/openbao.go new file mode 100644 index 0000000..6509ac7 --- /dev/null +++ b/pkg/secrets/openbao.go @@ -0,0 +1,399 @@ +package secrets + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "os" + "strings" + "sync" + "time" + + api "github.com/openbao/openbao/api/v2" +) + +const ( + kubernetesAuthMount = "kubernetes" + requestTimeout = 10 * time.Second + reloginCooldown = time.Minute + renewFractionDenom = 3 + // loginFailureBackoff is how long a failed login is answered from memory + // instead of with a new login. + loginFailureBackoff = 5 * time.Second +) + +// client wraps an openbao API client for a single OpenBaoConfig. It handles +// lazy kubernetes-auth login, renewal in the background from 2/3 of the +// lease, and one automatic re-login on 403 (rate-limited to reloginCooldown). +// +// api is shared by every read and by the logins: api.Client guards its token +// with its own lock (SetToken writes it, each request reads it), so swapping +// the token while reads are in flight is safe. +type client struct { + api *api.Client + kv *api.KVv2 + role string + tokenPath string + + mu sync.Mutex + token string + loggedInAt time.Time + lease time.Duration + // renewing is set while a background renewal runs. lastRenewAttempt is + // when the last one started, so a failing renewal is retried at most once + // per policyDenialWindow instead of on every read. + renewing bool + lastRenewAttempt time.Time + // flight is the login reads are waiting for, nil when none runs. + // lastLoginErr is the error of the last login reads waited for, and + // lastLoginFailedAt when it failed; it is cleared by a successful one. + flight *loginFlight + lastLoginErr error + lastLoginFailedAt time.Time + now func() time.Time + logger *slog.Logger +} + +// loginFlight is one login that any number of reads wait for. err is set +// before done is closed. +type loginFlight struct { + done chan struct{} + err error +} + +func newClient(cfg *OpenBaoConfig, now func() time.Time, logger *slog.Logger) (*client, error) { + apiCfg := api.NewConfig() + if apiCfg.Error != nil { + return nil, fmt.Errorf("%w: %w", ErrClientConfig, apiCfg.Error) + } + apiCfg.Address = cfg.Addr + apiCfg.MaxRetries = 0 + apiCfg.Timeout = requestTimeout + + ac, err := api.NewClient(apiCfg) + if err != nil { + return nil, fmt.Errorf("%w: creating openbao client: %w", ErrClientConfig, err) + } + + return &client{ + api: ac, + kv: ac.KVv2(cfg.KVMount), + role: cfg.Role, + tokenPath: cfg.ServiceAccountTokenPath, + now: now, + logger: logger, + }, nil +} + +// readField fetches the secret at path and returns the value of the configured +// field as raw bytes. +func (c *client) readField(ctx context.Context, path, field string) ([]byte, error) { + var secret *api.KVSecret + err := c.do(ctx, path, func() error { + var getErr error + secret, getErr = c.kv.Get(ctx, path) + return getErr + }) + if err != nil { + return nil, err + } + + // Soft-deleted secret: Data is nil. + if secret == nil || secret.Data == nil { + return nil, ErrNotFound + } + + raw, ok := secret.Data[field] + if !ok { + return nil, fmt.Errorf("%w: field %q not present in secret at %q", ErrInvalidSecret, field, path) + } + s, ok := raw.(string) + if !ok { + return nil, fmt.Errorf("%w: field %q is not a string in secret at %q", ErrInvalidSecret, field, path) + } + return []byte(s), nil +} + +// renewDue reports whether the token should be renewed. Must be called with +// c.mu held. +func (c *client) renewDue() bool { + return c.lease > 0 && !c.now().Before(c.loggedInAt.Add(c.lease*2/renewFractionDenom)) +} + +// policyDenialWindow is how young a token must be for a 403 on it to read as +// a policy denial rather than an expired or revoked token: reloginCooldown, +// shortened to the first third of the lease when token_ttl is short. A token +// is renewed at 2/3 of its lease, so with a fixed minute and a ttl under 90s +// every token would read as fresh and a 403 would never get its re-login. Must +// be called with c.mu held. +func (c *client) policyDenialWindow() time.Duration { + if c.lease > 0 && c.lease/renewFractionDenom < reloginCooldown { + return c.lease / renewFractionDenom + } + return reloginCooldown +} + +// expired reports whether the token's lease has fully elapsed. Must be called +// with c.mu held. +func (c *client) expired() bool { + return c.lease > 0 && !c.now().Before(c.loggedInAt.Add(c.lease)) +} + +// readToken returns the token to read with. A token past 2/3 of its lease is +// returned at once and renewed in the background, so a slow login never +// stalls reads that still hold a valid token. Without a token, or with an +// expired one, the read waits for a login (see loginLocked and awaitLogin). +func (c *client) readToken(ctx context.Context) (string, error) { + c.mu.Lock() + if c.token != "" && !c.expired() { + if c.renewDue() { + c.startRenewal() + } + token := c.token + c.mu.Unlock() + return token, nil + } + flight, err := c.loginLocked() + c.mu.Unlock() + if err != nil { + return "", err + } + if err := awaitLogin(ctx, flight); err != nil { + return "", err + } + c.mu.Lock() + defer c.mu.Unlock() + return c.token, nil +} + +// loginLocked returns the login reads are waiting for, starting one if none +// runs. The login runs on its own goroutine and context, without c.mu, so +// readers neither queue on the mutex nor cancel it for each other. Within +// loginFailureBackoff of a failed login it returns that login's error instead +// of trying again, so a down OpenBao costs one login per backoff rather than +// one per read. Must be called with c.mu held. +func (c *client) loginLocked() (*loginFlight, error) { + if c.flight != nil { + return c.flight, nil + } + if c.lastLoginErr != nil && c.now().Sub(c.lastLoginFailedAt) < loginFailureBackoff { + return nil, c.lastLoginErr + } + flight := &loginFlight{done: make(chan struct{})} + c.flight = flight + go c.runLogin(flight) + return flight, nil +} + +// runLogin logs in for flight, swaps the new token in or records the failure, +// and wakes the reads waiting for it. +func (c *client) runLogin(flight *loginFlight) { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + token, lease, err := c.requestToken(ctx) + + c.mu.Lock() + if err != nil { + c.lastLoginErr = err + c.lastLoginFailedAt = c.now() + } else { + c.lastLoginErr = nil + c.setToken(token, lease) + } + c.flight = nil + flight.err = err + c.mu.Unlock() + close(flight.done) +} + +// awaitLogin waits for flight, or until ctx ends: a read with a short +// deadline is not held up by a slow login it shares with others. +func awaitLogin(ctx context.Context, flight *loginFlight) error { + select { + case <-flight.done: + return flight.err + case <-ctx.Done(): + return ctx.Err() + } +} + +// startRenewal starts a background renewal unless one is running or the last +// one started less than policyDenialWindow ago. Must be called with c.mu held. +func (c *client) startRenewal() { + now := c.now() + if c.renewing || (!c.lastRenewAttempt.IsZero() && now.Sub(c.lastRenewAttempt) < c.policyDenialWindow()) { + return + } + c.renewing = true + c.lastRenewAttempt = now + go c.renew() +} + +// renew logs in without holding c.mu, then swaps the new token in. A failure +// keeps the current token, which stays usable until its lease ends; the next +// read past the retry window starts another renewal. +func (c *client) renew() { + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + token, lease, err := c.requestToken(ctx) + + c.mu.Lock() + defer c.mu.Unlock() + c.renewing = false + if err != nil { + c.logger.Warn("openbao token renewal failed, using current token", "error", err) + return + } + c.setToken(token, lease) +} + +// do ensures a valid token exists, runs fn, and retries once after a re-login +// on 403. Renewal from 2/3 of the lease prevents most 403s. A 403 on a token +// still younger than policyDenialWindow when the 403 arrives is treated as a +// policy denial and returns ErrForbidden without attempting re-login. The +// re-login is the same shared login a missing token waits for, so concurrent +// readers do not log in twice. +func (c *client) do(ctx context.Context, path string, fn func() error) error { + if err := ctx.Err(); err != nil { + return err + } + usedToken, err := c.readToken(ctx) + if err != nil { + return err + } + + err = fn() + if err == nil { + return nil + } + + if !is403(err) { + return mapError(ctx, err) + } + + // 403: re-login once, skip if another goroutine or a background renewal + // already swapped the token. The token's age is taken here, at the 403 + // rather than before fn, so a slow request does not make an expired token + // look fresh. loggedInAt still belongs to usedToken, since only a login + // moves it. + c.mu.Lock() + if c.token == usedToken { + if c.now().Sub(c.loggedInAt) < c.policyDenialWindow() { + // Fresh token denied: this is a policy denial, not an expired token. + c.mu.Unlock() + return fmt.Errorf("%w: denied with fresh token for path %q", ErrForbidden, path) + } + flight, loginErr := c.loginLocked() + c.mu.Unlock() + if loginErr != nil { + return loginErr + } + if loginErr := awaitLogin(ctx, flight); loginErr != nil { + return loginErr + } + } else { + c.mu.Unlock() + } + + err = fn() + if err != nil { + if is403(err) { + return fmt.Errorf("%w: denied after re-login for path %q", ErrForbidden, path) + } + return mapError(ctx, err) + } + return nil +} + +// requestToken reads the service-account JWT from disk and authenticates +// against the kubernetes auth backend, returning the new token and its lease. +// It touches no client state, so it runs without c.mu. +func (c *client) requestToken(ctx context.Context) (string, time.Duration, error) { + // The kubelet rotates the projected token file, so a failed read is + // treated as transient rather than as a denial. + jwt, err := os.ReadFile(c.tokenPath) + if err != nil { + return "", 0, fmt.Errorf("%w: reading service account token: %w", ErrUnavailable, err) + } + + secret, err := c.api.Logical().WriteWithContext(ctx, + "auth/"+kubernetesAuthMount+"/login", + map[string]any{ + "role": c.role, + "jwt": strings.TrimSpace(string(jwt)), + }) + if err != nil { + return "", 0, mapLoginError(err) + } + + if secret == nil || secret.Auth == nil { + return "", 0, fmt.Errorf("%w: login returned no auth data", ErrForbidden) + } + return secret.Auth.ClientToken, time.Duration(secret.Auth.LeaseDuration) * time.Second, nil +} + +// setToken makes token the one reads use. Must be called with c.mu held. +func (c *client) setToken(token string, lease time.Duration) { + c.token = token + c.api.SetToken(token) + c.loggedInAt = c.now() + c.lease = lease +} + +// transient reports whether an HTTP status code indicates a transient error +// that should be retried. +func transient(code int) bool { + return code >= 500 || code == http.StatusTooManyRequests +} + +// statusError maps an HTTP status code to the appropriate package sentinel, +// wrapping both the sentinel and the original error. prefix distinguishes +// read-path errors ("status") from login-path errors ("login status"). +func statusError(code int, prefix string, err error) error { + switch { + case code == http.StatusForbidden: + return fmt.Errorf("%w (%s %d): %w", ErrForbidden, prefix, code, err) + case transient(code): + return fmt.Errorf("%w (%s %d): %w", ErrUnavailable, prefix, code, err) + default: + return fmt.Errorf("%w (%s %d): %w", ErrRejected, prefix, code, err) + } +} + +// mapError translates openbao errors into package sentinels. +func mapError(ctx context.Context, err error) error { + if ctx.Err() != nil { + return ctx.Err() + } + + if errors.Is(err, api.ErrSecretNotFound) { + return ErrNotFound + } + + if respErr, ok := errors.AsType[*api.ResponseError](err); ok { + if respErr.StatusCode == http.StatusNotFound { + return ErrNotFound + } + return statusError(respErr.StatusCode, "status", err) + } + + return fmt.Errorf("%w: %w", ErrUnavailable, err) +} + +// mapLoginError translates errors from the kubernetes auth login request. +func mapLoginError(err error) error { + if respErr, ok := errors.AsType[*api.ResponseError](err); ok { + if respErr.StatusCode == http.StatusBadRequest { + return fmt.Errorf("%w (login status %d): %w", ErrForbidden, respErr.StatusCode, err) + } + return statusError(respErr.StatusCode, "login status", err) + } + return fmt.Errorf("%w: %w", ErrUnavailable, err) +} + +func is403(err error) bool { + respErr, ok := errors.AsType[*api.ResponseError](err) + return ok && respErr.StatusCode == http.StatusForbidden +} diff --git a/pkg/secrets/store.go b/pkg/secrets/store.go new file mode 100644 index 0000000..9dbe7b7 --- /dev/null +++ b/pkg/secrets/store.go @@ -0,0 +1,226 @@ +package secrets + +import ( + "bytes" + "context" + "errors" + "log/slog" + "sync" + "time" + + "github.com/obmondo/gfetch/pkg/telemetry" +) + +var ( + ErrNotFound = errors.New("secret not found") + ErrForbidden = errors.New("secret access denied") + ErrUnavailable = errors.New("secret backend unavailable") + ErrRejected = errors.New("secret backend rejected request") + ErrInvalidSecret = errors.New("secret field missing or not a string") + // ErrClientConfig is a client that cannot be built from the OpenBao + // config, such as an address that does not parse. A retry does not fix it. + ErrClientConfig = errors.New("openbao client config invalid") +) + +// OpenBaoConfig holds the connection parameters for an OpenBao KV v2 backend. +// It is comparable, so a config change can be detected by value. +type OpenBaoConfig struct { + Addr string `yaml:"addr"` + Role string `yaml:"role"` + ServiceAccountTokenPath string `yaml:"service_account_token_path"` + KVMount string `yaml:"kv_mount"` + Field string `yaml:"field"` +} + +// Store reads secrets from an OpenBao KV v2 backend, caching the value per +// OpenBao config and path after first fetch. A path is evicted when a config +// reload adds, removes or re-keys its repo (Invalidate), and replaced when a +// refetch after an SSH auth failure finds a different key (Refetch). Callers +// get their own copy of a value, so the cache is never written through. +// +// Each distinct OpenBao config gets its own client, built on first use and +// kept for the process, and its own cache entries. After a reload that changes +// the openbao block, syncs still running on the old config and syncs on the +// new one therefore use their own client and token side by side, rather than +// replacing a shared client and clearing the cache on every alternate read. +// Configs change rarely, so the clients kept for old ones cost little. +// +// Failures are never cached: an OpenBao outage on cache miss fails the sync; +// the next sync retries. It is safe for concurrent use. +type Store struct { + mu sync.Mutex + clients map[OpenBaoConfig]*client + cache map[cacheKey][]byte + // gens counts, per path, the evictions and key replacements. A fetch + // caches its value only if its path's generation is unchanged since it + // started, so an eviction or replacement of one path is not undone by a + // read already in flight, and does not stop reads of other paths from + // caching. + gens map[string]uint64 + now func() time.Time + logger *slog.Logger +} + +// cacheKey identifies a cached value: the path read under one OpenBao config. +type cacheKey struct { + cfg OpenBaoConfig + path string +} + +// NewStore creates a new Store. +func NewStore() *Store { + return &Store{ + clients: make(map[OpenBaoConfig]*client), + cache: make(map[cacheKey][]byte), + gens: make(map[string]uint64), + now: time.Now, + logger: slog.Default(), + } +} + +// Read fetches the SSH private key for repoName from the OpenBao secret at +// secretPath, using the provided OpenBao configuration. On success the value +// is cached under that config and path, unless a read of them that finished +// first already cached one; subsequent reads return a copy of the cached value +// without contacting OpenBao. Failures are never cached. The raw key bytes are +// never logged. +func (s *Store) Read(ctx context.Context, repoName string, obCfg *OpenBaoConfig, secretPath string) ([]byte, error) { + // The cache lookup and the gen capture share one critical section, so a + // read that started before an eviction or replacement of its path fails + // the gen check below and does not cache what it fetched. + key := cacheKey{cfg: *obCfg, path: secretPath} + s.mu.Lock() + c, err := s.clientForLocked(obCfg) + if err != nil { + s.mu.Unlock() + s.countFailure(repoName, secretPath, err) + return nil, err + } + if cached, ok := s.cache[key]; ok { + s.mu.Unlock() + return bytes.Clone(cached), nil + } + gen := s.gens[secretPath] + s.mu.Unlock() + + data, err := s.fetch(ctx, c, repoName, obCfg, secretPath) + if err != nil { + return nil, err + } + + // A read of the same path that finished first has already cached its + // value; this one, slower, may hold the key from before a rotation, so it + // does not overwrite it. + s.mu.Lock() + if _, cached := s.cache[key]; !cached && s.gens[secretPath] == gen { + s.cache[key] = bytes.Clone(data) + } + s.mu.Unlock() + return data, nil +} + +// Refetch reads the secret at secretPath from OpenBao, bypassing the cache. +// The value cached under obCfg is stored only when the fetched one differs, +// so a refetch that finds the same key leaves the cache as it was. Storing it +// bumps the path's generation, also when it fills an empty entry: a read of +// the path already in flight may have fetched the key from before a rotation, +// and must not cache it over this one. That read still returns its value to +// its caller, and the next read hits the value stored here, so the bump costs +// no extra OpenBao read. Failures are never cached and leave the cached value +// in place. +func (s *Store) Refetch(ctx context.Context, repoName string, obCfg *OpenBaoConfig, secretPath string) ([]byte, error) { + key := cacheKey{cfg: *obCfg, path: secretPath} + s.mu.Lock() + c, err := s.clientForLocked(obCfg) + if err != nil { + s.mu.Unlock() + s.countFailure(repoName, secretPath, err) + return nil, err + } + gen := s.gens[secretPath] + s.mu.Unlock() + + data, err := s.fetch(ctx, c, repoName, obCfg, secretPath) + if err != nil { + return nil, err + } + + s.mu.Lock() + if s.gens[secretPath] == gen && !bytes.Equal(s.cache[key], data) { + s.cache[key] = bytes.Clone(data) + s.gens[secretPath]++ + } + s.mu.Unlock() + return data, nil +} + +// fetch reads the secret at secretPath through c, counting and logging a +// failure. A failure caused by ctx returns ctx's error, uncounted. +func (s *Store) fetch(ctx context.Context, c *client, repoName string, obCfg *OpenBaoConfig, secretPath string) ([]byte, error) { + data, err := c.readField(ctx, secretPath, obCfg.Field) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + s.countFailure(repoName, secretPath, err) + return nil, err + } + return data, nil +} + +// countFailure counts and logs a failed secret read under its reason label. +func (s *Store) countFailure(repoName, secretPath string, err error) { + label := reason(err) + telemetry.SecretFetchFailuresTotal.WithLabelValues(repoName, label).Inc() + s.logger.Warn("secret fetch failed", "repo", repoName, "path", secretPath, "reason", label, "error", err) +} + +// Invalidate evicts the cached value for secretPath under every OpenBao +// config and bumps the path's generation, so reads of the path in flight since +// before the invalidation do not re-populate it. Other paths are untouched. +func (s *Store) Invalidate(secretPath string) { + s.mu.Lock() + for key := range s.cache { + if key.path == secretPath { + delete(s.cache, key) + } + } + s.gens[secretPath]++ + s.mu.Unlock() +} + +// clientForLocked returns the client for cfg, building it on first use. Must +// be called with s.mu held. +func (s *Store) clientForLocked(cfg *OpenBaoConfig) (*client, error) { + if c, ok := s.clients[*cfg]; ok { + return c, nil + } + + c, err := newClient(cfg, s.now, s.logger) + if err != nil { + return nil, err + } + s.clients[*cfg] = c + return c, nil +} + +// reason returns the reason label for a secret fetch error, used by the +// secret fetch failure metric. +func reason(err error) string { + switch { + case errors.Is(err, ErrNotFound): + return "not_found" + case errors.Is(err, ErrForbidden): + return "forbidden" + case errors.Is(err, ErrUnavailable): + return "unavailable" + case errors.Is(err, ErrInvalidSecret): + return "invalid" + case errors.Is(err, ErrRejected): + return "rejected" + case errors.Is(err, ErrClientConfig): + return "config_invalid" + default: + return "unavailable" + } +} diff --git a/pkg/secrets/store_test.go b/pkg/secrets/store_test.go new file mode 100644 index 0000000..d590a85 --- /dev/null +++ b/pkg/secrets/store_test.go @@ -0,0 +1,1695 @@ +package secrets + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus/testutil" + + "github.com/obmondo/gfetch/pkg/telemetry" +) + +const ( + testFieldName = "private_key" + testPEMValue = "pem" + testReasonUnavail = "unavailable" + testReasonRejected = "rejected" +) + +// newTestServer starts an httptest.Server that simulates the OpenBao API. +// handler is called for each request. The server URL is returned for use as +// the OpenBao address. +func newTestServer(t *testing.T, handler http.HandlerFunc) *httptest.Server { + t.Helper() + ts := httptest.NewServer(handler) + t.Cleanup(ts.Close) + return ts +} + +// writeBody is a test helper that writes b to w, discarding the return values +// to satisfy errcheck. +func writeBody(w http.ResponseWriter, b []byte) { + _, _ = w.Write(b) +} + +func writeTokenFile(t *testing.T, content string) string { + t.Helper() + dir := t.TempDir() + p := filepath.Join(dir, "token") + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +// kvResponse builds the JSON body for a successful KV v2 GET response. +func kvResponse(data map[string]any) []byte { + body := map[string]any{ + "data": map[string]any{ + "data": data, + "metadata": map[string]any{"version": 1}, + }, + } + b, _ := json.Marshal(body) + return b +} + +func loginResponseWithLease(token string, leaseDuration int) []byte { + body := map[string]any{ + "auth": map[string]any{ + "client_token": token, + "lease_duration": leaseDuration, + }, + } + b, _ := json.Marshal(body) + return b +} + +func loginResponse(token string) []byte { + return loginResponseWithLease(token, 0) +} + +func TestStore_LoginSendsRoleAndTrimmedJWT(t *testing.T) { + tokenFile := writeTokenFile(t, " my-jwt-token \n") + var gotRole, gotJWT string + var gotHeaders http.Header + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + gotHeaders = r.Header.Clone() + body, _ := io.ReadAll(r.Body) + var req map[string]string + _ = json.Unmarshal(body, &req) + gotRole = req["role"] + gotJWT = req["jwt"] + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("test-token")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: "PEM"})) + default: + w.WriteHeader(http.StatusNotFound) + } + }) + + // Set BAO_* env vars that should be ignored because api.NewConfig uses + // DisableEnvironment:true internally. + t.Setenv("BAO_TOKEN", "env-should-be-ignored") + t.Setenv("BAO_NAMESPACE", "env-ns-should-be-ignored") + t.Setenv("BAO_ADDR", "http://env-addr-should-be-ignored:9999") + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "my-role", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + data, err := store.Read(context.Background(), "test-repo", cfg, "ssh-keys/acme") + if err != nil { + t.Fatalf("Read: %v", err) + } + if string(data) != "PEM" { + t.Errorf("got %q, want %q", data, "PEM") + } + if gotRole != "my-role" { + t.Errorf("role = %q, want %q", gotRole, "my-role") + } + if gotJWT != "my-jwt-token" { + t.Errorf("jwt = %q, want %q (trimmed)", gotJWT, "my-jwt-token") + } + // BAO_TOKEN / BAO_NAMESPACE env must not leak into login request headers. + if v := gotHeaders.Get("X-Vault-Token"); v != "" { + t.Errorf("X-Vault-Token header = %q, want empty (env must not leak)", v) + } + if v := gotHeaders.Get("X-Vault-Namespace"); v != "" { + t.Errorf("X-Vault-Namespace header = %q, want empty (env must not leak)", v) + } +} + +func TestStore_TokenFileReReadPerLogin(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt-first") + var lastJWT atomic.Value + var logins atomic.Int32 + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + logins.Add(1) + body, _ := io.ReadAll(r.Body) + var req map[string]string + _ = json.Unmarshal(body, &req) + lastJWT.Store(req["jwt"]) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponseWithLease("tok", 90)) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: "ok"})) + default: + w.WriteHeader(http.StatusNotFound) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + fakeNow := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + store := NewStore() + store.now = func() time.Time { return fakeNow } + + // First read: login reads jwt-first from disk. + data, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("first Read: %v", err) + } + if string(data) != "ok" { + t.Errorf("got %q, want %q", data, "ok") + } + if v := lastJWT.Load(); v != "jwt-first" { + t.Errorf("first JWT = %q, want %q", v, "jwt-first") + } + + // Rotate the token file, move past the 90s lease so the read itself logs + // in again, and evict the path so the read reaches OpenBao. + if err := os.WriteFile(tokenFile, []byte("jwt-second"), 0o600); err != nil { + t.Fatal(err) + } + fakeNow = fakeNow.Add(91 * time.Second) + store.Invalidate("path") + + data, err = store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("second Read: %v", err) + } + if string(data) != "ok" { + t.Errorf("got %q, want %q", data, "ok") + } + if v := lastJWT.Load(); v != "jwt-second" { + t.Errorf("last JWT = %q, want %q (re-read from disk)", v, "jwt-second") + } + if n := logins.Load(); n != 2 { + t.Errorf("logins = %d, want 2", n) + } +} + +func TestStore_ReadReturnsField(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + var kvHits atomic.Int32 + var loginHits atomic.Int32 + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + loginHits.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + kvHits.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: "-----BEGIN OPENSSH PRIVATE KEY-----\ndata\n-----END OPENSSH PRIVATE KEY-----\n"})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + data, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("Read: %v", err) + } + if !strings.HasPrefix(string(data), "-----BEGIN OPENSSH PRIVATE KEY-----") { + t.Errorf("expected PEM prefix, got %q", data) + } + want := string(data) + // A caller writing into its copy must not reach the cache. + data[0] = 'X' + + // Second read must return cached value without hitting OpenBao. + data2, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("second Read: %v", err) + } + if string(data2) != want { + t.Errorf("second read returned different value: %q vs %q", data2, want) + } + data2[0] = 'Y' + data3, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("third Read: %v", err) + } + if string(data3) != want { + t.Errorf("third read returned different value: %q vs %q", data3, want) + } + if got := kvHits.Load(); got != 1 { + t.Errorf("kv hits = %d, want 1 (second read should be cached)", got) + } + if got := loginHits.Load(); got != 1 { + t.Errorf("login hits = %d, want 1", got) + } +} + +func TestStore_MissingField_ErrInvalidSecret(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{"other_field": "value"})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "repo", cfg, "path") + if err == nil { + t.Fatal("expected error for missing field") + } + if !strings.Contains(err.Error(), "not present") { + t.Errorf("expected 'not present' in error, got %q", err) + } +} + +func TestStore_403FreshToken_ErrForbidden(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + var loginCalls atomic.Int32 + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + loginCalls.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusForbidden) + writeBody(w, []byte(`{"errors":["permission denied"]}`)) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "repo", cfg, "path") + if err == nil { + t.Fatal("expected ErrForbidden") + } + if !errors.Is(err, ErrForbidden) { + t.Errorf("expected ErrForbidden, got %v", err) + } + if !strings.Contains(err.Error(), "denied") { + t.Errorf("expected 'denied' in error, got %q", err) + } + // Fresh token: should only login once (no 403 re-login attempt for fresh tokens). + if n := loginCalls.Load(); n != 1 { + t.Errorf("login called %d times, want exactly 1 (fresh token should not re-login)", n) + } +} + +type reloginRetryRow struct { + name string + retryStatus int // HTTP status for 3rd KV call (after 403 + re-login) + wantErr error + leaseSeconds int // token lease; 0 means none + tokenAge time.Duration // token age when the read starts; 0 means past reloginCooldown + slowBy time.Duration // how far the clock moves while OpenBao answers the 403 +} + +func runReloginRetryRow(t *testing.T, tt reloginRetryRow) { + t.Helper() + tokenFile := writeTokenFile(t, "jwt") + var kvCalls atomic.Int32 + var loginCalls atomic.Int32 + + // The handler moves the clock while the client reads it, so it is shared + // under a mutex. + var clockMu sync.Mutex + fakeNow := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + advance := func(d time.Duration) { + clockMu.Lock() + fakeNow = fakeNow.Add(d) + clockMu.Unlock() + } + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + loginCalls.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponseWithLease("fresh-token", tt.leaseSeconds)) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + n := kvCalls.Add(1) + switch n { + case 1: + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: "initial"})) + case 2: + advance(tt.slowBy) + w.WriteHeader(http.StatusForbidden) + writeBody(w, []byte(`{"errors":["permission denied"]}`)) + default: + w.WriteHeader(tt.retryStatus) + if tt.retryStatus == http.StatusOK { + writeBody(w, kvResponse(map[string]any{testFieldName: "ok"})) + } else { + writeBody(w, []byte(`{"errors":["permission denied"]}`)) + } + } + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + store.now = func() time.Time { + clockMu.Lock() + defer clockMu.Unlock() + return fakeNow + } + + // First read populates cache. + if _, err := store.Read(context.Background(), "repo", cfg, "path"); err != nil { + t.Fatalf("initial read: %v", err) + } + + // Age the token so that, by the 403, it is past its policy denial window + // and the 403 triggers re-login. + tokenAge := tt.tokenAge + if tokenAge == 0 { + tokenAge = 2 * time.Minute + } + advance(tokenAge) + + // Invalidate so next read hits OpenBao (which will 403 then retry). + store.Invalidate("path") + + data, err := store.Read(context.Background(), "repo", cfg, "path") + if tt.wantErr != nil { + if !errors.Is(err, tt.wantErr) { + t.Errorf("expected %v, got %v", tt.wantErr, err) + } + } else { + if err != nil { + t.Fatalf("Read: %v", err) + } + if string(data) != "ok" { + t.Errorf("got %q, want %q", data, "ok") + } + } + if n := loginCalls.Load(); n != 2 { + t.Errorf("login called %d times, want 2", n) + } +} + +func TestStore_403ThenReloginThen200(t *testing.T) { + tests := []reloginRetryRow{ + {name: "retry succeeds", retryStatus: http.StatusOK}, + {name: "retry also 403", retryStatus: http.StatusForbidden, wantErr: ErrForbidden}, + // A 30s lease is renewed at 20s, so its token never reaches the one + // minute cooldown; past a third of the lease the 403 still re-logs in. + {name: "short lease retry succeeds", retryStatus: http.StatusOK, leaseSeconds: 30, tokenAge: 15 * time.Second}, + // The token is 5s old, inside the 10s window, when the read starts, + // but the read takes 10s: at the 403 it is 15s old, so it re-logs in. + {name: "slow read past the window retry succeeds", retryStatus: http.StatusOK, leaseSeconds: 30, tokenAge: 5 * time.Second, slowBy: 10 * time.Second}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + runReloginRetryRow(t, tt) + }) + } +} + +func TestStore_NotFound(t *testing.T) { + tests := []struct { + name string + response func(w http.ResponseWriter) + }{ + { + name: "404 status", + response: func(w http.ResponseWriter) { + w.WriteHeader(http.StatusNotFound) + writeBody(w, []byte(`{"errors":[]}`)) + }, + }, + { + name: "soft-deleted secret", + response: func(w http.ResponseWriter) { + // KV v2 returns 200 with data.data=null for soft-deleted secrets. + w.WriteHeader(http.StatusOK) + writeBody(w, []byte(`{"data":{"data":null,"metadata":{"created_time":"2026-01-01T00:00:00Z","deletion_time":"2026-06-01T00:00:00Z","destroyed":false,"version":2}}}`)) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + tt.response(w) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "repo", cfg, "path") + if err == nil { + t.Fatal("expected ErrNotFound") + } + }) + } +} + +func TestStore_5xx_ErrUnavailable(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + tests := []struct { + code int + wantErr error + wantReason string + }{ + {500, ErrUnavailable, testReasonUnavail}, + {503, ErrUnavailable, testReasonUnavail}, + {429, ErrUnavailable, testReasonUnavail}, + {400, ErrRejected, testReasonRejected}, + {405, ErrRejected, testReasonRejected}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("status_%d", tt.code), func(t *testing.T) { + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(tt.code) + writeBody(w, []byte(`{"errors":["error"]}`)) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + before := testutil.ToFloat64(telemetry.SecretFetchFailuresTotal.WithLabelValues("status-repo-"+fmt.Sprint(tt.code), tt.wantReason)) + + store := NewStore() + _, err := store.Read(context.Background(), "status-repo-"+fmt.Sprint(tt.code), cfg, "path") + if err == nil { + t.Fatal("expected error") + } + if !errors.Is(err, tt.wantErr) { + t.Errorf("expected %v, got %v", tt.wantErr, err) + } + + after := testutil.ToFloat64(telemetry.SecretFetchFailuresTotal.WithLabelValues("status-repo-"+fmt.Sprint(tt.code), tt.wantReason)) + if after != before+1 { + t.Errorf("metric delta: got %v, want 1", after-before) + } + }) + } + +} + +func TestStore_503ThenSuccess_FailureNotCached(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + var kvCalls atomic.Int32 + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + n := kvCalls.Add(1) + if n == 1 { + w.WriteHeader(http.StatusServiceUnavailable) + writeBody(w, []byte(`{"errors":["unavailable"]}`)) + } else { + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: "ok"})) + } + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "retry-repo", cfg, "path") + if err == nil { + t.Fatal("first read: expected error") + } + + // Second read should succeed (failure was not cached). + data, err := store.Read(context.Background(), "retry-repo", cfg, "path") + if err != nil { + t.Fatalf("second read: %v", err) + } + if string(data) != "ok" { + t.Errorf("got %q, want %q", data, "ok") + } +} + +func TestStore_Login404_ErrRejected(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusNotFound) + writeBody(w, []byte(`{"errors":["not found"]}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "login-404-repo", cfg, "path") + if err == nil { + t.Fatal("expected error") + } + if !errors.Is(err, ErrRejected) { + t.Errorf("expected ErrRejected, got %v", err) + } +} + +func TestStore_ConnectionRefused_ErrUnavailable(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + cfg := &OpenBaoConfig{ + Addr: "http://127.0.0.1:1", // nothing listening + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "repo", cfg, "path") + if err == nil { + t.Fatal("expected error for connection refused") + } +} + +func TestStore_Timeout_ErrUnavailable(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + default: + // Stall long enough for the 10s client timeout (we override it below). + time.Sleep(5 * time.Second) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + store.mu.Lock() + c, err := store.clientForLocked(cfg) + store.mu.Unlock() + if err != nil { + t.Fatal(err) + } + // Override the HTTP client timeout to something short. + c.api.SetClientTimeout(100 * time.Millisecond) + + _, err = store.Read(context.Background(), "repo", cfg, "path") + if err == nil { + t.Fatal("expected error for timeout") + } +} + +// Actions run by TestStore_Invalidate between its first and last read. +const ( + invalidateActionPath = "invalidate_path" + invalidateActionOther = "invalidate_other" + invalidateActionOtherPath = "other_path" + invalidateActionConfigChanged = "config_changed" + invalidateActionConfigAlternated = "config_alternated" +) + +type invalidateRow struct { + name string + action string // one of the invalidateAction constants + wantKVHits int32 + wantLogins int32 +} + +func TestStore_Invalidate(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + + tests := []invalidateRow{ + { + name: "invalidate path refetches", + action: invalidateActionPath, + wantKVHits: 2, + wantLogins: 1, + }, + { + name: "invalidate other path does not evict", + action: invalidateActionOther, + wantKVHits: 1, + wantLogins: 1, + }, + { + name: "other path reuses the client", + action: invalidateActionOtherPath, + wantKVHits: 2, + wantLogins: 1, + }, + { + name: "changed config gets its own client and cache", + action: invalidateActionConfigChanged, + wantKVHits: 2, + wantLogins: 2, + }, + { + // Syncs on the old and the new config interleave after a reload: + // each config logs in once and keeps its cached key. + name: "alternating configs keep their clients and caches", + action: invalidateActionConfigAlternated, + wantKVHits: 2, + wantLogins: 2, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + runInvalidateRow(t, tokenFile, tt) + }) + } +} + +func runInvalidateRow(t *testing.T, tokenFile string, tt invalidateRow) { + t.Helper() + var kvHits, loginHits atomic.Int32 + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + loginHits.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse(fmt.Sprintf("tok-%d", loginHits.Load()))) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + kvHits.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: testPEMValue})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + + // First read to populate cache. + if _, err := store.Read(context.Background(), "repo", cfg, "path/a"); err != nil { + t.Fatalf("initial read: %v", err) + } + + secondCfg, secondPath := cfg, "path/a" + switch tt.action { + case invalidateActionPath: + store.Invalidate("path/a") + case invalidateActionOther: + store.Invalidate("path/b") + case invalidateActionOtherPath: + secondPath = "path/b" + case invalidateActionConfigChanged, invalidateActionConfigAlternated: + changed := *cfg + changed.Role = "r2" + secondCfg = &changed + } + if tt.action == invalidateActionConfigAlternated { + for _, c := range []*OpenBaoConfig{secondCfg, cfg} { + if _, err := store.Read(context.Background(), "repo", c, secondPath); err != nil { + t.Fatalf("alternating read: %v", err) + } + } + } + + // Second read. + if _, err := store.Read(context.Background(), "repo", secondCfg, secondPath); err != nil { + t.Fatalf("second read: %v", err) + } + + if got := kvHits.Load(); got != tt.wantKVHits { + t.Errorf("kv hits = %d, want %d", got, tt.wantKVHits) + } + if got := loginHits.Load(); got != tt.wantLogins { + t.Errorf("login hits = %d, want %d", got, tt.wantLogins) + } +} + +type refetchRow struct { + name string + refetchStatus int // status of the second KV read, the refetch + refetchValue string // value the refetch finds + wantErr error + wantCached string // what a Read after the refetch returns +} + +func runRefetchRow(t *testing.T, tt refetchRow) { + t.Helper() + tokenFile := writeTokenFile(t, "jwt") + var kvHits atomic.Int32 + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + if kvHits.Add(1) == 1 { + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: testPEMValue})) + return + } + w.WriteHeader(tt.refetchStatus) + if tt.refetchStatus == http.StatusOK { + writeBody(w, kvResponse(map[string]any{testFieldName: tt.refetchValue})) + } else { + writeBody(w, []byte(`{"errors":["unavailable"]}`)) + } + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + if _, err := store.Read(context.Background(), "repo", cfg, "path"); err != nil { + t.Fatalf("initial read: %v", err) + } + + data, err := store.Refetch(context.Background(), "repo", cfg, "path") + switch { + case tt.wantErr != nil && !errors.Is(err, tt.wantErr): + t.Fatalf("Refetch error = %v, want %v", err, tt.wantErr) + case tt.wantErr == nil && err != nil: + t.Fatalf("Refetch: %v", err) + case tt.wantErr == nil && string(data) != tt.refetchValue: + t.Errorf("Refetch = %q, want %q", data, tt.refetchValue) + } + + cached, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("read after refetch: %v", err) + } + if string(cached) != tt.wantCached { + t.Errorf("cached = %q, want %q", cached, tt.wantCached) + } + // The refetch always reads OpenBao; the read after it is served from the cache. + if got := kvHits.Load(); got != 2 { + t.Errorf("kv hits = %d, want 2", got) + } +} + +// TestStore_Refetch verifies that Refetch always reads OpenBao, replaces the +// cached value only when the fetched one differs, and leaves the cache in +// place when the fetch fails. +func TestStore_Refetch(t *testing.T) { + const rotatedPEMValue = "rotated-pem" + + tests := []refetchRow{ + {name: "same key keeps the cache", refetchStatus: http.StatusOK, refetchValue: testPEMValue, wantCached: testPEMValue}, + {name: "rotated key replaces the cache", refetchStatus: http.StatusOK, refetchValue: rotatedPEMValue, wantCached: rotatedPEMValue}, + {name: "failed refetch keeps the cache", refetchStatus: http.StatusServiceUnavailable, wantErr: ErrUnavailable, wantCached: testPEMValue}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + runRefetchRow(t, tt) + }) + } +} + +// TestStore_Invalidate_InFlightRace verifies that evicting or replacing a path +// while a read of it is in flight stops that read from caching what it +// fetched, and that doing so to another path does not. +// inFlightRaceSecondRead is what TestStore_Invalidate_InFlightRace's second +// OpenBao read of path/x returns. +const inFlightRaceSecondRead = "path/x-2" + +func TestStore_Invalidate_InFlightRace(t *testing.T) { + tests := []struct { + name string + act func(store *Store, cfg *OpenBaoConfig) error + wantHits int32 // OpenBao reads of path/x, in-flight read included + wantFinal string // what a read of path/x returns afterwards + }{ + { + name: "invalidate same path stops caching", + act: func(store *Store, _ *OpenBaoConfig) error { store.Invalidate("path/x"); return nil }, + wantHits: 2, + wantFinal: inFlightRaceSecondRead, + }, + { + name: "invalidate other path still caches", + act: func(store *Store, _ *OpenBaoConfig) error { store.Invalidate("path/y"); return nil }, + wantHits: 1, + wantFinal: "path/x-1", + }, + { + // path/x is not cached yet, so the refetch fills an empty entry. + // It must still stop the older in-flight read from caching. + name: "changed key on same path is not overwritten", + act: func(store *Store, cfg *OpenBaoConfig) error { + _, err := store.Refetch(context.Background(), "repo", cfg, "path/x") + return err + }, + wantHits: 2, + wantFinal: inFlightRaceSecondRead, + }, + { + // Another read of path/x finishes first and caches the newer + // key; the older in-flight read must not overwrite it. + name: "older read finishing last does not overwrite a newer cached key", + act: func(store *Store, cfg *OpenBaoConfig) error { + _, err := store.Read(context.Background(), "repo", cfg, "path/x") + return err + }, + wantHits: 2, + wantFinal: inFlightRaceSecondRead, + }, + { + name: "changed key on other path still caches", + act: func(store *Store, cfg *OpenBaoConfig) error { + _, err := store.Refetch(context.Background(), "repo", cfg, "path/y") + return err + }, + wantHits: 1, + wantFinal: "path/x-1", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + runInFlightRaceRow(t, tt.act, tt.wantHits, tt.wantFinal) + }) + } +} + +// runInFlightRaceRow blocks the first OpenBao read of path/x, runs act while +// it is in flight, then releases it. Each OpenBao read of a path returns +// "-" for its n-th read, so a changed key is always found. +func runInFlightRaceRow(t *testing.T, act func(*Store, *OpenBaoConfig) error, wantHits int32, wantFinal string) { + t.Helper() + tokenFile := writeTokenFile(t, "jwt") + gate := make(chan struct{}) + var hitsMu sync.Mutex + hits := map[string]int32{} + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + path := strings.TrimPrefix(r.URL.Path, "/v1/kv/data/") + hitsMu.Lock() + hits[path]++ + n := hits[path] + hitsMu.Unlock() + if path == "path/x" && n == 1 { + <-gate // block the first read of path/x + } + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: fmt.Sprintf("%s-%d", path, n)})) + } + }) + xHits := func() int32 { + hitsMu.Lock() + defer hitsMu.Unlock() + return hits["path/x"] + } + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + // path/y is cached up front, so a refetch of it finds a changed key. + if _, err := store.Read(context.Background(), "repo", cfg, "path/y"); err != nil { + t.Fatalf("path/y read: %v", err) + } + + var wg sync.WaitGroup + wg.Go(func() { + _, _ = store.Read(context.Background(), "repo", cfg, "path/x") + }) + + // Wait for the blocked request to be in-flight. + deadline := time.After(5 * time.Second) + for xHits() < 1 { + select { + case <-deadline: + t.Fatal("timed out waiting for in-flight request") + default: + time.Sleep(time.Millisecond) + } + } + + if err := act(store, cfg); err != nil { + t.Fatalf("act: %v", err) + } + + // Release the blocked request. + close(gate) + wg.Wait() + + data, err := store.Read(context.Background(), "repo", cfg, "path/x") + if err != nil { + t.Fatalf("final read: %v", err) + } + if string(data) != wantFinal { + t.Errorf("final read = %q, want %q", data, wantFinal) + } + if got := xHits(); got != wantHits { + t.Errorf("path/x kv hits = %d, want %d", got, wantHits) + } +} + +// TestStore_ConfigChangeDuringInFlightRead verifies that a read in flight on +// the old config when a read on a changed config starts caches only under the +// old config: neither read's key replaces the other's, and each config keeps +// its own client. +func TestStore_ConfigChangeDuringInFlightRead(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + var oldKVHits, newKVHits atomic.Int32 + gate := make(chan struct{}) + + kvServer := func(value string, hits *atomic.Int32, block bool) *httptest.Server { + return newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + hits.Add(1) + if block { + <-gate + } + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: value})) + } + }) + } + oldTS := kvServer("old-key", &oldKVHits, true) + newTS := kvServer("new-key", &newKVHits, false) + + oldCfg := &OpenBaoConfig{Addr: oldTS.URL, Role: "r", ServiceAccountTokenPath: tokenFile, KVMount: "kv", Field: testFieldName} + newCfg := *oldCfg + newCfg.Addr = newTS.URL + + store := NewStore() + + var wg sync.WaitGroup + wg.Go(func() { + _, _ = store.Read(context.Background(), "repo", oldCfg, "path/x") + }) + + deadline := time.After(5 * time.Second) + for oldKVHits.Load() < 1 { + select { + case <-deadline: + t.Fatal("timed out waiting for in-flight request") + default: + time.Sleep(time.Millisecond) + } + } + + // Read on the changed config while the old read is in flight. + data, err := store.Read(context.Background(), "repo", &newCfg, "path/x") + if err != nil { + t.Fatalf("new-config read: %v", err) + } + if string(data) != "new-key" { + t.Fatalf("new-config read = %q, want %q", data, "new-key") + } + + close(gate) + wg.Wait() + + // The in-flight old read must not have overwritten the cache. + data, err = store.Read(context.Background(), "repo", &newCfg, "path/x") + if err != nil { + t.Fatalf("final read: %v", err) + } + if string(data) != "new-key" { + t.Errorf("final read = %q, want %q (old backend key cached)", data, "new-key") + } + if got := newKVHits.Load(); got != 1 { + t.Errorf("new backend kv hits = %d, want 1 (final read served from cache)", got) + } + + // The old config's read cached its own key. + data, err = store.Read(context.Background(), "repo", oldCfg, "path/x") + if err != nil { + t.Fatalf("old-config read: %v", err) + } + if string(data) != "old-key" { + t.Errorf("old-config read = %q, want %q", data, "old-key") + } + if got := oldKVHits.Load(); got != 1 { + t.Errorf("old backend kv hits = %d, want 1 (served from its cache)", got) + } +} + +func TestStore_CancelledContext(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: testPEMValue})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() // cancel immediately + + _, err := store.Read(ctx, "repo", cfg, "path") + if err == nil { + t.Fatal("expected error for cancelled context") + } + if !errors.Is(err, context.Canceled) { + t.Errorf("expected context.Canceled, got %v", err) + } +} + +func TestStore_ConcurrentFirstReads_OneLogin(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + var loginCalls atomic.Int32 + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + loginCalls.Add(1) + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: testPEMValue})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + const n = 10 + var wg sync.WaitGroup + wg.Add(n) + for range n { + go func() { + defer wg.Done() + _, _ = store.Read(context.Background(), "repo", cfg, "path") + }() + } + wg.Wait() + + // The server never returns 403, so exactly one login should happen. + // Subsequent goroutines find the token already set under the mutex. + if got := loginCalls.Load(); got != 1 { + t.Errorf("login called %d times, want exactly 1", got) + } +} + +// A missing or unreadable token file is transient (the kubelet rotates it), not +// a denial. +func TestStore_TokenFileMissing_ErrUnavailable(t *testing.T) { + cfg := &OpenBaoConfig{ + Addr: "http://localhost:8200", + Role: "r", + ServiceAccountTokenPath: "/nonexistent/token/path", + KVMount: "kv", + Field: testFieldName, + } + + store := NewStore() + _, err := store.Read(context.Background(), "repo", cfg, "path") + if !errors.Is(err, ErrUnavailable) { + t.Fatalf("expected ErrUnavailable for missing token file, got %v", err) + } +} + +func TestStore_KeyBytesNeverInSlogOutput(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + secretPEM := "-----BEGIN OPENSSH PRIVATE KEY-----\nSUPERSECRET\n-----END OPENSSH PRIVATE KEY-----\n" + + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: secretPEM})) + } + }) + + cfg := &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + // Capture slog output. + var buf strings.Builder + logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})) + old := slog.Default() + slog.SetDefault(logger) + t.Cleanup(func() { slog.SetDefault(old) }) + + store := NewStore() + data, err := store.Read(context.Background(), "repo", cfg, "path") + if err != nil { + t.Fatalf("Read: %v", err) + } + if string(data) != secretPEM { + t.Errorf("data mismatch") + } + + logged := buf.String() + if strings.Contains(logged, "SUPERSECRET") { + t.Errorf("key bytes leaked into slog output: %s", logged) + } + if strings.Contains(logged, "BEGIN OPENSSH") { + t.Errorf("PEM header leaked into slog output: %s", logged) + } +} + +// TestStore_FetchFailuresMetric verifies that a failed read returns the +// matching sentinel and is counted under its reason label, including a client +// that cannot be built from the config. +func TestStore_FetchFailuresMetric(t *testing.T) { + tokenFile := writeTokenFile(t, "jwt") + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + w.WriteHeader(http.StatusOK) + writeBody(w, loginResponse("tok")) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + w.WriteHeader(http.StatusNotFound) + writeBody(w, []byte(`{"errors":[]}`)) + } + }) + + tests := []struct { + name string + addr string + wantErr error + reason string + }{ + {name: "secret not found", addr: ts.URL, wantErr: ErrNotFound, reason: "not_found"}, + {name: "address that does not parse", addr: "http://[::1", wantErr: ErrClientConfig, reason: "config_invalid"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := &OpenBaoConfig{ + Addr: tt.addr, + Role: "r", + ServiceAccountTokenPath: tokenFile, + KVMount: "kv", + Field: testFieldName, + } + + before := testutil.ToFloat64(telemetry.SecretFetchFailuresTotal.WithLabelValues("metric-repo", tt.reason)) + + _, err := NewStore().Read(context.Background(), "metric-repo", cfg, "path") + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Read error = %v, want %v", err, tt.wantErr) + } + + after := testutil.ToFloat64(telemetry.SecretFetchFailuresTotal.WithLabelValues("metric-repo", tt.reason)) + if after != before+1 { + t.Errorf("SecretFetchFailuresTotal{reason=%q}: got %v, want %v", tt.reason, after, before+1) + } + }) + } +} + +// tokenRenewalHarness serves logins and KV reads for TestStore_TokenRenewal. +// Login n answers loginStatus[n] (200 by default) with token "tok-", and +// blocks until loginGate[n] is closed when one is set. The clock is shared +// with the background renewal, so it is guarded. +type tokenRenewalHarness struct { + t *testing.T + store *Store + cfg *OpenBaoConfig + + mu sync.Mutex + clock time.Time + logins int + loginStatus map[int]int + loginGate map[int]chan struct{} + kvToken string +} + +func newTokenRenewalHarness(t *testing.T, leaseSeconds int) *tokenRenewalHarness { + t.Helper() + h := &tokenRenewalHarness{ + t: t, + clock: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), + loginStatus: map[int]int{}, + loginGate: map[int]chan struct{}{}, + } + ts := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasPrefix(r.URL.Path, "/v1/auth/kubernetes/login"): + h.mu.Lock() + h.logins++ + n := h.logins + status := cmp.Or(h.loginStatus[n], http.StatusOK) + gate := h.loginGate[n] + h.mu.Unlock() + if gate != nil { + <-gate + } + w.WriteHeader(status) + if status != http.StatusOK { + writeBody(w, []byte(`{"errors":["unavailable"]}`)) + return + } + writeBody(w, loginResponseWithLease(fmt.Sprintf("tok-%d", n), leaseSeconds)) + case strings.HasPrefix(r.URL.Path, "/v1/kv/data/"): + h.mu.Lock() + h.kvToken = r.Header.Get("X-Vault-Token") + h.mu.Unlock() + w.WriteHeader(http.StatusOK) + writeBody(w, kvResponse(map[string]any{testFieldName: testPEMValue})) + } + }) + h.cfg = &OpenBaoConfig{ + Addr: ts.URL, + Role: "r", + ServiceAccountTokenPath: writeTokenFile(t, "jwt"), + KVMount: "kv", + Field: testFieldName, + } + h.store = NewStore() + h.store.now = func() time.Time { + h.mu.Lock() + defer h.mu.Unlock() + return h.clock + } + return h +} + +func (h *tokenRenewalHarness) advance(d time.Duration) { + h.mu.Lock() + h.clock = h.clock.Add(d) + h.mu.Unlock() +} + +// blockLogin makes login n wait until the returned func is called; the +// test's cleanup releases it too. +func (h *tokenRenewalHarness) blockLogin(n int) func() { + gate := make(chan struct{}) + h.mu.Lock() + h.loginGate[n] = gate + h.mu.Unlock() + var once sync.Once + release := func() { once.Do(func() { close(gate) }) } + h.t.Cleanup(release) + return release +} + +func (h *tokenRenewalHarness) failLogin(n, status int) { + h.mu.Lock() + h.loginStatus[n] = status + h.mu.Unlock() +} + +func (h *tokenRenewalHarness) loginCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return h.logins +} + +// read evicts the path and reads it, so it reaches OpenBao, and returns the +// token the KV request carried. It fails the test if the read waits longer +// than a second, the bound for a read that must not wait on a login. +func (h *tokenRenewalHarness) read() (string, error) { + h.t.Helper() + h.store.Invalidate("path/renew") + done := make(chan error, 1) + go func() { + _, err := h.store.Read(context.Background(), "repo", h.cfg, "path/renew") + done <- err + }() + select { + case err := <-done: + h.mu.Lock() + defer h.mu.Unlock() + return h.kvToken, err + case <-time.After(time.Second): + h.t.Fatal("read waited on a login") + return "", nil + } +} + +// client returns the store's client for the harness config. +func (h *tokenRenewalHarness) client() *client { + h.store.mu.Lock() + defer h.store.mu.Unlock() + return h.store.clients[*h.cfg] +} + +func (h *tokenRenewalHarness) renewing() bool { + c := h.client() + c.mu.Lock() + defer c.mu.Unlock() + return c.renewing +} + +// waitFor polls cond until it holds, failing the test after five seconds. +func (h *tokenRenewalHarness) waitFor(what string, cond func() bool) { + h.t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + h.t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(time.Millisecond) + } +} + +func (h *tokenRenewalHarness) mustRead(wantToken string) { + h.t.Helper() + token, err := h.read() + if err != nil { + h.t.Fatalf("read: %v", err) + } + if token != wantToken { + h.t.Fatalf("read used token %q, want %q", token, wantToken) + } +} + +// TestStore_TokenRenewal verifies that a token past 2/3 of its lease is +// renewed in the background while reads keep using it, that a failed renewal +// keeps it and is retried once the retry window passes, and that only a +// missing or expired token makes a read wait for a login. +func TestStore_TokenRenewal(t *testing.T) { + tests := []struct { + name string + run func(t *testing.T) + }{ + {name: "no renewal before two thirds of the lease", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + h.mustRead("tok-1") + h.advance(59 * time.Second) + h.mustRead("tok-1") + if h.renewing() || h.loginCount() != 1 { + t.Errorf("renewing = %v, logins = %d, want no renewal", h.renewing(), h.loginCount()) + } + }}, + {name: "non-expiring token is never renewed", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 0) + h.mustRead("tok-1") + h.advance(24 * time.Hour) + h.mustRead("tok-1") + if h.renewing() || h.loginCount() != 1 { + t.Errorf("renewing = %v, logins = %d, want no renewal", h.renewing(), h.loginCount()) + } + }}, + {name: "reads keep the current token while the renewal runs", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + h.mustRead("tok-1") + release := h.blockLogin(2) + h.advance(61 * time.Second) + h.mustRead("tok-1") + h.waitFor("the renewal login", func() bool { return h.loginCount() == 2 }) + // A second read while the renewal is blocked neither waits nor + // starts another login. + h.mustRead("tok-1") + release() + h.waitFor("the renewal to finish", func() bool { return !h.renewing() }) + h.mustRead("tok-2") + if n := h.loginCount(); n != 2 { + t.Errorf("logins = %d, want 2", n) + } + }}, + {name: "failed renewal keeps the token and is retried after the window", run: func(t *testing.T) { + // A 600s lease renews from 400s and retries a failure once a + // minute, well before it expires. + h := newTokenRenewalHarness(t, 600) + h.failLogin(2, http.StatusServiceUnavailable) + h.mustRead("tok-1") + h.advance(401 * time.Second) + h.mustRead("tok-1") + h.waitFor("the failed renewal", func() bool { return h.loginCount() == 2 && !h.renewing() }) + h.mustRead("tok-1") + if h.renewing() || h.loginCount() != 2 { + t.Fatalf("renewing = %v, logins = %d, want no retry inside the window", h.renewing(), h.loginCount()) + } + h.advance(time.Minute) + h.mustRead("tok-1") + h.waitFor("the retried renewal", func() bool { return h.loginCount() == 3 && !h.renewing() }) + h.mustRead("tok-3") + }}, + {name: "expired token logs in before the read", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + h.mustRead("tok-1") + h.advance(91 * time.Second) + h.mustRead("tok-2") + }}, + {name: "failed login on an expired token fails the read", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + h.failLogin(2, http.StatusServiceUnavailable) + h.mustRead("tok-1") + h.advance(91 * time.Second) + if _, err := h.read(); !errors.Is(err, ErrUnavailable) { + t.Errorf("read error = %v, want ErrUnavailable", err) + } + }}, + } + + for _, tt := range tests { + t.Run(tt.name, tt.run) + } +} + +// readSharedForSharedLogin evicts and reads the path TestStore_SharedLogin uses, +// so the read reaches the client. +func readSharedForSharedLogin(ctx context.Context, h *tokenRenewalHarness) error { + h.store.Invalidate("path/shared") + _, err := h.store.Read(ctx, "repo", h.cfg, "path/shared") + return err +} + +// readConcurrentlyForSharedLogin starts n reads of the shared path, waits +// until the first login has started, runs release, and returns every read's +// error. +func readConcurrentlyForSharedLogin(h *tokenRenewalHarness, n int, release func()) []error { + errs := make([]error, n) + var wg sync.WaitGroup + wg.Add(n) + for i := range n { + go func() { + defer wg.Done() + errs[i] = readSharedForSharedLogin(context.Background(), h) + }() + } + h.waitFor("the first login", func() bool { return h.loginCount() == 1 }) + release() + wg.Wait() + return errs +} + +// TestStore_SharedLogin verifies that reads without a token share one login, +// that a failed login is answered from memory for loginFailureBackoff instead +// of being retried by every read, and that a read waiting for a login gives up +// at its own deadline. +func TestStore_SharedLogin(t *testing.T) { + const readers = 5 + tests := []struct { + name string + run func(t *testing.T) + }{ + {name: "concurrent reads share one successful login", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + release := h.blockLogin(1) + for i, err := range readConcurrentlyForSharedLogin(h, readers, release) { + if err != nil { + t.Errorf("read %d: %v", i, err) + } + } + if n := h.loginCount(); n != 1 { + t.Errorf("logins = %d, want 1", n) + } + }}, + {name: "concurrent reads share one failed login, which is not retried until the backoff ends", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + for n := 1; n <= readers; n++ { + h.failLogin(n, http.StatusServiceUnavailable) + } + release := h.blockLogin(1) + for i, err := range readConcurrentlyForSharedLogin(h, readers, release) { + if !errors.Is(err, ErrUnavailable) { + t.Errorf("read %d error = %v, want ErrUnavailable", i, err) + } + } + if n := h.loginCount(); n != 1 { + t.Fatalf("logins = %d, want 1", n) + } + // Inside the backoff the failure is answered without a login. + if err := readSharedForSharedLogin(context.Background(), h); !errors.Is(err, ErrUnavailable) { + t.Errorf("read inside the backoff error = %v, want ErrUnavailable", err) + } + if n := h.loginCount(); n != 1 { + t.Fatalf("logins inside the backoff = %d, want 1", n) + } + // Past it the next read logs in again. + h.advance(loginFailureBackoff) + h.failLogin(2, http.StatusOK) + h.mustRead("tok-2") + }}, + {name: "a read waiting for a slow login returns at its deadline", run: func(t *testing.T) { + h := newTokenRenewalHarness(t, 90) + release := h.blockLogin(1) + firstDone := make(chan error, 1) + go func() { firstDone <- readSharedForSharedLogin(context.Background(), h) }() + h.waitFor("the first login", func() bool { return h.loginCount() == 1 }) + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + start := time.Now() + err := readSharedForSharedLogin(ctx, h) + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("read error = %v, want context.DeadlineExceeded", err) + } + if waited := time.Since(start); waited > time.Second { + t.Errorf("read waited %v for a login past its deadline", waited) + } + + release() + if err := <-firstDone; err != nil { + t.Fatalf("first read: %v", err) + } + if n := h.loginCount(); n != 1 { + t.Errorf("logins = %d, want 1", n) + } + }}, + } + + for _, tt := range tests { + t.Run(tt.name, tt.run) + } +} diff --git a/pkg/telemetry/telemetry.go b/pkg/telemetry/telemetry.go index b2d39fb..dbfb9eb 100644 --- a/pkg/telemetry/telemetry.go +++ b/pkg/telemetry/telemetry.go @@ -2,7 +2,10 @@ package telemetry import "github.com/prometheus/client_golang/prometheus" -const labelRepo = "repo" +const ( + labelRepo = "repo" + labelReason = "reason" +) var ( SyncFailuresTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ @@ -74,7 +77,7 @@ var ( ConfigReloadFailuresTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "gfetch_config_reload_failures_total", Help: "Total number of config reload failures, by reason (load, validate, apply).", - }, []string{"reason"}) + }, []string{labelReason}) ConfigRepoValidateFailuresTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ Name: "gfetch_config_repo_validate_failures_total", @@ -105,6 +108,16 @@ var ( Name: "gfetch_cache_sync_retries_total", Help: "Total number of times the central cache sync was retried due to missing remote refs.", }, []string{labelRepo}) + + SecretFetchFailuresTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "gfetch_secret_fetch_failures_total", + Help: "Total number of secret fetch failures per repo and reason.", + }, []string{labelRepo, labelReason}) + + SecretAuthRefetchTotal = prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "gfetch_secret_auth_refetch_total", + Help: "Total number of times a secret key was refetched after an SSH authentication failure.", + }, []string{labelRepo}) ) func init() { @@ -129,5 +142,7 @@ func init() { RemoteRefsCount, LocalActiveRefsCount, CacheSyncRetriesTotal, + SecretFetchFailuresTotal, + SecretAuthRefetchTotal, ) }