diff --git a/.github/.copilot/breadcrumbs/2026-10-08-1729-selected-resource-authorization.md b/.github/.copilot/breadcrumbs/2026-10-08-1729-selected-resource-authorization.md index ae7a3d325..ae71fe7fd 100644 --- a/.github/.copilot/breadcrumbs/2026-10-08-1729-selected-resource-authorization.md +++ b/.github/.copilot/breadcrumbs/2026-10-08-1729-selected-resource-authorization.md @@ -34,14 +34,14 @@ - [x] Require `get` for named selections and `list` for label/all-of-kind selections in the RP namespace. - [x] Authorize creates and spec-changing updates; preserve existing validation and deletion cleanup behavior. - [x] Add RP constructor, scope, selector, overlapping-review, identity, denial, and failure tests. -- **Success criterion:** RP authorization is independently testable, fails closed, and does not require live object or informer dependencies. +- **Success criterion:** RP authorization is independently testable, fails closed, and derives get/list checks without fetching source objects. ### Phase 2b: ClusterResourcePlacement authorization (follow-up slice) -- [ ] Add direct cluster-scoped resource authorization. -- [ ] Resolve selected Namespaces using live hub API reads. -- [ ] Add NamespaceOnly, NamespaceWithResourceSelectors, and NamespaceWithResources authorization. -- [ ] Add CRP webhook tests for namespace modes, scope, overlapping selectors, and failure cases. +- [x] Add direct cluster-scoped resource authorization. +- [x] Resolve selected Namespaces using live hub API reads. +- [x] Add NamespaceOnly, NamespaceWithResourceSelectors, and NamespaceWithResources authorization. +- [x] Add focused CRP authorizer unit tests for namespace modes, scope, overlapping selectors, eligibility, fresh reads, and failures. - **Success criterion:** CRP authorization follows the agreed get/list policy without expanding the RP-only review scope. ### Phase 3: Override authorization @@ -64,7 +64,7 @@ - [ ] Run formatting and focused authorization, webhook, and option tests. - [ ] Run the smallest relevant integration tests using real Kubernetes RBAC authorization. -- [ ] Add focused RP webhook authorization wiring and update-gating coverage. +- [ ] Add focused RP/CRP webhook authorization wiring and update-gating coverage. - [ ] Run `make reviewable` before submission. - [ ] Update this breadcrumb with implementation details, changed files, and validation results. - **Success criterion:** Focused and repository-required checks pass with no authorization bypass or unrelated behavior regression. @@ -89,17 +89,21 @@ ## Status Plan approved by the user. Phase 1 and the Phase 2a RP-only slice are complete on -`feat/selected-resource-authorization-phase-2`. Phase 2b and Phases 3-5 remain. +`feat/selected-resource-authorization-phase-2`. Phase 2b authorizer logic and unit +tests are complete on `feat/selected-resource-authorization-crp`; Phases 3-5 remain. On October 19, the user requested a smaller review scope. The full implementation is preserved in pushed commit `e640d9b2`; the follow-up slice retains RP only. +Phase 2a merged as kubefleet-dev/kubefleet#988. Phase 2b is based on that merged RP +implementation. Production webhook wiring, SAR RBAC, and the default-on flag +remain Phase 4. + ## Phase 2a implementation details -- Added `ResourcePlacementAuthorizer` and `NewResourcePlacementAuthorizer` in - `pkg/utils/authorization/placement.go`, with private mapper, reviewer, and - eligibility-checker dependencies. No reader, informer, or Namespace resolution - is needed. An explicit RP/CRP type switch routes RP to its typed resolver; - the CRP branch returns a clear not-implemented error for the follow-up slice. +- Added the RP authorizer in `pkg/utils/authorization/placement.go`. Phase 2b + generalizes its type and construction for both placement APIs. RP requests + still need no Namespace resolution or ordinary object reads. The explicit + RP/CRP type switch initially deferred CRP; Phase 2b fills in that branch. - Build get checks for named selectors and list checks for label/all-of-kind selectors in the RP namespace. No source objects are fetched. Reuse the Phase 1 reviewer's identity preservation, deduplication, and bounded concurrency. @@ -112,12 +116,69 @@ is preserved in pushed commit `e640d9b2`; the follow-up slice retains RP only. shared validator tests cover admission decision mapping. The dedicated RP webhook authorization test file was removed at the user's request; its wiring and update-gating coverage is deferred. -- Defer CRP authorization and its tests. Its handler passes nil to the shared +- Defer CRP production wiring and webhook tests. Its handler passes nil to the shared authorization parameter, preserving existing behavior. The controller's resource selector resolver is unchanged. - Production registration still does not inject the RP authorizer. Default-on enforcement, rollout wiring, and SAR RBAC remain Phase 4. +## Phase 2b implementation details + +- A single `NewPlacementAuthorizer` creates the shared `PlacementAuthorizer` for + both RP and CRP. It validates the mapper, reviewer, eligibility checker, + uncached Namespace reader, and resource-type inventory up front. All five are + required even though RP requests do not use the Namespace dependencies. + The RP/CRP-specific constructors and RP-specific type alias were removed. + One fully configured instance can later be injected into both webhooks. +- CRP resolution composes two helpers: Namespace selection returns checks and a + `namespaceScope` value; non-Namespace selection consumes that scope and returns + its own checks. The outer method only validates the CRP and combines results, + without sharing mutable state between the two passes. + NamespaceOnly, NamespaceWithResources (including default), and + NamespaceWithResourceSelectors have explicit separate cases. Selective mode + requires exactly one named active Namespace and cannot mix Namespace selectors. +- NamespaceOnly builds get/list checks without any Namespace reader calls or + existence checks. Mapping, kind eligibility, and selector validation still run. + Expansion and selective modes resolve Namespaces live, filter deleting objects, + and enforce content-namespace eligibility; NamespaceOnly does not apply those + content exclusions, matching the controller. +- Before any CRP Namespace reads, authorize all Namespace get/list checks derived + from selector metadata. Denied, no-opinion, and indeterminate Namespace reviews + stop resolution immediately, so responses cannot disclose discovered Namespace + names or existence through lookup errors or expanded denial reasons. After an + allowed preflight, resolve expansion and authorize the full batch. Namespace + checks are intentionally repeated in that batch to keep the implementation + simple; no cross-phase filtering or deduplication optimization is used. +- Expansion builds list checks for each eligible tracked namespaced resource type + in each active selected Namespace. Ordinary resource checks remain metadata-only: + get by name or list for label/all-of-kind, with no per-object get checks. +- Namespace expansion skips inventory entries whose kinds no longer map + (`NoMatch`), with a debug log, matching the controller's removed-CRD handling. + Other mapper/eligibility failures and explicit unknown selectors still fail + closed. Tests retain valid checks before and after a stale inventory entry. +- Added focused tests for exact attributes, all modes, multiple Namespaces, + ordering, overlaps, exclusions, missing/deleting Namespaces, malformed selectors, + mapping/inventory/API failures, denials, and fresh Namespace reads using the + current requester. Tests fail on any non-Namespace reader operation. + NamespaceOnly tests additionally require exactly zero reader calls for named, + label, all-of-kind, and nonexistent named selections. Namespace read failures + are tested in expansion modes, and non-NoMatch inventory mapper errors remain + explicit failures. + Preflight regressions assert zero Namespace reads and no expanded reviews on + Namespace denial, no opinion, API failure, or evaluation error, including named + missing Namespaces, label/all selections, and selective mode. Label/all failure + responses must not contain discovered Namespace names. +- No controller resolver, shared validation, or webhook code changed. No new + webhook test scaffold or production enforcement wiring is included. + +## Phase 2b validation + +- Focused uncached race tests and `go vet` passed for authorization, validator, and + both placement webhook packages. +- `go build ./cmd/hubagent/...`, new-code lint, repository `make lint` using the + installed v2.13.2 linter, and `git diff --check` passed. +- Go commands use `MS_GOTOOLCHAIN_ALLOW_NON_LOCAL=1 GOTOOLCHAIN=auto`. + ## Phase 2a validation - Focused race tests passed for `pkg/utils/authorization`, `pkg/utils/validator`, diff --git a/.github/skills/tiered-memory/SKILL.md b/.github/skills/tiered-memory/SKILL.md index 5921eb80a..e94b74c6f 100644 --- a/.github/skills/tiered-memory/SKILL.md +++ b/.github/skills/tiered-memory/SKILL.md @@ -8,7 +8,7 @@ source: design proposal # Skill: Tiered Agent Memory -> **Status (v0.10.0):** This skill describes a **design proposal**, not a shipped runtime. Skill files install via `squad init`/`upgrade`, but the underlying tier scaffolding (`.squad/memory/hot/`, `cold/`, `wiki/`), Scribe promotion logic, and spawn-template tier-aware reads are tracked in [bradygaster/squad#1264](https://github.com/bradygaster/squad/issues/1264). Until those land, agents continue to load full `history.md` + `decisions.md` on every spawn. +> **Status (v0.10.0):** This skill describes a **design proposal**, not a shipped runtime. Skill files install via `squad init`/`upgrade`, but the underlying tier scaffolding (`.squad/memory/hot/`, `cold/`, `wiki/`), Scribe promotion logic, and spawn-template tier-aware reads are tracked in [github/squad#1264](https://github.com/github/squad/issues/1264). Until those land, agents continue to load full `history.md` + `decisions.md` on every spawn. ## Overview @@ -116,9 +116,9 @@ Until then, see the Scribe charter for current behavior: `.squad/agents/scribe/c ## References -- Tracking issue: [bradygaster/squad#1264](https://github.com/bradygaster/squad/issues/1264) — installation gap + runtime status -- Original design spike: [bradygaster/squad#686](https://github.com/bradygaster/squad/issues/686) — tiered memory implementation plan -- Related: [bradygaster/squad#600](https://github.com/bradygaster/squad/issues/600) — context payload growth +- Tracking issue: [github/squad#1264](https://github.com/github/squad/issues/1264) — installation gap + runtime status +- Original design spike: [github/squad#686](https://github.com/github/squad/issues/686) — tiered memory implementation plan +- Related: [github/squad#600](https://github.com/github/squad/issues/600) — context payload growth --- @@ -217,5 +217,5 @@ If blocked or uncertain: - Hot tier is always included; keep it focused - Cold adds a summary; only include when history is relevant - Wiki adds variable size; only include specific relevant docs -- Runtime backing is tracked in [bradygaster/squad#1264](https://github.com/bradygaster/squad/issues/1264) — until those changes land, this skill is design-only and agents continue to load full history.md + decisions.md on every spawn +- Runtime backing is tracked in [github/squad#1264](https://github.com/github/squad/issues/1264) — until those changes land, this skill is design-only and agents continue to load full history.md + decisions.md on every spawn diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e6b7e3d8..c90b1e1d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,7 +45,7 @@ jobs: - name: Set up Ginkgo CLI run: | - go install github.com/onsi/ginkgo/v2/ginkgo@v2.23.4 + go install github.com/onsi/ginkgo/v2/ginkgo - name: Prepare necessary environment variables run: | @@ -170,7 +170,10 @@ jobs: - name: Install Ginkgo CLI run: | - go install github.com/onsi/ginkgo/v2/ginkgo@v2.23.4 + go install github.com/onsi/ginkgo/v2/ginkgo + + - name: Increase inotify limits for multi-node Kind clusters + run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=1048576 - name: Install Kind # Before updating the kind version to use, verify that the current kind image diff --git a/.github/workflows/code-lint.yml b/.github/workflows/code-lint.yml index 717439c85..e45f8e271 100644 --- a/.github/workflows/code-lint.yml +++ b/.github/workflows/code-lint.yml @@ -79,7 +79,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Helm - uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5 + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5 with: version: v3.17.0 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index b0566085d..38167aa43 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -42,7 +42,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4 + uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4 + uses: github/codeql-action/autobuild@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -69,4 +69,4 @@ jobs: # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4 + uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4 diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index f94f440d8..d89692b62 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Harden Runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9692630b9..662e15749 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -87,7 +87,7 @@ jobs: ref: ${{ needs.setup.outputs.tag }} - name: Login to ghcr.io - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -187,7 +187,7 @@ jobs: ref: ${{ needs.setup.outputs.tag }} - name: Login to GitHub Container Registry - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -197,7 +197,7 @@ jobs: # version that packages a release is the same one code-lint.yml lints the # charts with. - name: Set up Helm - uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5 + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5 with: version: v3.17.0 @@ -252,7 +252,7 @@ jobs: # follow-up issue). Auditing egress at least records what it reaches out # to until that action is replaced. - name: Harden Runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit diff --git a/.github/workflows/trivy.yml b/.github/workflows/trivy.yml index 26aa4b05f..9be2344ec 100644 --- a/.github/workflows/trivy.yml +++ b/.github/workflows/trivy.yml @@ -50,7 +50,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Login to ${{ env.REGISTRY }} - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} diff --git a/.github/workflows/upgrade.yml b/.github/workflows/upgrade.yml index 0ba9e395b..8859396e5 100644 --- a/.github/workflows/upgrade.yml +++ b/.github/workflows/upgrade.yml @@ -69,9 +69,12 @@ jobs: echo "=== Docker moved to /mnt, verifying ===" docker info | grep "Docker Root Dir" || true + - name: Increase inotify limits for Kind clusters + run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=1048576 + - name: Set up Ginkgo CLI run: | - go install github.com/onsi/ginkgo/v2/ginkgo@v2.23.4 + go install github.com/onsi/ginkgo/v2/ginkgo - name: Travel back in time to the before upgrade version run: | @@ -171,9 +174,12 @@ jobs: echo "=== Docker moved to /mnt, verifying ===" docker info | grep "Docker Root Dir" || true + - name: Increase inotify limits for Kind clusters + run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=1048576 + - name: Set up Ginkgo CLI run: | - go install github.com/onsi/ginkgo/v2/ginkgo@v2.23.4 + go install github.com/onsi/ginkgo/v2/ginkgo - name: Travel back in time to the before upgrade version run: | @@ -273,9 +279,12 @@ jobs: echo "=== Docker moved to /mnt, verifying ===" docker info | grep "Docker Root Dir" || true + - name: Increase inotify limits for Kind clusters + run: sudo sysctl -w fs.inotify.max_user_instances=1024 fs.inotify.max_user_watches=1048576 + - name: Set up Ginkgo CLI run: | - go install github.com/onsi/ginkgo/v2/ginkgo@v2.23.4 + go install github.com/onsi/ginkgo/v2/ginkgo - name: Travel back in time to the before upgrade version run: | diff --git a/.github/workflows/workflow-lint.yml b/.github/workflows/workflow-lint.yml index 829a63667..75d439594 100644 --- a/.github/workflows/workflow-lint.yml +++ b/.github/workflows/workflow-lint.yml @@ -24,7 +24,7 @@ jobs: timeout-minutes: 10 steps: - name: Harden Runner - uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: egress-policy: audit diff --git a/apis/placement/v1/clusterresourceplacement_types.go b/apis/placement/v1/clusterresourceplacement_types.go index b8620ae9a..a7f594043 100644 --- a/apis/placement/v1/clusterresourceplacement_types.go +++ b/apis/placement/v1/clusterresourceplacement_types.go @@ -994,7 +994,7 @@ type RollingUpdateConfig struct { // We have a built-in resource state detector to determine the availability status of following well-known Kubernetes // native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, // ClusterRole, ClusterRoleBinding, Role, RoleBinding. - // Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + // Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. // For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds // have passed since they were successfully applied to the target cluster. // Default is 60. diff --git a/apis/placement/v1beta1/clusterresourceplacement_types.go b/apis/placement/v1beta1/clusterresourceplacement_types.go index 3cd137cf6..858b7c6b6 100644 --- a/apis/placement/v1beta1/clusterresourceplacement_types.go +++ b/apis/placement/v1beta1/clusterresourceplacement_types.go @@ -1009,7 +1009,7 @@ type RollingUpdateConfig struct { // We have a built-in resource state detector to determine the availability status of following well-known Kubernetes // native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, // ClusterRole, ClusterRoleBinding, Role, RoleBinding. - // Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + // Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. // For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds // have passed since they were successfully applied to the target cluster. // Default is 60. diff --git a/config/crd/bases/placement.kubernetes-fleet.io_clusterresourceplacements.yaml b/config/crd/bases/placement.kubernetes-fleet.io_clusterresourceplacements.yaml index 9aa1b1e41..e349f1505 100644 --- a/config/crd/bases/placement.kubernetes-fleet.io_clusterresourceplacements.yaml +++ b/config/crd/bases/placement.kubernetes-fleet.io_clusterresourceplacements.yaml @@ -988,7 +988,7 @@ spec: We have a built-in resource state detector to determine the availability status of following well-known Kubernetes native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, ClusterRole, ClusterRoleBinding, Role, RoleBinding. - Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds have passed since they were successfully applied to the target cluster. Default is 60. @@ -2674,7 +2674,7 @@ spec: We have a built-in resource state detector to determine the availability status of following well-known Kubernetes native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, ClusterRole, ClusterRoleBinding, Role, RoleBinding. - Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds have passed since they were successfully applied to the target cluster. Default is 60. diff --git a/config/crd/bases/placement.kubernetes-fleet.io_resourceplacements.yaml b/config/crd/bases/placement.kubernetes-fleet.io_resourceplacements.yaml index df15dd56a..87d6255b3 100644 --- a/config/crd/bases/placement.kubernetes-fleet.io_resourceplacements.yaml +++ b/config/crd/bases/placement.kubernetes-fleet.io_resourceplacements.yaml @@ -980,7 +980,7 @@ spec: We have a built-in resource state detector to determine the availability status of following well-known Kubernetes native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, ClusterRole, ClusterRoleBinding, Role, RoleBinding. - Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds have passed since they were successfully applied to the target cluster. Default is 60. @@ -2651,7 +2651,7 @@ spec: We have a built-in resource state detector to determine the availability status of following well-known Kubernetes native resources: Deployment, StatefulSet, DaemonSet, Service, Namespace, ConfigMap, Secret, ClusterRole, ClusterRoleBinding, Role, RoleBinding. - Please see [SafeRollout](https://github.com/Azure/fleet/tree/main/docs/concepts/SafeRollout/README.md) for more details. + Please see [SafeRollout](https://kubefleet.dev/docs/concepts/safe-rollout/) for more details. For other types of resources, we consider them as available after `UnavailablePeriodSeconds` seconds have passed since they were successfully applied to the target cluster. Default is 60. diff --git a/docker/hub-agent.Dockerfile b/docker/hub-agent.Dockerfile index 17d0f2e19..914ac9d7c 100644 --- a/docker/hub-agent.Dockerfile +++ b/docker/hub-agent.Dockerfile @@ -8,7 +8,7 @@ # Segmentation fault" / "cgo: gcc produced no output" in runtime/cgo and net) # and, when it did not crash, took over an hour per image. Only the final # distroless stage is per-target, and it runs no commands. -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.10-1 AS builder +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.11-1 AS builder WORKDIR /workspace # Copy the Go Modules manifests diff --git a/docker/member-agent.Dockerfile b/docker/member-agent.Dockerfile index c3f1581ea..6c0ab64d1 100644 --- a/docker/member-agent.Dockerfile +++ b/docker/member-agent.Dockerfile @@ -8,7 +8,7 @@ # Segmentation fault" / "cgo: gcc produced no output" in runtime/cgo and net) # and, when it did not crash, took over an hour per image. Only the final # distroless stage is per-target, and it runs no commands. -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.10-1 AS builder +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.11-1 AS builder WORKDIR /workspace # Copy the Go Modules manifests diff --git a/docker/refresh-token.Dockerfile b/docker/refresh-token.Dockerfile index d40bb0afa..4a4283b71 100644 --- a/docker/refresh-token.Dockerfile +++ b/docker/refresh-token.Dockerfile @@ -8,7 +8,7 @@ # Segmentation fault" / "cgo: gcc produced no output" in runtime/cgo and net) # and, when it did not crash, took over an hour per image. Only the final # distroless stage is per-target, and it runs no commands. -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.10-1 AS builder +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/oss/go/microsoft/golang:1.26.11-1 AS builder WORKDIR /workspace # Copy the Go Modules manifests diff --git a/go.mod b/go.mod index b4c91309a..e78ec6b0f 100644 --- a/go.mod +++ b/go.mod @@ -6,25 +6,25 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 github.com/Azure/karpenter-provider-azure v1.14.2 - github.com/crossplane/crossplane-runtime/v2 v2.4.2 + github.com/crossplane/crossplane-runtime/v2 v2.4.3 github.com/evanphx/json-patch/v5 v5.9.11 github.com/go-logr/logr v1.4.4 github.com/gofrs/uuid v4.4.0+incompatible github.com/google/go-cmp v0.7.0 github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 - github.com/onsi/ginkgo/v2 v2.33.0 + github.com/onsi/ginkgo/v2 v2.34.0 github.com/onsi/gomega v1.44.0 - github.com/prometheus/client_golang v1.24.1 + github.com/prometheus/client_golang v1.25.0 github.com/prometheus/client_model v0.6.3 github.com/qri-io/jsonpointer v0.1.1 github.com/spf13/cobra v1.10.2 - github.com/spf13/pflag v1.0.10 + github.com/spf13/pflag v1.1.0 github.com/stretchr/testify v1.12.1 github.com/wI2L/jsondiff v0.7.1 go.goms.io/fleet-networking v0.3.44 go.uber.org/atomic v1.12.0 go.uber.org/zap v1.28.0 - golang.org/x/sync v0.23.0 + golang.org/x/sync v0.25.0 golang.org/x/time v0.16.0 gomodules.xyz/jsonpatch/v2 v2.5.0 google.golang.org/grpc v1.83.2 @@ -112,8 +112,8 @@ require ( github.com/patrickmn/go-cache v2.1.0+incompatible // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/common v0.70.1 // indirect - github.com/prometheus/procfs v0.21.1 // indirect + github.com/prometheus/common v0.72.0 // indirect + github.com/prometheus/procfs v0.22.0 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect github.com/samber/lo v1.53.0 // indirect github.com/tidwall/gjson v1.18.0 // indirect @@ -128,15 +128,15 @@ require ( go.uber.org/multierr v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/crypto v0.57.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirect golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect - golang.org/x/tools v0.49.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/term v0.47.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/tools v0.51.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect diff --git a/go.sum b/go.sum index dfc80a940..8a339bdd1 100644 --- a/go.sum +++ b/go.sum @@ -110,8 +110,8 @@ github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2y 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/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/crossplane/crossplane-runtime/v2 v2.4.2 h1:MXc37IyL7iyrQIxs0qrAtdOsy0mdQkxOMie4UVWSFQ4= -github.com/crossplane/crossplane-runtime/v2 v2.4.2/go.mod h1:jDwOCwt+LMD6KXsnvvm1mNNiVqKZ2ZWZxuUnkxdkBPE= +github.com/crossplane/crossplane-runtime/v2 v2.4.3 h1:L50ZZl5sePBAHw5nKUqgtwKhp4o7LDZ/19Fi5Ryn9Co= +github.com/crossplane/crossplane-runtime/v2 v2.4.3/go.mod h1:XETDdRo3qbzYa1lOwJG11bQFgCKEs+PwJpwXzhXK9bI= github.com/crossplane/crossplane/apis/v2 v2.3.4 h1:qB1YqF300msWEkDQTFUhqfeOq3HtVfSZ1+3wNz1JStA= github.com/crossplane/crossplane/apis/v2 v2.3.4/go.mod h1:s0cfMZA+Y/dwQ577PLQn5SBWyUg9k6vKjGAkHEwBShg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -249,8 +249,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU= github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -277,8 +277,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s= github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= -github.com/onsi/ginkgo/v2 v2.33.0 h1:C8gBA6Uc2ZEubiV+SXiu5tZnMTwEmXHgkJwGozKtZf8= -github.com/onsi/ginkgo/v2 v2.33.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= +github.com/onsi/ginkgo/v2 v2.34.0 h1:aN3Us823mHHTSWMIi8WIQTdYuSPhl2lWY46E/w3SiAk= +github.com/onsi/ginkgo/v2 v2.34.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= @@ -290,14 +290,14 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/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= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= -github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= -github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4= +github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/qri-io/jsonpointer v0.1.1 h1:prVZBZLL6TW5vsSB9fFHFAMBLI4b0ri5vribQlTJiBA= github.com/qri-io/jsonpointer v0.1.1/go.mod h1:DnJPaYgiKu56EuDp8TU5wFLdZIcAnb/uH9v37ZaMV64= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= @@ -314,8 +314,8 @@ github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+D github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= -github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag= +github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -380,8 +380,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU= golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -394,15 +394,15 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -413,15 +413,15 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -429,16 +429,16 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gomodules.xyz/jsonpatch/v2 v2.5.0 h1:JELs8RLM12qJGXU4u/TO3V25KW8GreMKl9pdkk14RM0= gomodules.xyz/jsonpatch/v2 v2.5.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= diff --git a/pkg/utils/authorization/authorization.go b/pkg/utils/authorization/authorization.go index 38f2a018d..e4af84b2a 100644 --- a/pkg/utils/authorization/authorization.go +++ b/pkg/utils/authorization/authorization.go @@ -50,12 +50,15 @@ const ( DecisionAllowed Decision = "Allowed" // DecisionDenied means at least one required permission was not granted. DecisionDenied Decision = "Denied" + // DecisionInvalid means the placement input is invalid. + DecisionInvalid Decision = "Invalid" // DecisionIndeterminate means authorization could not be completed. DecisionIndeterminate Decision = "Indeterminate" ) // Result reports the aggregate outcome of an authorization batch. // A denied decision may include Err for additional review failures without changing the decision. +// An invalid decision must include Err describing the invalid input. type Result struct { Decision Decision DenialReason string diff --git a/pkg/utils/authorization/clusterresourceplacement.go b/pkg/utils/authorization/clusterresourceplacement.go new file mode 100644 index 000000000..b83d642c2 --- /dev/null +++ b/pkg/utils/authorization/clusterresourceplacement.go @@ -0,0 +1,231 @@ +/* +Copyright 2026 The KubeFleet Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package authorization + +import ( + "context" + "errors" + "fmt" + + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/klog/v2" + "sigs.k8s.io/controller-runtime/pkg/client" + + placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" + "go.goms.io/fleet/pkg/utils" +) + +// NamespacedResourceInventory supplies the namespaced resource types tracked by the placement controller. +type NamespacedResourceInventory interface { + GetNameSpaceScopedResources() []schema.GroupVersionResource +} + +type namespaceScope struct { + hasSelectiveNamespace bool + selectedNamespaceName string +} + +func (a *PlacementAuthorizer) resolveClusterResourcePlacement(ctx context.Context, crp *placementv1beta1.ClusterResourcePlacement) ([]authorizationv1.ResourceAttributes, error) { + if crp == nil { + return nil, errors.New("cluster resource placement must not be nil") + } + if crp.Namespace != "" { + return nil, invalidPlacementError("cluster resource placement must not specify a namespace") + } + expandedChecks, scope, err := a.resolveNamespaceSelectors(ctx, crp.Spec.ResourceSelectors) + if err != nil { + return nil, err + } + resourceChecks, err := a.resolveNonNamespaceSelectors(crp.Spec.ResourceSelectors, scope) + if err != nil { + return nil, err + } + return append(expandedChecks, resourceChecks...), nil +} + +func (a *PlacementAuthorizer) resolveNamespaceSelectors(ctx context.Context, selectors []placementv1beta1.ResourceSelectorTerm) ([]authorizationv1.ResourceAttributes, namespaceScope, error) { + var namespaces []corev1.Namespace + var scope namespaceScope + namespaceSelectorCount := 0 + for _, selector := range selectors { + if selectorGVK(selector) != utils.NamespaceGVK { + continue + } + namespaceSelectorCount++ + if selector.SelectionScope == placementv1beta1.NamespaceWithResourceSelectors { + if scope.hasSelectiveNamespace { + return nil, namespaceScope{}, invalidPlacementError("NamespaceWithResourceSelectors requires exactly one namespace selector") + } + scope.hasSelectiveNamespace = true + scope.selectedNamespaceName = selector.Name + } + if !a.resourceEligibilityChecker.AllowsGVK(utils.NamespaceGVK) { + continue + } + switch selector.SelectionScope { + case placementv1beta1.NamespaceOnly: + continue + case placementv1beta1.NamespaceWithResourceSelectors: + if !a.resourceEligibilityChecker.AllowsNamespace(selector.Name) { + return nil, namespaceScope{}, invalidPlacementError(fmt.Sprintf("namespace %q is not eligible for placement", selector.Name)) + } + continue + case "", placementv1beta1.NamespaceWithResources: + selected, err := a.selectNamespaces(ctx, selector) + if err != nil { + return nil, namespaceScope{}, err + } + namespaces = append(namespaces, selected...) + default: + return nil, namespaceScope{}, invalidPlacementError(fmt.Sprintf("unsupported namespace selection scope %q", selector.SelectionScope)) + } + } + if scope.hasSelectiveNamespace && namespaceSelectorCount != 1 { + return nil, namespaceScope{}, invalidPlacementError("NamespaceWithResourceSelectors requires exactly one namespace selector") + } + attributes, err := a.expandNamespaces(namespaces) + if err != nil { + return nil, namespaceScope{}, err + } + return attributes, scope, nil +} + +func (a *PlacementAuthorizer) resolveNonNamespaceSelectors(selectors []placementv1beta1.ResourceSelectorTerm, scope namespaceScope) ([]authorizationv1.ResourceAttributes, error) { + var attributes []authorizationv1.ResourceAttributes + for _, selector := range selectors { + gvk := selectorGVK(selector) + if gvk == utils.NamespaceGVK { + continue + } + mapping, err := a.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err != nil { + return nil, fmt.Errorf("failed to resolve selector %s: %w", gvk, err) + } + namespace := "" + if mapping.Scope.Name() == meta.RESTScopeNameNamespace { + if !scope.hasSelectiveNamespace { + return nil, invalidPlacementError(fmt.Sprintf("cluster resource placement requires NamespaceWithResourceSelectors to select namespaced resource %s", gvk)) + } + namespace = scope.selectedNamespaceName + } + if !a.resourceEligibilityChecker.AllowsGVK(gvk) { + continue + } + check, err := a.selectorAttributes(mapping.Resource, namespace, selector) + if err != nil { + return nil, err + } + attributes = append(attributes, check) + } + return attributes, nil +} + +func (a *PlacementAuthorizer) namespaceChecksForPlacement(placement placementv1beta1.PlacementObj) ([]authorizationv1.ResourceAttributes, error) { + crp, ok := placement.(*placementv1beta1.ClusterResourcePlacement) + if !ok { + return nil, nil + } + if crp == nil { + return nil, errors.New("cluster resource placement must not be nil") + } + if crp.Namespace != "" { + return nil, invalidPlacementError("cluster resource placement must not specify a namespace") + } + var attributes []authorizationv1.ResourceAttributes + for _, selector := range crp.Spec.ResourceSelectors { + if selectorGVK(selector) != utils.NamespaceGVK { + continue + } + checks, err := a.namespaceSelectorAttributes(selector) + if err != nil { + return nil, err + } + attributes = append(attributes, checks...) + } + return attributes, nil +} + +func (a *PlacementAuthorizer) namespaceSelectorAttributes(selector placementv1beta1.ResourceSelectorTerm) ([]authorizationv1.ResourceAttributes, error) { + if selector.SelectionScope == placementv1beta1.NamespaceWithResourceSelectors && (selector.Name == "" || selector.LabelSelector != nil) { + return nil, invalidPlacementError("NamespaceWithResourceSelectors requires a namespace selected by name") + } + mapping, err := a.restMapper.RESTMapping(utils.NamespaceGVK.GroupKind(), utils.NamespaceGVK.Version) + if err != nil { + return nil, fmt.Errorf("failed to resolve Namespace mapping: %w", err) + } + if !a.resourceEligibilityChecker.AllowsGVK(utils.NamespaceGVK) { + return nil, nil + } + check, err := a.selectorAttributes(mapping.Resource, "", selector) + if err != nil { + return nil, err + } + return []authorizationv1.ResourceAttributes{check}, nil +} + +func (a *PlacementAuthorizer) selectNamespaces(ctx context.Context, selector placementv1beta1.ResourceSelectorTerm) ([]corev1.Namespace, error) { + if selector.Name != "" { + return []corev1.Namespace{{ObjectMeta: metav1.ObjectMeta{Name: selector.Name}}}, nil + } + labelSelector := labels.Everything() + if selector.LabelSelector != nil { + var err error + labelSelector, err = metav1.LabelSelectorAsSelector(selector.LabelSelector) + if err != nil { + return nil, invalidPlacementError(fmt.Sprintf("invalid namespace label selector: %v", err)) + } + } + var list corev1.NamespaceList + if err := a.namespaceReader.List(ctx, &list, client.MatchingLabelsSelector{Selector: labelSelector}); err != nil { + return nil, fmt.Errorf("failed to list selected namespaces: %w", err) + } + return list.Items, nil +} + +func (a *PlacementAuthorizer) expandNamespaces(namespaces []corev1.Namespace) ([]authorizationv1.ResourceAttributes, error) { + if len(namespaces) == 0 { + return nil, nil + } + for i := range namespaces { + namespace := namespaces[i].Name + if !a.resourceEligibilityChecker.AllowsNamespace(namespace) { + return nil, invalidPlacementError(fmt.Sprintf("namespace %q is not eligible for placement", namespace)) + } + } + var attributes []authorizationv1.ResourceAttributes + for _, gvr := range a.namespacedResources.GetNameSpaceScopedResources() { + eligible, err := a.resourceEligibilityChecker.AllowsGVR(gvr) + switch { + case meta.IsNoMatchError(err): + klog.V(2).InfoS("Skip namespace expansion authorization for a resource with no registered kind", "GVR", gvr.String()) + continue + case err != nil: + return nil, fmt.Errorf("failed to determine eligibility for %s: %w", gvr, err) + case !eligible: + continue + } + for i := range namespaces { + attributes = append(attributes, resourceAttributes(gvr, "list", namespaces[i].Name, "")) + } + } + return attributes, nil +} diff --git a/pkg/utils/authorization/clusterresourceplacement_test.go b/pkg/utils/authorization/clusterresourceplacement_test.go new file mode 100644 index 000000000..22308be81 --- /dev/null +++ b/pkg/utils/authorization/clusterresourceplacement_test.go @@ -0,0 +1,598 @@ +/* +Copyright 2026 The KubeFleet Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package authorization + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + authenticationv1 "k8s.io/api/authentication/v1" + authorizationv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" + "go.goms.io/fleet/pkg/utils" + "go.goms.io/fleet/pkg/utils/resourceeligibility" +) + +const ( + crpNamespaceA = "team-a" + crpNamespaceB = "team-b" + crpDeletingNS = "deleting" + crpMissingNS = "missing" + crpSource = "source" + crpLabel = "env" + crpLabelValue = "production" + crpRoleKind = "ClusterRole" + crpConfigMaps = "configmaps" + crpUnknown = "Unknown" + crpGet = "get" + crpList = "list" + crpSecretKind = "Secret" + crpSecrets = "secrets" +) + +type crpResourceInventory []schema.GroupVersionResource + +func (i crpResourceInventory) GetNameSpaceScopedResources() []schema.GroupVersionResource { + return i +} + +type crpCountingResourceInventory struct { + NamespacedResourceInventory + calls int +} + +func (i *crpCountingResourceInventory) GetNameSpaceScopedResources() []schema.GroupVersionResource { + i.calls++ + return i.NamespacedResourceInventory.GetNameSpaceScopedResources() +} + +type crpCountingEligibilityChecker struct { + resourceeligibility.Checker + calls []schema.GroupVersionResource +} + +func (c *crpCountingEligibilityChecker) AllowsGVR(gvr schema.GroupVersionResource) (bool, error) { + c.calls = append(c.calls, gvr) + return c.Checker.AllowsGVR(gvr) +} + +type crpErrorRESTMapper struct { + meta.RESTMapper + err error +} + +func (m crpErrorRESTMapper) KindsFor(schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { + return nil, m.err +} + +func newClusterPlacementTestAuthorizer(t *testing.T, sarClient SubjectAccessReviewClient) (*PlacementAuthorizer, client.Client) { + t.Helper() + mapper := resourcePlacementTestMapper() + mapper.Add(rbacv1.SchemeGroupVersion.WithKind(crpRoleKind), meta.RESTScopeRoot) + mapper.Add(corev1.SchemeGroupVersion.WithKind(crpSecretKind), meta.RESTScopeNamespace) + now := metav1.Now() + reader := fake.NewClientBuilder().WithObjects( + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: crpNamespaceA, Labels: map[string]string{crpLabel: crpLabelValue}}}, + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: crpNamespaceB}}, + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: crpDeletingNS, Labels: map[string]string{crpLabel: crpLabelValue}, DeletionTimestamp: &now, Finalizers: []string{"cleanup"}}}, + ).WithInterceptorFuncs(interceptor.Funcs{ + Get: func(_ context.Context, _ client.WithWatch, _ client.ObjectKey, obj client.Object, _ ...client.GetOption) error { + err := fmt.Errorf("unexpected source object read: %T", obj) + t.Error(err) + return err + }, + List: func(ctx context.Context, c client.WithWatch, list client.ObjectList, opts ...client.ListOption) error { + if _, ok := list.(*corev1.NamespaceList); !ok { + err := fmt.Errorf("unexpected source collection read: %T", list) + t.Error(err) + return err + } + return c.List(ctx, list, opts...) + }, + }).Build() + reviewer, err := NewReviewer(sarClient, mapper, 1) + if err != nil { + t.Fatal(err) + } + inventory := crpResourceInventory{corev1.SchemeGroupVersion.WithResource(crpConfigMaps), corev1.SchemeGroupVersion.WithResource(crpSecrets)} + a, err := NewPlacementAuthorizer(mapper, reviewer, resourceeligibility.AllowAll(mapper), reader, inventory) + if err != nil { + t.Fatal(err) + } + return a, reader +} + +func TestClusterResourcePlacementAuthorizeSelections(t *testing.T) { + role := placementv1beta1.ResourceSelectorTerm{Group: rbacv1.GroupName, Version: "v1", Kind: crpRoleKind, Name: crpSource} + allRoles := placementv1beta1.ResourceSelectorTerm{Group: rbacv1.GroupName, Version: "v1", Kind: crpRoleKind} + labeledRoles := placementv1beta1.ResourceSelectorTerm{Group: rbacv1.GroupName, Version: "v1", Kind: crpRoleKind, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}} + nsOnly := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceOnly} + allNSOnly := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceOnly} + labeledNSOnly := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceOnly, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}} + withResources := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResources} + defaultScope := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA} + allNamespaces := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources} + labeledNamespaces := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}} + selective := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors} + configMap := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.ConfigMapKind, Name: crpSource} + allConfigMaps := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.ConfigMapKind} + labeledConfigMaps := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.ConfigMapKind, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}} + deletingNamespace := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpDeletingNS, SelectionScope: placementv1beta1.NamespaceWithResources} + missingNamespace := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpMissingNS, SelectionScope: placementv1beta1.NamespaceWithResources} + missingSelective := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpMissingNS, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors} + deletingSelective := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpDeletingNS, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors} + getNS := resourceAttributes(utils.NamespaceGVR, crpGet, "", crpNamespaceA) + listNS := resourceAttributes(utils.NamespaceGVR, crpList, "", "") + getRole := resourceAttributes(rbacv1.SchemeGroupVersion.WithResource("clusterroles"), crpGet, "", crpSource) + listRoles := resourceAttributes(rbacv1.SchemeGroupVersion.WithResource("clusterroles"), crpList, "", "") + getCM := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpGet, crpNamespaceA, crpSource) + listCMA := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpList, crpNamespaceA, "") + listCMB := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpList, crpNamespaceB, "") + listSecretA := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpSecrets), crpList, crpNamespaceA, "") + listSecretB := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpSecrets), crpList, crpNamespaceB, "") + getDeletingNS := resourceAttributes(utils.NamespaceGVR, crpGet, "", crpDeletingNS) + listCMDeleting := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpList, crpDeletingNS, "") + listSecretDeleting := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpSecrets), crpList, crpDeletingNS, "") + getMissingNS := resourceAttributes(utils.NamespaceGVR, crpGet, "", crpMissingNS) + listCMMissing := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpList, crpMissingNS, "") + listSecretMissing := resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpSecrets), crpList, crpMissingNS, "") + tests := []struct { + name string + selectors []placementv1beta1.ResourceSelectorTerm + rp bool + exclude []schema.GroupVersionKind + excludeNamespaces []string + inventory NamespacedResourceInventory + want []authorizationv1.ResourceAttributes + }{ + {name: "named cluster resource", selectors: []placementv1beta1.ResourceSelectorTerm{role}, want: []authorizationv1.ResourceAttributes{getRole}}, + {name: "labeled cluster resources", selectors: []placementv1beta1.ResourceSelectorTerm{labeledRoles}, want: []authorizationv1.ResourceAttributes{listRoles}}, + {name: "all cluster resources of kind", selectors: []placementv1beta1.ResourceSelectorTerm{allRoles}, want: []authorizationv1.ResourceAttributes{listRoles}}, + {name: "namespace only by name", selectors: []placementv1beta1.ResourceSelectorTerm{nsOnly}, want: []authorizationv1.ResourceAttributes{getNS}}, + {name: "namespace only does not expand an excluded namespace", selectors: []placementv1beta1.ResourceSelectorTerm{nsOnly}, excludeNamespaces: []string{crpNamespaceA}, want: []authorizationv1.ResourceAttributes{getNS}}, + {name: "namespace only by label", selectors: []placementv1beta1.ResourceSelectorTerm{labeledNSOnly}, want: []authorizationv1.ResourceAttributes{listNS}}, + {name: "namespace only all", selectors: []placementv1beta1.ResourceSelectorTerm{allNSOnly}, want: []authorizationv1.ResourceAttributes{listNS}}, + {name: "namespace expansion", selectors: []placementv1beta1.ResourceSelectorTerm{withResources}, want: []authorizationv1.ResourceAttributes{getNS, listCMA, listSecretA}}, + {name: "default namespace scope", selectors: []placementv1beta1.ResourceSelectorTerm{defaultScope}, want: []authorizationv1.ResourceAttributes{getNS, listCMA, listSecretA}}, + {name: "labeled namespace expansion includes deleting", selectors: []placementv1beta1.ResourceSelectorTerm{labeledNamespaces}, want: []authorizationv1.ResourceAttributes{listNS, listCMA, listSecretA, listCMDeleting, listSecretDeleting}}, + {name: "all namespaces expand separately including deleting", selectors: []placementv1beta1.ResourceSelectorTerm{allNamespaces}, want: []authorizationv1.ResourceAttributes{listNS, listCMA, listSecretA, listCMB, listSecretB, listCMDeleting, listSecretDeleting}}, + {name: "selective named resource", selectors: []placementv1beta1.ResourceSelectorTerm{selective, configMap}, want: []authorizationv1.ResourceAttributes{getNS, getCM}}, + {name: "selective namespace without additional resources", selectors: []placementv1beta1.ResourceSelectorTerm{selective}, want: []authorizationv1.ResourceAttributes{getNS}}, + {name: "selective labeled resources", selectors: []placementv1beta1.ResourceSelectorTerm{selective, labeledConfigMaps}, want: []authorizationv1.ResourceAttributes{getNS, listCMA}}, + {name: "selective all resources of kind", selectors: []placementv1beta1.ResourceSelectorTerm{selective, allConfigMaps}, want: []authorizationv1.ResourceAttributes{getNS, listCMA}}, + {name: "namespace selector after mixed resources", selectors: []placementv1beta1.ResourceSelectorTerm{role, configMap, selective}, want: []authorizationv1.ResourceAttributes{getRole, getCM, getNS}}, + {name: "namespace expansion and cluster resource", selectors: []placementv1beta1.ResourceSelectorTerm{role, withResources}, want: []authorizationv1.ResourceAttributes{getRole, getNS, listCMA, listSecretA}}, + {name: "overlapping namespace selectors", selectors: []placementv1beta1.ResourceSelectorTerm{nsOnly, labeledNSOnly, nsOnly}, want: []authorizationv1.ResourceAttributes{getNS, listNS}}, + {name: "overlapping namespace expansion selectors", selectors: []placementv1beta1.ResourceSelectorTerm{withResources, withResources}, want: []authorizationv1.ResourceAttributes{getNS, listCMA, listSecretA}}, + {name: "overlapping cluster selectors", selectors: []placementv1beta1.ResourceSelectorTerm{role, allRoles, role}, want: []authorizationv1.ResourceAttributes{getRole, listRoles}}, + {name: "deleting namespace expansion", selectors: []placementv1beta1.ResourceSelectorTerm{deletingNamespace}, want: []authorizationv1.ResourceAttributes{getDeletingNS, listCMDeleting, listSecretDeleting}}, + {name: "missing namespace expansion", selectors: []placementv1beta1.ResourceSelectorTerm{missingNamespace}, want: []authorizationv1.ResourceAttributes{getMissingNS, listCMMissing, listSecretMissing}}, + {name: "missing selective namespace", selectors: []placementv1beta1.ResourceSelectorTerm{missingSelective, configMap}, want: []authorizationv1.ResourceAttributes{getMissingNS, resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpGet, crpMissingNS, crpSource)}}, + {name: "deleting selective namespace", selectors: []placementv1beta1.ResourceSelectorTerm{deletingSelective, configMap}, want: []authorizationv1.ResourceAttributes{getDeletingNS, resourceAttributes(corev1.SchemeGroupVersion.WithResource(crpConfigMaps), crpGet, crpDeletingNS, crpSource)}}, + {name: "no namespace matches still requires list", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: "absent"}}}}, want: []authorizationv1.ResourceAttributes{listNS}}, + {name: "ineligible cluster kind skipped", selectors: []placementv1beta1.ResourceSelectorTerm{role}, exclude: []schema.GroupVersionKind{rbacv1.SchemeGroupVersion.WithKind(crpRoleKind)}}, + {name: "ineligible Namespace kind skipped", selectors: []placementv1beta1.ResourceSelectorTerm{nsOnly}, exclude: []schema.GroupVersionKind{utils.NamespaceGVK}}, + {name: "ineligible expanded type skipped", selectors: []placementv1beta1.ResourceSelectorTerm{withResources}, exclude: []schema.GroupVersionKind{corev1.SchemeGroupVersion.WithKind(crpSecretKind)}, want: []authorizationv1.ResourceAttributes{getNS, listCMA}}, + {name: "duplicate inventory entries deduplicate reviews", selectors: []placementv1beta1.ResourceSelectorTerm{withResources}, inventory: crpResourceInventory{corev1.SchemeGroupVersion.WithResource(crpConfigMaps), corev1.SchemeGroupVersion.WithResource(crpConfigMaps)}, want: []authorizationv1.ResourceAttributes{getNS, listCMA}}, + {name: "removed inventory type skipped without dropping valid types", selectors: []placementv1beta1.ResourceSelectorTerm{withResources}, inventory: crpResourceInventory{ + corev1.SchemeGroupVersion.WithResource(crpConfigMaps), + {Group: "removed.example.io", Version: "v1", Resource: "widgets"}, + corev1.SchemeGroupVersion.WithResource(crpSecrets), + }, want: []authorizationv1.ResourceAttributes{getNS, listCMA, listSecretA}}, + {name: "RP still supported by configured authorizer", rp: true, selectors: []placementv1beta1.ResourceSelectorTerm{configMap}, want: []authorizationv1.ResourceAttributes{getCM}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got []authorizationv1.ResourceAttributes + a, _ := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + if review.Spec.User != rpRequester { + t.Errorf("Authorize() review user = %q, want %q", review.Spec.User, rpRequester) + } + got = append(got, *review.Spec.ResourceAttributes) + review.Status.Allowed = true + return nil + }}) + if len(tt.exclude) != 0 { + if err := a.resourceEligibilityChecker.SetGVKCheckList(resourceeligibility.GVKEligibilityModeDenyList, tt.exclude); err != nil { + t.Fatal(err) + } + } + if tt.inventory != nil { + a.namespacedResources = tt.inventory + } + if len(tt.excludeNamespaces) != 0 { + a.resourceEligibilityChecker.SetNamespaceCheckList(resourceeligibility.NamespaceEligibilityModeDenyList, tt.excludeNamespaces, nil) + } + var placement placementv1beta1.PlacementObj = &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: tt.selectors}} + if tt.rp { + placement = &placementv1beta1.ResourcePlacement{ObjectMeta: metav1.ObjectMeta{Namespace: crpNamespaceA}, Spec: placementv1beta1.PlacementSpec{ResourceSelectors: tt.selectors}} + } + + result := a.Authorize(context.Background(), authenticationv1.UserInfo{Username: rpRequester}, placement) + if diff := cmp.Diff(Result{Decision: DecisionAllowed}, result); diff != "" { + t.Fatalf("Authorize() mismatch (-want +got):\n%s", diff) + } + if diff := cmp.Diff(tt.want, got, cmpopts.SortSlices(func(a, b authorizationv1.ResourceAttributes) bool { return fmt.Sprint(a) < fmt.Sprint(b) })); diff != "" { + t.Errorf("Authorize() checks mismatch (-want +got):\n%s", diff) + } + }) + } +} + +func TestClusterResourcePlacementResolvesInventoryOncePerRequest(t *testing.T) { + all := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources} + named := all + named.Name = crpNamespaceA + otherNamed := all + otherNamed.Name = crpNamespaceB + labeled := all + labeled.LabelSelector = &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}} + unmatched := all + unmatched.LabelSelector = &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: "absent"}} + namespaceOnly := named + namespaceOnly.SelectionScope = placementv1beta1.NamespaceOnly + selective := named + selective.SelectionScope = placementv1beta1.NamespaceWithResourceSelectors + tests := []struct { + name string + selectors []placementv1beta1.ResourceSelectorTerm + expand bool + }{ + {name: "all namespaces", selectors: []placementv1beta1.ResourceSelectorTerm{all}, expand: true}, + {name: "labeled namespaces", selectors: []placementv1beta1.ResourceSelectorTerm{labeled}, expand: true}, + {name: "multiple named selectors", selectors: []placementv1beta1.ResourceSelectorTerm{named, otherNamed}, expand: true}, + {name: "overlapping selectors", selectors: []placementv1beta1.ResourceSelectorTerm{all, named}, expand: true}, + {name: "no matches before named selector", selectors: []placementv1beta1.ResourceSelectorTerm{unmatched, named}, expand: true}, + {name: "no matches", selectors: []placementv1beta1.ResourceSelectorTerm{unmatched}}, + {name: "namespace only", selectors: []placementv1beta1.ResourceSelectorTerm{namespaceOnly}}, + {name: "selective resources", selectors: []placementv1beta1.ResourceSelectorTerm{selective, {Version: "v1", Kind: utils.ConfigMapKind, Name: crpSource}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a, _ := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + review.Status.Allowed = true + return nil + }}) + inventory := &crpCountingResourceInventory{NamespacedResourceInventory: a.namespacedResources} + checker := &crpCountingEligibilityChecker{Checker: a.resourceEligibilityChecker} + a.namespacedResources = inventory + a.resourceEligibilityChecker = checker + p := &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: tt.selectors}} + for request := 0; request < 2; request++ { + inventory.calls = 0 + checker.calls = nil + result := a.Authorize(context.Background(), authenticationv1.UserInfo{Username: rpRequester}, p) + if diff := cmp.Diff(Result{Decision: DecisionAllowed}, result); diff != "" { + t.Fatalf("Authorize() request %d mismatch (-want +got):\n%s", request, diff) + } + wantInventoryCalls := 0 + var wantEligibilityCalls []schema.GroupVersionResource + if tt.expand { + wantInventoryCalls = 1 + wantEligibilityCalls = []schema.GroupVersionResource{ + corev1.SchemeGroupVersion.WithResource(crpConfigMaps), + corev1.SchemeGroupVersion.WithResource(crpSecrets), + } + } + if inventory.calls != wantInventoryCalls { + t.Errorf("Authorize() request %d inventory calls = %d, want %d", request, inventory.calls, wantInventoryCalls) + } + if diff := cmp.Diff(wantEligibilityCalls, checker.calls); diff != "" { + t.Errorf("Authorize() request %d eligibility calls mismatch (-want +got):\n%s", request, diff) + } + } + }) + } +} + +func TestClusterResourcePlacementNamespaceOnlyDoesNotReadNamespaces(t *testing.T) { + tests := []struct { + name string + selector placementv1beta1.ResourceSelectorTerm + want authorizationv1.ResourceAttributes + }{ + { + name: "named", + selector: placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceOnly}, + want: resourceAttributes(utils.NamespaceGVR, crpGet, "", crpNamespaceA), + }, + { + name: "named missing namespace", + selector: placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpMissingNS, SelectionScope: placementv1beta1.NamespaceOnly}, + want: resourceAttributes(utils.NamespaceGVR, crpGet, "", crpMissingNS), + }, + { + name: "labeled", + selector: placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceOnly, LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}}, + want: resourceAttributes(utils.NamespaceGVR, crpList, "", ""), + }, + { + name: "all", + selector: placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceOnly}, + want: resourceAttributes(utils.NamespaceGVR, crpList, "", ""), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got []authorizationv1.ResourceAttributes + a, _ := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + got = append(got, *review.Spec.ResourceAttributes) + review.Status.Allowed = true + return nil + }}) + readerCalls := 0 + readErr := errors.New("NamespaceOnly must not read namespaces") + a.namespaceReader = fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{ + Get: func(context.Context, client.WithWatch, client.ObjectKey, client.Object, ...client.GetOption) error { + readerCalls++ + return readErr + }, + List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + readerCalls++ + return readErr + }, + }).Build() + p := &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: []placementv1beta1.ResourceSelectorTerm{tt.selector}}} + result := a.Authorize(context.Background(), authenticationv1.UserInfo{Username: rpRequester}, p) + if diff := cmp.Diff(Result{Decision: DecisionAllowed}, result); diff != "" { + t.Errorf("Authorize() mismatch (-want +got):\n%s", diff) + } + if diff := cmp.Diff([]authorizationv1.ResourceAttributes{tt.want}, got); diff != "" { + t.Errorf("Authorize() checks mismatch (-want +got):\n%s", diff) + } + if readerCalls != 0 { + t.Errorf("Authorize() namespace reader calls = %d, want 0", readerCalls) + } + }) + } +} + +func TestClusterResourcePlacementNamespacePreflightStopsResolution(t *testing.T) { + const denialReason = "namespace access denied" + namedExpansion := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResources} + missingExpansion := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpMissingNS, SelectionScope: placementv1beta1.NamespaceWithResources} + labeledExpansion := placementv1beta1.ResourceSelectorTerm{ + Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources, + LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{crpLabel: crpLabelValue}}, + } + allExpansion := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources} + selectiveNamespace := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors} + apiErr := errors.New("namespace authorization unavailable") + tests := []struct { + name string + selector placementv1beta1.ResourceSelectorTerm + reviewStatus authorizationv1.SubjectAccessReviewStatus + reviewErr error + wantDecision Decision + }{ + {name: "named expansion denied", selector: namedExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{Denied: true, Reason: denialReason}, wantDecision: DecisionDenied}, + {name: "named expansion no opinion", selector: namedExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{}, wantDecision: DecisionDenied}, + {name: "named expansion API error", selector: namedExpansion, reviewErr: apiErr, wantDecision: DecisionIndeterminate}, + {name: "named expansion evaluation error", selector: namedExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{EvaluationError: apiErr.Error()}, wantDecision: DecisionIndeterminate}, + {name: "missing named expansion denied", selector: missingExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{Denied: true, Reason: denialReason}, wantDecision: DecisionDenied}, + {name: "missing named expansion no opinion", selector: missingExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{}, wantDecision: DecisionDenied}, + {name: "missing named expansion API error", selector: missingExpansion, reviewErr: apiErr, wantDecision: DecisionIndeterminate}, + {name: "missing named expansion evaluation error", selector: missingExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{EvaluationError: apiErr.Error()}, wantDecision: DecisionIndeterminate}, + {name: "labeled expansion denied", selector: labeledExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{Denied: true, Reason: denialReason}, wantDecision: DecisionDenied}, + {name: "labeled expansion no opinion", selector: labeledExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{}, wantDecision: DecisionDenied}, + {name: "labeled expansion API error", selector: labeledExpansion, reviewErr: apiErr, wantDecision: DecisionIndeterminate}, + {name: "labeled expansion evaluation error", selector: labeledExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{EvaluationError: apiErr.Error()}, wantDecision: DecisionIndeterminate}, + {name: "all namespaces expansion denied", selector: allExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{Denied: true, Reason: denialReason}, wantDecision: DecisionDenied}, + {name: "all namespaces expansion no opinion", selector: allExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{}, wantDecision: DecisionDenied}, + {name: "all namespaces expansion API error", selector: allExpansion, reviewErr: apiErr, wantDecision: DecisionIndeterminate}, + {name: "all namespaces expansion evaluation error", selector: allExpansion, reviewStatus: authorizationv1.SubjectAccessReviewStatus{EvaluationError: apiErr.Error()}, wantDecision: DecisionIndeterminate}, + {name: "selective namespace denied", selector: selectiveNamespace, reviewStatus: authorizationv1.SubjectAccessReviewStatus{Denied: true, Reason: denialReason}, wantDecision: DecisionDenied}, + {name: "selective namespace no opinion", selector: selectiveNamespace, reviewStatus: authorizationv1.SubjectAccessReviewStatus{}, wantDecision: DecisionDenied}, + {name: "selective namespace API error", selector: selectiveNamespace, reviewErr: apiErr, wantDecision: DecisionIndeterminate}, + {name: "selective namespace evaluation error", selector: selectiveNamespace, reviewStatus: authorizationv1.SubjectAccessReviewStatus{EvaluationError: apiErr.Error()}, wantDecision: DecisionIndeterminate}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var reviews []authorizationv1.ResourceAttributes + a, _ := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + if review.Spec.User != rpRequester { + t.Errorf("Authorize() review user = %q, want %q", review.Spec.User, rpRequester) + } + reviews = append(reviews, *review.Spec.ResourceAttributes) + review.Status = tt.reviewStatus + return tt.reviewErr + }}) + readerCalls := 0 + readErr := errors.New("unexpected namespace read before authorization") + a.namespaceReader = fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{ + Get: func(context.Context, client.WithWatch, client.ObjectKey, client.Object, ...client.GetOption) error { + readerCalls++ + return readErr + }, + List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + readerCalls++ + return readErr + }, + }).Build() + p := &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: []placementv1beta1.ResourceSelectorTerm{tt.selector}}} + result := a.Authorize(context.Background(), authenticationv1.UserInfo{Username: rpRequester}, p) + if result.Decision != tt.wantDecision { + t.Errorf("Authorize() decision = %s, want %s", result.Decision, tt.wantDecision) + } + if tt.reviewErr != nil && !errors.Is(result.Err, tt.reviewErr) { + t.Errorf("Authorize() error = %v, want error containing %v", result.Err, tt.reviewErr) + } + verb := crpList + if tt.selector.Name != "" { + verb = crpGet + } + wantReviews := []authorizationv1.ResourceAttributes{resourceAttributes(utils.NamespaceGVR, verb, "", tt.selector.Name)} + if diff := cmp.Diff(wantReviews, reviews); diff != "" { + t.Errorf("Authorize() reviews mismatch (-want +got):\n%s", diff) + } + if readerCalls != 0 { + t.Errorf("Authorize() namespace reader calls = %d, want 0", readerCalls) + } + if tt.selector.Name == "" { + message := result.DenialReason + if result.Err != nil { + message += result.Err.Error() + } + for _, namespace := range []string{crpNamespaceA, crpNamespaceB, crpDeletingNS} { + if strings.Contains(message, namespace) { + t.Errorf("Authorize() response %q disclosed namespace %q", message, namespace) + } + } + } + }) + } +} + +func TestClusterResourcePlacementAuthorizeReadsNamespacesFresh(t *testing.T) { + var got []string + user := authenticationv1.UserInfo{Username: "creator"} + a, reader := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + if review.Spec.User != user.Username { + t.Errorf("Authorize() review user = %q, want %q", review.Spec.User, user.Username) + } + if review.Spec.ResourceAttributes.Resource == crpConfigMaps { + got = append(got, review.Spec.ResourceAttributes.Namespace) + } + review.Status.Allowed = true + return nil + }}) + p := &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: []placementv1beta1.ResourceSelectorTerm{{ + Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources, + }}}} + if result := a.Authorize(context.Background(), user, p); result.Decision != DecisionAllowed { + t.Fatal(result) + } + const newNamespace = "team-c" + if err := reader.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: newNamespace}}); err != nil { + t.Fatal(err) + } + got = nil + user.Username = "updater" + if result := a.Authorize(context.Background(), user, p); result.Decision != DecisionAllowed { + t.Fatal(result) + } + if diff := cmp.Diff([]string{crpNamespaceA, crpNamespaceB, crpDeletingNS, newNamespace}, got, cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("Authorize() expanded namespaces mismatch (-want +got):\n%s", diff) + } +} + +func TestClusterResourcePlacementAuthorizeFailures(t *testing.T) { + ns := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResources} + selective := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors} + configMap := placementv1beta1.ResourceSelectorTerm{Version: "v1", Kind: utils.ConfigMapKind, Name: crpSource} + role := placementv1beta1.ResourceSelectorTerm{Group: rbacv1.GroupName, Version: "v1", Kind: crpRoleKind, Name: crpSource} + tests := []struct { + name string + selectors []placementv1beta1.ResourceSelectorTerm + modify func(*PlacementAuthorizer, *placementv1beta1.ClusterResourcePlacement) + denyVerb string + sarError bool + wantErr string + invalid bool + }{ + {name: "CRP has namespace", selectors: []placementv1beta1.ResourceSelectorTerm{role}, modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ClusterResourcePlacement) { + p.Namespace = crpNamespaceA + }, wantErr: "must not specify a namespace", invalid: true}, + {name: "missing reader", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { a.namespaceReader = nil }, wantErr: "dependencies are incomplete"}, + {name: "missing inventory", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.namespacedResources = nil + }, wantErr: "dependencies are incomplete"}, + {name: "Namespace mapping failure", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.restMapper = meta.NewDefaultRESTMapper(nil) + }, wantErr: "failed to resolve Namespace mapping"}, + {name: "unknown resource kind", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: crpUnknown}}, wantErr: "failed to resolve selector"}, + {name: "namespaced resource without selective namespace", selectors: []placementv1beta1.ResourceSelectorTerm{configMap}, wantErr: "requires NamespaceWithResourceSelectors", invalid: true}, + {name: "namespace expansion cannot scope explicit resources", selectors: []placementv1beta1.ResourceSelectorTerm{ns, configMap}, wantErr: "requires NamespaceWithResourceSelectors", invalid: true}, + {name: "selective namespace without name", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors}}, wantErr: "selected by name", invalid: true}, + {name: "selective namespace with label", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: placementv1beta1.NamespaceWithResourceSelectors, LabelSelector: &metav1.LabelSelector{}}}, wantErr: "selected by name", invalid: true}, + {name: "multiple selective namespace selectors", selectors: []placementv1beta1.ResourceSelectorTerm{selective, selective}, wantErr: "exactly one namespace selector", invalid: true}, + {name: "mixing namespace modes with selective namespace", selectors: []placementv1beta1.ResourceSelectorTerm{ns, selective}, wantErr: "exactly one namespace selector", invalid: true}, + {name: "unsupported namespace scope", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpNamespaceA, SelectionScope: crpUnknown}}, wantErr: "unsupported namespace selection scope", invalid: true}, + {name: "invalid namespace label", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceOnly, LabelSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: crpLabel, Operator: "invalid"}}}}}, wantErr: "invalid resource label selector", invalid: true}, + {name: "namespace eligibility denied", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.resourceEligibilityChecker.SetNamespaceCheckList(resourceeligibility.NamespaceEligibilityModeDenyList, []string{crpNamespaceA}, nil) + }, wantErr: "not eligible for placement", invalid: true}, + {name: "selective namespace eligibility denied", selectors: []placementv1beta1.ResourceSelectorTerm{selective, configMap}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.resourceEligibilityChecker.SetNamespaceCheckList(resourceeligibility.NamespaceEligibilityModeDenyList, []string{crpNamespaceA}, nil) + }, wantErr: "not eligible for placement", invalid: true}, + {name: "selective namespace eligibility denied without additional resources", selectors: []placementv1beta1.ResourceSelectorTerm{selective}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.resourceEligibilityChecker.SetNamespaceCheckList(resourceeligibility.NamespaceEligibilityModeDenyList, []string{crpNamespaceA}, nil) + }, wantErr: "not eligible for placement", invalid: true}, + {name: "namespace list API failure", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources}}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.namespaceReader = fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return errors.New("list unavailable") + }}).Build() + }, wantErr: "list unavailable"}, + {name: "namespace list bad request remains operational", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, SelectionScope: placementv1beta1.NamespaceWithResources}}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + a.namespaceReader = fake.NewClientBuilder().WithInterceptorFuncs(interceptor.Funcs{List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return apierrors.NewBadRequest("namespace list rejected") + }}).Build() + }, wantErr: "namespace list rejected"}, + {name: "inventory mapper failure", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ClusterResourcePlacement) { + mapper := crpErrorRESTMapper{RESTMapper: a.restMapper, err: errors.New("inventory mapping unavailable")} + a.resourceEligibilityChecker = resourceeligibility.AllowAll(mapper) + }, wantErr: "inventory mapping unavailable"}, + {name: "get denied", selectors: []placementv1beta1.ResourceSelectorTerm{role}, denyVerb: crpGet}, + {name: "expanded list denied", selectors: []placementv1beta1.ResourceSelectorTerm{ns}, denyVerb: crpList}, + {name: "missing namespace expanded list denied", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpMissingNS, SelectionScope: placementv1beta1.NamespaceWithResources}}, denyVerb: crpList}, + {name: "deleting namespace expanded list denied", selectors: []placementv1beta1.ResourceSelectorTerm{{Version: "v1", Kind: utils.NamespaceGVK.Kind, Name: crpDeletingNS, SelectionScope: placementv1beta1.NamespaceWithResources}}, denyVerb: crpList}, + {name: "SAR API failure", selectors: []placementv1beta1.ResourceSelectorTerm{role}, sarError: true, wantErr: "SAR unavailable"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + a, _ := newClusterPlacementTestAuthorizer(t, &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { + if tt.sarError { + return errors.New("SAR unavailable") + } + review.Status.Denied = review.Spec.ResourceAttributes.Verb == tt.denyVerb + review.Status.Allowed = !review.Status.Denied + return nil + }}) + p := &placementv1beta1.ClusterResourcePlacement{Spec: placementv1beta1.PlacementSpec{ResourceSelectors: tt.selectors}} + if tt.modify != nil { + tt.modify(a, p) + } + result := a.Authorize(context.Background(), authenticationv1.UserInfo{Username: rpRequester}, p) + wantDecision := DecisionIndeterminate + if tt.invalid { + wantDecision = DecisionInvalid + } + if tt.denyVerb != "" { + if result.Decision != DecisionDenied || result.DenialReason == "" || result.Err != nil { + t.Errorf("Authorize() = %+v, want denied", result) + } + } else if result.Decision != wantDecision || result.Err == nil || !strings.Contains(result.Err.Error(), tt.wantErr) { + t.Errorf("Authorize() = %+v, want %s with error containing %q", result, wantDecision, tt.wantErr) + } + }) + } +} diff --git a/pkg/utils/authorization/placement.go b/pkg/utils/authorization/placement.go index d1a86c0da..6d8811c40 100644 --- a/pkg/utils/authorization/placement.go +++ b/pkg/utils/authorization/placement.go @@ -26,20 +26,24 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" "go.goms.io/fleet/pkg/utils/resourceeligibility" ) -// ResourcePlacementAuthorizer reviews source-resource access for ResourcePlacement selectors. -type ResourcePlacementAuthorizer struct { +// PlacementAuthorizer reviews source-resource access for CRP and RP selectors. +type PlacementAuthorizer struct { restMapper meta.RESTMapper reviewer *Reviewer resourceEligibilityChecker resourceeligibility.Checker + namespaceReader client.Reader + namespacedResources NamespacedResourceInventory } -// NewResourcePlacementAuthorizer creates an authorizer for namespaced ResourcePlacements. -func NewResourcePlacementAuthorizer(restMapper meta.RESTMapper, reviewer *Reviewer, checker resourceeligibility.Checker) (*ResourcePlacementAuthorizer, error) { +// NewPlacementAuthorizer creates an authorizer for RP and CRP selectors. +// namespaceReader must be uncached, for example manager.GetAPIReader(). inventory supplies resource types only. +func NewPlacementAuthorizer(restMapper meta.RESTMapper, reviewer *Reviewer, checker resourceeligibility.Checker, namespaceReader client.Reader, inventory NamespacedResourceInventory) (*PlacementAuthorizer, error) { if restMapper == nil { return nil, errors.New("REST mapper must not be nil") } @@ -49,52 +53,86 @@ func NewResourcePlacementAuthorizer(restMapper meta.RESTMapper, reviewer *Review if checker == nil { return nil, errors.New("resource eligibility checker must not be nil") } - return &ResourcePlacementAuthorizer{ + if namespaceReader == nil { + return nil, errors.New("namespace reader must not be nil") + } + if inventory == nil { + return nil, errors.New("namespaced resource inventory must not be nil") + } + return &PlacementAuthorizer{ restMapper: restMapper, reviewer: reviewer, resourceEligibilityChecker: checker, + namespaceReader: namespaceReader, + namespacedResources: inventory, }, nil } // Authorize requires get access for named selections and list access for enumerated scopes. -func (a *ResourcePlacementAuthorizer) Authorize(ctx context.Context, user authenticationv1.UserInfo, placement placementv1beta1.PlacementObj) Result { - if a == nil || a.restMapper == nil || a.reviewer == nil || a.resourceEligibilityChecker == nil { +func (a *PlacementAuthorizer) Authorize(ctx context.Context, user authenticationv1.UserInfo, placement placementv1beta1.PlacementObj) Result { + if a == nil || a.restMapper == nil || a.reviewer == nil || a.resourceEligibilityChecker == nil || a.namespaceReader == nil || a.namespacedResources == nil { return Result{Decision: DecisionIndeterminate, Err: fmt.Errorf("placement authorization dependencies are incomplete")} } - attributes, err := a.resolve(placement) + // Check Namespace access before resolution can reveal names or existence. + namespaceChecks, err := a.namespaceChecksForPlacement(placement) if err != nil { - return Result{Decision: DecisionIndeterminate, Err: err} + return placementErrorResult(err) + } + if len(namespaceChecks) != 0 { + result := a.reviewer.Authorize(ctx, user, namespaceChecks...) + if result.Decision != DecisionAllowed { + return result + } + } + attributes, err := a.resolve(ctx, placement) + if err != nil { + return placementErrorResult(err) } return a.reviewer.Authorize(ctx, user, attributes...) } -func (a *ResourcePlacementAuthorizer) resolve(placement placementv1beta1.PlacementObj) ([]authorizationv1.ResourceAttributes, error) { +type invalidPlacementError string + +func (e invalidPlacementError) Error() string { + return string(e) +} + +func placementErrorResult(err error) Result { + decision := DecisionIndeterminate + var invalidErr invalidPlacementError + if errors.As(err, &invalidErr) { + decision = DecisionInvalid + } + return Result{Decision: decision, Err: err} +} + +func (a *PlacementAuthorizer) resolve(ctx context.Context, placement placementv1beta1.PlacementObj) ([]authorizationv1.ResourceAttributes, error) { switch placement := placement.(type) { case *placementv1beta1.ResourcePlacement: return a.resolveResourcePlacement(placement) case *placementv1beta1.ClusterResourcePlacement: - return nil, errors.New("cluster resource placement authorization is not implemented") + return a.resolveClusterResourcePlacement(ctx, placement) default: return nil, fmt.Errorf("unsupported placement type %T", placement) } } -func (a *ResourcePlacementAuthorizer) resolveResourcePlacement(rp *placementv1beta1.ResourcePlacement) ([]authorizationv1.ResourceAttributes, error) { +func (a *PlacementAuthorizer) resolveResourcePlacement(rp *placementv1beta1.ResourcePlacement) ([]authorizationv1.ResourceAttributes, error) { if rp == nil { return nil, fmt.Errorf("resource placement must not be nil") } if rp.Namespace == "" { - return nil, fmt.Errorf("resource placement must specify a namespace") + return nil, invalidPlacementError("resource placement must specify a namespace") } var attributes []authorizationv1.ResourceAttributes for _, selector := range rp.Spec.ResourceSelectors { - gvk := schema.GroupVersionKind{Group: selector.Group, Version: selector.Version, Kind: selector.Kind} + gvk := selectorGVK(selector) mapping, err := a.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { return nil, fmt.Errorf("failed to resolve selector %s: %w", gvk, err) } if mapping.Scope.Name() != meta.RESTScopeNameNamespace { - return nil, fmt.Errorf("resource placement cannot select cluster-scoped resource %s", gvk) + return nil, invalidPlacementError(fmt.Sprintf("resource placement cannot select cluster-scoped resource %s", gvk)) } if !a.resourceEligibilityChecker.AllowsGVK(gvk) { continue @@ -108,19 +146,23 @@ func (a *ResourcePlacementAuthorizer) resolveResourcePlacement(rp *placementv1be return attributes, nil } -func (a *ResourcePlacementAuthorizer) selectorAttributes(gvr schema.GroupVersionResource, namespace string, selector placementv1beta1.ResourceSelectorTerm) (authorizationv1.ResourceAttributes, error) { +func selectorGVK(selector placementv1beta1.ResourceSelectorTerm) schema.GroupVersionKind { + return schema.GroupVersionKind{Group: selector.Group, Version: selector.Version, Kind: selector.Kind} +} + +func (a *PlacementAuthorizer) selectorAttributes(gvr schema.GroupVersionResource, namespace string, selector placementv1beta1.ResourceSelectorTerm) (authorizationv1.ResourceAttributes, error) { if namespace != "" && !a.resourceEligibilityChecker.AllowsNamespace(namespace) { - return authorizationv1.ResourceAttributes{}, fmt.Errorf("namespace %q is not eligible for placement", namespace) + return authorizationv1.ResourceAttributes{}, invalidPlacementError(fmt.Sprintf("namespace %q is not eligible for placement", namespace)) } if selector.Name != "" { if selector.LabelSelector != nil { - return authorizationv1.ResourceAttributes{}, fmt.Errorf("name and labelSelector are mutually exclusive") + return authorizationv1.ResourceAttributes{}, invalidPlacementError("name and labelSelector are mutually exclusive") } return resourceAttributes(gvr, "get", namespace, selector.Name), nil } if selector.LabelSelector != nil { if _, err := metav1.LabelSelectorAsSelector(selector.LabelSelector); err != nil { - return authorizationv1.ResourceAttributes{}, fmt.Errorf("invalid resource label selector: %w", err) + return authorizationv1.ResourceAttributes{}, invalidPlacementError(fmt.Sprintf("invalid resource label selector: %v", err)) } } return resourceAttributes(gvr, "list", namespace, ""), nil diff --git a/pkg/utils/authorization/placement_test.go b/pkg/utils/authorization/placement_test.go index 1da433358..926216204 100644 --- a/pkg/utils/authorization/placement_test.go +++ b/pkg/utils/authorization/placement_test.go @@ -19,6 +19,7 @@ package authorization import ( "context" "errors" + "fmt" "testing" "github.com/google/go-cmp/cmp" @@ -29,6 +30,8 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" placementv1beta1 "go.goms.io/fleet/apis/placement/v1beta1" "go.goms.io/fleet/pkg/utils" @@ -48,38 +51,44 @@ func resourcePlacementTestMapper() *meta.DefaultRESTMapper { return mapper } -func TestNewResourcePlacementAuthorizer(t *testing.T) { +func TestNewPlacementAuthorizer(t *testing.T) { mapper := resourcePlacementTestMapper() reviewer := newTestReviewer(t, &fakeSubjectAccessReviewClient{}, 1) checker := resourceeligibility.AllowAll(mapper) + reader := fake.NewClientBuilder().Build() + inventory := crpResourceInventory{} tests := []struct { - name string - mapper meta.RESTMapper - reviewer *Reviewer - checker resourceeligibility.Checker - wantErr string + name string + mapper meta.RESTMapper + reviewer *Reviewer + checker resourceeligibility.Checker + reader client.Reader + inventory NamespacedResourceInventory + wantErr string }{ - {name: "valid", mapper: mapper, reviewer: reviewer, checker: checker}, - {name: "missing mapper", reviewer: reviewer, checker: checker, wantErr: "REST mapper must not be nil"}, - {name: "missing reviewer", mapper: mapper, checker: checker, wantErr: "authorization reviewer must not be nil"}, - {name: "missing checker", mapper: mapper, reviewer: reviewer, wantErr: "resource eligibility checker must not be nil"}, + {name: "valid", mapper: mapper, reviewer: reviewer, checker: checker, reader: reader, inventory: inventory}, + {name: "missing mapper", reviewer: reviewer, checker: checker, reader: reader, inventory: inventory, wantErr: "REST mapper must not be nil"}, + {name: "missing reviewer", mapper: mapper, checker: checker, reader: reader, inventory: inventory, wantErr: "authorization reviewer must not be nil"}, + {name: "missing checker", mapper: mapper, reviewer: reviewer, reader: reader, inventory: inventory, wantErr: "resource eligibility checker must not be nil"}, + {name: "missing reader", mapper: mapper, reviewer: reviewer, checker: checker, inventory: inventory, wantErr: "namespace reader must not be nil"}, + {name: "missing inventory", mapper: mapper, reviewer: reviewer, checker: checker, reader: reader, wantErr: "namespaced resource inventory must not be nil"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := NewResourcePlacementAuthorizer(tt.mapper, tt.reviewer, tt.checker) + got, err := NewPlacementAuthorizer(tt.mapper, tt.reviewer, tt.checker, tt.reader, tt.inventory) if tt.wantErr != "" { if got != nil || err == nil || err.Error() != tt.wantErr { - t.Fatalf("NewResourcePlacementAuthorizer() = (%v, %v), want (nil, %q)", got, err, tt.wantErr) + t.Fatalf("NewPlacementAuthorizer() = (%v, %v), want (nil, %q)", got, err, tt.wantErr) } } else if got == nil || err != nil { - t.Fatalf("NewResourcePlacementAuthorizer() = (%v, %v), want initialized authorizer and nil error", got, err) + t.Fatalf("NewPlacementAuthorizer() = (%v, %v), want initialized authorizer and nil error", got, err) } }) } } func TestResourcePlacementAuthorizeUninitialized(t *testing.T) { - for name, authorizer := range map[string]*ResourcePlacementAuthorizer{"nil": nil, "zero value": {}} { + for name, authorizer := range map[string]*PlacementAuthorizer{"nil": nil, "zero value": {}} { t.Run(name, func(t *testing.T) { result := authorizer.Authorize(context.Background(), authenticationv1.UserInfo{}, &placementv1beta1.ResourcePlacement{}) if result.Decision != DecisionIndeterminate || result.Err == nil { @@ -122,7 +131,7 @@ func TestResourcePlacementAuthorizeSelections(t *testing.T) { review.Status.Allowed = true return nil }}, 1) - a, err := NewResourcePlacementAuthorizer(mapper, reviewer, resourceeligibility.AllowAll(mapper)) + a, err := NewPlacementAuthorizer(mapper, reviewer, resourceeligibility.AllowAll(mapper), fake.NewClientBuilder().Build(), crpResourceInventory{}) if err != nil { t.Fatal(err) } @@ -143,20 +152,18 @@ func TestResourcePlacementAuthorizeSelections(t *testing.T) { } } -func TestResourcePlacementAuthorizeRejectsUnsupportedTypes(t *testing.T) { - const deferredCRPErr = "cluster resource placement authorization is not implemented" +func TestPlacementAuthorizeRejectsInvalidInputs(t *testing.T) { for name, tt := range map[string]struct { placement placementv1beta1.PlacementObj wantErr string }{ "nil": {wantErr: "unsupported placement type "}, "typed nil RP": {placement: (*placementv1beta1.ResourcePlacement)(nil), wantErr: "resource placement must not be nil"}, - "CRP": {placement: &placementv1beta1.ClusterResourcePlacement{}, wantErr: deferredCRPErr}, - "typed nil CRP": {placement: (*placementv1beta1.ClusterResourcePlacement)(nil), wantErr: deferredCRPErr}, + "typed nil CRP": {placement: (*placementv1beta1.ClusterResourcePlacement)(nil), wantErr: "cluster resource placement must not be nil"}, } { t.Run(name, func(t *testing.T) { mapper := resourcePlacementTestMapper() - a, err := NewResourcePlacementAuthorizer(mapper, newTestReviewer(t, &fakeSubjectAccessReviewClient{}, 1), resourceeligibility.AllowAll(mapper)) + a, err := NewPlacementAuthorizer(mapper, newTestReviewer(t, &fakeSubjectAccessReviewClient{}, 1), resourceeligibility.AllowAll(mapper), fake.NewClientBuilder().Build(), crpResourceInventory{}) if err != nil { t.Fatal(err) } @@ -168,41 +175,62 @@ func TestResourcePlacementAuthorizeRejectsUnsupportedTypes(t *testing.T) { } } +func TestPlacementErrorResult(t *testing.T) { + tests := []struct { + name string + err error + wantDecision Decision + }{ + {name: "invalid input", err: invalidPlacementError("invalid selector"), wantDecision: DecisionInvalid}, + {name: "wrapped invalid input", err: fmt.Errorf("resolve placement: %w", invalidPlacementError("invalid selector")), wantDecision: DecisionInvalid}, + {name: "operational error", err: errors.New("API unavailable"), wantDecision: DecisionIndeterminate}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := placementErrorResult(tt.err) + if result.Decision != tt.wantDecision || result.Err != tt.err { + t.Errorf("placementErrorResult(%v) = %+v, want %s with original error", tt.err, result, tt.wantDecision) + } + }) + } +} + func TestResourcePlacementAuthorizeFailures(t *testing.T) { tests := []struct { - name string - modify func(*ResourcePlacementAuthorizer, *placementv1beta1.ResourcePlacement) - denied bool + name string + modify func(*PlacementAuthorizer, *placementv1beta1.ResourcePlacement) + denied bool + invalid bool }{ - {name: "unknown kind", modify: func(_ *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { + {name: "unknown kind", modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Spec.ResourceSelectors[0].Kind = "Unknown" }}, - {name: "missing namespace", modify: func(_ *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Namespace = "" }}, - {name: "cluster-scoped selector", modify: func(_ *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { + {name: "missing namespace", invalid: true, modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Namespace = "" }}, + {name: "cluster-scoped selector", modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Spec.ResourceSelectors[0].Kind = utils.NamespaceGVK.Kind - }}, - {name: "name and label selector", modify: func(_ *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { + }, invalid: true}, + {name: "name and label selector", modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Spec.ResourceSelectors[0].LabelSelector = &metav1.LabelSelector{} - }}, - {name: "invalid label selector", modify: func(_ *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { + }, invalid: true}, + {name: "invalid label selector", modify: func(_ *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Spec.ResourceSelectors[0].Name = "" p.Spec.ResourceSelectors[0].LabelSelector = &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "app", Operator: "invalid"}}} - }}, - {name: "namespace excluded", modify: func(a *ResourcePlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { + }, invalid: true}, + {name: "namespace excluded", modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { a.resourceEligibilityChecker.SetNamespaceCheckList(resourceeligibility.NamespaceEligibilityModeDenyList, []string{rpNamespace}, nil) - }}, - {name: "SAR error", modify: func(a *ResourcePlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { + }, invalid: true}, + {name: "SAR error", modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { a.reviewer.client = &fakeSubjectAccessReviewClient{create: func(context.Context, *authorizationv1.SubjectAccessReview) error { return errors.New("SAR unavailable") }} }}, - {name: "get denied", denied: true, modify: func(a *ResourcePlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { + {name: "get denied", denied: true, modify: func(a *PlacementAuthorizer, _ *placementv1beta1.ResourcePlacement) { a.reviewer.client = &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { review.Status.Denied = true return nil }} }}, - {name: "list denied", denied: true, modify: func(a *ResourcePlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { + {name: "list denied", denied: true, modify: func(a *PlacementAuthorizer, p *placementv1beta1.ResourcePlacement) { p.Spec.ResourceSelectors[0].Name = "" a.reviewer.client = &fakeSubjectAccessReviewClient{create: func(_ context.Context, review *authorizationv1.SubjectAccessReview) error { review.Status.Denied = true @@ -217,7 +245,7 @@ func TestResourcePlacementAuthorizeFailures(t *testing.T) { review.Status.Allowed = true return nil }}, 1) - a, err := NewResourcePlacementAuthorizer(mapper, reviewer, resourceeligibility.AllowAll(mapper)) + a, err := NewPlacementAuthorizer(mapper, reviewer, resourceeligibility.AllowAll(mapper), fake.NewClientBuilder().Build(), crpResourceInventory{}) if err != nil { t.Fatal(err) } @@ -228,6 +256,9 @@ func TestResourcePlacementAuthorizeFailures(t *testing.T) { tt.modify(a, p) result := a.Authorize(context.Background(), authenticationv1.UserInfo{}, p) wantDecision := DecisionIndeterminate + if tt.invalid { + wantDecision = DecisionInvalid + } if tt.denied { wantDecision = DecisionDenied } @@ -248,7 +279,7 @@ func TestResourcePlacementAuthorizeSkipsIneligibleKinds(t *testing.T) { t.Error("Authorize() submitted a SubjectAccessReview for an ineligible kind") return errors.New("unexpected SubjectAccessReview") }}, 1) - a, err := NewResourcePlacementAuthorizer(mapper, reviewer, checker) + a, err := NewPlacementAuthorizer(mapper, reviewer, checker, fake.NewClientBuilder().Build(), crpResourceInventory{}) if err != nil { t.Fatal(err) } diff --git a/pkg/utils/validator/placement.go b/pkg/utils/validator/placement.go index 66b66fc5a..9281d1a02 100644 --- a/pkg/utils/validator/placement.go +++ b/pkg/utils/validator/placement.go @@ -842,6 +842,11 @@ func HandlePlacementValidation( return admission.Errored(http.StatusInternalServerError, result.Err) } invalidResultErr = fmt.Errorf("selected-resource authorization returned an indeterminate decision without an error") + case authorization.DecisionInvalid: + if result.Err != nil { + return admission.Errored(http.StatusBadRequest, result.Err) + } + invalidResultErr = fmt.Errorf("selected-resource authorization returned an invalid decision without an error") default: invalidResultErr = fmt.Errorf("selected-resource authorization returned an unknown decision %q", result.Decision) } diff --git a/pkg/utils/validator/placement_authorization_test.go b/pkg/utils/validator/placement_authorization_test.go index 7f3c63874..75bac4198 100644 --- a/pkg/utils/validator/placement_authorization_test.go +++ b/pkg/utils/validator/placement_authorization_test.go @@ -44,6 +44,7 @@ func (a *stubPlacementAuthorizer) Authorize(context.Context, authenticationv1.Us func TestHandlePlacementValidationAuthorizationDecision(t *testing.T) { const denialReason = "requester cannot get selected resources" reviewErr := errors.New("authorization API unavailable") + validationErr := errors.New("NamespaceWithResourceSelectors requires a namespace selected by name") type outcome struct { Allowed bool Code int32 @@ -69,6 +70,16 @@ func TestHandlePlacementValidationAuthorizationDecision(t *testing.T) { result: authorization.Result{Decision: authorization.DecisionDenied, DenialReason: denialReason, Err: reviewErr}, want: outcome{Code: http.StatusForbidden, Message: denialReason}, }, + { + name: "invalid", + result: authorization.Result{Decision: authorization.DecisionInvalid, Err: validationErr}, + want: outcome{Code: http.StatusBadRequest, Message: validationErr.Error()}, + }, + { + name: "invalid without error", + result: authorization.Result{Decision: authorization.DecisionInvalid}, + want: outcome{Code: http.StatusInternalServerError, Message: "selected-resource authorization returned an invalid decision without an error"}, + }, { name: "indeterminate", result: authorization.Result{Decision: authorization.DecisionIndeterminate, Err: reviewErr}, diff --git a/test/e2e/setup_test.go b/test/e2e/setup_test.go index fdf862f78..d7079cbdf 100644 --- a/test/e2e/setup_test.go +++ b/test/e2e/setup_test.go @@ -90,11 +90,14 @@ const ( ) const ( - // Do not bump this value unless you have a good reason. This is to safeguard any performance related regressions. + // The eventually check duration for most test cases that involve hub cluster only operations. + // + // Do not bump this value unless you have a good reason. This helps safeguard performance related regressions. eventuallyDuration = time.Second * 10 - // this is for workload related test cases + // The eventually check duration for test cases that involve operations on workloads applied on the member + // side. workloadEventuallyDuration = time.Second * 45 - // This is for cluster setup. + // A longer eventually check duration for cluster setup related tasks. longEventuallyDuration = time.Minute * 2 eventuallyInterval = time.Millisecond * 250 consistentlyDuration = time.Second * 15 diff --git a/test/e2e/utils_test.go b/test/e2e/utils_test.go index a0116847c..2491da4d6 100644 --- a/test/e2e/utils_test.go +++ b/test/e2e/utils_test.go @@ -302,6 +302,8 @@ func checkIfMemberClusterHasJoined(memberCluster *framework.Cluster) { // provider, as indicated by the PROPERTY_PROVIDER environment variable; for setup that // does not use it, the check will always pass. func checkIfAzurePropertyProviderIsWorking() { + const costDiffTolerance = 0.003 + 1e-9 + if !isAzurePropertyProviderEnabled { return } @@ -344,7 +346,7 @@ func checkIfAzurePropertyProviderIsWorking() { // Check the cost properties separately. // - // The test suite consider cost outputs with a margin of no more than 0.002 to be acceptable. + // Allow a cost difference of 0.003 with a small floating-point tolerance. perCPUCoreCostProperty, found := mcObj.Status.Properties[azure.PerCPUCoreCostProperty] wantPerCPUCoreCostProperty, wantFound := wantStatus.Properties[azure.PerCPUCoreCostProperty] if found != wantFound { @@ -355,7 +357,7 @@ func checkIfAzurePropertyProviderIsWorking() { if err != nil || wantErr != nil { return fmt.Errorf("failed to parse per CPU core cost property: val=%s, err=%w, wantVal=%s, wantErr=%w", perCPUCoreCostProperty.Value, err, wantPerCPUCoreCostProperty.Value, wantErr) } - if diff := math.Abs(perCPUCoreCost - wantPerCPUCoreCost); diff > 0.002 { + if diff := math.Abs(perCPUCoreCost - wantPerCPUCoreCost); diff > costDiffTolerance { return fmt.Errorf("member cluster per CPU core cost property diff: got=%f, want=%f, diff=%f", perCPUCoreCost, wantPerCPUCoreCost, diff) } @@ -369,7 +371,7 @@ func checkIfAzurePropertyProviderIsWorking() { if err != nil || wantErr != nil { return fmt.Errorf("failed to parse per GB memory cost property: val=%s, err=%w, wantVal=%s, wantErr=%w", perGBMemoryCostProperty.Value, err, wantPerGBMemoryCostProperty.Value, wantErr) } - if diff := math.Abs(perGBMemoryCost - wantPerGBMemoryCost); diff > 0.002 { + if diff := math.Abs(perGBMemoryCost - wantPerGBMemoryCost); diff > costDiffTolerance { return fmt.Errorf("member cluster per GB memory cost property diff: got=%f, want=%f, diff=%f", perGBMemoryCost, wantPerGBMemoryCost, diff) } @@ -1396,7 +1398,9 @@ func ensureCRPAndRelatedResourcesDeleted(crpName string, memberClusters []*frame memberCluster := memberClusters[idx] workResourcesRemovedActual := workNamespaceRemovedFromClusterActual(memberCluster) - Eventually(workResourcesRemovedActual, workloadEventuallyDuration, time.Second*5).Should(Succeed(), "Failed to remove work resources from member cluster %s", memberCluster.ClusterName) + // Use a longer eventually duration as namespace GC might take additional time, esp. in test environments + // with less capacity. + Eventually(workResourcesRemovedActual, workloadEventuallyDuration*2, time.Second*5).Should(Succeed(), "Failed to remove work resources from member cluster %s", memberCluster.ClusterName) } // Verify that related finalizers have been removed from the CRP.