diff --git a/.coderabbit.yaml b/.coderabbit.yaml deleted file mode 100644 index c75ce5699..000000000 --- a/.coderabbit.yaml +++ /dev/null @@ -1,112 +0,0 @@ -# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json - -# CodeRabbit Configuration Template -# Complete reference: https://docs.coderabbit.ai/reference/configuration -# Copy this file to .coderabbit.yaml in your repository root - -# ============================================================================= -# GLOBAL SETTINGS -# These settings apply to your entire CodeRabbit configuration -# ============================================================================= - -# Set the language for reviews by using the corresponding ISO language code. -# Options: de, de-DE, de-AT, de-CH, en, en-US, en-AU, en-GB, en-CA, en-NZ, en-ZA, es, es-AR, fr, fr-CA, fr-CH, fr-BE, nl, nl-BE, pt-AO, pt, pt-BR, pt-MZ, pt-PT, ar, ast-ES, ast, be-BY, be, br-FR, br, ca-ES, ca, ca-ES-valencia, ca-ES-balear, da-DK, da, de-DE-x-simple-language, el-GR, el, eo, fa, ga-IE, ga, gl-ES, gl, it, ja-JP, ja, km-KH, km, ko-KR, ko, pl-PL, pl, ro-RO, ro, ru-RU, ru, sk-SK, sk, sl-SI, sl, sv, ta-IN, ta, tl-PH, tl, tr, uk-UA, uk, zh-CN, zh, crh-UA, crh, cs-CZ, cs, nb, no, nl-NL, de-DE-x-simple-language-DE, es-ES, it-IT, fa-IR, sv-SE, de-LU, fr-FR, bg-BG, bg, he-IL, he, hi-IN, hi, vi-VN, vi, th-TH, th, bn-BD, bn -# Default: "en-US" -language: "en-US" - -# Set the tone of reviews and chat. Example: 'You must use talk like Mr. T. I pity the fool who doesn't!' -# Default: "" -tone_instructions: "be professional and concise, avoid humor, no familiar language" -early_access: false -enable_free_tier: true - -chat: - art: false - auto_reply: true - -reviews: - profile: "chill" - - # This lets coderabbit its status as a workflow check on the PR, while - # it is making a review the status is pending. Otherwise it will be - # green (or red if something catastrophically fails). - commit_status: true - - # If enabled and coderabbit encounters an error during review, it will - # set the commit status to failed, preventing e.g. merging. - fail_commit_status: false - - # This causes coderabbit to edit the PR description with a summary of - # changes. Can be noisy and is often wrong in big PRs. - high_level_summary: false - - # With this enabled coderabbit makes a comment on every PR (with or - # without the label) and updates it with the status. - # OK-ish on PRs it reviews but noisy on others. - # This comment also contains the "walkthrough" mentioned in other - # settings. - review_status: false - - # Stop the review if the PR is closed while the review is in progress. - abort_on_close: true - - # Let coderabbit approve a PR if there are no issues found. - request_changes_workflow: true - - # If enabled coderabbit will apply labels to the PR based on its - # analysis. Can be noisy. And wrong. - auto_apply_labels: false - - # If enabled coderabbit assigns reviewers based on who edited files - # recently. Generally this should be resolved by code ownership. - auto_assign_reviewers: false - - # Disabling general fluff. Each of these can be request individually - # with a command. - collapse_walkthrough: false - changed_files_summary: false - sequence_diagrams: false - high_level_summary_in_walkthrough: false - estimate_code_review_effort: false - assess_linked_issues: false - related_issues: false - related_prs: false - suggested_labels: false - suggested_reviewers: false - poem: false - in_progress_fortune: false - finishing_touches: - docstrings: - enabled: False - unit_tests: - enabled: False - pre_merge_checks: - docstrings: - mode: off - title: - mode: off - description: - mode: off - issue_assessment: - mode: off - - # Specify file patterns to include or exclude in a review using glob patterns (e.g., !dist/**, src/**). These patterns also apply to 'git sparse-checkout', including specified patterns and ignoring excluded ones (starting with '!') when cloning the repository. - # Default: [] - path_filters: [ - # ignore generated files - '!**/*_generated.*', - '!sdk/client/**', - # ignore generated yaml (e.g. crd) files - '!**/*.yaml', - # allow inspecting examples - '**/examples/*.yaml' - ] - - # Configuration for auto review - # Default: {} - auto_review: - # List of labels to control which PRs/MRs to review. Labels starting with '!' are negative matches. Examples: ['bug', 'feature'] - reviews PRs with 'bug' OR 'feature' label. ['!wip'] - reviews all PRs except those with 'wip' label. ['bug', '!wip'] - reviews PRs with 'bug' label but not if they have 'wip' label. - # Default: [] - labels: [ - "ai-code-review", - ] diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index eb8d7c753..fa1c99846 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -8,3 +8,13 @@ updates: groups: all-github-actions: patterns: [ "*" ] +# Go modules: root (konnector) and the sdk module. +- package-ecosystem: "gomod" + directories: + - "/" + - "/sdk" + schedule: + interval: "weekly" + groups: + all-gomod: + patterns: [ "*" ] diff --git a/.github/workflows/ci-docs-only.yaml b/.github/workflows/ci-docs-only.yaml deleted file mode 100644 index 26526240b..000000000 --- a/.github/workflows/ci-docs-only.yaml +++ /dev/null @@ -1,50 +0,0 @@ -name: CI Docs Only - -# To satisfy required status checks for docs-only changes, configure jobs that match those in ci.yaml that -# always return true. -on: - pull_request: - branches: - - main - - 'release-*' - paths: - - "docs/**" - - "**/*.md" - - ".github/ISSUE_TEMPLATE/*" - - ".goreleaser.yaml" - - "contrib/manifests/**" - push: - tags: - - 'v*' - - -jobs: - go-test-e2e: - name: go-test-e2e - runs-on: ubuntu-latest - steps: - - run: 'echo "No build required"' - - go-test-e2e-contrib: - name: go-test-e2e-contrib - runs-on: ubuntu-latest - steps: - - run: 'echo "No build required"' - - go-test: - name: go-test - runs-on: ubuntu-latest - steps: - - run: 'echo "No build required"' - - lint: - name: lint - runs-on: ubuntu-latest - steps: - - run: 'echo "No build required"' - - verify: - name: verify - runs-on: ubuntu-latest - steps: - - run: 'echo "No build required"' diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0532fb0d1..684cd3a2c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -4,92 +4,76 @@ on: push: branches: - main - - 'release-*' + - v2-next pull_request: branches: - main - - 'release-*' - paths-ignore: - - "docs/**" - - "**/*.md" - - ".github/ISSUE_TEMPLATE/*" - - ".goreleaser.yaml" - - "contrib/manifests/**" + - v2-next -# NOTE!!! -# -# If you add a job here that is a REQUIRED status check in GitHub, you MUST add a job with the same name to ci-docs-only.yaml -# -# NOTE!!! +permissions: + contents: read jobs: - go-test-e2e: - name: go-test-e2e - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: v1.26.9 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: '20' - - run: cd web && npm install - - run: make build-web - - run: make test-e2e - - go-test-e2e-contrib: - name: go-test-e2e-contrib - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: v1.26.9 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: '20' - - run: cd web && npm install - - run: make build-web - - run: make test-e2e-contribs - - go-test: - name: go-test + lint: + name: lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: v1.26.9 - - run: make test + go-version: v1.26.2 + - run: go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.3 + - run: make lint - lint: - name: lint + test: + name: test runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: v1.26.9 - - run: make lint + go-version: v1.26.2 + - run: make build vet test + # test-e2e downloads envtest binaries on demand via setup-envtest. + - run: make test-e2e verify: name: verify runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: v1.26.9 - - run: make verify + go-version: v1.26.2 + - run: make verify-boilerplate image-build: name: image-build runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: v1.26.9 - - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - run: make image-local + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + # Multi-arch build for all release architectures, without pushing. + - name: Build konnector image (multi-arch, no push) + run: | + docker buildx build \ + --platform linux/amd64,linux/arm64 \ + --provenance=false \ + . + + e2e-kind: + name: e2e-kind + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + # kubectl and docker are preinstalled on ubuntu-latest; pin kind and helm via + # direct downloads to keep the toolchain reproducible without extra actions. + - name: Install kind and helm + run: | + curl -fsSLo ./kind https://kind.sigs.k8s.io/dl/v0.27.0/kind-linux-amd64 + chmod +x ./kind && sudo mv ./kind /usr/local/bin/kind + curl -fsSL https://get.helm.sh/helm-v3.17.1-linux-amd64.tar.gz | tar -xz + sudo mv linux-amd64/helm /usr/local/bin/helm + # Builds the image, loads it into a kind consumer cluster, helm-installs the + # konnector, and asserts the full bind/sync flow against a kind provider. + - run: make test-e2e-kind diff --git a/.github/workflows/cli.yaml b/.github/workflows/cli.yaml new file mode 100644 index 000000000..ee15c0723 --- /dev/null +++ b/.github/workflows/cli.yaml @@ -0,0 +1,42 @@ +name: CLI + +# Release the bind CLI on FINAL tags via goreleaser (archives, checksums, +# GitHub release), then let krew-release-bot render .krew.yaml and PR +# krew-index for the "bind" plugin (name kept from v1; archive binary is +# kubectl-bind). +# +# Release candidates (v*-rc*, any v*-* prerelease) do NOT release the CLI: +# users' binaries and the krew plugin only move forward on final versions. +# (Images still publish on every v* tag — see image.yaml — so RCs stay +# testable in-cluster.) +on: + push: + tags: + - 'v*' + - '!v*-*' + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 + with: + go-version: v1.26.2 + + # goreleaser run via `go run` (version-pinned) — no third-party action. + - name: Run goreleaser + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: go run github.com/goreleaser/goreleaser/v2@v2.5.0 release --clean + + # Renders .krew.yaml against this release and PRs krew-index. Pinned by + # tag (upstream publishes no SHA-stable releases); it only needs the + # public release artifacts, no repo secrets. + - name: Update krew-index + uses: rajatjindal/krew-release-bot@v0.0.47 diff --git a/.github/workflows/docs-gen-and-push.yaml b/.github/workflows/docs-gen-and-push.yaml index d06f231c5..fbd4f223f 100644 --- a/.github/workflows/docs-gen-and-push.yaml +++ b/.github/workflows/docs-gen-and-push.yaml @@ -1,47 +1,89 @@ name: Docs on: - # So we can trigger manually if needed workflow_dispatch: - # To confirm any changes to docs build successfully, without deploying them pull_request: - # Pushes to branches do the full build + deployment - push: - tags: - - 'v*' branches: - - main - - "release-*" + - v2-next paths: + - "docs/**" + - "cli/**" - "cmd/**" + - "backend/**" + - "engine/**" + - "pkg/**" + - "deploy/charts/**" + - "sdk/apis/**" + - "go.mod" + - "go.sum" + - "sdk/go.mod" + - "sdk/go.sum" + - "Makefile" + - ".github/workflows/docs-gen-and-push.yaml" + push: + branches: + - v2-next + - docs-v2 + paths: - "docs/**" + - "cli/**" + - "cmd/**" + - "backend/**" + - "engine/**" - "pkg/**" + - "deploy/charts/**" + - "sdk/apis/**" + - "go.mod" + - "go.sum" + - "sdk/go.mod" + - "sdk/go.sum" + - "Makefile" - ".github/workflows/docs-gen-and-push.yaml" permissions: - contents: write - -concurrency: - group: ${{ github.workflow }} + contents: read jobs: - generate-and-push: - name: Docs + build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - run: git fetch origin gh-pages - - run: git fetch origin '+refs/tags/v*:refs/tags/v*' --no-tags - - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: v1.26.9 - cache: true - + go-version-file: go.mod - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: - python-version: '3.10' - cache: 'pip' + python-version: "3.12" + cache: pip + cache-dependency-path: docs/requirements.txt + - run: make docs-venv build-docs - - run: make generate-cli-docs generate-api-docs deploy-docs + publish: + if: >- + github.repository == 'kbind-dev/kbind' && + github.event_name != 'pull_request' && + (github.ref == 'refs/heads/v2-next' || github.ref == 'refs/heads/docs-v2') + needs: build + permissions: + contents: write + concurrency: + group: Docs + cancel-in-progress: false + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 + with: + go-version-file: go.mod + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: docs/requirements.txt + - name: Publish preview without changing latest + env: + PUSH: "1" + run: | + git config user.name "kbind-ci-bot" + git config user.email "no-reply@kbind.dev" + make docs-venv deploy-docs diff --git a/.github/workflows/goreleaser.yaml b/.github/workflows/goreleaser.yaml deleted file mode 100644 index 1961f368a..000000000 --- a/.github/workflows/goreleaser.yaml +++ /dev/null @@ -1,54 +0,0 @@ -name: Release - -on: - pull_request: - paths: - - .github/workflows/goreleaser.yaml - - .goreleaser.yaml - push: - tags: - - 'v*' - -permissions: - contents: write - -jobs: - goreleaser: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: v1.26.9 - - name: Delete non-semver tags - run: 'git tag -d $(git tag -l | grep -v "^v")' - - name: Set LDFLAGS - run: echo LDFLAGS="$(make ldflags)" >> $GITHUB_ENV - - name: Run GoReleaser on tag - if: github.event_name != 'pull_request' - uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7.2.3 - with: - distribution: goreleaser - version: latest - args: release --timeout 60m - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - KREW_GITHUB_TOKEN: ${{ secrets.KREW_GITHUB_TOKEN }} - - name: Run GoReleaser on pull request - if: github.event_name == 'pull_request' - uses: goreleaser/goreleaser-action@f06c13b6b1a9625abc9e6e439d9c05a8f2190e94 # v7.2.3 - with: - distribution: goreleaser - version: latest - args: release --timeout 60m --snapshot - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - KREW_GITHUB_TOKEN: ${{ secrets.KREW_GITHUB_TOKEN }} - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: ${{ always() }} - with: - name: binaries - path: dist/*.tar.gz diff --git a/.github/workflows/image.yaml b/.github/workflows/image.yaml index 6c1527059..f4b057907 100644 --- a/.github/workflows/image.yaml +++ b/.github/workflows/image.yaml @@ -1,81 +1,70 @@ name: Image +# Build and push the konnector + backend images and Helm charts on tags: +# - tags v* -> ghcr.io//konnector:, ghcr.io//backend: +# - tags v* -> oci://ghcr.io//charts/{konnector-v2,backend-v2}: +# No :latest or : tags — the image repo is shared with v1/main images. on: push: tags: - - 'v*' - branches: - - main + - 'v*' permissions: contents: read packages: write - id-token: write jobs: image: runs-on: ubuntu-latest steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version: v1.26.9 - check-latest: true - - # We need this to remove local tags that are not semver so goreleaser doesn't get confused. - - name: Delete non-semver tags - run: 'git tag -d $(git tag -l | grep -v "^v")' + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - # If you notice signing errors, you may need to update the cosign version. - - uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 - - - name: Install Helm - uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1 - with: - version: 'v3.12.0' - - - name: Compute build env - run: | - { - echo "LDFLAGS=$(make ldflags)" - echo "IMAGE_REPO=ghcr.io/${{ github.repository_owner }}" - echo "IMAGE_TAGS=latest ${{ github.sha }} 0.0.0-${{ github.sha }} ${{ github.ref_name }}" - echo "BUILDX_CACHE_FROM=type=gha" - echo "BUILDX_CACHE_TO=type=gha,mode=max" - echo "COSIGN_ARGS=-a sha=${{ github.sha }} -a ref=${{ github.ref }} -a run_id=${{ github.run_id }} -a run_attempt=${{ github.run_attempt }}" - } >> "$GITHUB_ENV" - # Common OCI labels (one per line so build-image.sh can split on newlines) - { - echo 'IMAGE_LABELS<> "$GITHUB_ENV" - # App version: full tag (e.g. v0.8.1) for releases, otherwise 0.0.0- - if [[ "${{ github.ref_type }}" == "tag" ]]; then - echo "APP_VERSION=${{ github.ref_name }}" >> "$GITHUB_ENV" - else - echo "APP_VERSION=0.0.0-${{ github.sha }}" >> "$GITHUB_ENV" - fi + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 - name: Login to GitHub Container Registry - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Login to GHCR for Helm - env: - HELM_EXPERIMENTAL_OCI: '1' - run: echo "${{ github.token }}" | helm registry login ghcr.io --username ${{ github.actor }} --password-stdin + # Multi-arch via in-Dockerfile cross-compile (builder pinned to + # BUILDPLATFORM), so no QEMU is required. + - name: Build and push + run: | + owner="$(echo "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')" + for target in konnector backend; do + docker buildx build \ + --platform linux/amd64,linux/arm64 \ + --target "${target}" \ + --tag "ghcr.io/${owner}/${target}:${GITHUB_REF_NAME}" \ + --label "org.opencontainers.image.source=https://github.com/${{ github.repository }}" \ + --label "org.opencontainers.image.revision=${{ github.sha }}" \ + --label "org.opencontainers.image.title=${target}" \ + --cache-from type=gha \ + --cache-to type=gha,mode=max \ + --provenance=false \ + --push \ + . + done - - name: Build, push, and sign images - run: make release-images + publish-chart: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - name: Build and push Helm charts - run: make release-helm + - name: Install Helm + uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1 + + - name: Log in to GHCR for Helm + run: echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io --username ${{ github.actor }} --password-stdin + + - name: Version from tag + id: v + run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" + + - name: Package and push Helm charts (OCI) + run: | + owner="$(echo "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')" + make helm-push VERSION=${{ steps.v.outputs.version }} HELM_REPO="ghcr.io/${owner}/charts" diff --git a/.gitignore b/.gitignore index fd664da17..59a2e38a5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ coverage.* *.iml .DS_Store .env +.venv +__pycache__/ *.kubeconfig .kcp .kube-bind @@ -24,3 +26,6 @@ web/.vite/ web/*.tsbuildinfo go.work go.work.sum + +# Local Claude Code project settings +.claude/ diff --git a/.golangci.yaml b/.golangci.yaml index 80e33561a..23f020c91 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -91,8 +91,7 @@ formatters: sections: - standard - default - - prefix(github.com/kube-bind) - - prefix(github.com/kube-bind/sdk) + - prefix(github.com/kbind) - blank - dot custom-order: true diff --git a/.goreleaser.yaml b/.goreleaser.yaml index ee5a42cbd..45c2b3a39 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,97 +1,50 @@ +# goreleaser config for the bind CLI (pinned to goreleaser v2.5.x in CI). +# Archives carry the binary as kubectl-bind for the krew "bind" plugin; +# krew-release-bot (not goreleaser's krews) PRs upstream krew-index. version: 2 -git: - tag_sort: -version:refname - ignore_tags: - - "cli/*" - - "sdk/*" +project_name: bind builds: -- id: "kubectl-bind" - dir: cli - main: ./cmd/kubectl-bind - binary: bin/kubectl-bind - ldflags: - - "{{ .Env.LDFLAGS }}" - goos: - - linux - - darwin - - windows - goarch: - - amd64 - - arm64 - - ppc64le - ignore: - - goos: darwin - goarch: ppc64le - - goos: windows - goarch: ppc64le -- id: "backend" - main: ./cmd/backend - binary: bin/backend - env: - - CGO_ENABLED=0 - ldflags: - - "{{ .Env.LDFLAGS }}" - goos: - - linux - - darwin - goarch: - - amd64 - - arm64 - - ppc64le - ignore: - - goos: darwin - goarch: ppc64le -- id: "konnector" - main: ./cmd/konnector - binary: bin/konnector - env: - - CGO_ENABLED=0 - ldflags: - - "{{ .Env.LDFLAGS }}" - goos: - - linux - - darwin - goarch: - - amd64 - - arm64 - - ppc64le - ignore: - - goos: darwin - goarch: ppc64le + - id: bind + main: ./cmd/bind + binary: kubectl-bind + env: + - CGO_ENABLED=0 + - GOWORK=off + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - arm64 + ignore: + - goos: windows + goarch: arm64 + ldflags: + - -s -w -X github.com/kbind/kbind/cli/cmd.Version={{ .Tag }} archives: -- id: kubectl-bind - builds: - - kubectl-bind - name_template: "kubectl-bind_{{ .Version }}_{{ .Os }}_{{ .Arch }}" -- id: backend - builds: - - backend - name_template: "backend_{{ .Version }}_{{ .Os }}_{{ .Arch }}" -- id: konnector - builds: - - konnector - name_template: "konnector_{{ .Version }}_{{ .Os }}_{{ .Arch }}" + - id: bind + format: tar.gz + name_template: 'kubectl-bind_{{ .Tag }}_{{ .Os }}_{{ .Arch }}' + files: + - LICENSE + +checksum: + name_template: checksums.txt release: + # Attach to the tag's release; notes come from GitHub's generator. + mode: replace + # Belt and braces: the workflow already skips prerelease tags, but if + # goreleaser is ever run on one by hand, mark the GitHub release as a + # prerelease so it never becomes "latest". prerelease: auto - draft: true - mode: keep-existing -krews: -- name: bind - ids: - - kubectl-bind - repository: - owner: kube-bind - name: krew-index - token: "{{ .Env.KREW_GITHUB_TOKEN }}" - homepage: "https://kube-bind.io/" - description: | - Binds API services and other remote types into the current cluster. API services - are CRDs that are operated by a service provider without anything by that service - provider running in the local cluster. Real SaaS for Kubernetes. - short_description: "Bind API services and other remote types into the current cluster." - skip_upload: auto +snapshot: + version_template: '{{ .Tag }}-snapshot' + +changelog: + use: github-native diff --git a/.ko.yaml b/.ko.yaml deleted file mode 100644 index f985ab28f..000000000 --- a/.ko.yaml +++ /dev/null @@ -1,12 +0,0 @@ -baseImageOverrides: - github.com/google/ko: golang:1.26.9 - -builds: -- id: konnector - dir: ./cmd/konnector - ldflags: - - "{{ .Env.LDFLAGS }}" -- id: backend - dir: ./cmd/backend - ldflags: - - "{{ .Env.LDFLAGS }}" diff --git a/.krew.yaml b/.krew.yaml new file mode 100644 index 000000000..491ef0ab7 --- /dev/null +++ b/.krew.yaml @@ -0,0 +1,54 @@ +# krew-release-bot template for the "bind" plugin (name kept from v1 — the +# CLI binary is kbind, installed via krew as `kubectl bind`). The bot renders +# this on every GitHub release and opens the krew-index PR. +apiVersion: krew.googlecontainertools.github.com/v1alpha2 +kind: Plugin +metadata: + name: bind +spec: + version: {{ .TagName }} + homepage: https://github.com/kbind-dev/kbind + shortDescription: Bind a service provider's APIs into your cluster + description: | + bind binds APIs exported by a provider cluster into your cluster: + log in to a provider's gateway, browse its catalog, and bind a service — + the result is a one-apply bundle (Secret + Connection + ClusterBinding) + consumed by the konnector, the only component that runs on your side. + Everything the CLI does is reproducible by hand with curl + kubectl. + caveats: | + Typical flow: + kubectl bind login https://provider.example.com + kubectl bind connect # install the konnector + kubectl bind catalog + kubectl bind export # or: export -o yaml (GitOps) + platforms: + - selector: + matchLabels: + os: darwin + arch: amd64 + {{addURIAndSha "https://github.com/kbind-dev/kbind/releases/download/{{ .TagName }}/kubectl-bind_{{ .TagName }}_darwin_amd64.tar.gz" .TagName }} + bin: kubectl-bind + - selector: + matchLabels: + os: darwin + arch: arm64 + {{addURIAndSha "https://github.com/kbind-dev/kbind/releases/download/{{ .TagName }}/kubectl-bind_{{ .TagName }}_darwin_arm64.tar.gz" .TagName }} + bin: kubectl-bind + - selector: + matchLabels: + os: linux + arch: amd64 + {{addURIAndSha "https://github.com/kbind-dev/kbind/releases/download/{{ .TagName }}/kubectl-bind_{{ .TagName }}_linux_amd64.tar.gz" .TagName }} + bin: kubectl-bind + - selector: + matchLabels: + os: linux + arch: arm64 + {{addURIAndSha "https://github.com/kbind-dev/kbind/releases/download/{{ .TagName }}/kubectl-bind_{{ .TagName }}_linux_arm64.tar.gz" .TagName }} + bin: kubectl-bind + - selector: + matchLabels: + os: windows + arch: amd64 + {{addURIAndSha "https://github.com/kbind-dev/kbind/releases/download/{{ .TagName }}/kubectl-bind_{{ .TagName }}_windows_amd64.tar.gz" .TagName }} + bin: kubectl-bind.exe diff --git a/ADOPTERS.md b/ADOPTERS.md deleted file mode 100644 index 998007860..000000000 --- a/ADOPTERS.md +++ /dev/null @@ -1,11 +0,0 @@ -# kbind Adopters - -This file lists organizations and projects that have adopted kbind in -production or as a core part of their platform. - -If you are using kbind and would like to be listed here, please open a -pull request. - -| Organization | Type | Use Case | Link | -|---|---|---|---| -| Platform Mesh | OSS Project | Uses kbind as the cross-cluster service binding layer, enabling users to add kbind as a provider and automatically create bindings between workload clusters and managed services within their platform. | | diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 844dd654e..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,47 +0,0 @@ -# CHANGELOG - -Change log is high level summary of notable changes for each release. - -## API Changes in v0.6.0 release - -### Helm Chart Updates - -Introduction of helm chart, `kube-bind/backend`, to deploy the backend components with configurable options. - -### Catalog API -Introduction of new `Collection` and `APIServiceExportTemplate` CRDs for better service organization: -- **Collections**: Function as folders in the UI, grouping bindable resources such as templates -- **APIServiceExportTemplate**: Group multiple CRDs with their related resources and permission claims that can be used to create a `APIServiceExportRequest` - -### Enhanced Permission Claims -Major improvements to `PermissionClaims` in APIServiceExportSpec: -- **NamedResources**: Specify exact resources by name and namespace -- **Combined Selectors**: Use both label selectors AND named resources (both must match) -- **Granular Control**: More precise access control for service resources - -### Provider-side Namespace Management -Enhanced namespace management on the provider side: -- **APIServiceNamespace Controller**: Automatically creates Roles and RoleBindings -- **Namespace Isolation**: Each consumer gets isolated provider-side namespaces -- **RBAC Automation**: Proper permissions created based on scope (namespaced vs cluster-scoped) -- **Namespace Pre-provisioning**: Providers can pre-create namespaces for better UX - -**Important**: When `ClusterScope` mode is used, cluster-wide permissions are created instead of namespaced ones. - -## API Changes in v0.5.0 release - -Version v0.5.0 includes significant architectural improvements to the API structure: - -### Major Changes - -- **API Version Upgrade**: Introduced `v1alpha2` API version alongside existing `v1alpha1` -- **Service Exposure Refactoring**: Refactored the service exposure mechanism from embedded CRD specifications to a resource-based model: - - `APIServiceExportSpec` now uses `Resources []APIServiceExportResource` instead of embedded CRD specs - - `BoundSchema`: New resource type in `v1alpha2` that represents bound schemas in consumer clusters and tracks the status of synced resources - - This allows one APIServiceExport to reference multiple CRDs more efficiently - -### Backend Architecture Improvements - -- **MultiCluster Runtime Integration**: The backend now leverages `sigs.k8s.io/multicluster-runtime` for enhanced cluster management capabilities -- **Provider Support**: Built-in support for multiple backend providers including kcp through `github.com/kcp-dev/multicluster-provider` -- **Enhanced Cluster Operations**: Improved cluster-aware resource management with dedicated manager architecture for handling multi-cluster scenarios diff --git a/CODEOWNERS b/CODEOWNERS deleted file mode 100644 index 685a54e43..000000000 --- a/CODEOWNERS +++ /dev/null @@ -1 +0,0 @@ -* @kube-bind/kube-bind-maintainers diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index e13aa5069..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,98 +0,0 @@ -# Contributing to kbind - -kbind is [Apache 2.0 licensed](LICENSE) and we accept contributions via -GitHub pull requests. - -Please read the following guide if you're interested in contributing to kbind. - -## Certificate of Origin - -By contributing to this project you agree to the Developer Certificate of -Origin (DCO). This document was created by the Linux Kernel community and is a -simple statement that you, as a contributor, have the legal right to make the -contribution. See the [DCO](DCO) file for details. - -## Getting started - -### Prerequisites - -1. Clone this repository. -2. [Install Go](https://golang.org/doc/install) (1.18+). -3. Install [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl). - -### Build & verify -1. In one terminal, build and start `bin/kubectl-bind`: -``` -make -bin/kubectl-bind -``` - -## Finding areas to contribute - -Starting to participate in a new project can sometimes be overwhelming, and you may not know where to begin. Fortunately, we are here to help! We track all of our tasks here in GitHub, and we label our issues to categorize them. Here are a couple of handy links to check out: - -* [Good first issue](https://github.com/kbind-dev/kbind/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) issues -* [Help wanted](https://github.com/kbind-dev/kbind/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) issues - -You're certainly not limited to only these kinds of issues, though! If you're comfortable, please feel free to try working on anything that is open. - -We do use the assignee feature in GitHub for issues. If you find an unassigned issue, comment asking if you can be assigned, and ideally wait for a maintainer to respond. If you find an assigned issue and you want to work on it or help out, please reach out to the assignee first. - -Sometimes you might get an amazing idea and start working on a huge amount of code. We love and encourage excitement like this, but we do ask that before you embarking on a giant pull request, please reach out to the community first for an initial discussion. You could [file an issue](https://github.com/kbind-dev/kbind/issues/new/choose). - -Finally, we welcome and value all types of contributions, beyond "just code"! Other types include triaging bugs, tracking down and fixing flaky tests, improving our documentation, helping answer community questions, proposing and reviewing designs, etc. - -## Coding guidelines & conventions - -- Logging: - - We use klog's contextual logging: `logging := klog.FromContext(ctx)`. - - Default log-level is 2. - - Controllers should generally log (a) **one** line (not more) non-error progress per item with `klog.Info` (b) actions like create/update/delete via `klog.V(1).Info` and (c) skipped actions, i.e. what was not done for reasons via `klog.V(2).Info`. -- Go Proverbs are good guidelines for style: https://go-proverbs.github.io/ – watch https://www.youtube.com/watch?v=PAAkCSZUG1c. -- We use [https://github.com/stretchr/testify/tree/master/require](github.com/stretchr/testify/require) a lot in tests, and avoid - [https://github.com/stretchr/testify/tree/master/assert](https://github.com/stretchr/testify/assert). - - Note this subtle distinction of nested `require` statements: - ```Golang - require.Eventually(t, func() bool { - foos, err := client.List(...) - require.NoError(err) // fail fast, including failing require.Eventually immediately - return someCondition(foos) - }, ...) - ``` - and - ```Golang - require.Eventually(t, func() bool { - foos, err := client.List(...) - if err != nil { - return false // keep trying - } - return someCondition(foos) - }, ...) - ``` - The first fails fast on every client error. The second ignores client errors and keeps trying. Either - has its place, depending on whether the client error is to be expected (e.g. because of asynchronicity making the resource available), - or signals a real test problem. - -### Using Kubebuilder CRD Validation Annotations - -All of the API resources for `kbind` are `CustomResourceDefinitions`, and we generate YAML spec for them from our Go types using [kubebuilder](https://github.com/kubernetes-sigs/kubebuilder). - -When adding a field that requires validation, custom annotations are used to translate this logic into the generated OpenAPI spec. [This doc](https://book.kubebuilder.io/reference/markers/crd-validation.html) gives an overview of possible validations. These annotations map directly to concepts in the [OpenAPI Spec](https://swagger.io/specification/#data-type-format) so, for instance, the `format` of strings is defined there, not in kubebuilder. Furthermore, Kubernetes has forked the OpenAPI project [here](https://github.com/kubernetes/kube-openapi/tree/master/pkg/validation) and extends more formats in the extensions-apiserver [here](https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1/types_jsonschema.go#L27). - -## Community Roles - -### Reviewers - -Reviewers are responsible for reviewing code for correctness and adherence to standards. Oftentimes reviewers will -be able to advise on code efficiency and style as it relates to golang or project conventions as well as other considerations -that might not be obvious to the contributor. - -### Approvers - -Approvers are responsible for sign-off on the acceptance of the contribution. In essence, approval indicates that the -change is desired and good for the project, aligns with code, api, and system conventions, and appears to follow all required -process including adequate testing, documentation, follow ups, or notifications to other areas who might be interested -or affected by the change. - -Approvers are also reviewers. diff --git a/DCO b/DCO deleted file mode 100644 index d950df0c3..000000000 --- a/DCO +++ /dev/null @@ -1,34 +0,0 @@ -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index cd7c1c3df..8487968a6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# Copyright 2022 The Kube Bind Authors. +# Copyright 2026 The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,64 +12,45 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Use node:lts-alpine for better compatibility and smaller size -FROM node:22-alpine AS ui-build-env -WORKDIR /app - -# Install build dependencies needed for native modules -RUN apk add --no-cache python3 make g++ - -# Copy package files -COPY ./web/package*.json ./ -COPY ./web/.npmrc ./ - -RUN npm ci - -# Copy the Vue app files -COPY ./web . - -# Set environment to avoid native dependency issues -ENV NODE_ENV=production -ENV VITE_BUILD_TARGET=docker - -# Building UI with Docker-specific config -RUN npm run build - -# Build Go binary with embedded UI assets -FROM golang:1.26.9 AS go-build-env -WORKDIR /app +# kbind images. Build context is the repo root; the root module pulls in the +# sibling sdk module via `replace github.com/kbind/kbind/sdk => ./sdk`: +# +# docker build -t kbind/konnector:dev . # default target +# docker build --target backend -t kbind/backend:dev . +# +# Pin the builder to the build host's native platform and cross-compile via +# GOARCH/GOOS (CGO disabled), so multi-arch builds need no QEMU emulation. +FROM --platform=$BUILDPLATFORM golang:1.26.2 AS builder +WORKDIR /workspace -# Accept build arguments for multi-arch support ARG TARGETARCH ARG TARGETOS ARG LDFLAGS -RUN apt-get update && apt-get install -y make jq - -# Copy go.mod and go.sum files first for better caching -COPY go.mod . -COPY go.sum . - -# Copy the source code -COPY . . - -# Copy built UI assets for embedding -COPY --from=ui-build-env /app/dist ./backend/static/web/dist - -# Build with embedded assets -RUN if [ -n "$LDFLAGS" ]; then \ - echo "Building with LDFLAGS: $LDFLAGS for $TARGETOS/$TARGETARCH"; \ - CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -ldflags="$LDFLAGS" -o bin/backend ./cmd/backend; \ - else \ - CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH make build; \ - fi - -FROM alpine:3.22.1 -RUN apk --update add ca-certificates - -COPY --from=go-build-env /app/bin/backend /bin -COPY --from=ui-build-env /app/dist /www - - - +# Build standalone (GOWORK=off) so the image does not depend on go.work. The sdk +# module must be present for the local replace before `go mod download`. +ENV GOWORK=off +COPY go.mod go.sum ./ +COPY sdk/ sdk/ +RUN go mod download + +COPY cmd/ cmd/ +COPY engine/ engine/ +COPY backend/ backend/ +COPY cli/ cli/ +COPY pkg/ pkg/ +COPY web/ web/ +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="${LDFLAGS}" -o /bin/konnector ./cmd/konnector && \ + CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="${LDFLAGS}" -o /bin/backend ./cmd/backend + +# The provider-side service layer (gateway + issuer + reaper), module-flagged. +FROM gcr.io/distroless/static:nonroot AS backend +COPY --from=builder /bin/backend /bin/backend +USER 65532:65532 ENTRYPOINT ["/bin/backend"] + +# The konnector — last stage, so a target-less build keeps producing it. +FROM gcr.io/distroless/static:nonroot AS konnector +COPY --from=builder /bin/konnector /bin/konnector +USER 65532:65532 +ENTRYPOINT ["/bin/konnector"] diff --git a/Dockerfile.konnector b/Dockerfile.konnector deleted file mode 100644 index ca9f56599..000000000 --- a/Dockerfile.konnector +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2025 The Kube Bind 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. - -FROM golang:1.26.9 AS builder -WORKDIR /app - -# Accept build arguments for multi-arch support -ARG TARGETARCH -ARG TARGETOS -ARG LDFLAGS - -# Copy the source code (needed for local replacements in go.mod) -COPY . . -RUN go mod download - -# Build the konnector binary -RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build -ldflags="$LDFLAGS" -o bin/konnector ./cmd/konnector - -FROM alpine:3.22.1 -RUN apk --update add ca-certificates - -COPY --from=builder /app/bin/konnector /bin/konnector - -ENTRYPOINT ["/bin/konnector"] diff --git a/GOVERNANCE.md b/GOVERNANCE.md deleted file mode 100644 index 9d7e4ae52..000000000 --- a/GOVERNANCE.md +++ /dev/null @@ -1,139 +0,0 @@ -# kbind Project Governance - -The kbind project is dedicated to build a vendor-neutral mechanism to bind -services of different kinds into Kubernetes clusters using Kubernetes-native APIs. -This governance explains how the project is run. - -- [Values](#values) -- [Maintainers](#maintainers) -- [Code of Conduct Enforcement](#code-of-conduct) -- [Security Response Team](#security-response-team) -- [Voting](#voting) -- [Modifying this Charter](#modifying-this-charter) - -## Values - -The kbind and its leadership embrace the following values: - - * *Openness*: Communication and decision-making happens in the open and is - discoverable for future reference. As much as possible, all discussions and - work take place in public forums and open repositories. - * *Fairness*: All stakeholders have the opportunity to provide feedback and - submit contributions, which will be considered on their merits. - * *Community over Product or Company*: Sustaining and growing our community - takes priority over shipping code or sponsors' organizational goals. Each - contributor participates in the project as an individual. - * *Inclusivity*: We innovate through different perspectives and skill sets, - which can only be accomplished in a welcoming and respectful environment. - * *Participation*: Responsibilities within the project are earned through - participation, and there is a clear path up the contributor ladder into - leadership positions. - -## Maintainers - -kbind Maintainers have write access to the [project GitHub repository](https://github.com/kbind-dev/kbind). -They can merge their own patches or patches from others. The current maintainers -can be found as top-level approvers in [OWNERS](./OWNERS). Maintainers collectively -manage the project's resources and contributors. - -This privilege is granted with some expectation of responsibility: maintainers -are people who care about the kbind project and want to help it grow and -improve. A maintainer is not just someone who can make changes, but someone who -has demonstrated their ability to collaborate with the team, get the most -knowledgeable people to review code and docs, contribute high-quality code, and -follow through to fix issues (in code or tests). - -A maintainer is a contributor to the project's success and a citizen helping -the project succeed. - -The collective team of all Maintainers is known as the Maintainer Council, which -is the governing body for the project. - -## Becoming a Maintainer - - - -To become a Maintainer you need to demonstrate the following: - - * commitment to the project: - * participate in discussions, contributions, code and documentation reviews - for 3 months or more, - * perform reviews for 5 non-trivial pull requests, - * contribute 5 non-trivial pull requests and have them merged, - * ability to write quality code and/or documentation, - * ability to collaborate with the team, - * understanding of how the team works (policies, processes for testing and code review, etc), - * understanding of the project's code base and coding and documentation style. - - -A new Maintainer must be proposed by an existing maintainer by sending a message to the -[developer mailing list](https://groups.google.com/g/kube-bind-dev). A simple majority -vote of existing Maintainers approves the application. - -Maintainers who are selected will be granted the necessary GitHub rights, -and invited to the [private maintainer mailing list](https://groups.google.com/g/kube-bind-dev-private). - -### Bootstrapping Maintainers - -To bootstrap the process, 3 maintainers are defined (in the initial PR adding -this to the repository) that do not necessarily follow the above rules. When a -new maintainer is added following the above rules, the existing maintainers -define one not following the rules to step down, until all of them follow the -rules. - -### Removing a Maintainer - -Maintainers may resign at any time if they feel that they will not be able to -continue fulfilling their project duties. - -Maintainers may also be removed after being inactive, failure to fulfill their -Maintainer responsibilities, violating the Code of Conduct, or other reasons. -Inactivity is defined as a period of very low or no activity in the project for -a year or more, with no definite schedule to return to full Maintainer activity. - -A Maintainer may be removed at any time by a 2/3 vote of the remaining maintainers. - -Depending on the reason for removal, a Maintainer may be converted to Emeritus -status. Emeritus Maintainers will still be consulted on some project matters, -and can be rapidly returned to Maintainer status if their availability changes. - -## Code of Conduct - - - -[Code of Conduct](./code-of-conduct.md) -violations by community members will be discussed and resolved -on the [private Maintainer mailing list](https://groups.google.com/g/kube-bind-dev-private). - -## Security Response Team - -The Maintainers will appoint a Security Response Team to handle security reports. -This committee may simply consist of the Maintainer Council themselves. If this -responsibility is delegated, the Maintainers will appoint a team of at least two -contributors to handle it. The Maintainers will review who is assigned to this -at least once a year. - -The Security Response Team is responsible for handling all reports of security -holes and breaches according to the [security policy](./SECURITY.md). - -## Voting - -While most business in kbind is conducted by "lazy consensus", periodically -the Maintainers may need to vote on specific actions or changes. -A vote can be taken on [the developer mailing list](https://groups.google.com/g/kube-bind-dev) or -[the private Maintainer mailing list](https://groups.google.com/g/kube-bind-dev-private) -for security or conduct matters. Votes may also be taken at the community call -meeting. Any Maintainer may demand a vote be taken. - -Most votes require a simple majority of all Maintainers to succeed. Maintainers -can be removed by a 2/3 majority vote of all Maintainers, and changes to this -Governance require a 2/3 vote of all Maintainers. - -## Modifying this Charter - -Changes to this Governance and its supporting documents may be approved by a -2/3 vote of the Maintainers. diff --git a/Makefile b/Makefile index 17389061c..8edf2b120 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -# Copyright 2021 The Kube Bind Authors. +# Copyright 2026 The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12,505 +12,203 @@ # See the License for the specific language governing permissions and # limitations under the License. -# We need bash for some conditional logic below. -SHELL := /usr/bin/env bash -e - -ROOT_DIR = $(abspath .) -TOOLS_DIR = hack/tools -BUILD_DIR = $(ROOT_DIR)/bin - -export UGET_DIRECTORY = $(TOOLS_DIR) -export UGET_CHECKSUMS = hack/tools.checksums -export UGET_VERSIONED_BINARIES = true - -# Image build configuration -# REV is the short git sha of latest commit. -export REV ?= $(shell git rev-parse --short HEAD) -export IMAGE_REPO ?= kbind-dev - -BOILERPLATE_VERSION := 201dcad9616c117927232ee0bc499ff38a27023e -CODE_GENERATOR_VERSION := v2.4.0 -CONTROLLER_GEN_VERSION := v0.17.3 -DEX_VERSION := v2.43.1 -GOLANGCI_LINT_VERSION := 2.11.3 -GORELEASER_VERSION := 2.13.0 -GOTESTSUM_VERSION := 1.8.1 -HELM_DOCS_VERSION := 1.14.2 -HELM_VERSION := 3.18.6 -# unreleased kcp version with vw code for schemas -KCP_VERSION := 301a8f749e7b99a0c81f43b37aa5b5e5ff0fc0b4 -KUBE_APPLYCONFIGURATION_GEN_VERSION := v0.32.0 -KUBE_CLIENT_GEN_VERSION := v0.32.0 -KUBE_INFORMER_GEN_VERSION := v0.32.0 -KUBE_LISTER_GEN_VERSION := v0.32.0 -LOGCHECK_VERSION := v0.2.0 -YAML_PATCH_VERSION ?= v0.0.11 - -KUBE_MAJOR_VERSION := 1 -KUBE_MINOR_VERSION := $(shell go mod edit -json | jq '.Require[] | select(.Path == "k8s.io/client-go") | .Version' --raw-output | sed "s/v[0-9]*\.\([0-9]*\).*/\1/") -GIT_COMMIT := $(shell git rev-parse --short HEAD || echo 'local') -# --quiet would still produces output when files are deleted -GIT_DIRTY := $(shell git diff --quiet >/dev/null && echo 'clean' || echo 'dirty') -GIT_VERSION := $(shell go mod edit -json | jq '.Require[] | select(.Path == "k8s.io/client-go") | .Version' --raw-output | sed 's/v0/v1/')+kube-bind-$(shell git describe --tags --match='v*' --abbrev=14 "$(GIT_COMMIT)^{commit}" 2>/dev/null || echo v0.0.0-$(GIT_COMMIT)) -BUILD_DATE := $(shell date -u +'%Y-%m-%dT%H:%M:%SZ') -LDFLAGS := \ - -X k8s.io/client-go/pkg/version.gitCommit=${GIT_COMMIT} \ - -X k8s.io/client-go/pkg/version.gitTreeState=${GIT_DIRTY} \ - -X k8s.io/client-go/pkg/version.gitVersion=${GIT_VERSION} \ - -X k8s.io/client-go/pkg/version.gitMajor=${KUBE_MAJOR_VERSION} \ - -X k8s.io/client-go/pkg/version.gitMinor=${KUBE_MINOR_VERSION} \ - -X k8s.io/client-go/pkg/version.buildDate=${BUILD_DATE} \ - \ - -X k8s.io/component-base/version.gitCommit=${GIT_COMMIT} \ - -X k8s.io/component-base/version.gitTreeState=${GIT_DIRTY} \ - -X k8s.io/component-base/version.gitVersion=${GIT_VERSION} \ - -X k8s.io/component-base/version.gitMajor=${KUBE_MAJOR_VERSION} \ - -X k8s.io/component-base/version.gitMinor=${KUBE_MINOR_VERSION} \ - -X k8s.io/component-base/version.buildDate=${BUILD_DATE} - -CONTRIBS ?= $(patsubst contrib/%,%,$(wildcard contrib/*)) +# kbind slim-core. The repo root is the konnector module; sdk/ is the +# standalone API module (github.com/kbind/kbind/sdk), joined via go.work. -.PHONY: all -all: build - -.PHONY: clean -clean: - rm -rf $(BUILD_DIR) - @echo "Cleaned $(BUILD_DIR)." - -.PHONY: clean-tools -clean-tools: - rm -rf $(UGET_DIRECTORY) - @echo "Cleaned $(UGET_DIRECTORY)." - -.PHONY: check -check: verify lint test test-e2e test-e2e-contribs - -GOMODS := $(shell find . -name 'go.mod' -exec dirname {} \; | grep -v hack/tools | grep -v ./dex) - -.PHONY: ldflags -ldflags: - @echo $(LDFLAGS) +CONTROLLER_GEN ?= go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.17.2 +GOLANGCI_LINT ?= golangci-lint +ENVTEST_K8S_VERSION ?= 1.34.1 +SETUP_ENVTEST ?= go run sigs.k8s.io/controller-runtime/tools/setup-envtest@release-0.21 +CHART ?= deploy/charts/konnector-v2 +BACKEND_CHART ?= deploy/charts/backend-v2 +IMAGE ?= ghcr.io/kbind-dev/konnector:dev +DOCS_VENV ?= $(CURDIR)/docs/.venv +CRD_REF_DOCS ?= go run github.com/elastic/crd-ref-docs@v0.3.0 -.PHONY: require-% -require-%: - @if ! command -v $* 1> /dev/null 2>&1; then echo "$* not found in \$$PATH"; exit 1; fi +.PHONY: all +all: codegen build .PHONY: build -build: WHAT ?= ./cmd/... ./cli/cmd/... ./contrib/kcp/cmd/kcp-init/... -build: export CGO_ENABLED=0 -build: verify-go-versions ## Build the project - @mkdir -p $(BUILD_DIR) - @for W in $(WHAT); do \ - (set -x; cd $${W%...}; go build $(BUILDFLAGS) -ldflags="$(LDFLAGS)" -o $(BUILD_DIR)/ ./...); \ - done - -.PHONY: install -install: WHAT ?= ./cmd/... ./cli/cmd/... -install: ## install binaries to GOBIN - go install -ldflags="$(LDFLAGS)" $(WHAT) - -.PHONY: install-crds -install-crds: ## Install all CRDs into the current cluster - kubectl apply -f deploy/crd - -GOLANGCI_LINT = $(ROOT_DIR)/$(UGET_DIRECTORY)/golangci-lint-$(GOLANGCI_LINT_VERSION) - -.PHONY: install-golangci-lint -install-golangci-lint: - @hack/uget.sh https://github.com/golangci/golangci-lint/releases/download/v{VERSION}/golangci-lint-{VERSION}-{GOOS}-{GOARCH}.tar.gz golangci-lint $(GOLANGCI_LINT_VERSION) - -.PHONY: install-logcheck -install-logcheck: - @GO_MODULE=true hack/uget.sh sigs.k8s.io/logtools/logcheck logcheck $(LOGCHECK_VERSION) - -# .PHONY: install-kcp-codegen -# install-kcp-codegen: -# @GO_MODULE=true hack/uget.sh github.com/kcp-dev/code-generator/v2 kcp-code-generator $(CODE_GENERATOR_VERSION) code-generator - -.PHONY: install-controller-gen -install-controller-gen: - @GO_MODULE=true hack/uget.sh sigs.k8s.io/controller-tools/cmd/controller-gen controller-gen $(CONTROLLER_GEN_VERSION) - -.PHONY: install-yaml-patch -install-yaml-patch: - @GO_MODULE=true hack/uget.sh github.com/pivotal-cf/yaml-patch/cmd/yaml-patch yaml-patch $(YAML_PATCH_VERSION) - -.PHONY: install-gotestsum -install-gotestsum: - @hack/uget.sh https://github.com/gotestyourself/gotestsum/releases/download/v{VERSION}/gotestsum_{VERSION}_{GOOS}_{GOARCH}.tar.gz gotestsum $(GOTESTSUM_VERSION) gotestsum - -# .PHONY: install-client-gen -# install-client-gen: -# @GO_MODULE=true hack/uget.sh k8s.io/code-generator/cmd/client-gen client-gen $(CLIENT_GEN_VERSION) - -# .PHONY: install-lister-gen -# install-lister-gen: -# @GO_MODULE=true hack/uget.sh k8s.io/code-generator/cmd/lister-gen lister-gen $(CLIENT_GEN_VERSION) - -# .PHONY: install-informer-gen -# install-informer-gen: -# @GO_MODULE=true hack/uget.sh k8s.io/code-generator/cmd/informer-gen informer-gen $(CLIENT_GEN_VERSION) - -# .PHONY: install-applyconfiguration-gen -# install-applyconfiguration-gen: -# @GO_MODULE=true hack/uget.sh k8s.io/code-generator/cmd/applyconfiguration-gen applyconfiguration-gen $(APPLYCONFIGURATION_GEN_VERSION) - -.PHONY: install-boilerplate -install-boilerplate: - @UGET_VERSIONED_BINARIES=false UNCOMPRESSED=true hack/uget.sh https://raw.githubusercontent.com/kubernetes/repo-infra/{VERSION}/hack/verify_boilerplate.py verify_boilerplate.py $(BOILERPLATE_VERSION) verify_boilerplate.py +build: + go build ./... + cd sdk && go build ./... + +.PHONY: konnector +konnector: + go build -o bin/konnector ./cmd/konnector + +.PHONY: backend +backend: + go build -o bin/backend ./cmd/backend + +.PHONY: bind +bind: + go build -o bin/bind ./cmd/bind + +# CLI release archives for all platforms via goreleaser (kubectl-bind inside, +# for the krew "bind" plugin). Local dry-run; CI runs `release` on tags. +.PHONY: cli-snapshot +cli-snapshot: + goreleaser release --snapshot --clean + +# Container images. Build context is the repo root (see Dockerfile). +.PHONY: image +image: + docker build -t $(IMAGE) . + +BACKEND_IMAGE ?= ghcr.io/kbind-dev/backend:dev +.PHONY: image-backend +image-backend: + docker build --target backend -t $(BACKEND_IMAGE) . + +.PHONY: helm-lint +helm-lint: + helm lint $(CHART) + helm lint $(BACKEND_CHART) --set oidc.mock=true + +# Render the charts to stdout for review (extra flags via HELM_ARGS=...). +.PHONY: helm-template +helm-template: + helm template konnector $(CHART) -n kbind $(HELM_ARGS) + helm template backend $(BACKEND_CHART) -n kbind --set oidc.mock=true $(HELM_ARGS) + +# Refresh the charts' bundled CRDs from the generated sdk CRDs. +.PHONY: helm-sync-crds +helm-sync-crds: codegen + cp sdk/config/crd/core.kbind.io_*.yaml $(CHART)/files/crds/ + cp sdk/config/crd/catalog.kbind.io_*.yaml sdk/config/crd/iam.kbind.io_*.yaml $(BACKEND_CHART)/files/crds/ -.PHONY: install-kcp -install-kcp: - @if echo "$(KCP_VERSION)" | grep -qE '^v?[0-9]+\.[0-9]+'; then \ - hack/uget.sh https://github.com/kcp-dev/kcp/releases/download/v{VERSION}/kcp_{VERSION}_{GOOS}_{GOARCH}.tar.gz kcp $(KCP_VERSION); \ - else \ - GOBIN=$(abspath $(UGET_DIRECTORY)) hack/go-install.sh github.com/kcp-dev/kcp/cmd/kcp kcp $(KCP_VERSION); \ - fi - -GORELEASER = $(UGET_DIRECTORY)/goreleaser-$(GORELEASER_VERSION) - -.PHONY: install-goreleaser -install-goreleaser: export OS ?= $(shell uname -s) -install-goreleaser: export ARCH ?= $(shell uname -m) -install-goreleaser: - @hack/uget.sh https://github.com/goreleaser/goreleaser/releases/download/v{VERSION}/goreleaser_{ENV:OS}_{ENV:ARCH}.tar.gz goreleaser $(GORELEASER_VERSION) goreleaser - -.PHONY: install-helm -install-helm: - @hack/uget.sh https://get.helm.sh/helm-v{VERSION}-{GOOS}-{GOARCH}.tar.gz helm $(HELM_VERSION) - -HELM_DOCS = $(UGET_DIRECTORY)/helm-docs-$(HELM_DOCS_VERSION) - -.PHONY: install-helm-docs -install-helm-docs: export OS ?= $(shell uname -s) -install-helm-docs: export ARCH ?= $(shell uname -m) -install-helm-docs: - @hack/uget.sh https://github.com/norwoodj/helm-docs/releases/download/v{VERSION}/helm-docs_{VERSION}_{ENV:OS}_{ENV:ARCH}.tar.gz helm-docs $(HELM_DOCS_VERSION) helm-docs - -# e2e tests use this env name to locate the dex binary; make sure it's an absolute path -export DEX_BINARY = $(ROOT_DIR)/$(UGET_DIRECTORY)/dex-$(DEX_VERSION) - -.PHONY: install-dex -install-dex: $(DEX_BINARY) - -$(DEX_BINARY): - mkdir -p $(TOOLS_DIR) - git clone --branch $(DEX_VERSION) --depth 1 https://github.com/dexidp/dex $(TOOLS_DIR)/dex-clone-$(DEX_VERSION) || true - cd $(TOOLS_DIR)/dex-clone-$(DEX_VERSION) && GOWORK=off make build && cp bin/dex $(DEX_BINARY) - -# This target can be used to conveniently update the checksums for all checksummed tools. -# Combine with GOARCH to update for other archs, like "GOARCH=arm64 make update-tools". +.PHONY: codegen +codegen: + cd sdk && $(CONTROLLER_GEN) object paths=./apis/... + cd sdk && $(CONTROLLER_GEN) crd paths=./apis/... output:crd:dir=./config/crd + cp sdk/config/crd/core.kbind.io_*.yaml pkg/konnectorinstall/manifests/crds/ + cp sdk/config/crd/catalog.kbind.io_*.yaml sdk/config/crd/iam.kbind.io_*.yaml pkg/servicecrds/crds/ + +# Unit tests only. The envtest-based e2e (which needs KUBEBUILDER_ASSETS) is a +# separate target so `make test` runs with no external setup. +.PHONY: test +test: + go test $$(go list ./... | grep -v /test/e2e) + cd sdk && go test ./... -.PHONY: update-tools -update-tools: UGET_UPDATE=true -update-tools: clean-tools install-golangci-lint install-gotestsum install-boilerplate install-kcp install-helm install-goreleaser +# Run the envtest-based e2e (two in-process API servers + the engine). +.PHONY: test-e2e +test-e2e: + KUBEBUILDER_ASSETS="$$($(SETUP_ENVTEST) use $(ENVTEST_K8S_VERSION) -p path)" \ + go test ./test/e2e/... -count=1 -timeout 600s + +# Full kind-based e2e: build the image, load it into kind, helm-install the +# konnector, and assert the bind/sync flow end to end. Pass KEEP=1 to leave the +# clusters running, NO_BUILD=1 to reuse an already-loaded image. +.PHONY: test-e2e-kind +test-e2e-kind: + IMAGE=$(IMAGE) ./hack/e2e.sh + +.PHONY: vet +vet: + go vet ./... + cd sdk && go vet ./... .PHONY: lint -lint: install-golangci-lint install-logcheck ## Run golangci-lint - @if [ -n "$(WHAT)" ]; then \ - $(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m $(WHAT); \ - else \ - for MOD in $(GOMODS); do \ - (cd $$MOD; echo "Linting $$MOD"; $(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m); \ - done; \ - fi - -.PHONY: fix-lint -fix-lint: install-golangci-lint ## Run golangci-lint with --fix - GOLANGCI_LINT_FLAGS="--fix" $(MAKE) lint - -.PHONY: codegen -codegen: ## Generate code - go mod download - ./hack/update-codegen.sh - ./hack/update-codegen-clients.sh - $(MAKE) imports - -# Note, running this locally if you have any modified files, even those that are not generated, -# will result in an error. This target is mostly for CI jobs. -.PHONY: verify-codegen -verify-codegen: - if [[ -n "${GITHUB_WORKSPACE}" ]]; then \ - mkdir -p $$(go env GOPATH)/src/github.com/kube-bind; \ - ln -s ${GITHUB_WORKSPACE} $$(go env GOPATH)/src/github.com/kube-bind/kube-bind; \ - fi - - $(MAKE) codegen - - if ! git diff --quiet HEAD; then \ - git diff; \ - echo "You need to run 'make codegen' to update generated files and commit them"; \ - exit 1; \ - fi - -.PHONY: imports -imports: install-golangci-lint verify-go-versions ## Fix imports and format code - @if [ -n "$(WHAT)" ]; then \ - $(GOLANGCI_LINT) fmt --enable gci $(WHAT); \ - else \ - for MOD in $(GOMODS); do \ - ( cd $$MOD; $(GOLANGCI_LINT) fmt --enable gci -c $(ROOT_DIR)/.golangci.yaml; ) \ - done; \ - fi +lint: + $(GOLANGCI_LINT) run ./... + cd sdk && $(GOLANGCI_LINT) run ./... -.PHONY: verify-boilerplate -verify-boilerplate: install-boilerplate - $(TOOLS_DIR)/verify_boilerplate.py --boilerplate-dir=hack/boilerplate \ - --skip dex \ - --skip docs/venv \ - --skip docs/__pycache__ \ - --skip hack/uget.sh - -ifdef ARTIFACT_DIR -GOTESTSUM_ARGS += --junitfile=$(ARTIFACT_DIR)/junit.xml -endif - -GO_TEST = go test -ifdef USE_GOTESTSUM -GO_TEST = $(GOTESTSUM) $(GOTESTSUM_ARGS) -- -endif - -COUNT ?= 1 -# Only set parallelism if user specified E2E_PARALLELISM -ifdef E2E_PARALLELISM -E2E_PARALLELISM_FLAG := -p $(E2E_PARALLELISM) -parallel $(E2E_PARALLELISM) -else -E2E_PARALLELISM_FLAG := -endif - -.PHONY: run-dex -run-dex: $(DEX_BINARY) - $(DEX_BINARY) serve hack/dex-config-dev.yaml - -KCP = $(TOOLS_DIR)/kcp-$(KCP_VERSION) - -.PHONY: run-kcp -run-kcp: install-kcp - $(KCP) start --bind-address=127.0.0.1 - -.PHONY: run-kcp-infra -run-kcp-infra: install-kcp $(DEX_BINARY) ## Run kcp infrastructure for e2e tests (blocking) - mkdir -p .kcp - $(MAKE) run-dex 2>&1 & DEX_PID=$$!; \ - $(MAKE) run-kcp &>.kcp/kcp.log & KCP_PID=$$!; \ - trap 'kill -TERM $$DEX_PID $$KCP_PID; rm -rf .kcp' TERM INT EXIT && \ - echo "Waiting for kcp to be ready (check .kcp/kcp.log)." && while ! KUBECONFIG=.kcp/admin.kubeconfig kubectl get --raw /readyz &>/dev/null; do sleep 1; echo -n "."; done && echo && \ - echo "kcp is ready. Press Ctrl+C to stop." && \ - wait $$KCP_PID - -.PHONY: test-e2e-only -ifdef USE_GOTESTSUM -test-e2e-only: $(GOTESTSUM) -endif -test-e2e-only: TEST_ARGS ?= -test-e2e-only: WORK_DIR ?= . -test-e2e-only: WHAT ?= ./test/e2e... -test-e2e-only: build ## Run e2e tests against existing kcp infrastructure - KUBECONFIG=$$PWD/.kcp/admin.kubeconfig GOOS=$(OS) GOARCH=$(ARCH) $(GO_TEST) -race -v -count $(COUNT) $(E2E_PARALLELISM_FLAG) $(WHAT) $(TEST_ARGS) +.PHONY: tidy +tidy: + GOWORK=off go mod tidy + cd sdk && GOWORK=off go mod tidy -.PHONY: test-e2e -ifdef USE_GOTESTSUM -test-e2e: $(GOTESTSUM) -endif -test-e2e: TEST_ARGS ?= -test-e2e: WORK_DIR ?= . -test-e2e: TEST_WHAT ?= ./test/e2e... -test-e2e: $(DEX_BINARY) build ## Run e2e tests - mkdir .kcp - $(MAKE) run-kcp &>.kcp/kcp.log & KCP_PID=$$!; \ - trap 'kill -TERM $$KCP_PID; rm -rf .kcp' TERM INT EXIT && \ - echo "Waiting for kcp to be ready (check .kcp/kcp.log)." && while ! KUBECONFIG=.kcp/admin.kubeconfig kubectl get --raw /readyz &>/dev/null; do sleep 1; echo -n "."; done && echo && \ - KUBECONFIG=$$PWD/.kcp/admin.kubeconfig GOOS=$(OS) GOARCH=$(ARCH) $(GO_TEST) -race -count $(COUNT) $(E2E_PARALLELISM_FLAG) $(TEST_WHAT) $(TEST_ARGS) - -CONTRIBS_E2E := $(patsubst %,test-e2e-contrib-%,$(CONTRIBS)) - -.PHONY: test-e2e-contribs $(CONTRIBS_E2E) -test-e2e-contribs: $(CONTRIBS_E2E) ## Run e2e tests for external integrations - -.PHONY: test-e2e-contrib-kcp -test-e2e-contrib-kcp: $(DEX_BINARY) -$(CONTRIBS_E2E): - rm -rf .kcp - mkdir .kcp - $(MAKE) run-kcp &>.kcp/kcp.log & KCP_PID=$$!; \ - trap 'kill -TERM $$KCP_PID; rm -rf .kcp' TERM INT EXIT && \ - echo "Waiting for kcp to be ready (check .kcp/kcp.log)." && while ! KUBECONFIG=.kcp/admin.kubeconfig kubectl get --raw /readyz &>/dev/null; do sleep 1; echo -n "."; done && echo && \ - cd contrib/$(patsubst test-e2e-contrib-%,%,$@) && KUBECONFIG=$$PWD/../../.kcp/admin.kubeconfig $(GO_TEST) -race -count $(COUNT) $(E2E_PARALLELISM_FLAG) ./test/e2e/... +# Generate Apache license headers on source files. +.PHONY: generate-boilerplate +generate-boilerplate: + python3 hack/generate_boilerplate.py --boilerplate-dir=hack/boilerplate -.PHONY: test -ifdef USE_GOTESTSUM -test: $(GOTESTSUM) -endif -test: TEST_WHAT ?= ./... -# We will need to move into the sub package, of pkg/apis to run those tests. -test: ## Run unit tests - @if [ -n "$(TEST_WHAT)" ]; then \ - $(GO_TEST) -race -count $(COUNT) -coverprofile=coverage.txt -covermode=atomic $(TEST_ARGS) $$(go list "$(TEST_WHAT)" | grep -v ./test/e2e/); \ - else \ - for MOD in $(GOMODS); do \ - ( cd $$MOD; $(GO_TEST) -race -count $(COUNT) -coverprofile=coverage.txt -covermode=atomic $(TEST_ARGS) ) \ - done; \ - fi - -.PHONY: verify-imports -verify-imports: imports - if ! git diff --quiet HEAD; then \ - git diff; \ - echo "You need to run 'make imports' to update the immport statement ordering and commit them"; \ - exit 1; \ - fi - -.PHONY: verify-go-versions -verify-go-versions: - hack/verify-go-versions.sh - -.PHONY: modules -modules: ## Run go mod tidy to ensure modules are up to date - for MOD in $(GOMODS); do \ - (cd $$MOD; echo "Tidying $$MOD"; go mod tidy); \ - done - -.PHONY: verify-modules -verify-modules: modules # Verify go modules are up to date - @for MOD in $(GOMODS); do \ - (cd $$MOD; echo "Verifying $$MOD"; if ! git diff --quiet HEAD -- go.mod go.sum; then git diff -- go.mod go.sum; echo "[$$MOD] go modules are out of date, please run 'make modules'"; exit 1; fi; ) \ - done +# Verify Apache license headers on source files. +.PHONY: verify-boilerplate +verify-boilerplate: + python3 hack/verify_boilerplate.py --boilerplate-dir=hack/boilerplate --skip docs .PHONY: verify -verify: verify-go-versions verify-modules verify-imports verify-codegen verify-boilerplate verify-helm-docs ## verify formal properties of the code +verify: vet verify-boilerplate + +.PHONY: demo +demo: + ./hack/demo.sh + +# Tilt dev loop: two kind clusters (provider backend + consumer konnector), +# seeded catalog, rebuild-on-change — one command. +.PHONY: tilt +tilt: + ./hack/tilt/kind.sh + # --stream: no interactive HUD (make provides no TTY); the web UI is on + # http://localhost:10350 regardless. + cd hack/tilt && tilt up --stream + +# One-shot variant: deploy everything, wait until healthy, exit (CI-style). +.PHONY: tilt-ci +tilt-ci: + ./hack/tilt/kind.sh + cd hack/tilt && tilt ci + +# Tear the dev loop down: delete both kind clusters. +.PHONY: tilt-down +tilt-down: + kind delete cluster --name kbind-provider || true + kind delete cluster --name kbind-consumer || true + +# Helm publishing parameters +HELM ?= helm +HELM_REPO ?= ghcr.io/kbind-dev/charts +VERSION ?= 0.0.0-dev +CHART_VERSION ?= $(VERSION) +IMAGE_VERSION ?= v$(VERSION) +HELM_CHARTS ?= konnector-v2 backend-v2 + +## helm-push: Package and push Helm charts to $(HELM_REPO) as OCI artifacts +.PHONY: helm-push +helm-push: + mkdir -p bin/charts + @for chart in $(HELM_CHARTS); do \ + echo "==> packaging $$chart $(CHART_VERSION)"; \ + $(HELM) package deploy/charts/$$chart \ + --version $(CHART_VERSION) \ + --app-version $(IMAGE_VERSION) \ + --destination bin/charts || exit 1; \ + echo "==> pushing $$chart-$(CHART_VERSION).tgz to oci://$(HELM_REPO)"; \ + $(HELM) push bin/charts/$$chart-$(CHART_VERSION).tgz oci://$(HELM_REPO) || exit 1; \ + done -.PHONY: help -help: ## Show this help - @awk 'BEGIN { fs="## " } { FS=fs } /:.*##/ { doc=$$2; FS=":"; $$0=$$0; printf "\033[36m%-30s\033[0m %s\n", $$1, doc; }' $(MAKEFILE_LIST) | sort | grep -v fs= +.PHONY: docs-venv +docs-venv: + python3 -m venv $(DOCS_VENV) + $(DOCS_VENV)/bin/python -m pip install --upgrade pip + $(DOCS_VENV)/bin/python -m pip install -r docs/requirements.txt .PHONY: generate-cli-docs -generate-cli-docs: ## Generate cli docs - git clean -fdX docs/content/reference/cli - pushd . && cd docs/generators/cli-doc && go build . && popd - ./docs/generators/cli-doc/cli-doc -output docs/content/reference/cli +generate-cli-docs: + mkdir -p docs/content/reference/cli + go run ./docs/generators/cli-doc > docs/content/reference/cli/index.md .PHONY: generate-api-docs -generate-api-docs: ## Generate api docs - git clean -fdX docs/content/reference/api - docs/generators/crd-ref/run-crd-ref-gen.sh +generate-api-docs: + mkdir -p docs/content/reference/crd + $(CRD_REF_DOCS) --source-path=./sdk/apis \ + --config=docs/generators/crd-ref/config.yaml --renderer=markdown \ + --output-path=docs/content/reference/crd/index.md -VENVDIR=$(abspath docs/venv) -REQUIREMENTS_TXT=docs/requirements.txt +.PHONY: generate-docs +generate-docs: generate-cli-docs generate-api-docs -.PHONY: local-docs -local-docs: venv ## Run mkdocs serve - . $(VENV)/activate; \ - VENV=$(VENV) cd docs && mkdocs serve +.PHONY: build-docs +build-docs: generate-docs + cd docs && $(DOCS_VENV)/bin/mkdocs build --strict .PHONY: serve-docs -serve-docs: venv ## Serve docs - . $(VENV)/activate; \ - VENV=$(VENV) REMOTE=$(REMOTE) BRANCH=$(BRANCH) docs/scripts/serve-docs.sh +serve-docs: generate-docs + cd docs && $(DOCS_VENV)/bin/mkdocs serve .PHONY: deploy-docs -deploy-docs: venv ## Deploy docs - . $(VENV)/activate; \ - REMOTE=$(REMOTE) BRANCH=$(BRANCH) docs/scripts/deploy-docs.sh - -.PHONY: build-web -build-web: - cd web && npm run build - -LOGO_SOURCE = docs/images/logo.svg - -.PHONY: generate-logo-assets -generate-logo-assets: ## Generate logo and favicon assets from SVG - @command -v rsvg-convert >/dev/null 2>&1 || { echo "rsvg-convert not found; install librsvg (e.g. 'brew install librsvg')"; exit 1; } - mkdir -p docs/overrides web/src/assets - cp $(LOGO_SOURCE) docs/overrides/logo.svg - rsvg-convert -w 256 -h 256 $(LOGO_SOURCE) -o docs/images/logo.png - rsvg-convert -w 256 -h 256 $(LOGO_SOURCE) -o docs/overrides/logo.png - rsvg-convert -w 64 -h 64 $(LOGO_SOURCE) -o docs/overrides/favicon.png - rsvg-convert -w 128 -h 128 $(LOGO_SOURCE) -o web/src/assets/logo.png - rsvg-convert -w 64 -h 64 $(LOGO_SOURCE) -o web/src/assets/favicon.png - $(MAKE) build-web - -# Image / release configuration. -# IMAGE_TAGS is the space-separated list of tag suffixes applied to each component image. -# IMAGE_PUSH_PLATFORMS is the platform list for `image-push` (multi-arch by default). -# APP_VERSION is the application version passed to helm-build.sh; defaults to 0.0.0-$REV. -# helm-build.sh strips the leading "v" to derive a valid Helm chart semver. -# IMAGE_METADATA_DIR holds buildx metadata files used by `image-sign`. -export IMAGE_TAGS ?= $(REV) -IMAGE_PUSH_PLATFORMS ?= linux/amd64,linux/arm64 -export APP_VERSION ?= 0.0.0-$(REV) -IMAGE_METADATA_DIR ?= $(BUILD_DIR)/image-metadata - -# Example: make IMAGE_REPO=ghcr.io/ image-local -# Set PLATFORMS to override default architectures (e.g., make PLATFORMS=linux/amd64,linux/arm64 image-local) -# For local builds, default to current architecture on Linux platform to support --load -.PHONY: image-local -image-local: export PLATFORMS ?= linux/$(shell go env GOARCH) -image-local: ## Build images locally (single platform, --load) for the current commit - @LDFLAGS="$(LDFLAGS)" hack/build-image.sh - -# Dev example: -# make IMAGE_REPO=ghcr.io/ IMAGE_TAGS=v$(date -u +%Y%m%d) image-push -.PHONY: image-push -image-push: export PLATFORMS = $(IMAGE_PUSH_PLATFORMS) -image-push: export PUSH = true -image-push: export OUTPUT_DIR = $(IMAGE_METADATA_DIR) -image-push: ## Build multi-arch images and push to IMAGE_REPO with all IMAGE_TAGS - @LDFLAGS="$(LDFLAGS)" hack/build-image.sh - -.PHONY: image-sign -image-sign: export OUTPUT_DIR = $(IMAGE_METADATA_DIR) -image-sign: ## Cosign-sign pushed images by digest (requires cosign + image-push run first) - @hack/image-sign.sh - -.PHONY: release-images -release-images: image-push image-sign ## Build, push, and sign release images - -# Kind cluster configuration -KIND_CLUSTER ?= kbind -DOCKER_REPO ?= $(IMAGE_REPO) - -.PHONY: kind-load -kind-load: - @echo "Loading images into kind cluster '$(KIND_CLUSTER)'" - kind load docker-image $(DOCKER_REPO)/konnector:$(REV) --name $(KIND_CLUSTER) - kind load docker-image $(DOCKER_REPO)/backend:$(REV) --name $(KIND_CLUSTER) - @echo "Successfully loaded images into kind cluster '$(KIND_CLUSTER)'" - -.PHONY: helm-build-local -helm-build-local: ## Build and package Helm charts locally for testing - @hack/helm-build.sh - -.PHONY: helm-clean -helm-clean: ## Clean up built helm charts - rm -f ./bin/*.tgz - -.PHONY: goreleaser-test -goreleaser-test: install-goreleaser ## Test GoReleaser flow locally - LDFLAGS="$(LDFLAGS)" $(GORELEASER) release --snapshot --clean - -.PHONY: helm-push-local -helm-push-local: ## Push Helm charts to IMAGE_REPO registry - @hack/helm-push.sh - -.PHONY: release-helm -release-helm: helm-build-local helm-push-local ## Package and push helm charts to IMAGE_REPO - -.PHONY: helm-test -helm-test: helm-build-local ## Test Helm chart installation (dry-run) - @hack/helm-test.sh - -.PHONY: generate-helm-docs -generate-helm-docs: install-helm-docs ## Generate Helm chart documentation - $(HELM_DOCS) --chart-search-root deploy/charts - -.PHONY: verify-helm-docs -verify-helm-docs: generate-helm-docs ## Verify Helm chart documentation is up to date - @if ! git diff --quiet HEAD -- deploy/charts/**/README.md; then \ - git diff -- deploy/charts/**/README.md; \ - echo "Helm chart documentation is out of date, please run 'make generate-helm-docs'"; \ - exit 1; \ - fi - -include Makefile.venv +deploy-docs: build-docs + PATH="$(DOCS_VENV)/bin:$$PATH" bash docs/scripts/deploy-docs.sh diff --git a/Makefile.venv b/Makefile.venv deleted file mode 100644 index c79b9bbcd..000000000 --- a/Makefile.venv +++ /dev/null @@ -1,274 +0,0 @@ -# -# SEAMLESSLY MANAGE PYTHON VIRTUAL ENVIRONMENT WITH A MAKEFILE -# -# https://github.com/sio/Makefile.venv v2022.07.20 -# -# -# Insert `include Makefile.venv` at the bottom of your Makefile to enable these -# rules. -# -# When writing your Makefile use '$(VENV)/python' to refer to the Python -# interpreter within virtual environment and '$(VENV)/executablename' for any -# other executable in venv. -# -# This Makefile provides the following targets: -# venv -# Use this as a dependency for any target that requires virtual -# environment to be created and configured -# python, ipython -# Use these to launch interactive Python shell within virtual environment -# shell, bash, zsh -# Launch interactive command line shell. "shell" target launches the -# default shell Makefile executes its rules in (usually /bin/sh). -# "bash" and "zsh" can be used to refer to the specific desired shell. -# show-venv -# Show versions of Python and pip, and the path to the virtual environment -# clean-venv -# Remove virtual environment -# $(VENV)/executable_name -# Install `executable_name` with pip. Only packages with names matching -# the name of the corresponding executable are supported. -# Use this as a lightweight mechanism for development dependencies -# tracking. E.g. for one-off tools that are not required in every -# developer's environment, therefore are not included into -# requirements.txt or setup.py. -# Note: -# Rules using such target or dependency MUST be defined below -# `include` directive to make use of correct $(VENV) value. -# Example: -# codestyle: $(VENV)/pyflakes -# $(VENV)/pyflakes . -# See `ipython` target below for another example. -# -# This Makefile can be configured via following variables: -# PY -# Command name for system Python interpreter. It is used only initially to -# create the virtual environment -# Default: python3 -# REQUIREMENTS_TXT -# Space separated list of paths to requirements.txt files. -# Paths are resolved relative to current working directory. -# Default: requirements.txt -# -# Non-existent files are treated as hard dependencies, -# recipes for creating such files must be provided by the main Makefile. -# Providing empty value (REQUIREMENTS_TXT=) turns off processing of -# requirements.txt even when the file exists. -# SETUP_PY -# Space separated list of paths to setup.py files. -# Corresponding packages will be installed into venv in editable mode -# along with all their dependencies -# Default: setup.py -# -# Non-existent and empty values are treated in the same way as for REQUIREMENTS_TXT. -# WORKDIR -# Parent directory for the virtual environment. -# Default: current working directory. -# VENVDIR -# Python virtual environment directory. -# Default: $(WORKDIR)/.venv -# -# This Makefile was written for GNU Make and may not work with other make -# implementations. -# -# -# Copyright (c) 2019-2020 Vitaly Potyarkin -# -# Licensed under the Apache License, Version 2.0 -# -# - - -# -# Configuration variables -# - -WORKDIR?=. -VENVDIR?=$(WORKDIR)/.venv -REQUIREMENTS_TXT?=$(wildcard requirements.txt) # Multiple paths are supported (space separated) -SETUP_PY?=$(wildcard setup.py) # Multiple paths are supported (space separated) -SETUP_CFG?=$(foreach s,$(SETUP_PY),$(wildcard $(patsubst %setup.py,%setup.cfg,$(s)))) -MARKER=.initialized-with-Makefile.venv - - -# -# Python interpreter detection -# - -_PY_AUTODETECT_MSG=Detected Python interpreter: $(PY). Use PY environment variable to override - -ifeq (ok,$(shell test -e /dev/null 2>&1 && echo ok)) -NULL_STDERR=2>/dev/null -else -NULL_STDERR=2>NUL -endif - -ifndef PY -_PY_OPTION:=python3 -ifeq (ok,$(shell $(_PY_OPTION) -c "print('ok')" $(NULL_STDERR))) -PY=$(_PY_OPTION) -endif -endif - -ifndef PY -_PY_OPTION:=$(VENVDIR)/bin/python -ifeq (ok,$(shell $(_PY_OPTION) -c "print('ok')" $(NULL_STDERR))) -PY=$(_PY_OPTION) -$(info $(_PY_AUTODETECT_MSG)) -endif -endif - -ifndef PY -_PY_OPTION:=$(subst /,\,$(VENVDIR)/Scripts/python) -ifeq (ok,$(shell $(_PY_OPTION) -c "print('ok')" $(NULL_STDERR))) -PY=$(_PY_OPTION) -$(info $(_PY_AUTODETECT_MSG)) -endif -endif - -ifndef PY -_PY_OPTION:=py -3 -ifeq (ok,$(shell $(_PY_OPTION) -c "print('ok')" $(NULL_STDERR))) -PY=$(_PY_OPTION) -$(info $(_PY_AUTODETECT_MSG)) -endif -endif - -ifndef PY -_PY_OPTION:=python -ifeq (ok,$(shell $(_PY_OPTION) -c "print('ok')" $(NULL_STDERR))) -PY=$(_PY_OPTION) -$(info $(_PY_AUTODETECT_MSG)) -endif -endif - -ifndef PY -define _PY_AUTODETECT_ERR -Could not detect Python interpreter automatically. -Please specify path to interpreter via PY environment variable. -endef -$(error $(_PY_AUTODETECT_ERR)) -endif - - -# -# Internal variable resolution -# - -VENV=$(VENVDIR)/bin -EXE= -# Detect windows -ifeq (win32,$(shell $(PY) -c "import __future__, sys; print(sys.platform)")) -VENV=$(VENVDIR)/Scripts -EXE=.exe -endif - -touch=touch $(1) -ifeq (,$(shell command -v touch $(NULL_STDERR))) -# https://ss64.com/nt/touch.html -touch=type nul >> $(subst /,\,$(1)) && copy /y /b $(subst /,\,$(1))+,, $(subst /,\,$(1)) -endif - -RM?=rm -f -ifeq (,$(shell command -v $(firstword $(RM)) $(NULL_STDERR))) -RMDIR:=rd /s /q -else -RMDIR:=$(RM) -r -endif - - -# -# Virtual environment -# - -.PHONY: venv -venv: $(VENV)/$(MARKER) - -.PHONY: clean-venv -clean-venv: - -$(RMDIR) "$(VENVDIR)" - -.PHONY: show-venv -show-venv: venv - @$(VENV)/python -c "import sys; print('Python ' + sys.version.replace('\n',''))" - @$(VENV)/pip --version - @echo venv: $(VENVDIR) - -.PHONY: debug-venv -debug-venv: - @echo "PATH (Shell)=$$PATH" - @$(MAKE) --version - $(info PATH (GNU Make)="$(PATH)") - $(info SHELL="$(SHELL)") - $(info PY="$(PY)") - $(info REQUIREMENTS_TXT="$(REQUIREMENTS_TXT)") - $(info SETUP_PY="$(SETUP_PY)") - $(info SETUP_CFG="$(SETUP_CFG)") - $(info VENVDIR="$(VENVDIR)") - $(info VENVDEPENDS="$(VENVDEPENDS)") - $(info WORKDIR="$(WORKDIR)") - - -# -# Dependencies -# - -ifneq ($(strip $(REQUIREMENTS_TXT)),) -VENVDEPENDS+=$(REQUIREMENTS_TXT) -endif - -ifneq ($(strip $(SETUP_PY)),) -VENVDEPENDS+=$(SETUP_PY) -endif -ifneq ($(strip $(SETUP_CFG)),) -VENVDEPENDS+=$(SETUP_CFG) -endif - -$(VENV): - $(PY) -m venv $(VENVDIR) - $(VENV)/python -m pip install --upgrade pip setuptools wheel - -$(VENV)/$(MARKER): $(VENVDEPENDS) | $(VENV) -ifneq ($(strip $(REQUIREMENTS_TXT)),) - $(VENV)/pip install $(foreach path,$(REQUIREMENTS_TXT),-r $(path)) -endif -ifneq ($(strip $(SETUP_PY)),) - $(VENV)/pip install $(foreach path,$(SETUP_PY),-e $(dir $(path))) -endif - $(call touch,$(VENV)/$(MARKER)) - - -# -# Interactive shells -# - -.PHONY: python -python: venv - exec $(VENV)/python - -.PHONY: ipython -ipython: $(VENV)/ipython - exec $(VENV)/ipython - -.PHONY: shell -shell: venv - . $(VENV)/activate && exec $(notdir $(SHELL)) - -.PHONY: bash zsh -bash zsh: venv - . $(VENV)/activate && exec $@ - - -# -# Commandline tools (wildcard rule, executable name must match package name) -# - -ifneq ($(EXE),) -$(VENV)/%: $(VENV)/%$(EXE) ; -.PHONY: $(VENV)/% -.PRECIOUS: $(VENV)/%$(EXE) -endif - -$(VENV)/%$(EXE): $(VENV)/$(MARKER) - $(VENV)/pip install --upgrade $* - $(call touch,$@) diff --git a/OWNERS b/OWNERS deleted file mode 100644 index e721f3c3c..000000000 --- a/OWNERS +++ /dev/null @@ -1,12 +0,0 @@ -approvers: -- moadqassem -- s-urbaniak -- sttts -- mjudeikis -- cnvergence -- xrstf -- ntnn - -emeritus_approvers: -- pkbhowmick -- lhaendler \ No newline at end of file diff --git a/README.md b/README.md index ac3a25dc4..90fc15301 100644 --- a/README.md +++ b/README.md @@ -11,72 +11,67 @@ You are invited to [contribute](#contributing)! kbind (formerly known as kube-bind) provides better support for service providers and consumers that reside in distinct Kubernetes clusters. -- A service provider defines its API in terms of CRDs and associated permission claims/limitations, and exports it for use from other clusters. +- A service provider defines its API in terms of CRDs, exports it for use from other clusters, and controls access through Kubernetes RBAC. - Service consumers identify the services they want to consume. - The service CRDs get installed in the service consumer clusters, with objects of the defined kinds written and read by the service consumers. - The service provider indirectly reads and writes those objects as the interface to the service that it provides. - The service provider does not inject controllers/operators into the service consumer's cluster. -- A single vendor-neutral, OpenSource agent per consumer cluster connects it with the requested services. +- A single vendor-neutral, OpenSource agent per consumer cluster, the **konnector**, connects it with the requested services. ## Try it out -This is the 3 line pitch: +Follow the [Quickstart](docs/content/setup/quickstart.md) to try v2 with two local Kubernetes clusters. It runs from source without depending on a published v2 release. + +With the [CLI installed](docs/content/setup/kubectl-plugin.md), a [provider offering a `widgets` API](docs/content/developers/backend/index.md), and the [v2 konnector installed](docs/content/setup/helm.md) in your consumer cluster: ```shell -$ kubectl krew index add bind https://github.com/kube-bind/krew-index.git -$ kubectl krew install bind/bind -$ kubectl bind login https://mangodb -$ kubectl bind -Redirect to the browser to authenticate via OIDC. -BOOM – the MangoDB API is available in the local cluster, - without anything MangoDB-specific running. -$ kubectl get mangodbs +kubectl bind login https://bind.example.com +kubectl bind export widgets --kubeconfig=./consumer.kubeconfig --install-konnector=false ``` +Replace the provider URL and consumer kubeconfig with your own. The konnector makes the Widget API available in the consumer cluster, without a Widget-specific controller running there. See the [CLI guide](docs/content/setup/kubectl-plugin.md) for details. + ## For more information -For more information go to https://kbind.dev or watch the [ContainerDays talk](https://www.youtube.com/watch?v=dg0g15Qv5Fo&t=1s) -or the [KubeCon talk](https://www.youtube.com/watch?v=Uv0ivz5xej4). +For more information go to https://kbind.dev or watch the [ContainerDays talk](https://www.youtube.com/watch?v=dg0g15Qv5Fo&t=1s) or the [KubeCon talk](https://www.youtube.com/watch?v=Uv0ivz5xej4). kbind is following this manifesto from the linked talk: -![kbind manifesto](docs/images/manifesto.png) +Let's design a post-operator / post-cluster technology, that allows a service provider persona as a first-class citizen and can securely provide centrally operated kube-native services. ## Contributing We ❤️ our contributors! If you're interested in helping us out, please check out -[Contributing to kbind](./CONTRIBUTING.md) and [kbind Project Governance](./GOVERNANCE.md). +[Contributing to kbind](docs/content/contributing/index.md) and [kbind Project Governance](https://github.com/kbind-dev/kbind/blob/main/GOVERNANCE.md). + +The [developer guide](docs/content/developers/index.md) covers the architecture, development environments, builds, tests, and code generation. ## Getting in touch There are several ways to communicate with us: -- The [`#kube-bind` channel](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io) +- The [`#kbind-dev` channel](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io). - Our mailing list [kube-bind-dev](https://groups.google.com/g/kube-bind-dev) for development discussions. -- Our bi-weekly community meetings — every second Thursday at 11am EST (5pm CET). - - By joining the [kube-bind-dev mailing list](https://groups.google.com/g/kube-bind-dev), you should receive an invite. - - See our [community meeting notes document](https://docs.google.com/document/d/1qztpKOmdZu5iWq_4N9n3AZpcAPuPhBiGNbje5GPg0iM) for upcoming and past agendas. - - - - +- Our bi-weekly community meetings, every second Thursday at 11am EST (5pm CET). + Join the mailing list for an invite and see our [community meeting notes](https://docs.google.com/document/d/1qztpKOmdZu5iWq_4N9n3AZpcAPuPhBiGNbje5GPg0iM) for upcoming and past agendas. -See the [community page](https://docs.kbind.dev/main/community) for more details. +See the [community page](docs/content/community/index.md) for more details. ## Technical Overview -overview +![Technical overview of kbind connecting consumer and provider clusters](docs/content/images/overview.png) -All the actions shown between the clusters are done by the konnector, except: the pull at the start is done by the kubectl plugin that installs the konnector. +The konnector connects directly to the provider's Kubernetes API. The backend +adds a catalog, authentication, and credential issuance, but is not required for +synchronization. See the [architecture guide](docs/content/developers/architecture.md) for the implementation details. ## Usage -To get familiar with setting up the environment, please check out docs at [kbind.dev](https://docs.kbind.dev/main/setup). +To get familiar with setting up the environment, please check out the +[setup guide](docs/content/setup/index.md) and [usage guide](docs/content/usage/index.md). For an existing installation, start with [Moving from 0.x](docs/content/usage/migration.md). ### Limitations -These limitations are part of the roadmap and will be addressed in the future. - -* Currently we don't support related resources, like ConfigMaps, Secrets. -* We don't support lifecycle of `BoundSchema` resources, like schema changes. -* The backend currently does not support running with replicas > 1 due to missing external session storage implementation. Session storage is currently in-memory only, which prevents proper session sharing across multiple backend instances. +Resource scope, namespace, and name are preserved between +clusters. Namespace isolation must be arranged by the deployment. +See [API concepts](docs/content/usage/api-concepts.md) for schema limitations and [Resource Synchronization](docs/content/usage/synchronization.md) for isolation and cleanup behavior. diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index 0e630375b..000000000 --- a/ROADMAP.md +++ /dev/null @@ -1,67 +0,0 @@ -# kbind Roadmap - -This roadmap reflects the current direction of the kbind project. -Items are grouped by theme, not strict release milestones. -Track progress via [GitHub Issues](https://github.com/kbind-dev/kbind/issues). - -## 🏗️ Production Readiness - -- **Pluggable session storage** — replace in-memory backend session storage with - an external/pluggable implementation, enabling replicas > 1 for HA deployments - ([#424](https://github.com/kbind-dev/kbind/issues/424), - [#488](https://github.com/kbind-dev/kbind/issues/488)) -- **CRD lifecycle / BoundSchema changes** — support schema evolution after initial - binding, including updates and versioning - ([#404](https://github.com/kbind-dev/kbind/issues/404)) -- **Delete flow** — full lifecycle support for APIServiceExport deletion and - graceful unbinding - ([#352](https://github.com/kbind-dev/kbind/issues/352)) -- **Backend production hardening** — address remaining gaps for production-grade - deployments ([#284](https://github.com/kbind-dev/kbind/issues/284)) - -## 🔌 Feature Completeness - -- **Related resources** — support binding of associated resources such as - ConfigMaps and Secrets alongside primary CRDs -- **Multi-provider/consumer support** — allow a single consumer cluster to bind - the same CRD from multiple providers, and other multi-tenancy scenarios - ([#321](https://github.com/kbind-dev/kbind/issues/321)) -- **Object metadata propagation** — propagate selected labels/annotations between - provider and consumer objects - ([#315](https://github.com/kbind-dev/kbind/issues/315)) -- **Reduced konnector permissions** — tighten RBAC footprint of the konnector - agent in consumer clusters - ([#303](https://github.com/kbind-dev/kbind/issues/303)) -- **UI-only binding flow** — allow service binding without CLI, purely via - browser/OIDC redirect flow - ([#406](https://github.com/kbind-dev/kbind/issues/406)) -- **Dry-run support** — fix `--dry-run` in `bind apiservice` - ([#365](https://github.com/kbind-dev/kbind/issues/365)) - -## 🌐 Ecosystem Integration - -- **kcp integration** — make the konnector kcp-aware and support serving from - APIBindings ([#317](https://github.com/kbind-dev/kbind/issues/317), - [#300](https://github.com/kbind-dev/kbind/issues/300), - [#323](https://github.com/kbind-dev/kbind/issues/323)) -- **multicluster-runtime refactor** — refactor the konnector to use - [multicluster-runtime](https://github.com/kubernetes-sigs/multicluster-runtime) - for improved multi-cluster controller patterns - ([#299](https://github.com/kbind-dev/kbind/issues/299)) -- **PlatformMesh integration** — provider-side integration with PlatformMesh - ([#447](https://github.com/kbind-dev/kbind/issues/447)) - -## 📖 Documentation & Community - -- Blog post on external integrations - ([#452](https://github.com/kbind-dev/kbind/issues/452)) -- CNCF Sandbox application - ([#448](https://github.com/kbind-dev/kbind/issues/448)) -- Adopters file - ---- - -This roadmap is maintained by the [kube-bind maintainers](./MAINTAINERS.md). -Contributions and feedback welcome via -[GitHub Discussions](https://github.com/kbind-dev/kbind/discussions) or -[`#kube-bind`](https://kubernetes.slack.com/archives/C046PRXNJ4W) on Kubernetes Slack. diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index d93d11225..000000000 --- a/SECURITY.md +++ /dev/null @@ -1,18 +0,0 @@ -# Security Process for kbind - -## Reporting a Vulnerability - -kbind uses GitHub to allow submission of private security reports. Please report any security finding via -[this link](https://github.com/kbind-dev/kbind/security/advisories/new). -Maintainers will triage your report as soon as possible and get in touch with you via your report in case they have more questions. - -As a security researcher, please report vulnerabilities to kbind in a [coordinated vulnerability disclosure (CVD)](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html) -fashion. - -In return, maintainers pledge to engage in good faith and collaborate with security researchers to address and publish vulnerabilities found in kbind as soon as possible. We will not pursue or support legal action for good‑faith security research that adheres to this policy and avoids privacy violations, data exfiltration, or service disruption. - -Please understand that the maintainers also do not accept results of dependency scanners without proof that the detected CVE / vulnerability can be used against kbind. - -## Security Advisories - -Advisories are managed through GitHub Security Advisories. Where applicable, we request CVE IDs via GitHub’s CNA during the advisory process and credit reporters upon release. Please visit [Security Advisories](https://github.com/kbind-dev/kbind/security/advisories) to review security bulletins published by the maintainers. diff --git a/backend/auth/authenticator.go b/backend/auth/authenticator.go new file mode 100644 index 000000000..84a45363c --- /dev/null +++ b/backend/auth/authenticator.go @@ -0,0 +1,51 @@ +/* +Copyright 2026 The kbind 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 auth is the gateway's pluggable authentication layer. An +// Authenticator turns HTTP requests into consumer identities; OIDC is the +// reference implementation, not the contract. Sessions are stateless +// encrypted tokens (cookie or bearer), so any number of gateway replicas +// works with shared keys and no session store. +package auth + +import ( + "errors" + "net/http" +) + +// Identity is an authenticated consumer identity. Subject is the stable +// tenancy key ("#" for OIDC): the same human gets the same +// provider-side boundary on re-bind. +type Identity struct { + Subject string `json:"subject"` + DisplayName string `json:"displayName,omitempty"` + Groups []string `json:"groups,omitempty"` +} + +// ErrUnauthenticated is returned when a request carries no (valid) identity. +var ErrUnauthenticated = errors.New("unauthenticated") + +// Authenticator authenticates gateway requests. Implementations mount their +// interactive flow (if any) under /api/auth//. +type Authenticator interface { + // Name identifies the method (e.g. "oidc"), surfaced in /api/provider. + Name() string + // RegisterRoutes mounts the authenticator's HTTP flow on mux. + RegisterRoutes(mux *http.ServeMux) + // Authenticate extracts the identity from a request, or + // ErrUnauthenticated. + Authenticate(r *http.Request) (*Identity, error) +} diff --git a/backend/auth/handler.go b/backend/auth/handler.go deleted file mode 100644 index 95ac395c3..000000000 --- a/backend/auth/handler.go +++ /dev/null @@ -1,382 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 auth - -import ( - "context" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/gorilla/securecookie" - "golang.org/x/oauth2" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/backend/client" - "github.com/kube-bind/kube-bind/backend/session" -) - -type OIDCProvider interface { - GetOIDCProvider(ctx context.Context) (*OIDCServiceProvider, error) -} - -type AuthHandlerInterface interface { - HandleAuthorize(w http.ResponseWriter, r *http.Request) - HandleCallback(w http.ResponseWriter, r *http.Request) -} - -type AuthHandler struct { - oidc OIDCProvider - jwtService *JWTService - cookieSigningKey []byte - cookieEncryptionKey []byte - sessionStore session.Store - tokenExpiry time.Duration -} - -const maxCallbackFormSize int64 = 1 << 20 // 1 MiB - -func NewAuthHandler(oidc OIDCProvider, jwtService *JWTService, cookieSigningKey, cookieEncryptionKey []byte, sessionStore session.Store, tokenExpiry time.Duration) *AuthHandler { - return &AuthHandler{ - oidc: oidc, - jwtService: jwtService, - cookieSigningKey: cookieSigningKey, - cookieEncryptionKey: cookieEncryptionKey, - sessionStore: sessionStore, - tokenExpiry: tokenExpiry, - } -} - -func (ah *AuthHandler) HandleAuthorize(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()).WithValues("method", r.Method, "url", r.URL.String()) - - params := client.GetQueryParams(r) - - var authReq AuthorizeRequest - if r.Method == http.MethodPost { - if err := json.NewDecoder(r.Body).Decode(&authReq); err != nil { - ah.respondWithError(w, authReq.ClientType, "invalid JSON request", http.StatusBadRequest) - return - } - } else { - authReq = AuthorizeRequest{ - RedirectURL: params.RedirectURL, - SessionID: params.SessionID, - ClusterID: params.ClusterID, - ClientType: ClientType(params.ClientType), - ConsumerID: params.ConsumerID, - } - } - - logger.V(2).Info("AuthorizeRequest prepared", "authReq", authReq, "params", params) - - if authReq.RedirectURL == "" || authReq.SessionID == "" { - logger.Error(errors.New("missing required parameters"), "failed to authorize") - ah.respondWithError(w, authReq.ClientType, "missing redirect_url or session_id", http.StatusBadRequest) - return - } - - scopes := []string{"openid", "profile", "email", "offline_access", "groups"} - dataCode, err := json.Marshal(authReq) - if err != nil { - logger.Error(err, "failed to marshal auth code") - ah.respondWithError(w, authReq.ClientType, err.Error(), http.StatusInternalServerError) - return - } - - provider, err := ah.oidc.GetOIDCProvider(r.Context()) - if err != nil { - logger.Error(err, "failed to get OIDC provider") - ah.respondWithError(w, authReq.ClientType, err.Error(), http.StatusInternalServerError) - return - } - - encoded := base64.URLEncoding.EncodeToString(dataCode) - - verifier, challenge, err := generatePKCE() - if err != nil { - logger.Error(err, "failed to generate PKCE") - ah.respondWithError(w, authReq.ClientType, "failed to generate PKCE", http.StatusInternalServerError) - return - } - if err := ah.sessionStore.SavePKCEVerifier(r.Context(), authReq.SessionID, verifier); err != nil { - logger.Error(err, "failed to store PKCE verifier") - ah.respondWithError(w, authReq.ClientType, "failed to store PKCE verifier", http.StatusInternalServerError) - return - } - - opts := []oauth2.AuthCodeOption{ - oauth2.SetAuthURLParam("code_challenge", challenge), - oauth2.SetAuthURLParam("code_challenge_method", "S256"), - } - authURL := provider.OIDCProviderConfig(scopes).AuthCodeURL(encoded, opts...) - - http.Redirect(w, r, authURL, http.StatusFound) -} - -func (ah *AuthHandler) HandleCallback(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()).WithValues("method", r.Method, "url", r.URL.String()) - - r.Body = http.MaxBytesReader(w, r.Body, maxCallbackFormSize) - if err := r.ParseForm(); err != nil { - logger.Error(err, "failed to parse form") - ah.respondWithError(w, "", "failed to parse form", http.StatusBadRequest) - return - } - - state := r.Form.Get("state") - if state == "" { - state = r.URL.Query().Get("state") - } - - // URL decode the state parameter first (in case it's URL encoded) - if decodedState, err := url.QueryUnescape(state); err == nil { - state = decodedState - } - - decoded, err := base64.URLEncoding.DecodeString(state) - if err != nil { - logger.Error(err, "failed to decode state") - ah.respondWithError(w, "", "invalid state parameter", http.StatusBadRequest) - return - } - - authCode := &AuthorizeRequest{} - if err := json.Unmarshal(decoded, authCode); err != nil { - logger.Error(err, "failed to unmarshal authCode") - ah.respondWithError(w, authCode.ClientType, "invalid state format", http.StatusBadRequest) - return - } - - if errMsg := r.Form.Get("error"); errMsg != "" { - desc := r.Form.Get("error_description") - logger.Error(errors.New(errMsg), "OIDC provider returned error", "description", desc) - ah.respondWithError(w, authCode.ClientType, fmt.Sprintf("%s: %s", errMsg, desc), http.StatusBadRequest) - return - } - - code := r.Form.Get("code") - if code == "" { - code = r.URL.Query().Get("code") - } - if code == "" { - logger.Error(errors.New("missing code"), "no code in request") - ah.respondWithError(w, authCode.ClientType, "no authorization code in request", http.StatusBadRequest) - return - } - logger.V(2).Info("HandleCallback state unmarshaled", "authCode", authCode) - - provider, err := ah.oidc.GetOIDCProvider(r.Context()) - if err != nil { - logger.Info("failed to get OIDC provider", "error", err) - ah.respondWithError(w, authCode.ClientType, "failed to get OIDC provider", http.StatusInternalServerError) - return - } - - // Create context with custom HTTP client if TLS config is available - ctx := r.Context() - if tlsConfig := provider.GetTLSConfig(); tlsConfig != nil { - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - }, - } - ctx = context.WithValue(ctx, oauth2.HTTPClient, client) - } - - verifier, err := ah.sessionStore.LoadAndDeletePKCEVerifier(r.Context(), authCode.SessionID) - if err != nil || verifier == "" { - logger.Error(err, "PKCE verifier not found for session; cannot exchange code", "sessionID", authCode.SessionID) - msg := "PKCE verifier not found. If you run multiple backend instances, use a shared session store (e.g. Redis) so the instance handling the callback can read the verifier stored at authorize time." - ah.respondWithError(w, authCode.ClientType, msg, http.StatusBadRequest) - return - } - - exchangeOpts := []oauth2.AuthCodeOption{oauth2.VerifierOption(verifier)} - token, err := provider.OIDCProviderConfig(nil).Exchange(ctx, code, exchangeOpts...) - if err != nil { - logger.Error(err, "failed to exchange token") - ah.respondWithError(w, authCode.ClientType, "failed to exchange authorization code for token", http.StatusInternalServerError) - return - } - - sessionState, err := ah.createSessionState(authCode, token) - if err != nil { - logger.Error(err, "failed to create session sessionState") - ah.respondWithError(w, authCode.ClientType, "failed to create user session", http.StatusInternalServerError) - return - } - // Set session expiration and store in middleware - err = ah.sessionStore.Save(r.Context(), sessionState) - if err != nil { - logger.Error(err, "failed to save session state") - ah.respondWithError(w, authCode.ClientType, "failed to save session state", http.StatusInternalServerError) - return - } - - // Detect client type from redirect URL or user agent - clientType := authCode.ClientType - - if clientType == ClientTypeCLI { - // Generate JWT token for CLI - jwtToken, err := ah.jwtService.GenerateToken( - sessionState.Token.Subject, - sessionState.Token.Issuer, - sessionState.SessionID, - sessionState.ClusterID, - sessionState.RedirectURL, - sessionState.Token.Groups, - 24*time.Hour, // 24 hours expiration - ) - if err != nil { - logger.Error(err, "failed to generate JWT token") - ah.respondWithError(w, authCode.ClientType, "failed to generate JWT token", http.StatusInternalServerError) - return - } - - // Redirect to CLI redirect with JWT token - parsedRedirectURL, err := url.Parse(authCode.RedirectURL) - if err != nil { - logger.Error(err, "failed to parse redirect URL") - ah.respondWithError(w, authCode.ClientType, "failed to parse redirect URL", http.StatusInternalServerError) - return - } - - values := parsedRedirectURL.Query() - values.Add("access_token", jwtToken) - values.Add("token_type", "Bearer") - values.Add("expires_in", "86400") // 24 hours - if authCode.ClusterID != "" { - values.Add("cluster_id", authCode.ClusterID) - } - parsedRedirectURL.RawQuery = values.Encode() - - http.Redirect(w, r, parsedRedirectURL.String(), http.StatusFound) - return - } - - // UI flow - set cookie and redirect to UI - cookieName := ah.generateCookieName(authCode.ClusterID) - - s := securecookie.New(ah.cookieSigningKey, ah.cookieEncryptionKey) - encoded, err := s.Encode(cookieName, sessionState) - if err != nil { - logger.Error(err, "failed to encode secure session cookie") - ah.respondWithError(w, authCode.ClientType, "failed to encode session cookie", http.StatusInternalServerError) - return - } - - secure := false - http.SetCookie(w, session.MakeCookie(r, cookieName, encoded, secure, 1*time.Hour)) - - clientParams := &client.ClientParameters{ - ClusterID: authCode.ClusterID, - RedirectURL: authCode.RedirectURL, - SessionID: authCode.SessionID, - } - url := clientParams.WithParams(authCode.RedirectURL) - - http.Redirect(w, r, url, http.StatusFound) -} - -func (ah *AuthHandler) respondWithError(w http.ResponseWriter, clientType ClientType, message string, statusCode int) { - if clientType != ClientTypeCLI { - http.Error(w, message, statusCode) - return - } - - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(statusCode) - err := json.NewEncoder(w).Encode(AuthResponse{ - Success: false, - Error: message, - }) - if err != nil { - http.Error(w, "internal error", http.StatusInternalServerError) - } -} - -func (ah *AuthHandler) generateCookieName(clusterID string) string { - if clusterID == "" { - return "kube-bind" - } - return fmt.Sprintf("kube-bind-%s", clusterID) -} - -func (ah *AuthHandler) createSessionState(authCode *AuthorizeRequest, token *oauth2.Token) (*session.State, error) { - jwtStr, ok := token.Extra("id_token").(string) - if !ok { - return nil, errors.New("no id_token value found in token") - } - - jwt, err := ah.unwrapJWT(jwtStr) - if err != nil { - return nil, fmt.Errorf("failed to unpack ID token: %w", err) - } - - var idToken struct { - Subject string `json:"sub"` - Issuer string `json:"iss"` - Groups []string `json:"groups,omitempty"` - } - if err := json.Unmarshal(jwt, &idToken); err != nil { - return nil, fmt.Errorf("failed to parse ID token: %w", err) - } - - s := &session.State{ - Token: session.TokenInfo{ - Subject: idToken.Subject, - Issuer: idToken.Issuer, - Groups: idToken.Groups, - }, - SessionID: authCode.SessionID, - ClusterID: authCode.ClusterID, - RedirectURL: authCode.RedirectURL, - } - s.SetExpiration(ah.tokenExpiry) - return s, nil -} - -func (ah *AuthHandler) unwrapJWT(p string) ([]byte, error) { - parts := strings.Split(p, ".") - if len(parts) < 2 { - return nil, fmt.Errorf("OIDC: malformed JWT, expected 3 parts, got %d", len(parts)) - } - payload, err := base64.RawURLEncoding.DecodeString(parts[1]) - if err != nil { - return nil, fmt.Errorf("OIDC: malformed JWT payload: %w", err) - } - return payload, nil -} - -func generatePKCE() (string, string, error) { - data := make([]byte, 32) - if _, err := rand.Read(data); err != nil { - return "", "", err - } - verifier := base64.RawURLEncoding.EncodeToString(data) - hash := sha256.Sum256([]byte(verifier)) - challenge := base64.RawURLEncoding.EncodeToString(hash[:]) - return verifier, challenge, nil -} diff --git a/backend/auth/jwt.go b/backend/auth/jwt.go deleted file mode 100644 index 473956bff..000000000 --- a/backend/auth/jwt.go +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 auth - -import ( - "crypto/rand" - "crypto/rsa" - "fmt" - "time" - - "github.com/golang-jwt/jwt/v5" -) - -type JWTService struct { - privateKey *rsa.PrivateKey - publicKey *rsa.PublicKey - issuer string -} - -type Claims struct { - Subject string `json:"sub"` - Issuer string `json:"iss"` - SessionID string `json:"sid"` - ClusterID string `json:"cid"` - Groups []string `json:"groups,omitempty"` - RedirectURL string `json:"red,omitempty"` - jwt.RegisteredClaims -} - -func NewJWTService(issuer string) (*JWTService, error) { - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return nil, fmt.Errorf("failed to generate RSA private key: %w", err) - } - - return &JWTService{ - privateKey: privateKey, - publicKey: &privateKey.PublicKey, - issuer: issuer, - }, nil -} - -func (js *JWTService) GenerateToken(subject, oidcIssuer, sessionID, clusterID, redirectURL string, groups []string, expiration time.Duration) (string, error) { - now := time.Now() - claims := &Claims{ - Subject: subject, - Issuer: oidcIssuer, - SessionID: sessionID, - ClusterID: clusterID, - Groups: groups, - RedirectURL: redirectURL, - RegisteredClaims: jwt.RegisteredClaims{ - Subject: subject, - Issuer: js.issuer, - IssuedAt: jwt.NewNumericDate(now), - ExpiresAt: jwt.NewNumericDate(now.Add(expiration)), - NotBefore: jwt.NewNumericDate(now), - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) - return token.SignedString(js.privateKey) -} - -func (js *JWTService) ValidateToken(tokenString string) (*Claims, error) { - token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) - } - return js.publicKey, nil - }) - - if err != nil { - return nil, fmt.Errorf("failed to parse token: %w", err) - } - - if claims, ok := token.Claims.(*Claims); ok && token.Valid { - return claims, nil - } - - return nil, fmt.Errorf("invalid token") -} - -func (js *JWTService) GetPublicKey() *rsa.PublicKey { - return js.publicKey -} diff --git a/backend/auth/kubernetes.go b/backend/auth/kubernetes.go new file mode 100644 index 000000000..b2fd3efe2 --- /dev/null +++ b/backend/auth/kubernetes.go @@ -0,0 +1,81 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "fmt" + "net/http" + + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/rest" +) + +// Kubernetes authenticates bearer tokens with a TokenReview against the +// provider cluster — the second reference Authenticator, for in-platform +// callers (UIs, controllers) that already hold a provider-cluster identity +// and should not need a second SSO round trip. It has no interactive flow: +// the caller simply sends its own token as "Authorization: Bearer". +type Kubernetes struct { + client kubernetes.Interface +} + +// NewKubernetes builds the TokenReview authenticator for the cluster behind +// cfg (the provider). +func NewKubernetes(cfg *rest.Config) (*Kubernetes, error) { + clientset, err := kubernetes.NewForConfig(cfg) + if err != nil { + return nil, fmt.Errorf("building kubernetes authenticator client: %w", err) + } + return &Kubernetes{client: clientset}, nil +} + +// NewKubernetesFromClientset is the injection point for tests. +func NewKubernetesFromClientset(clientset kubernetes.Interface) *Kubernetes { + return &Kubernetes{client: clientset} +} + +// Name implements Authenticator. +func (k *Kubernetes) Name() string { return "kubernetes" } + +// RegisterRoutes implements Authenticator: no interactive flow to mount. +func (k *Kubernetes) RegisterRoutes(_ *http.ServeMux) {} + +// Authenticate reviews the request's bearer token against the provider. The +// tenancy key is "kubernetes#", so the same cluster identity gets +// the same boundary on re-bind. +func (k *Kubernetes) Authenticate(r *http.Request) (*Identity, error) { + token := TokenFromRequest(r) + if token == "" { + return nil, ErrUnauthenticated + } + review, err := k.client.AuthenticationV1().TokenReviews().Create(r.Context(), + &authenticationv1.TokenReview{Spec: authenticationv1.TokenReviewSpec{Token: token}}, + metav1.CreateOptions{}) + if err != nil { + return nil, fmt.Errorf("%w: token review failed: %v", ErrUnauthenticated, err) + } + if !review.Status.Authenticated || review.Status.User.Username == "" { + return nil, ErrUnauthenticated + } + return &Identity{ + Subject: "kubernetes#" + review.Status.User.Username, + DisplayName: review.Status.User.Username, + Groups: review.Status.User.Groups, + }, nil +} diff --git a/backend/auth/kubernetes_test.go b/backend/auth/kubernetes_test.go new file mode 100644 index 000000000..2d178f733 --- /dev/null +++ b/backend/auth/kubernetes_test.go @@ -0,0 +1,73 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" + authenticationv1 "k8s.io/api/authentication/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +func kubernetesAuthWithReview(t *testing.T, review func(token string) authenticationv1.TokenReviewStatus) *Kubernetes { + t.Helper() + clientset := fake.NewClientset() + clientset.PrependReactor("create", "tokenreviews", func(action k8stesting.Action) (bool, runtime.Object, error) { + tr := action.(k8stesting.CreateAction).GetObject().(*authenticationv1.TokenReview) + tr = tr.DeepCopy() + tr.Status = review(tr.Spec.Token) + return true, tr, nil + }) + return NewKubernetesFromClientset(clientset) +} + +func TestKubernetesAuthenticator(t *testing.T) { + k := kubernetesAuthWithReview(t, func(token string) authenticationv1.TokenReviewStatus { + if token == "good-token" { + return authenticationv1.TokenReviewStatus{ + Authenticated: true, + User: authenticationv1.UserInfo{ + Username: "system:serviceaccount:tools:portal", + Groups: []string{"system:serviceaccounts"}, + }, + } + } + return authenticationv1.TokenReviewStatus{Authenticated: false} + }) + + r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.Header.Set("Authorization", "Bearer good-token") + id, err := k.Authenticate(r) + require.NoError(t, err) + require.Equal(t, "kubernetes#system:serviceaccount:tools:portal", id.Subject, + "tenancy key is issuer-qualified, stable across re-binds") + require.Equal(t, []string{"system:serviceaccounts"}, id.Groups) + + r = httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.Header.Set("Authorization", "Bearer bad-token") + _, err = k.Authenticate(r) + require.ErrorIs(t, err, ErrUnauthenticated) + + r = httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + _, err = k.Authenticate(r) + require.ErrorIs(t, err, ErrUnauthenticated, "no token at all") +} diff --git a/backend/auth/middleware.go b/backend/auth/middleware.go deleted file mode 100644 index cb64e5cf9..000000000 --- a/backend/auth/middleware.go +++ /dev/null @@ -1,275 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 auth - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" - - "github.com/gorilla/securecookie" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/backend/kubernetes" - "github.com/kube-bind/kube-bind/backend/session" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type contextKey string - -const ( - AuthContextKey contextKey = "auth_context" -) - -type ClientType string - -const ( - ClientTypeUI ClientType = "ui" - ClientTypeCLI ClientType = "cli" - - // UIIdentity is the well-known identity value that the UI sends in bind requests. - // The backend resolves it to the actual identity derived from the authenticated session. - UIIdentity = "ui-identity" -) - -type AuthContext struct { - SessionState *session.State - ClientType ClientType - IsValid bool -} - -type AuthMiddleware struct { - jwtService *JWTService - kubernetesManager *kubernetes.Manager - cookieSigningKey []byte - cookieEncryptionKey []byte - sessionStore session.Store -} - -// writeErrorResponse writes a structured error response to the HTTP response writer -func writeErrorResponse(w http.ResponseWriter, statusCode int, code, message, details string) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(statusCode) - - errorResponse := kubebindv1alpha2.NewError(code, message, details) - if err := json.NewEncoder(w).Encode(errorResponse); err != nil { - // Fallback to plain text if JSON encoding fails - http.Error(w, message, statusCode) - } -} - -func NewAuthMiddleware( - jwtService *JWTService, - cookieSigningKey, cookieEncryptionKey []byte, - kubernetesManager *kubernetes.Manager, - sessionStore session.Store, -) *AuthMiddleware { - return &AuthMiddleware{ - jwtService: jwtService, - cookieSigningKey: cookieSigningKey, - cookieEncryptionKey: cookieEncryptionKey, - kubernetesManager: kubernetesManager, - sessionStore: sessionStore, - } -} - -func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler { - return am.authenticate( - am.verifyState( - am.authorizeK8S(next)), - ) -} - -func (am *AuthMiddleware) authenticate(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()) - - authCtx := &AuthContext{ - IsValid: false, - } - - authHeader := r.Header.Get("Authorization") - - if authHeader != "" { - if strings.HasPrefix(authHeader, "Bearer ") { - token := strings.TrimPrefix(authHeader, "Bearer ") - if claims, err := am.jwtService.ValidateToken(token); err == nil { - authCtx.SessionState = &session.State{ - Token: session.TokenInfo{ - Subject: claims.Subject, - Issuer: claims.Issuer, - Groups: claims.Groups, - }, - SessionID: claims.SessionID, - ClusterID: claims.ClusterID, - RedirectURL: claims.RedirectURL, - } - if claims.ExpiresAt != nil { - authCtx.SessionState.ExpiresAt = claims.ExpiresAt.Time - } - - authCtx.ClientType = ClientTypeCLI - } else { - logger.V(2).Error(err, "Invalid JWT token") - } - } - } - - // Fall back to cookie authentication (for UI clients) - if authCtx.SessionState == nil { - cookieName := "kube-bind" - if r.URL.Query().Get("cluster_id") != "" { - cookieName = "kube-bind-" + r.URL.Query().Get("cluster_id") - } - if cookie, err := r.Cookie(cookieName); err == nil { - s := securecookie.New(am.cookieSigningKey, am.cookieEncryptionKey) - state := &session.State{} - err := s.Decode(cookieName, cookie.Value, state) - if err != nil { - logger.V(2).Info("Failed to decode session cookie", "error", err) - } else { - // Only set as valid after all checks pass - authCtx.SessionState = state - authCtx.ClientType = ClientTypeUI - } - } else { - logger.V(2).Error(err, "Failed to decode session cookie") - } - } - - // Add auth context to request context - ctx := context.WithValue(r.Context(), AuthContextKey, authCtx) - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} - -func (am *AuthMiddleware) verifyState(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()) - - authCtx := GetAuthContext(r.Context()) - if authCtx.SessionState == nil { - logger.V(2).Info("No session state found in auth context") - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "No valid session found") - return - } - - state := authCtx.SessionState - // Validate session fields are present - if state.Token.Subject == "" || state.Token.Issuer == "" || state.SessionID == "" { - logger.V(2).Info("Invalid session state: missing required fields") - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Invalid session state: missing required fields") - return - } - - if state.IsExpired() { - logger.V(2).Info("Session has expired", "sessionID", state.SessionID) - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Session has expired") - return - } - - if !am.isValidSession(r.Context(), state.SessionID) { - logger.V(2).Info("Session expired or invalid", "sessionID", state.SessionID) - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Session has expired or is invalid") - return - } - - // Session is valid - authCtx.IsValid = true - - ctx := context.WithValue(r.Context(), AuthContextKey, authCtx) - next.ServeHTTP(w, r.WithContext(ctx)) - }) -} - -// isValidSession checks if a session ID exists and hasn't expired -func (am *AuthMiddleware) isValidSession(ctx context.Context, sessionID string) bool { - sessionInfo, err := am.sessionStore.Load(ctx, sessionID) - if err != nil { - return false - } - return time.Now().Before(sessionInfo.ExpiresAt) -} - -func (am *AuthMiddleware) authorizeK8S(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()) - - authCtx := GetAuthContext(r.Context()) - if !authCtx.IsValid { // should not happen if AuthenticateRequest is used before - logger.V(2).Info("Authentication context is not valid") - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Authentication context is not valid") - return - } - - // Authorize against Kubernetes RBAC - err := am.kubernetesManager.AuthorizeRequest(r.Context(), authCtx.SessionState.Token.Subject, authCtx.SessionState.Token.Groups, authCtx.SessionState.ClusterID, r.Method, r.URL.Path) - if err != nil { - logger.V(2).Info("Kubernetes RBAC authorization failed", "error", err) - statusCode, code, details := mapErrorToCode(err) - hint := fmt.Sprintf("%s Start the backend with --oidc-allowed-users=%s or --oidc-allowed-groups= (user must be in one of the allowed groups).", details, authCtx.SessionState.Token.Subject) - writeErrorResponse(w, statusCode, code, "Cluster authorization failed. Missing required permissions in the cluster to access bindings.", hint) - return - } - - next.ServeHTTP(w, r) - }) -} - -func GetAuthContext(ctx context.Context) *AuthContext { - if authCtx, ok := ctx.Value(AuthContextKey).(*AuthContext); ok { - return authCtx - } - return &AuthContext{ClientType: ClientTypeUI, IsValid: false} -} - -func RequireAuth(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authCtx := GetAuthContext(r.Context()) - if !authCtx.IsValid { - if authCtx.ClientType == ClientTypeCLI { - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid JWT token required") - } else { - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid authentication credentials required") - } - return - } - next.ServeHTTP(w, r) - }) -} - -// mapErrorToCode maps common errors to structured error codes -func mapErrorToCode(err error) (statusCode int, code string, details string) { - if apierrors.IsNotFound(err) { - return http.StatusNotFound, kubebindv1alpha2.ErrorCodeResourceNotFound, err.Error() - } - if apierrors.IsUnauthorized(err) { - return http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, err.Error() - } - if apierrors.IsForbidden(err) { - return http.StatusForbidden, kubebindv1alpha2.ErrorCodeAuthorizationFailed, err.Error() - } - if apierrors.IsBadRequest(err) { - return http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, err.Error() - } - // Default to internal server error - return http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, err.Error() -} diff --git a/backend/auth/mock.go b/backend/auth/mock.go new file mode 100644 index 000000000..51227560a --- /dev/null +++ b/backend/auth/mock.go @@ -0,0 +1,69 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "context" + "fmt" + "net" + + "github.com/oauth2-proxy/mockoidc" +) + +// StartMockOIDC runs an embedded mock OIDC issuer and returns an OIDCConfig +// pointing at it. Dev-mode only (the --oidc-mock flag): every login +// auto-approves as the mock's default user. The issuer stops when ctx ends. +// +// listen is the address to bind ("" = 127.0.0.1:). A fixed port +// (e.g. "127.0.0.1:5556") makes the issuer reachable from a host browser +// through a port-forward when the backend runs in-cluster — the issuer URL +// embedded in the discovery document is derived from this address, so the +// same 127.0.0.1: works from inside the pod and from the host. +func StartMockOIDC(ctx context.Context, redirectURL, listen string) (OIDCConfig, error) { + m, err := startMock(ctx, listen) + if err != nil { + return OIDCConfig{}, fmt.Errorf("starting mock OIDC issuer: %w", err) + } + go func() { + <-ctx.Done() + _ = m.Shutdown() + }() + + cfg := m.Config() + return OIDCConfig{ + IssuerURL: cfg.Issuer, + ClientID: cfg.ClientID, + ClientSecret: cfg.ClientSecret, + UsernameClaim: "email", + RedirectURL: redirectURL, + }, nil +} + +func startMock(ctx context.Context, listen string) (*mockoidc.MockOIDC, error) { + if listen == "" { + return mockoidc.Run() + } + m, err := mockoidc.NewServer(nil) + if err != nil { + return nil, err + } + ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen) + if err != nil { + return nil, err + } + return m, m.Start(ln, nil) +} diff --git a/backend/auth/oidc.go b/backend/auth/oidc.go new file mode 100644 index 000000000..6b2404ed4 --- /dev/null +++ b/backend/auth/oidc.go @@ -0,0 +1,328 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "context" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "fmt" + "net/http" + "net/url" + "os" + "time" + + gooidc "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +// OIDCConfig configures the OIDC authenticator, kube-apiserver/kcp flag style. +type OIDCConfig struct { + // IssuerURL is the OIDC issuer (--oidc-issuer-url). + IssuerURL string + // ClientID is the OAuth2 client ID (--oidc-client-id). + ClientID string + // ClientSecret is the OAuth2 client secret (--oidc-client-secret). The + // gateway is a confidential web client doing the code grant (with PKCE). + ClientSecret string + // CAFile is a PEM bundle for the issuer's TLS (--oidc-ca-file). Empty = + // system roots. + CAFile string + // UsernameClaim is the ID-token claim used as the stable username + // (--oidc-username-claim). Default "sub". + UsernameClaim string + // GroupsClaim is the ID-token claim holding groups + // (--oidc-groups-claim). Empty = no groups. + GroupsClaim string + // Scopes are the OAuth2 scopes to request (--oidc-scopes). Default + // "openid,profile,email". + Scopes []string + // RedirectURL is the externally reachable callback URL + // (--oidc-redirect-url), e.g. https://gateway.example.com/api/auth/oidc/callback. + RedirectURL string + // InsecureSkipTLSVerify disables TLS verification toward the issuer. + // Dev-mode only (used by --oidc-mock's self-signed issuer). + InsecureSkipTLSVerify bool +} + +// stateCookie is the short-lived cookie carrying the login flow state. +const stateCookie = "kbind_oidc_state" + +// oidcState is the per-login flow state, kept client-side in an encrypted +// cookie (no server state). +type oidcState struct { + State string `json:"state"` + Nonce string `json:"nonce"` + PKCEVerifier string `json:"pkceVerifier"` + Redirect string `json:"redirect"` +} + +// OIDC is the reference Authenticator: authorization-code grant with PKCE. +type OIDC struct { + cfg OIDCConfig + client *http.Client + provider *gooidc.Provider + verifier *gooidc.IDTokenVerifier + oauth2 oauth2.Config + sessions *Sessions +} + +// NewOIDC discovers the issuer and builds the OIDC authenticator. +func NewOIDC(ctx context.Context, cfg OIDCConfig, sessions *Sessions) (*OIDC, error) { + if cfg.IssuerURL == "" || cfg.ClientID == "" || cfg.RedirectURL == "" { + return nil, fmt.Errorf("oidc requires --oidc-issuer-url, --oidc-client-id and --oidc-redirect-url") + } + if cfg.UsernameClaim == "" { + cfg.UsernameClaim = "sub" + } + if len(cfg.Scopes) == 0 { + cfg.Scopes = []string{gooidc.ScopeOpenID, "profile", "email"} + } + + httpClient, err := issuerHTTPClient(cfg) + if err != nil { + return nil, err + } + provider, err := gooidc.NewProvider(gooidc.ClientContext(ctx, httpClient), cfg.IssuerURL) + if err != nil { + return nil, fmt.Errorf("discovering OIDC issuer %q: %w", cfg.IssuerURL, err) + } + + return &OIDC{ + cfg: cfg, + client: httpClient, + provider: provider, + verifier: provider.Verifier(&gooidc.Config{ClientID: cfg.ClientID}), + oauth2: oauth2.Config{ + ClientID: cfg.ClientID, + ClientSecret: cfg.ClientSecret, + Endpoint: provider.Endpoint(), + RedirectURL: cfg.RedirectURL, + Scopes: cfg.Scopes, + }, + sessions: sessions, + }, nil +} + +func issuerHTTPClient(cfg OIDCConfig) (*http.Client, error) { + transport := http.DefaultTransport.(*http.Transport).Clone() + if cfg.InsecureSkipTLSVerify { + transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // dev-mode flag, see OIDCConfig + } else if cfg.CAFile != "" { + pem, err := os.ReadFile(cfg.CAFile) + if err != nil { + return nil, fmt.Errorf("reading --oidc-ca-file: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("--oidc-ca-file %q contains no certificates", cfg.CAFile) + } + transport.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + } + return &http.Client{Transport: transport, Timeout: 30 * time.Second}, nil +} + +// Name implements Authenticator. +func (o *OIDC) Name() string { return "oidc" } + +// RegisterRoutes mounts the login and callback endpoints. +func (o *OIDC) RegisterRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/auth/oidc/login", o.handleLogin) + mux.HandleFunc("GET /api/auth/oidc/callback", o.handleCallback) +} + +// Authenticate implements Authenticator: session cookie or bearer token. +func (o *OIDC) Authenticate(r *http.Request) (*Identity, error) { + token := TokenFromRequest(r) + if token == "" { + return nil, ErrUnauthenticated + } + return o.sessions.Verify(token) +} + +// handleLogin starts the code+PKCE flow. ?redirect= says where to land after +// the callback: a local path (UI) or a http://localhost:/... URL (CLI). +func (o *OIDC) handleLogin(w http.ResponseWriter, r *http.Request) { + redirect := r.URL.Query().Get("redirect") + if redirect == "" { + redirect = "/" + } + if !safeRedirect(redirect) { + http.Error(w, "invalid redirect", http.StatusBadRequest) + return + } + + state := oidcState{ + State: randomToken(16), + Nonce: randomToken(16), + PKCEVerifier: oauth2.GenerateVerifier(), + Redirect: redirect, + } + encoded, err := o.sessions.codec.Encode(stateCookie, state) + if err != nil { + http.Error(w, "encoding state", http.StatusInternalServerError) + return + } + http.SetCookie(w, &http.Cookie{ + Name: stateCookie, + Value: encoded, + Path: "/api/auth/oidc/", + MaxAge: int((10 * time.Minute).Seconds()), + HttpOnly: true, + Secure: r.TLS != nil, + SameSite: http.SameSiteLaxMode, + }) + + http.Redirect(w, r, o.oauth2.AuthCodeURL(state.State, + gooidc.Nonce(state.Nonce), + oauth2.S256ChallengeOption(state.PKCEVerifier), + ), http.StatusFound) +} + +// handleCallback finishes the flow: code exchange, ID-token verification, +// session issuance, redirect. +func (o *OIDC) handleCallback(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(stateCookie) + if err != nil { + http.Error(w, "missing login state (restart login)", http.StatusBadRequest) + return + } + var state oidcState + if err := o.sessions.codec.Decode(stateCookie, cookie.Value, &state); err != nil { + http.Error(w, "invalid login state (restart login)", http.StatusBadRequest) + return + } + if r.URL.Query().Get("state") != state.State { + http.Error(w, "state mismatch", http.StatusBadRequest) + return + } + // The state cookie is one-shot. + http.SetCookie(w, &http.Cookie{Name: stateCookie, Path: "/api/auth/oidc/", MaxAge: -1}) + + ctx := gooidc.ClientContext(r.Context(), o.client) + token, err := o.oauth2.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(state.PKCEVerifier)) + if err != nil { + http.Error(w, "code exchange failed: "+err.Error(), http.StatusUnauthorized) + return + } + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + http.Error(w, "token response has no id_token", http.StatusUnauthorized) + return + } + idToken, err := o.verifier.Verify(ctx, rawIDToken) + if err != nil { + http.Error(w, "id_token verification failed: "+err.Error(), http.StatusUnauthorized) + return + } + if idToken.Nonce != state.Nonce { + http.Error(w, "nonce mismatch", http.StatusUnauthorized) + return + } + + identity, err := o.identityFromClaims(idToken) + if err != nil { + http.Error(w, err.Error(), http.StatusUnauthorized) + return + } + session, err := o.sessions.Issue(identity) + if err != nil { + http.Error(w, "issuing session", http.StatusInternalServerError) + return + } + o.sessions.SetSessionCookie(w, r, session) + + // CLI flow: a localhost redirect gets the token appended so the CLI can + // store it as its bearer token. UI flow: plain path redirect, cookie only. + redirect := state.Redirect + if u, err := url.Parse(redirect); err == nil && u.Host != "" { + q := u.Query() + q.Set("token", session) + u.RawQuery = q.Encode() + redirect = u.String() + } + http.Redirect(w, r, redirect, http.StatusFound) +} + +// identityFromClaims maps ID-token claims to an Identity per the configured +// username/groups claims. Subject is "#" — the stable +// tenancy key. +func (o *OIDC) identityFromClaims(idToken *gooidc.IDToken) (*Identity, error) { + var claims map[string]any + if err := idToken.Claims(&claims); err != nil { + return nil, fmt.Errorf("parsing id_token claims: %w", err) + } + username, ok := claims[o.cfg.UsernameClaim].(string) + if !ok || username == "" { + return nil, fmt.Errorf("id_token has no usable %q claim", o.cfg.UsernameClaim) + } + + display := username + for _, k := range []string{"email", "name", "preferred_username"} { + if v, ok := claims[k].(string); ok && v != "" { + display = v + break + } + } + + var groups []string + if o.cfg.GroupsClaim != "" { + switch v := claims[o.cfg.GroupsClaim].(type) { + case string: + groups = []string{v} + case []any: + for _, g := range v { + if s, ok := g.(string); ok { + groups = append(groups, s) + } + } + } + } + + return &Identity{ + Subject: o.cfg.IssuerURL + "#" + username, + DisplayName: display, + Groups: groups, + }, nil +} + +// safeRedirect allows local paths (UI) and localhost URLs (CLI callback), and +// nothing else — the callback must never become an open redirect. +func safeRedirect(redirect string) bool { + if redirect == "" { + return false + } + if redirect[0] == '/' { + return len(redirect) == 1 || redirect[1] != '/' // path, not scheme-relative //host + } + u, err := url.Parse(redirect) + if err != nil { + return false + } + host := u.Hostname() + return (u.Scheme == "http" || u.Scheme == "https") && (host == "localhost" || host == "127.0.0.1" || host == "::1") +} + +func randomToken(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return base64.RawURLEncoding.EncodeToString(b) +} diff --git a/backend/auth/oidc_test.go b/backend/auth/oidc_test.go new file mode 100644 index 000000000..27c912dd9 --- /dev/null +++ b/backend/auth/oidc_test.go @@ -0,0 +1,120 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "context" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// TestOIDCCodeFlow drives the full authorization-code + PKCE dance against +// the embedded mock issuer: login → issuer → callback → session cookie, then +// authenticates with both the cookie and the bearer token. +func TestOIDCCodeFlow(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + sessions := NewSessions(nil, nil, time.Hour) + + // The gateway mux: OIDC routes + a probe endpoint that reports identity. + mux := http.NewServeMux() + var oidc *OIDC + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("GET /whoami", func(w http.ResponseWriter, r *http.Request) { + id, err := oidc.Authenticate(r) + if err != nil { + http.Error(w, "nope", http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(id.Subject)) + }) + server := httptest.NewServer(mux) + defer server.Close() + + cfg, err := StartMockOIDC(ctx, server.URL+"/api/auth/oidc/callback", "") + require.NoError(t, err) + + oidc, err = NewOIDC(ctx, cfg, sessions) + require.NoError(t, err) + oidc.RegisterRoutes(mux) + + jar, err := cookiejar.New(nil) + require.NoError(t, err) + browser := &http.Client{Jar: jar} + + // The mock issuer auto-approves as its default user; the whole dance is + // redirects the "browser" follows. + loginReq, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/auth/oidc/login?redirect=/", nil) + require.NoError(t, err) + res, err := browser.Do(loginReq) + require.NoError(t, err) + defer func() { _ = res.Body.Close() }() + require.Equal(t, http.StatusOK, res.StatusCode, "login flow should land back on /") + + // Cookie authenticates. + whoamiReq, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/whoami", nil) + require.NoError(t, err) + res2, err := browser.Do(whoamiReq) + require.NoError(t, err) + defer func() { _ = res2.Body.Close() }() + require.Equal(t, http.StatusOK, res2.StatusCode) + + // The session cookie's value works verbatim as a bearer token (CLI path). + u, _ := res2.Request.URL.Parse("/") + var bearer string + for _, c := range jar.Cookies(u) { + if c.Name == SessionCookie { + bearer = c.Value + } + } + require.NotEmpty(t, bearer) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/whoami", nil) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+bearer) + res3, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer func() { _ = res3.Body.Close() }() + require.Equal(t, http.StatusOK, res3.StatusCode) + + id, err := sessions.Verify(bearer) + require.NoError(t, err) + require.Contains(t, id.Subject, cfg.IssuerURL+"#", "subject is issuer-qualified") + require.Equal(t, "jane.doe@example.com", id.DisplayName) +} + +func TestSafeRedirect(t *testing.T) { + for redirect, want := range map[string]bool{ + "/": true, + "/catalog": true, + "//evil.example.com": false, + "https://evil.example.com/x": false, + "http://localhost:8123/cb": true, + "http://127.0.0.1:9999/cb": true, + "ftp://localhost/x": false, + "": false, + } { + require.Equal(t, want, safeRedirect(redirect), "redirect %q", redirect) + } +} diff --git a/backend/auth/sessions.go b/backend/auth/sessions.go new file mode 100644 index 000000000..8878bcb7d --- /dev/null +++ b/backend/auth/sessions.go @@ -0,0 +1,109 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "crypto/rand" + "fmt" + "net/http" + "strings" + "time" + + "github.com/gorilla/securecookie" +) + +// SessionCookie is the cookie carrying the encrypted session token. The same +// token verbatim is accepted as "Authorization: Bearer ..." (the CLI path). +const SessionCookie = "kbind_session" + +// Sessions encodes identities into stateless encrypted tokens and back. With +// shared keys, every gateway replica can verify every token — no store. +type Sessions struct { + codec *securecookie.SecureCookie + ttl time.Duration +} + +// NewSessions builds a Sessions codec. signingKey (32 or 64 bytes) and +// encryptionKey (16, 24 or 32 bytes) must be shared across replicas; pass nil +// to generate ephemeral random keys (dev only — sessions die with the +// process). +func NewSessions(signingKey, encryptionKey []byte, ttl time.Duration) *Sessions { + if len(signingKey) == 0 { + signingKey = randomKey(64) + } + if len(encryptionKey) == 0 { + encryptionKey = randomKey(32) + } + codec := securecookie.New(signingKey, encryptionKey) + codec.MaxAge(int(ttl.Seconds())) + return &Sessions{codec: codec, ttl: ttl} +} + +// TTL is the session lifetime tokens are issued with. +func (s *Sessions) TTL() time.Duration { return s.ttl } + +// Issue encodes an identity into a session token. +func (s *Sessions) Issue(id *Identity) (string, error) { + return s.codec.Encode(SessionCookie, id) +} + +// Verify decodes and validates a session token. +func (s *Sessions) Verify(token string) (*Identity, error) { + var id Identity + if err := s.codec.Decode(SessionCookie, token, &id); err != nil { + return nil, fmt.Errorf("%w: %v", ErrUnauthenticated, err) + } + if id.Subject == "" { + return nil, ErrUnauthenticated + } + return &id, nil +} + +// TokenFromRequest extracts the session token from the Authorization header +// (Bearer) or the session cookie. Empty if neither is present. +func TokenFromRequest(r *http.Request) string { + if h := r.Header.Get("Authorization"); h != "" { + if token, ok := strings.CutPrefix(h, "Bearer "); ok { + return token + } + } + if c, err := r.Cookie(SessionCookie); err == nil { + return c.Value + } + return "" +} + +// SetSessionCookie writes the session token as a cookie. +func (s *Sessions) SetSessionCookie(w http.ResponseWriter, r *http.Request, token string) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookie, + Value: token, + Path: "/", + MaxAge: int(s.ttl.Seconds()), + HttpOnly: true, + Secure: r.TLS != nil, + SameSite: http.SameSiteLaxMode, + }) +} + +func randomKey(n int) []byte { + key := make([]byte, n) + if _, err := rand.Read(key); err != nil { + panic(err) // crypto/rand never fails on supported platforms + } + return key +} diff --git a/backend/auth/sessions_test.go b/backend/auth/sessions_test.go new file mode 100644 index 000000000..cd2d05713 --- /dev/null +++ b/backend/auth/sessions_test.go @@ -0,0 +1,89 @@ +/* +Copyright 2026 The kbind 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 auth + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestSessionsRoundTrip(t *testing.T) { + s := NewSessions(nil, nil, time.Hour) + id := &Identity{Subject: "https://issuer#alice", DisplayName: "alice@example.com", Groups: []string{"dev"}} + + token, err := s.Issue(id) + require.NoError(t, err) + + got, err := s.Verify(token) + require.NoError(t, err) + require.Equal(t, id, got) +} + +func TestSessionsRejectsTamperedAndForeignTokens(t *testing.T) { + s := NewSessions(nil, nil, time.Hour) + token, err := s.Issue(&Identity{Subject: "s"}) + require.NoError(t, err) + + _, err = s.Verify(token + "x") + require.ErrorIs(t, err, ErrUnauthenticated) + + // A token minted with different keys must not verify. + other := NewSessions(nil, nil, time.Hour) + foreign, err := other.Issue(&Identity{Subject: "s"}) + require.NoError(t, err) + _, err = s.Verify(foreign) + require.ErrorIs(t, err, ErrUnauthenticated) +} + +func TestSessionsSharedKeysVerifyAcrossInstances(t *testing.T) { + sign := []byte("0123456789abcdef0123456789abcdef") + encrypt := []byte("fedcba9876543210fedcba9876543210") + a := NewSessions(sign, encrypt, time.Hour) + b := NewSessions(sign, encrypt, time.Hour) + + token, err := a.Issue(&Identity{Subject: "replica-safe"}) + require.NoError(t, err) + got, err := b.Verify(token) + require.NoError(t, err) + require.Equal(t, "replica-safe", got.Subject) +} + +func TestSessionsExpiry(t *testing.T) { + s := NewSessions(nil, nil, time.Second) + token, err := s.Issue(&Identity{Subject: "s"}) + require.NoError(t, err) + // securecookie's max-age granularity is whole seconds; overshoot clearly. + time.Sleep(2500 * time.Millisecond) + _, err = s.Verify(token) + require.ErrorIs(t, err, ErrUnauthenticated) +} + +func TestTokenFromRequest(t *testing.T) { + r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + require.Empty(t, TokenFromRequest(r)) + + r.Header.Set("Authorization", "Bearer abc") + require.Equal(t, "abc", TokenFromRequest(r)) + + r = httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.AddCookie(&http.Cookie{Name: SessionCookie, Value: "cookie-token"}) + require.Equal(t, "cookie-token", TokenFromRequest(r)) +} diff --git a/backend/auth/types.go b/backend/auth/types.go deleted file mode 100644 index 70fc19a21..000000000 --- a/backend/auth/types.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 auth - -import ( - "context" - "crypto/tls" - "net/http" - "time" - - oidc "github.com/coreos/go-oidc/v3/oidc" - "golang.org/x/oauth2" -) - -type AuthResponse struct { - Success bool `json:"success"` - Data interface{} `json:"data,omitempty"` - Error string `json:"error,omitempty"` - Message string `json:"message,omitempty"` - Meta map[string]interface{} `json:"meta,omitempty"` -} - -type TokenResponse struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int64 `json:"expires_in"` - ExpiresAt time.Time `json:"expires_at"` - Scope string `json:"scope,omitempty"` - RefreshToken string `json:"refresh_token,omitempty"` - - ClusterID string `json:"cluster_id,omitempty"` -} - -type AuthorizeRequest struct { - RedirectURL string `json:"redirect_url" form:"redirect_url"` - SessionID string `json:"session_id" form:"session_id"` - ClusterID string `json:"cluster_id" form:"cluster_id"` - ClientType ClientType `json:"client_type" form:"client_type"` - ConsumerID string `json:"consumer_id" form:"consumer_id"` -} - -type CallbackRequest struct { - Code string `json:"code" form:"code"` - State string `json:"state" form:"state"` - Error string `json:"error,omitempty" form:"error"` - ErrorDescription string `json:"error_description,omitempty" form:"error_description"` -} - -type OIDCServiceProvider struct { - clientID string - clientSecret string - redirectURI string - issuerURL string - - verifier *oidc.IDTokenVerifier - provider *oidc.Provider - tlsConfig *tls.Config -} - -func NewOIDCServiceProvider(ctx context.Context, clientID, clientSecret, redirectURI, issuerURL string) (*OIDCServiceProvider, error) { - provider, err := oidc.NewProvider(ctx, issuerURL) - if err != nil { - return nil, err - } - - return &OIDCServiceProvider{ - clientID: clientID, - clientSecret: clientSecret, - redirectURI: redirectURI, - issuerURL: issuerURL, - provider: provider, - verifier: provider.Verifier(&oidc.Config{ClientID: clientID}), - tlsConfig: nil, - }, nil -} - -func NewOIDCServiceProviderWithTLS( - ctx context.Context, - clientID, clientSecret, redirectURI, issuerURL string, - tlsConfig *tls.Config, -) (*OIDCServiceProvider, error) { - // Create a custom HTTP client that trusts the TLS config - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsConfig, - }, - } - - // Create context with the custom client - ctxWithClient := oidc.ClientContext(ctx, client) - - provider, err := oidc.NewProvider(ctxWithClient, issuerURL) - if err != nil { - return nil, err - } - - return &OIDCServiceProvider{ - clientID: clientID, - clientSecret: clientSecret, - redirectURI: redirectURI, - issuerURL: issuerURL, - provider: provider, - verifier: provider.Verifier(&oidc.Config{ClientID: clientID}), - tlsConfig: tlsConfig, - }, nil -} - -func (o *OIDCServiceProvider) OIDCProviderConfig(scopes []string) *oauth2.Config { - config := &oauth2.Config{ - ClientID: o.clientID, - Endpoint: o.provider.Endpoint(), - RedirectURL: o.redirectURI, - Scopes: scopes, - } - - if o.clientSecret != "" { - config.ClientSecret = o.clientSecret - } - - return config -} - -func (o *OIDCServiceProvider) GetTLSConfig() *tls.Config { - return o.tlsConfig -} - -func (o *OIDCServiceProvider) ClientID() string { - return o.clientID -} - -func (o *OIDCServiceProvider) ClientSecret() string { - return o.clientSecret -} - -func (o *OIDCServiceProvider) IssuerURL() string { - return o.issuerURL -} diff --git a/backend/client/client.go b/backend/client/client.go deleted file mode 100644 index fb14658b7..000000000 --- a/backend/client/client.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 client - -import ( - "net/http" - "net/url" -) - -type ClientParameters struct { - ClusterID string - RedirectURL string - SessionID string - ClientType string - ConsumerID string - - IsClusterScoped bool -} - -// GetQueryParams extracts the client parameters from the given HTTP request. -func GetQueryParams(r *http.Request) *ClientParameters { - p := &ClientParameters{ - ClusterID: r.URL.Query().Get("cluster_id"), - RedirectURL: r.URL.Query().Get("redirect_url"), - SessionID: r.URL.Query().Get("session_id"), - ClientType: r.URL.Query().Get("client_type"), - ConsumerID: r.URL.Query().Get("consumer_id"), - } - p.IsClusterScoped = p.ClusterID != "" - return p -} - -// WithParams adds the client parameters to the given URL as query parameters. -func (r *ClientParameters) WithParams(urlStr string) string { - parsedURL, err := url.Parse(urlStr) - if err != nil { - // Return original URL if parsing fails - return urlStr - } - - query := parsedURL.Query() - - // Add all non-empty client parameters - if r.ClusterID != "" { - query.Set("cluster_id", r.ClusterID) - } - if r.SessionID != "" { - query.Set("session_id", r.SessionID) - } - if r.ClientType != "" { - query.Set("client_type", r.ClientType) - } - if r.ConsumerID != "" { - query.Set("consumer_id", r.ConsumerID) - } - - parsedURL.RawQuery = query.Encode() - return parsedURL.String() -} diff --git a/backend/config.go b/backend/config.go deleted file mode 100644 index 3064ece43..000000000 --- a/backend/config.go +++ /dev/null @@ -1,143 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 backend - -import ( - "fmt" - - "github.com/kcp-dev/multicluster-provider/apiexport" - apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1" - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/runtime" - clientgoscheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/utils/ptr" - ctrl "sigs.k8s.io/controller-runtime" - ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" - metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - "github.com/kube-bind/kube-bind/backend/options" - kcpprovider "github.com/kube-bind/kube-bind/backend/provider/kcp" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Config struct { - Options *options.CompletedOptions - - Provider multicluster.Provider - ExternalAddressGenerator kuberesources.ExternalAddressGeneratorFunc - - Manager mcmanager.Manager - Scheme *runtime.Scheme - - ClientConfig *rest.Config -} - -func NewConfig(options *options.CompletedOptions) (*Config, error) { - config := &Config{ - Options: options, - } - - // create clients - rules := clientcmd.NewDefaultClientConfigLoadingRules() - rules.ExplicitPath = options.KubeConfig - var overrides *clientcmd.ConfigOverrides - if options.Context != "" { - overrides = &clientcmd.ConfigOverrides{ - CurrentContext: options.Context, - } - } - var err error - config.ClientConfig, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig() - if err != nil { - return nil, err - } - config.ClientConfig = rest.CopyConfig(config.ClientConfig) - config.ClientConfig = rest.AddUserAgent(config.ClientConfig, "kube-bind-backend") - - // Set up controller-runtime manager - scheme := runtime.NewScheme() - if err := clientgoscheme.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding client-go scheme: %w", err) - } - if err := apiextensionsv1.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding apiextensions scheme: %w", err) - } - if err := kubebindv1alpha1.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding kubebind scheme: %w", err) - } - if err := kubebindv1alpha2.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding kubebind scheme: %w", err) - } - - config.Scheme = scheme - - switch options.Provider { - case "kcp": - if options.ProviderKcp == nil { - return nil, fmt.Errorf("kcp provider options must be provided when provider is kcp") - } - if err := apisv1alpha1.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding apis scheme: %w", err) - } - if err := apisv1alpha2.AddToScheme(scheme); err != nil { - return nil, fmt.Errorf("error adding apis scheme: %w", err) - } - provider, err := kcpprovider.New(config.ClientConfig, options.ProviderKcp.APIExportEndpointSliceName, apiexport.Options{ - Scheme: scheme, - }) - if err != nil { - return nil, fmt.Errorf("error setting up kcp provider: %w", err) - } - - gen, err := kcpprovider.NewKCPExternalAddressGenerator(options.ExternalAddress) - if err != nil { - return nil, err - } - - config.ExternalAddressGenerator = gen - config.Provider = provider - default: - config.ExternalAddressGenerator = kuberesources.NewFixedExternalAddressGenerator(options.ExternalAddress) - config.Provider = nil - } - - opts := ctrl.Options{ - Controller: ctrlconfig.Controller{ - SkipNameValidation: ptr.To(config.Options.ExtraOptions.TestingSkipNameValidation), - }, - Metrics: metricsserver.Options{ - BindAddress: "0", - }, - Scheme: scheme, - } - - manager, err := mcmanager.New(config.ClientConfig, config.Provider, opts) - if err != nil { - return nil, fmt.Errorf("error setting up controller manager: %w", err) - } - - config.Manager = manager - - return config, nil -} diff --git a/backend/controllers/bindableresourcesrequest/bindableresourcesrequest_controller.go b/backend/controllers/bindableresourcesrequest/bindableresourcesrequest_controller.go deleted file mode 100644 index f4f5ba881..000000000 --- a/backend/controllers/bindableresourcesrequest/bindableresourcesrequest_controller.go +++ /dev/null @@ -1,399 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 bindableresourcesrequest - -import ( - "context" - "encoding/json" - "fmt" - "reflect" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/log" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/backend/kubernetes" - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-bindableresourcesrequest" -) - -// BindableResourcesRequestReconciler reconciles a BindableResourcesRequest object. -// This controller handles direct binding requests created as CRDs when the -// backend is running without the HTTP API/OIDC flow (frontend disabled mode). -// -// The controller: -// 1. Reads the kubeconfig from the referenced secret -// 2. Creates a BindingResourceResponse secret with the kubeconfig -// 3. Creates an APIServiceExportRequest based on the template -type BindableResourcesRequestReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - - informerScope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - reconciler reconciler -} - -// NewBindableResourcesRequestReconciler returns a new BindableResourcesRequestReconciler. -func NewBindableResourcesRequestReconciler( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - scope kubebindv1alpha2.InformerScope, - isolation kubebindv1alpha2.Isolation, - kubeManager *kubernetes.Manager, -) (*BindableResourcesRequestReconciler, error) { - // Set up field indexers for BindableResourcesRequests - if err := mgr.GetFieldIndexer().IndexField(ctx, &kubebindv1alpha2.BindableResourcesRequest{}, indexers.BindableResourcesRequestByTemplate, - indexers.IndexBindableResourcesRequestByTemplate); err != nil { - return nil, fmt.Errorf("failed to setup BindableResourcesRequestByTemplate indexer: %w", err) - } - - r := &BindableResourcesRequestReconciler{ - manager: mgr, - opts: opts, - informerScope: scope, - isolation: isolation, - reconciler: reconciler{ - informerScope: scope, - isolation: isolation, - kubeManager: kubeManager, - }, - } - - return r, nil -} - -//+kubebuilder:rbac:groups=kube-bind.io,resources=bindableresourcesrequests,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=bindableresourcesrequests/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=kube-bind.io,resources=bindableresourcesrequests/finalizers,verbs=update -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexportrequests,verbs=get;list;watch;create -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexporttemplates,verbs=get;list;watch -//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update - -// Reconcile is part of the main kubernetes reconciliation loop. -func (r *BindableResourcesRequestReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling BindableResourcesRequest", "cluster", req.ClusterName, "namespace", req.Namespace, "name", req.Name) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - - // Fetch the BindableResourcesRequest instance - bindableRequest := &kubebindv1alpha2.BindableResourcesRequest{} - if err := client.Get(ctx, req.NamespacedName, bindableRequest); err != nil { - if errors.IsNotFound(err) { - logger.Info("BindableResourcesRequest not found, ignoring") - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to get BindableResourcesRequest: %w", err) - } - - // Check TTL-based deletion for completed (ttl) requests - if bindableRequest.Status.Phase == kubebindv1alpha2.BindableResourcesRequestPhaseSucceeded || - bindableRequest.Status.Phase == kubebindv1alpha2.BindableResourcesRequestPhaseFailed { - return r.handleTTL(ctx, client, bindableRequest) - } - - // Create a copy to modify - original := bindableRequest.DeepCopy() - - // Run the reconciliation logic - result, err := r.reconciler.reconcile(ctx, string(req.ClusterName), client, bindableRequest) - if err != nil { - logger.Error(err, "Failed to reconcile BindableResourcesRequest") - if !reflect.DeepEqual(original.Status, bindableRequest.Status) { - if updateErr := client.Status().Update(ctx, bindableRequest); updateErr != nil { - logger.Error(updateErr, "Failed to update BindableResourcesRequest status") - return ctrl.Result{}, fmt.Errorf("failed to update BindableResourcesRequest status: %w", updateErr) - } - } - return ctrl.Result{}, err - } - - // Update status if it has changed - if !reflect.DeepEqual(original.Status, bindableRequest.Status) { - if err := client.Status().Update(ctx, bindableRequest); err != nil { - logger.Error(err, "Failed to update BindableResourcesRequest status") - return ctrl.Result{}, fmt.Errorf("failed to update BindableResourcesRequest status: %w", err) - } - logger.Info("BindableResourcesRequest status updated", "namespace", bindableRequest.Namespace, "name", bindableRequest.Name) - } - - return result, nil -} - -// handleTTL checks if the request should be deleted based on TTL settings. -func (r *BindableResourcesRequestReconciler) handleTTL(ctx context.Context, cl client.Client, req *kubebindv1alpha2.BindableResourcesRequest) (ctrl.Result, error) { - logger := log.FromContext(ctx) - - // If no TTL is set, don't delete - if req.Spec.TTLAfterFinished == nil { - return ctrl.Result{}, nil - } - - // If no completion time is set, something is wrong - skip - if req.Status.CompletionTime == nil { - return ctrl.Result{}, nil - } - - ttl := req.Spec.TTLAfterFinished.Duration - expireTime := req.Status.CompletionTime.Add(ttl) - now := time.Now() - - if now.After(expireTime) { - logger.Info("TTL expired, deleting BindableResourcesRequest", "name", req.Name, "namespace", req.Namespace) - if err := cl.Delete(ctx, req); err != nil { - if errors.IsNotFound(err) { - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to delete expired BindableResourcesRequest: %w", err) - } - return ctrl.Result{}, nil - } - - // Requeue to check again when TTL expires - requeueAfter := expireTime.Sub(now) - return ctrl.Result{RequeueAfter: requeueAfter}, nil -} - -// SetupWithManager sets up the controller with the Manager. -func (r *BindableResourcesRequestReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.BindableResourcesRequest{}). - Owns(&corev1.Secret{}). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} - -type reconciler struct { - informerScope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - kubeManager *kubernetes.Manager -} - -func (r *reconciler) reconcile(ctx context.Context, clusterName string, cl client.Client, req *kubebindv1alpha2.BindableResourcesRequest) (ctrl.Result, error) { - logger := log.FromContext(ctx) - - // Determine the secret name and key to use for the binding response - var secretName, secretKey string - if req.Spec.KubeconfigSecretRef != nil { - // Use the specified secret reference - secretName = req.Spec.KubeconfigSecretRef.Name - secretKey = req.Spec.KubeconfigSecretRef.Key - if secretKey == "" { - secretKey = "kubeconfig" - } - } else { - // Create a new secret with default naming - secretName = req.Name + "-binding-response" - secretKey = "binding-response" - } - - // Update status with the secret reference - req.Status.KubeconfigSecretRef = &kubebindv1alpha2.LocalSecretKeyRef{ - Name: secretName, - Key: secretKey, - } - - // Get the template if specified - var template kubebindv1alpha2.APIServiceExportTemplate - if req.Spec.TemplateRef.Name != "" { - if err := cl.Get(ctx, types.NamespacedName{Name: req.Spec.TemplateRef.Name}, &template); err != nil { - if errors.IsNotFound(err) { - req.Status.Phase = kubebindv1alpha2.BindableResourcesRequestPhaseFailed - now := metav1.Now() - req.Status.CompletionTime = &now - meta.SetStatusCondition(&req.Status.Conditions, metav1.Condition{ - Type: string(kubebindv1alpha2.BindableResourcesRequestConditionReady), - Status: metav1.ConditionFalse, - Reason: "TemplateNotFound", - Message: fmt.Sprintf("APIServiceExportTemplate %q not found", req.Spec.TemplateRef.Name), - LastTransitionTime: now, - }) - return ctrl.Result{}, nil // Don't retry - template doesn't exist - } - return ctrl.Result{}, fmt.Errorf("failed to get template %q: %w", req.Spec.TemplateRef.Name, err) - } - } - - // Default the pretty name to the request name if not provided. - clusterPrettyName := req.Spec.ClusterIdentity.PrettyName - if clusterPrettyName == "" { - clusterPrettyName = req.Name - } - - // Handle resources and get kubeconfig - result, err := r.kubeManager.HandleResources(ctx, req.Spec.Author, req.Spec.ClusterIdentity.Identity, clusterName, clusterPrettyName) - if err != nil { - meta.SetStatusCondition(&req.Status.Conditions, metav1.Condition{ - Type: string(kubebindv1alpha2.BindableResourcesRequestConditionReady), - Status: metav1.ConditionFalse, - Reason: "HandleResourcesFailed", - Message: fmt.Sprintf("Failed to handle resources: %v", err), - LastTransitionTime: metav1.Now(), - }) - return ctrl.Result{}, fmt.Errorf("failed to handle resources for cluster identity %q: %w", req.Spec.ClusterIdentity.Identity, err) - } - - // Set the namespace in the status - req.Status.Namespace = result.Namespace - - // Create or update the BindingResourceResponse secret - if err := r.ensureBindingResponseSecret(ctx, cl, req, result.Kubeconfig, secretName, secretKey); err != nil { - meta.SetStatusCondition(&req.Status.Conditions, metav1.Condition{ - Type: string(kubebindv1alpha2.BindableResourcesRequestConditionReady), - Status: metav1.ConditionFalse, - Reason: "SecretCreationFailed", - Message: fmt.Sprintf("Failed to create/update secret: %v", err), - LastTransitionTime: metav1.Now(), - }) - return ctrl.Result{}, fmt.Errorf("failed to ensure binding response secret: %w", err) - } - - // Set success status - now := metav1.Now() - req.Status.Phase = kubebindv1alpha2.BindableResourcesRequestPhaseSucceeded - req.Status.CompletionTime = &now - meta.SetStatusCondition(&req.Status.Conditions, metav1.Condition{ - Type: string(kubebindv1alpha2.BindableResourcesRequestConditionReady), - Status: metav1.ConditionTrue, - Reason: "SecretReady", - Message: fmt.Sprintf("Binding response secret %q is ready", secretName), - LastTransitionTime: now, - }) - - logger.Info("BindableResourcesRequest succeeded", "name", req.Name, "namespace", req.Namespace, "secret", secretName) - - // If TTL is set, requeue for deletion - if req.Spec.TTLAfterFinished != nil { - return ctrl.Result{RequeueAfter: req.Spec.TTLAfterFinished.Duration}, nil - } - - return ctrl.Result{}, nil -} - -// ensureBindingResponseSecret creates or updates a secret containing the BindingResourceResponse -// with only the kubeconfig set (no authentication or requests). -func (r *reconciler) ensureBindingResponseSecret( - ctx context.Context, - cl client.Client, - req *kubebindv1alpha2.BindableResourcesRequest, - kubeconfig []byte, - secretName string, - secretKey string, -) error { - logger := log.FromContext(ctx) - - // Create the BindingResourceResponse with only kubeconfig - response := kubebindv1alpha2.BindingResourceResponse{ - TypeMeta: metav1.TypeMeta{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "BindingResourceResponse", - }, - Kubeconfig: kubeconfig, - } - - responseBytes, err := json.Marshal(&response) - if err != nil { - return fmt.Errorf("failed to marshal BindingResourceResponse: %w", err) - } - - // Check if secret already exists - existingSecret := &corev1.Secret{} - err = cl.Get(ctx, types.NamespacedName{Namespace: req.Namespace, Name: secretName}, existingSecret) - if err != nil && !errors.IsNotFound(err) { - return fmt.Errorf("failed to get existing secret: %w", err) - } - - // Build owner reference - the secret is owned by the BindableResourcesRequest - ownerRef := metav1.OwnerReference{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "BindableResourcesRequest", - Name: req.Name, - UID: req.UID, - Controller: func() *bool { b := true; return &b }(), - } - - if errors.IsNotFound(err) { - // Create new secret - secret := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: secretName, - Namespace: req.Namespace, - OwnerReferences: []metav1.OwnerReference{ownerRef}, - }, - Type: corev1.SecretTypeOpaque, - Data: map[string][]byte{ - secretKey: responseBytes, - }, - } - logger.Info("Creating BindingResourceResponse secret", "name", secretName, "namespace", req.Namespace, "key", secretKey) - if err := cl.Create(ctx, secret); err != nil { - if errors.IsAlreadyExists(err) { - return nil // Race condition, secret was created - } - return fmt.Errorf("failed to create secret: %w", err) - } - } else { - // Update existing secret - // Ensure owner reference is set - hasOwnerRef := false - for _, ref := range existingSecret.OwnerReferences { - if ref.UID == req.UID { - hasOwnerRef = true - break - } - } - if !hasOwnerRef { - existingSecret.OwnerReferences = append(existingSecret.OwnerReferences, ownerRef) - } - - // Update data if changed - if existingSecret.Data == nil { - existingSecret.Data = make(map[string][]byte) - } - if string(existingSecret.Data[secretKey]) != string(responseBytes) { - existingSecret.Data[secretKey] = responseBytes - logger.Info("Updating BindingResourceResponse secret", "name", secretName, "namespace", req.Namespace, "key", secretKey) - if err := cl.Update(ctx, existingSecret); err != nil { - return fmt.Errorf("failed to update secret: %w", err) - } - } - } - - return nil -} diff --git a/backend/controllers/cluster/cluster_controller.go b/backend/controllers/cluster/cluster_controller.go deleted file mode 100644 index c5d622c9f..000000000 --- a/backend/controllers/cluster/cluster_controller.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cluster - -import ( - "context" - "fmt" - "reflect" - - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/log" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-cluster" -) - -// ClusterReconciler reconciles a Cluster object. -type ClusterReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - reconciler reconciler -} - -// NewClusterReconciler returns a new ClusterReconciler to reconcile Clusters -// ands its resources. -func NewClusterReconciler( - _ context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - allowedGroups []string, - allowedUsers []string, -) (*ClusterReconciler, error) { - r := &ClusterReconciler{ - manager: mgr, - opts: opts, - reconciler: reconciler{ - allowedGroups: allowedGroups, - allowedUsers: allowedUsers, - }, - } - - return r, nil -} - -//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterroles,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch;create;update;patch;delete - -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -func (r *ClusterReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling Cluster", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - cluster := &kubebindv1alpha2.Cluster{} - if err := client.Get(ctx, req.NamespacedName, cluster); err != nil { - if errors.IsNotFound(err) { - logger.Info("Cluster not found, skipping reconciliation") - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to get Cluster: %w", err) - } - - original := cluster.DeepCopy() - if err := r.reconciler.reconcile(ctx, client, cache, cluster); err != nil { - logger.Error(err, "Failed to reconcile Cluster") - return ctrl.Result{}, err - } - - if !reflect.DeepEqual(original, cluster) { - err := client.Update(ctx, cluster) - if err != nil { - logger.Error(err, "Failed to update Cluster status") - return ctrl.Result{}, fmt.Errorf("failed to update Cluster status: %w", err) - } - logger.Info("Cluster status updated") - } - - return ctrl.Result{}, nil -} - -// SetupWithManager sets up the controller with the Manager. -func (r *ClusterReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.Cluster{}). - Owns(&rbacv1.ClusterRole{}). - Owns(&rbacv1.ClusterRoleBinding{}). - Owns(&rbacv1.RoleBinding{}). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/controllers/cluster/cluster_reconcile.go b/backend/controllers/cluster/cluster_reconcile.go deleted file mode 100644 index ca946a7fa..000000000 --- a/backend/controllers/cluster/cluster_reconcile.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cluster - -import ( - "context" - - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type reconciler struct { - allowedGroups []string - allowedUsers []string -} - -func (r *reconciler) reconcile(ctx context.Context, client client.Client, _ cache.Cache, cluster *kubebindv1alpha2.Cluster) error { - var errs []error - - if err := r.ensureOIDCRBAC(ctx, client, cluster); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureOIDCRBAC(ctx context.Context, client client.Client, cluster *kubebindv1alpha2.Cluster) error { - if err := r.ensureUserClusterRole(ctx, client, cluster); err != nil { - return err - } - return r.ensureUserClusterRoleBinding(ctx, client, cluster) -} - -func (r *reconciler) ensureUserClusterRole(ctx context.Context, client client.Client, cluster *kubebindv1alpha2.Cluster) error { - clusterRole := &rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-bind-oidc-user", - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"*"}, - Verbs: []string{"bind"}, - }, - { - NonResourceURLs: []string{"/", "/api", "/api/*", "/apis", "/apis/*"}, - Verbs: []string{"access"}, - }, - }, - } - - if err := controllerutil.SetControllerReference(cluster, clusterRole, client.Scheme()); err != nil { - return err - } - - var existing rbacv1.ClusterRole - err := client.Get(ctx, types.NamespacedName{Name: "kube-bind-oidc-user"}, &existing) - if err != nil { - if errors.IsNotFound(err) { - return client.Create(ctx, clusterRole) - } - return err - } - - existing.Rules = clusterRole.Rules - existing.OwnerReferences = clusterRole.OwnerReferences - return client.Update(ctx, &existing) -} - -func (r *reconciler) ensureUserClusterRoleBinding(ctx context.Context, client client.Client, cluster *kubebindv1alpha2.Cluster) error { - clusterRoleBinding := &rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-bind-oidc-user", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: "rbac.authorization.k8s.io", - Kind: "ClusterRole", - Name: "kube-bind-oidc-user", - }, - } - - for _, group := range r.allowedGroups { - clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{ - Kind: "Group", - Name: group, - }) - } - - for _, user := range r.allowedUsers { - clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1.Subject{ - Kind: "User", - Name: user, - }) - } - - if err := controllerutil.SetControllerReference(cluster, clusterRoleBinding, client.Scheme()); err != nil { - return err - } - - var existing rbacv1.ClusterRoleBinding - err := client.Get(ctx, types.NamespacedName{Name: "kube-bind-oidc-user"}, &existing) - if err != nil { - if errors.IsNotFound(err) { - return client.Create(ctx, clusterRoleBinding) - } - return err - } - - existing.RoleRef = clusterRoleBinding.RoleRef - existing.Subjects = clusterRoleBinding.Subjects - existing.OwnerReferences = clusterRoleBinding.OwnerReferences - return client.Update(ctx, &existing) -} diff --git a/backend/controllers/clusterbinding/clusterbinding_controller.go b/backend/controllers/clusterbinding/clusterbinding_controller.go deleted file mode 100644 index 4f2c5caeb..000000000 --- a/backend/controllers/clusterbinding/clusterbinding_controller.go +++ /dev/null @@ -1,156 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 clusterbinding - -import ( - "context" - "fmt" - "reflect" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-clusterbinding" -) - -// ClusterBindingReconciler reconciles a ClusterBinding object. -type ClusterBindingReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - scope kubebindv1alpha2.InformerScope - reconciler reconciler -} - -// NewClusterBindingReconciler returns a new ClusterBindingReconciler to reconcile ClusterBindings. -func NewClusterBindingReconciler( - _ context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - scope kubebindv1alpha2.InformerScope, -) (*ClusterBindingReconciler, error) { - r := &ClusterBindingReconciler{ - manager: mgr, - opts: opts, - scope: scope, - } - - return r, nil -} - -//+kubebuilder:rbac:groups=kube-bind.io,resources=clusterbindings,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=clusterbindings/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=kube-bind.io,resources=clusterbindings/finalizers,verbs=update -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports,verbs=get;list;watch -//+kubebuilder:rbac:groups=kube-bind.io,resources=collections,verbs=get;list;watch -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexporttemplates,verbs=get;list;watch - -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -func (r *ClusterBindingReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling ClusterBinding", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - // Fetch the ClusterBinding instance - clusterBinding := &kubebindv1alpha2.ClusterBinding{} - if err := client.Get(ctx, req.NamespacedName, clusterBinding); err != nil { - if errors.IsNotFound(err) { - // Request object not found, could have been deleted after reconcile request. - logger.Info("ClusterBinding not found, ignoring") - return ctrl.Result{}, nil - } - // Error reading the object - requeue the request. - return ctrl.Result{}, fmt.Errorf("failed to get ClusterBinding: %w", err) - } - - // Create a copy to modify - original := clusterBinding.DeepCopy() - - // Run the reconciliation logic - if err := r.reconciler.reconcile(ctx, client, cache, clusterBinding); err != nil { - logger.Error(err, "Failed to reconcile ClusterBinding") - return ctrl.Result{}, err - } - - // Update status if it has changed - if !reflect.DeepEqual(original, clusterBinding) { - err := client.Update(ctx, clusterBinding) - if err != nil { - logger.Error(err, "Failed to update ClusterBinding status") - return ctrl.Result{}, fmt.Errorf("failed to update ClusterBinding status: %w", err) - } - logger.Info("ClusterBinding status updated") - } - - return ctrl.Result{}, nil -} - -// SetupWithManager sets up the controller with the Manager. -func (r *ClusterBindingReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.ClusterBinding{}). - Watches( - &kubebindv1alpha2.APIServiceExport{}, - mapAPIResourceSchema, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} - -func mapAPIResourceSchema(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - serviceExport, ok := obj.(*kubebindv1alpha2.APIServiceExport) - if !ok { - return nil - } - return []mcreconcile.Request{ - { - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: serviceExport.GetNamespace(), - Name: "cluster", - }, - }, - ClusterName: clusterName, - }, - } - }) -} diff --git a/backend/controllers/clusterbinding/clusterbinding_reconcile.go b/backend/controllers/clusterbinding/clusterbinding_reconcile.go deleted file mode 100644 index 0f62bd254..000000000 --- a/backend/controllers/clusterbinding/clusterbinding_reconcile.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 clusterbinding - -import ( - "context" - "time" - - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct{} - -func (r *reconciler) reconcile(ctx context.Context, client client.Client, cache cache.Cache, clusterBinding *kubebindv1alpha2.ClusterBinding) error { - var errs []error - - if err := r.ensureClusterBindingConditions(ctx, clusterBinding); err != nil { - errs = append(errs, err) - } - - conditions.SetSummary(clusterBinding) - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureClusterBindingConditions(_ context.Context, clusterBinding *kubebindv1alpha2.ClusterBinding) error { - if clusterBinding.Status.LastHeartbeatTime.IsZero() { - conditions.MarkFalse(clusterBinding, - kubebindv1alpha2.ClusterBindingConditionHealthy, - "FirstHeartbeatPending", - conditionsapi.ConditionSeverityInfo, - "Waiting for first heartbeat", - ) - } else if clusterBinding.Status.HeartbeatInterval.Duration == 0 { - conditions.MarkFalse(clusterBinding, - kubebindv1alpha2.ClusterBindingConditionHealthy, - "HeartbeatIntervalMissing", - conditionsapi.ConditionSeverityInfo, - "Waiting for consumer cluster reporting its heartbeat interval", - ) - } else if ago := time.Since(clusterBinding.Status.LastHeartbeatTime.Time); ago > clusterBinding.Status.HeartbeatInterval.Duration*2 { - conditions.MarkFalse(clusterBinding, - kubebindv1alpha2.ClusterBindingConditionHealthy, - "HeartbeatTimeout", - conditionsapi.ConditionSeverityError, - "Heartbeat timeout: expected heartbeat within %s, but last one has been at %s", - clusterBinding.Status.HeartbeatInterval.Duration, - clusterBinding.Status.LastHeartbeatTime.Time, // do not put "ago" here. It will hotloop. - ) - } else if ago < time.Second*10 { - conditions.MarkFalse(clusterBinding, - kubebindv1alpha2.ClusterBindingConditionHealthy, - "HeartbeatTimeDrift", - conditionsapi.ConditionSeverityWarning, - "Clocks of consumer cluster and service account cluster seem to be off by more than 10s", - ) - } else { - conditions.MarkTrue(clusterBinding, - kubebindv1alpha2.ClusterBindingConditionHealthy, - ) - } - - return nil -} diff --git a/backend/controllers/rbac.go b/backend/controllers/rbac.go deleted file mode 100644 index 49d4d6c88..000000000 --- a/backend/controllers/rbac.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 controllers - -// This is Core access needed for backend controllers. -//+kubebuilder:rbac:groups=apiextensions.k8s.io,resources=customresourcedefinitions,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch;create;update;patch;delete - -// Additional RBAC permissions for export functionality -// These permissions allow the backend to grant RBAC permissions for exported resources -//+kubebuilder:rbac:groups="",resources=configmaps,verbs=* -//+kubebuilder:rbac:groups="",resources=secrets,verbs=* - -// Wildcard permissions to allow granting RBAC permissions for any API group/resource -// This is needed for kube-bind to create ClusterRoles with permissions for bound resources -// In a way this makes all the above specific permissions redundant, but they are left for clarity and traceability. -//+kubebuilder:rbac:groups=*,resources=*,verbs=* diff --git a/backend/controllers/serviceexport/serviceexport_controller.go b/backend/controllers/serviceexport/serviceexport_controller.go deleted file mode 100644 index 4a5fb76cf..000000000 --- a/backend/controllers/serviceexport/serviceexport_controller.go +++ /dev/null @@ -1,185 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexport - -import ( - "context" - "fmt" - - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-serviceexport" -) - -// APIServiceExportReconciler reconciles a APIServiceExport object. -type APIServiceExportReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - - reconciler reconciler -} - -// NewAPIServiceExportReconciler returns a new APIServiceExportReconciler to reconcile APIServiceExports. -func NewAPIServiceExportReconciler( - ctx context.Context, - mgr mcmanager.Manager, - scope kubebindv1alpha2.InformerScope, - opts controller.TypedOptions[mcreconcile.Request], -) (*APIServiceExportReconciler, error) { - if err := mgr.GetFieldIndexer().IndexField(ctx, &kubebindv1alpha2.APIServiceExport{}, indexers.ServiceExportByBoundSchema, - indexers.IndexServiceExportByBoundSchemaControllerRuntime); err != nil { - return nil, fmt.Errorf("failed to setup ServiceExportByBoundSchema indexer: %w", err) - } - - r := &APIServiceExportReconciler{ - manager: mgr, - opts: opts, - reconciler: reconciler{ - scope: scope, - getBoundSchema: func(ctx context.Context, cache cache.Cache, namespace, name string) (*kubebindv1alpha2.BoundSchema, error) { - var schema kubebindv1alpha2.BoundSchema - key := types.NamespacedName{Namespace: namespace, Name: name} - if err := cache.Get(ctx, key, &schema); err != nil { - return nil, err - } - return &schema, nil - }, - }, - } - - return r, nil -} - -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports/finalizers,verbs=update -//+kubebuilder:rbac:groups=kube-bind.io,resources=boundschemas,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=boundschemas/status,verbs=get;update;patch;list - -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -func (r *APIServiceExportReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling APIServiceExport", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - // Fetch the APIServiceExport instance - apiServiceExport := &kubebindv1alpha2.APIServiceExport{} - if err := client.Get(ctx, req.NamespacedName, apiServiceExport); err != nil { - if errors.IsNotFound(err) { - // Request object not found, could have been deleted after reconcile request. - logger.Info("APIServiceExport not found, ignoring") - return ctrl.Result{}, nil - } - // Error reading the object - requeue the request. - return ctrl.Result{}, fmt.Errorf("failed to get APIServiceExport: %w", err) - } - - // Create a copy to modify - original := apiServiceExport.DeepCopy() - - // Run the reconciliation logic - if err := r.reconciler.reconcile(ctx, cache, apiServiceExport); err != nil { - logger.Error(err, "Failed to reconcile APIServiceExport") - return ctrl.Result{}, err - } - - // Update annotations changed (hash), we need to propagate it and requeue for status changes. - // This is why we compare annotations only as we don't expect any changes to spec. - // Status changes are handled below. - if !equality.Semantic.DeepEqual(original.Annotations, apiServiceExport.Annotations) { - if err := client.Update(ctx, apiServiceExport); err != nil { - return ctrl.Result{}, fmt.Errorf("failed to update APIServiceExport: %w", err) - } - logger.Info("APIServiceExport hash updated", "namespace", apiServiceExport.Namespace, "name", apiServiceExport.Name) - return ctrl.Result{Requeue: true}, nil - } - if !equality.Semantic.DeepEqual(original.Status, apiServiceExport.Status) { - if err := client.Status().Update(ctx, apiServiceExport); err != nil { - return ctrl.Result{}, fmt.Errorf("failed to update APIServiceExport status: %w", err) - } - logger.Info("APIServiceExport status updated", "namespace", apiServiceExport.Namespace, "name", apiServiceExport.Name) - } - - return ctrl.Result{}, nil -} - -// getAPIResourceSchemaMapper returns a mapper function that uses the manager to find related APIServiceExports. -func getBoundSchemaMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - boundSchema := obj.(*kubebindv1alpha2.BoundSchema) - boundSchemaKey := boundSchema.Spec.Names.Plural + "." + boundSchema.Spec.Group - c := cl.GetClient() - - var exports kubebindv1alpha2.APIServiceExportList - if err := c.List(ctx, &exports, client.MatchingFields{indexers.ServiceExportByBoundSchema: boundSchemaKey}); err != nil { - return []mcreconcile.Request{} - } - - var requests []mcreconcile.Request - for _, export := range exports.Items { - requests = append(requests, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: client.ObjectKeyFromObject(&export), - }, - ClusterName: clusterName, - }) - } - - return requests - }) -} - -// SetupWithManager sets up the controller with the Manager. -func (r *APIServiceExportReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.APIServiceExport{}). - Watches( - &kubebindv1alpha2.BoundSchema{}, - getBoundSchemaMapper, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/controllers/serviceexport/serviceexport_reconcile.go b/backend/controllers/serviceexport/serviceexport_reconcile.go deleted file mode 100644 index 23061c530..000000000 --- a/backend/controllers/serviceexport/serviceexport_reconcile.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexport - -import ( - "context" - - "k8s.io/apimachinery/pkg/api/errors" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/cache" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2/helpers" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct { - scope kubebindv1alpha2.InformerScope - getBoundSchema func(ctx context.Context, cache cache.Cache, namespace, name string) (*kubebindv1alpha2.BoundSchema, error) -} - -func (r *reconciler) reconcile(ctx context.Context, cache cache.Cache, export *kubebindv1alpha2.APIServiceExport) error { - var errs []error - - if err := r.ensureSchema(ctx, cache, export); err != nil { - errs = append(errs, err) - } - - if r.scope == kubebindv1alpha2.ClusterScope { - if err := r.ensureClusterPermissions(ctx, cache, export); err != nil { - errs = append(errs, err) - } - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureSchema(ctx context.Context, cache cache.Cache, export *kubebindv1alpha2.APIServiceExport) error { - logger := klog.FromContext(ctx) - schemas := make([]*kubebindv1alpha2.BoundSchema, 0, len(export.Spec.Resources)) - - for _, res := range export.Spec.Resources { - name := res.ResourceGroupName() - schema, err := r.getBoundSchema(ctx, cache, export.Namespace, name) - if err != nil { - if errors.IsNotFound(err) { - conditions.MarkFalse( - export, - kubebindv1alpha2.APIServiceExportConditionProviderInSync, - "BoundSchemaMissing", - conditionsapi.ConditionSeverityError, - "BoundSchema %q is not available: %v", name, err) - return nil - } - return err - } - - schemas = append(schemas, schema) - } - - hash, err := helpers.BoundSchemasSpecHash(schemas) - if err != nil { - return err - } - - if export.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey] != hash { - // both exist, update APIServiceExport - logger.V(1).Info("Updating APIServiceExport. Hash mismatch", "hash", hash, "expected", export.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey]) - if export.Annotations == nil { - export.Annotations = map[string]string{} - } - export.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey] = hash - return nil - } - - conditions.MarkTrue(export, kubebindv1alpha2.APIServiceExportConditionProviderInSync) - - return nil -} - -// ensureClusterPermissions ensures that the necessary cluster-wide permissions are in place for the exported APIs. -// This runs only when backend is operating in ClusterScope. In this scenario, there might not yet be a namespace so -// APIServiceNamespace reconciliation cannot be used. -func (r *reconciler) ensureClusterPermissions(ctx context.Context, cache cache.Cache, export *kubebindv1alpha2.APIServiceExport) error { - // TODO(mjudeikis): implement this for cluster scoped resources. - // https://github.com/kube-bind/kube-bind/issues/344 - return nil -} diff --git a/backend/controllers/serviceexportrbac/rbac_controller.go b/backend/controllers/serviceexportrbac/rbac_controller.go deleted file mode 100644 index 982df5550..000000000 --- a/backend/controllers/serviceexportrbac/rbac_controller.go +++ /dev/null @@ -1,220 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 serviceexportrbac - -import ( - "context" - "fmt" - - v1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-serviceexport-rbac" -) - -type APIServiceExportRBACReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - reconciler reconciler -} - -func NewAPIServiceExportRBACReconciler( - ctx context.Context, - mgr mcmanager.Manager, - scope kubebindv1alpha2.InformerScope, - opts controller.TypedOptions[mcreconcile.Request], -) (*APIServiceExportRBACReconciler, error) { - return &APIServiceExportRBACReconciler{ - manager: mgr, - opts: opts, - - reconciler: reconciler{ - scope: scope, - // Namespace related. - listServiceNamespaces: func(ctx context.Context, cache cache.Cache, namespace string) ([]*kubebindv1alpha2.APIServiceNamespace, error) { - var list kubebindv1alpha2.APIServiceNamespaceList - if err := cache.List(ctx, &list, client.InNamespace(namespace)); err != nil { - return nil, err - } - var serviceNamespaces []*kubebindv1alpha2.APIServiceNamespace - for i := range list.Items { - serviceNamespaces = append(serviceNamespaces, &list.Items[i]) - } - return serviceNamespaces, nil - }, - getNamespace: func(ctx context.Context, cache cache.Cache, name string) (*v1.Namespace, error) { - var ns v1.Namespace - key := types.NamespacedName{Name: name} - if err := cache.Get(ctx, key, &ns); err != nil { - return nil, err - } - return &ns, nil - }, - // ClusterRole. - getClusterRole: func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRole, error) { - var role rbacv1.ClusterRole - if err := cache.Get(ctx, key, &role); err != nil { - return nil, err - } - return &role, nil - }, - createClusterRole: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRole) error { - return client.Create(ctx, binding) - }, - updateClusterRole: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRole) error { - return client.Update(ctx, binding) - }, - // ClusterRoleBinding. - getClusterRoleBinding: func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRoleBinding, error) { - var binding rbacv1.ClusterRoleBinding - if err := cache.Get(ctx, key, &binding); err != nil { - return nil, err - } - return &binding, nil - }, - createClusterRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRoleBinding) error { - return client.Create(ctx, binding) - }, - updateClusterRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.ClusterRoleBinding) error { - return client.Update(ctx, binding) - }, - // Role. - getRole: func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.Role, error) { - var role rbacv1.Role - if err := cache.Get(ctx, key, &role); err != nil { - return nil, err - } - return &role, nil - }, - createRole: func(ctx context.Context, client client.Client, role *rbacv1.Role) error { - return client.Create(ctx, role) - }, - updateRole: func(ctx context.Context, client client.Client, role *rbacv1.Role) error { - return client.Update(ctx, role) - }, - // RoleBinding. - getRoleBinding: func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.RoleBinding, error) { - var binding rbacv1.RoleBinding - if err := cache.Get(ctx, key, &binding); err != nil { - return nil, err - } - return &binding, nil - }, - createRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.RoleBinding) error { - return client.Create(ctx, binding) - }, - updateRoleBinding: func(ctx context.Context, client client.Client, binding *rbacv1.RoleBinding) error { - return client.Update(ctx, binding) - }, - }, - }, nil -} - -func (r *APIServiceExportRBACReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling APIServiceExport", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - // Fetch the APIServiceExport instance - export := kubebindv1alpha2.APIServiceExport{} - if err := client.Get(ctx, req.NamespacedName, &export); err != nil { - if errors.IsNotFound(err) { - // Request object not found, could have been deleted after reconcile request. - logger.Info("APIServiceExport not found, ignoring") - return ctrl.Result{}, nil - } - // Error reading the object - requeue the request. - return ctrl.Result{}, fmt.Errorf("failed to get APIServiceExport: %w", err) - } - - // Run the reconciliation logic - if err := r.reconciler.reconcile(ctx, client, cache, &export); err != nil { - logger.Error(err, "Failed to reconcile APIServiceExport") - return ctrl.Result{}, err - } - - return ctrl.Result{}, nil -} - -func (r *APIServiceExportRBACReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.APIServiceExport{}). - Watches( - &kubebindv1alpha2.APIServiceNamespace{}, - mapAPIServiceNamespace, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} - -func mapAPIServiceNamespace(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - serviceNamespace, ok := obj.(*kubebindv1alpha2.APIServiceNamespace) - if !ok { - return nil - } - - c := cl.GetClient() - - var exports kubebindv1alpha2.APIServiceExportList - if err := c.List(ctx, &exports, client.InNamespace(serviceNamespace.Namespace)); err != nil { - return []mcreconcile.Request{} - } - - var results []mcreconcile.Request - for _, export := range exports.Items { - results = append(results, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: export.Namespace, - Name: export.Name, - }, - }, - ClusterName: clusterName, - }) - } - - return results - }) -} diff --git a/backend/controllers/serviceexportrbac/rbac_reconciler.go b/backend/controllers/serviceexportrbac/rbac_reconciler.go deleted file mode 100644 index dcb9ae957..000000000 --- a/backend/controllers/serviceexportrbac/rbac_reconciler.go +++ /dev/null @@ -1,443 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 serviceexportrbac - -import ( - "context" - "fmt" - "maps" - "reflect" - "slices" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" - - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type reconciler struct { - scope kubebindv1alpha2.InformerScope - - listServiceNamespaces func(ctx context.Context, cache cache.Cache, namespace string) ([]*kubebindv1alpha2.APIServiceNamespace, error) - getNamespace func(ctx context.Context, cache cache.Cache, name string) (*corev1.Namespace, error) - - getClusterRole func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRole, error) - createClusterRole func(ctx context.Context, client client.Client, clusterRole *rbacv1.ClusterRole) error - updateClusterRole func(ctx context.Context, client client.Client, clusterRole *rbacv1.ClusterRole) error - - getClusterRoleBinding func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRoleBinding, error) - createClusterRoleBinding func(ctx context.Context, client client.Client, clusterRoleBinding *rbacv1.ClusterRoleBinding) error - updateClusterRoleBinding func(ctx context.Context, client client.Client, clusterRoleBinding *rbacv1.ClusterRoleBinding) error - - getRole func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.Role, error) - createRole func(ctx context.Context, client client.Client, role *rbacv1.Role) error - updateRole func(ctx context.Context, client client.Client, role *rbacv1.Role) error - - getRoleBinding func(ctx context.Context, cache cache.Cache, key types.NamespacedName) (*rbacv1.RoleBinding, error) - createRoleBinding func(ctx context.Context, client client.Client, roleBinding *rbacv1.RoleBinding) error - updateRoleBinding func(ctx context.Context, client client.Client, roleBinding *rbacv1.RoleBinding) error -} - -const ( - rbacAggregateLabelKey = "rbac.kube-bind.io/aggregate-to-parent" -) - -func (r *reconciler) reconcile(ctx context.Context, client client.Client, cache cache.Cache, export *kubebindv1alpha2.APIServiceExport) error { - logger := log.FromContext(ctx) - - var errs []error - - // Retrieve policy rules for exported and claimed resources. - - // buildPolicyRules transforms the input groupResourceSet - // into a slice of PolicyRules with deterministic ordering. - buildPolicyRules := func(verbs []string, groupResourceSet map[string]metav1.GroupResource) []rbacv1.PolicyRule { - rules := make([]rbacv1.PolicyRule, 0, len(groupResourceSet)) - for _, key := range slices.Sorted(maps.Keys(groupResourceSet)) { - gr := groupResourceSet[key] - rules = append(rules, rbacv1.PolicyRule{ - APIGroups: []string{gr.Group}, - Resources: []string{gr.Resource}, - Verbs: verbs, - }) - } - return rules - } - - resourceGroupResourceSet := make(map[string]metav1.GroupResource) - for _, res := range export.Spec.Resources { - resourceGroupResourceSet[res.GroupResource.String()] = metav1.GroupResource(res.GroupResource) - } - resourceRules := buildPolicyRules( - []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - resourceGroupResourceSet, - ) - - clusterScopedClaimsGroupResourceSet := make(map[string]metav1.GroupResource) - namespaceScopedClaimsGroupResourceSet := make(map[string]metav1.GroupResource) - for _, claim := range export.Spec.PermissionClaims { - var claimScope apiextensionsv1.ResourceScope - for _, claimableAPI := range kubebindv1alpha2.ClaimableAPIs { - if claim.Group == claimableAPI.GroupVersionResource.Group && claim.Resource == claimableAPI.GroupVersionResource.Resource { - claimScope = claimableAPI.ResourceScope - break - } - } - switch claimScope { - case apiextensionsv1.ClusterScoped: - clusterScopedClaimsGroupResourceSet[claim.GroupResource.String()] = metav1.GroupResource(claim.GroupResource) - case apiextensionsv1.NamespaceScoped: - namespaceScopedClaimsGroupResourceSet[claim.GroupResource.String()] = metav1.GroupResource(claim.GroupResource) - default: - // This claimed resource is not in our claimable APIs list. - // There is nothing we can do about it here, just skip it. - logger.V(2).Info("Skipping RBAC reconciliation for claimed resource because it's not a claimable API", - "resource", claim.GroupResource.String()) - continue - } - } - clusterScopedClaimRules := buildPolicyRules( - []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - clusterScopedClaimsGroupResourceSet, - ) - namespaceScopedClaimRules := buildPolicyRules( - []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - namespaceScopedClaimsGroupResourceSet, - ) - - // Here we ensure RBAC objects are in place. - // - // Cluster-scoped RBACs: - // - // - kube-binder-exports ClusterRole and ClusterRoleBinding - // * bound to /kube-binder ServiceAccount - // Aggregating ClusterRole for all subsequent ClusterRoles we create. - // - kube-binder-resources-- ClusterRole - // Access to all resources declared in APIServiceExport.Spec.Resources. - // Aggregates into kube-binder-exports ClusterRole. - // - kube-binder-claims-- ClusterRole - // Access to all cluster-scoped claimed resources declared in APIServiceExport.Spec.PermissionClaims. - // Aggregates into kube-binder-exports ClusterRole. - // - // Namespace-scoped RBACs: - // - // - /kube-binder-claims- Role and RoleBinding - // * bound to /kube-binder ServiceAccount - // Access to namespace-scoped claimed resources declared in APIServiceExport.Spec.PermissionClaims. - - // We use the owner ref below in "kube-binder-{resources,claims}-*" - // ClusterRoles and ClusterRoleBindings for automatic cleanup. - ns, err := r.getNamespace(ctx, cache, export.Namespace) - if err != nil { - return err - } - ownerRefs := []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: ns.Name, - UID: ns.UID, - }, - } - - // We always bind to the /kube-binder ServiceAccount. - kubebinderSubject := []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: export.Namespace, - Name: kuberesources.ServiceAccountName, - }, - } - - errs = append(errs, - r.ensureAggregatingClusteRoleAndClusterRoleBinding(ctx, client, cache, kubebinderSubject), - // We always use cluster-scoped RBACs for exported resources. - r.ensureAggregatedClusterRole(ctx, client, cache, - fmt.Sprintf("kube-binder-resources-%s-%s", export.Namespace, export.Name), - ownerRefs, - resourceRules, - ), - ) - - // Now onto claimed resources RBACs. - - switch r.scope { - case kubebindv1alpha2.ClusterScope: - errs = append(errs, - r.ensureAggregatedClusterRole(ctx, client, cache, - fmt.Sprintf("kube-binder-claims-%s-%s", export.Namespace, export.Name), - ownerRefs, - append(clusterScopedClaimRules, namespaceScopedClaimRules...), - ), - ) - case kubebindv1alpha2.NamespacedScope: - errs = append(errs, - r.ensureAggregatedClusterRole(ctx, client, cache, - fmt.Sprintf("kube-binder-claims-%s-%s", export.Namespace, export.Name), - ownerRefs, - clusterScopedClaimRules, - ), - ) - serviceNamespaces, err := r.listServiceNamespaces(ctx, cache, export.Namespace) - if err != nil { - errs = append(errs, err) - return utilerrors.NewAggregate(errs) - } - for _, serviceNamespace := range serviceNamespaces { - if serviceNamespace.Status.Namespace == "" { - continue - } - errs = append(errs, - r.ensureRoleAndRoleBinding(ctx, client, cache, - serviceNamespace.Status.Namespace, - fmt.Sprintf("kube-binder-claims-%s", export.Name), - kubebinderSubject, - namespaceScopedClaimRules, - ), - ) - } - default: - errs = append(errs, fmt.Errorf("unknown informer scope %q", r.scope)) // This should not happen! - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureRoleAndRoleBinding(ctx context.Context, client client.Client, cache cache.Cache, namespace, name string, subjects []rbacv1.Subject, rules []rbacv1.PolicyRule) error { - // Ensure the Role exists. - - expectedRole := rbacv1.Role{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Rules: rules, - } - - role, err := getOrCreate(ctx, - cache, - client, - &expectedRole, - r.getRole, - r.createRole, - ) - if err != nil { - return err - } - - if !reflect.DeepEqual(expectedRole.Rules, role.Rules) { - copyRole := role.DeepCopy() - copyRole.Rules = expectedRole.Rules - if err := r.updateRole(ctx, client, copyRole); err != nil { - return err - } - } - - // And also ensure its RoleBinding exists too. - - expectedRoleBinding := rbacv1.RoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "Role", - Name: name, - }, - Subjects: subjects, - } - - roleBinding, err := getOrCreate( - ctx, - cache, - client, - &expectedRoleBinding, - r.getRoleBinding, - r.createRoleBinding, - ) - if err != nil { - return err - } - - if !reflect.DeepEqual(expectedRoleBinding.Subjects, roleBinding.Subjects) { - // We don't check .RoleRef because it's immutable. - copyRoleBinding := roleBinding.DeepCopy() - copyRoleBinding.Subjects = expectedRoleBinding.Subjects - return r.updateRoleBinding(ctx, client, copyRoleBinding) - } - - return nil -} - -func (r *reconciler) ensureAggregatedClusterRole(ctx context.Context, client client.Client, cache cache.Cache, name string, owners []metav1.OwnerReference, rules []rbacv1.PolicyRule) error { - expectedClusterRole := rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Labels: map[string]string{ - rbacAggregateLabelKey: "true", - }, - OwnerReferences: owners, - }, - Rules: rules, - } - - clusterRole, err := getOrCreate(ctx, - cache, - client, - &expectedClusterRole, - r.getClusterRole, - r.createClusterRole, - ) - if err != nil { - return err - } - - if clusterRole.Labels == nil || clusterRole.Labels[rbacAggregateLabelKey] != "true" || - !reflect.DeepEqual(expectedClusterRole.OwnerReferences, clusterRole.OwnerReferences) || - !reflect.DeepEqual(expectedClusterRole.Rules, clusterRole.Rules) { - // We don't check .RoleRef because it's immutable. - copyClusterRole := clusterRole.DeepCopy() - if copyClusterRole.Labels == nil { - copyClusterRole.Labels = make(map[string]string) - } - copyClusterRole.Labels[rbacAggregateLabelKey] = "true" - copyClusterRole.OwnerReferences = expectedClusterRole.OwnerReferences - copyClusterRole.Rules = expectedClusterRole.Rules - return r.updateClusterRole(ctx, client, copyClusterRole) - } - - return nil -} - -func (r *reconciler) ensureAggregatingClusteRoleAndClusterRoleBinding(ctx context.Context, client client.Client, cache cache.Cache, subjects []rbacv1.Subject) error { - const name = "kube-binder-exports" - - // Ensure the "kube-binder-exports" ClusterRole exists. - - expectedClusterRole := rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - AggregationRule: &rbacv1.AggregationRule{ - ClusterRoleSelectors: []metav1.LabelSelector{ - { - MatchLabels: map[string]string{ - rbacAggregateLabelKey: "true", - }, - }, - }, - }, - } - - clusterRole, err := getOrCreate(ctx, - cache, - client, - &expectedClusterRole, - r.getClusterRole, - r.createClusterRole, - ) - if err != nil { - return err - } - - if !reflect.DeepEqual(expectedClusterRole.AggregationRule, clusterRole.AggregationRule) { - copyClusterRole := clusterRole.DeepCopy() - copyClusterRole.AggregationRule = expectedClusterRole.AggregationRule - if err := r.updateClusterRole(ctx, client, copyClusterRole); err != nil { - return err - } - } - - // Now ensure its "kube-binder-exports" ClusterRoleBinding exists. - - expectedClusterRoleBinding := rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: name, - }, - Subjects: subjects, - } - - clusterRoleBinding, err := getOrCreate(ctx, - cache, - client, - &expectedClusterRoleBinding, - r.getClusterRoleBinding, - r.createClusterRoleBinding, - ) - if err != nil { - return err - } - - if !reflect.DeepEqual(expectedClusterRoleBinding.Subjects, clusterRoleBinding.Subjects) { - // We don't check .RoleRef because it's immutable. - copyClusterRoleBinding := clusterRoleBinding.DeepCopy() - copyClusterRoleBinding.Subjects = expectedClusterRoleBinding.Subjects - return r.updateClusterRoleBinding(ctx, client, copyClusterRoleBinding) - } - - return nil -} - -func getOrCreate[R client.Object]( - ctx context.Context, - cache cache.Cache, - client client.Client, - expectedObj R, - - get func( - ctx context.Context, - cache cache.Cache, - key types.NamespacedName, - ) (R, error), - - create func( - ctx context.Context, - client client.Client, - obj R, - ) error, - -) (R, error) { - var empty R - obj, err := get(ctx, cache, types.NamespacedName{Name: expectedObj.GetName(), Namespace: expectedObj.GetNamespace()}) - - if err != nil { - if !apierrors.IsNotFound(err) { - return empty, err - } - if err = create(ctx, client, expectedObj); err != nil && !apierrors.IsAlreadyExists(err) { - return empty, err - } - return expectedObj, nil - } - - return obj, nil -} diff --git a/backend/controllers/serviceexportrbac/rbac_reconciler_test.go b/backend/controllers/serviceexportrbac/rbac_reconciler_test.go deleted file mode 100644 index d5cc60fb8..000000000 --- a/backend/controllers/serviceexportrbac/rbac_reconciler_test.go +++ /dev/null @@ -1,857 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 serviceexportrbac - -import ( - "context" - "maps" - "slices" - "testing" - - "github.com/stretchr/testify/require" - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func Test_reconciler_reconcile(t *testing.T) { - type state struct { - clusterRoles map[string]*rbacv1.ClusterRole - clusterRoleBindings map[string]*rbacv1.ClusterRoleBinding - roles map[string]*rbacv1.Role - roleBindings map[string]*rbacv1.RoleBinding - } - normalizeState := func(st *state) { - if st.clusterRoles == nil { - st.clusterRoles = make(map[string]*rbacv1.ClusterRole) - } - if st.clusterRoleBindings == nil { - st.clusterRoleBindings = make(map[string]*rbacv1.ClusterRoleBinding) - } - if st.clusterRoleBindings == nil { - st.clusterRoleBindings = make(map[string]*rbacv1.ClusterRoleBinding) - } - if st.roles == nil { - st.roles = make(map[string]*rbacv1.Role) - } - if st.roleBindings == nil { - st.roleBindings = make(map[string]*rbacv1.RoleBinding) - } - } - - newReconcilerWithState := func(scope kubebindv1alpha2.InformerScope, namespaces map[string]*corev1.Namespace, apiServiceNamespaces map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace, st *state) reconciler { - return reconciler{ - scope: scope, - listServiceNamespaces: func(ctx context.Context, _ cache.Cache, namespace string) ([]*kubebindv1alpha2.APIServiceNamespace, error) { - return slices.Collect(maps.Values(apiServiceNamespaces)), nil - }, - getClusterRole: func(ctx context.Context, _ cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRole, error) { - clusterRole, ok := st.clusterRoles[key.Name] - if !ok { - return nil, apierrors.NewNotFound(rbacv1.Resource("clusterroles"), key.Name) - } - return clusterRole, nil - }, - createClusterRole: func(ctx context.Context, _ client.Client, binding *rbacv1.ClusterRole) error { - _, ok := st.clusterRoles[binding.Name] - if ok { - return apierrors.NewAlreadyExists(rbacv1.Resource("clusterroles"), binding.Name) - } - st.clusterRoles[binding.Name] = binding - return nil - }, - updateClusterRole: func(ctx context.Context, _ client.Client, binding *rbacv1.ClusterRole) error { - _, ok := st.clusterRoles[binding.Name] - if !ok { - return apierrors.NewNotFound(rbacv1.Resource("clusterroles"), binding.Name) - } - st.clusterRoles[binding.Name] = binding - return nil - }, - getRole: func(ctx context.Context, _ cache.Cache, key types.NamespacedName) (*rbacv1.Role, error) { - role, ok := st.roles[key.String()] - if !ok { - return nil, apierrors.NewNotFound(rbacv1.Resource("roles"), key.String()) - } - return role, nil - }, - createRole: func(ctx context.Context, _ client.Client, role *rbacv1.Role) error { - key := types.NamespacedName{Namespace: role.Namespace, Name: role.Name}.String() - _, ok := st.roles[key] - if ok { - return apierrors.NewAlreadyExists(rbacv1.Resource("roles"), key) - } - st.roles[key] = role - return nil - }, - updateRole: func(ctx context.Context, _ client.Client, role *rbacv1.Role) error { - key := types.NamespacedName{Namespace: role.Namespace, Name: role.Name}.String() - _, ok := st.roles[key] - if !ok { - return apierrors.NewNotFound(rbacv1.Resource("roles"), key) - } - st.roles[key] = role - return nil - }, - getClusterRoleBinding: func(ctx context.Context, _ cache.Cache, key types.NamespacedName) (*rbacv1.ClusterRoleBinding, error) { - clusterRoleBinding, ok := st.clusterRoleBindings[key.Name] - if !ok { - return nil, apierrors.NewNotFound(rbacv1.Resource("clusterrolebindings"), key.Name) - } - return clusterRoleBinding, nil - }, - createClusterRoleBinding: func(ctx context.Context, _ client.Client, binding *rbacv1.ClusterRoleBinding) error { - _, ok := st.clusterRoleBindings[binding.Name] - if ok { - return apierrors.NewAlreadyExists(rbacv1.Resource("clusterrolebindings"), binding.Name) - } - st.clusterRoleBindings[binding.Name] = binding - return nil - }, - updateClusterRoleBinding: func(ctx context.Context, _ client.Client, binding *rbacv1.ClusterRoleBinding) error { - _, ok := st.clusterRoleBindings[binding.Name] - if !ok { - return apierrors.NewNotFound(rbacv1.Resource("clusterrolebindings"), binding.Name) - } - st.clusterRoleBindings[binding.Name] = binding - return nil - }, - getRoleBinding: func(ctx context.Context, _ cache.Cache, key types.NamespacedName) (*rbacv1.RoleBinding, error) { - roleBinding, ok := st.roleBindings[key.String()] - if !ok { - return nil, apierrors.NewNotFound(rbacv1.Resource("rolebindings"), key.String()) - } - return roleBinding, nil - }, - createRoleBinding: func(ctx context.Context, _ client.Client, binding *rbacv1.RoleBinding) error { - key := types.NamespacedName{Namespace: binding.Namespace, Name: binding.Name}.String() - _, ok := st.roleBindings[key] - if ok { - return apierrors.NewAlreadyExists(rbacv1.Resource("rolebindings"), key) - } - st.roleBindings[key] = binding - return nil - }, - updateRoleBinding: func(ctx context.Context, _ client.Client, binding *rbacv1.RoleBinding) error { - key := types.NamespacedName{Namespace: binding.Namespace, Name: binding.Name}.String() - _, ok := st.roleBindings[key] - if !ok { - return apierrors.NewNotFound(rbacv1.Resource("rolebindings"), key) - } - st.roleBindings[key] = binding - return nil - }, - getNamespace: func(ctx context.Context, _ cache.Cache, name string) (*corev1.Namespace, error) { - namespace, ok := namespaces[name] - if !ok { - return nil, apierrors.NewNotFound(corev1.Resource("namespaces"), name) - } - return namespace, nil - }, - } - } - - export := &kubebindv1alpha2.APIServiceExport{ - ObjectMeta: metav1.ObjectMeta{ - Name: "my-export", - Namespace: "kube-binder-abcd1234", - }, - Spec: kubebindv1alpha2.APIServiceExportSpec{ - Resources: []kubebindv1alpha2.APIServiceExportResource{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "wildwest.dev", - Resource: "cowboys", - }, - Versions: []string{"v1alpha1"}, - }, - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "wildwest.dev", - Resource: "cowgirls", - }, - Versions: []string{"v1alpha1"}, - }, - }, - PermissionClaims: []kubebindv1alpha2.PermissionClaim{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "", - Resource: "secrets", - }, - }, - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "", - Resource: "configmaps", - }, - }, - }, - }, - } - - tests := map[string]struct { - scope kubebindv1alpha2.InformerScope - namespaces map[string]*corev1.Namespace - apiServiceNamespaces map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace - st state - - expectedState state - expectedErr error - }{ - "cluster scoped with no pre-existing RBACs": { - scope: kubebindv1alpha2.ClusterScope, - namespaces: map[string]*corev1.Namespace{ - "kube-binder-abcd1234": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - apiServiceNamespaces: map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace{ - {Namespace: "kube-binder-abcd1234", Name: "consumer-ns-1"}: { - ObjectMeta: metav1.ObjectMeta{ - Name: "consumer-ns-1", - Namespace: "kube-binder-abcd1234", - }, - Status: kubebindv1alpha2.APIServiceNamespaceStatus{ - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - }, - }, - st: state{}, - expectedState: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - AggregationRule: &rbacv1.AggregationRule{ - ClusterRoleSelectors: []metav1.LabelSelector{ - { - MatchLabels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - }, - }, - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowboys"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowgirls"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{""}, - Resources: []string{"configmaps"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"secrets"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - }, - }, - "cluster scoped with wrong pre-existing RBACs": { - scope: kubebindv1alpha2.ClusterScope, - namespaces: map[string]*corev1.Namespace{ - "kube-binder-abcd1234": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - apiServiceNamespaces: map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace{ - {Namespace: "kube-binder-abcd1234", Name: "consumer-ns-1"}: { - ObjectMeta: metav1.ObjectMeta{ - Name: "consumer-ns-1", - Namespace: "kube-binder-abcd1234", - }, - Status: kubebindv1alpha2.APIServiceNamespaceStatus{ - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - }, - }, - st: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - }, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - }, - }, - }, - expectedState: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - AggregationRule: &rbacv1.AggregationRule{ - ClusterRoleSelectors: []metav1.LabelSelector{ - { - MatchLabels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - }, - }, - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowboys"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowgirls"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{""}, - Resources: []string{"configmaps"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"secrets"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - }, - }, - "namespaced scoped with no pre-existing RBACs": { - scope: kubebindv1alpha2.NamespacedScope, - namespaces: map[string]*corev1.Namespace{ - "kube-binder-abcd1234": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - apiServiceNamespaces: map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace{ - {Namespace: "kube-binder-abcd1234", Name: "consumer-ns-1"}: { - ObjectMeta: metav1.ObjectMeta{ - Name: "consumer-ns-1", - Namespace: "kube-binder-abcd1234", - }, - Status: kubebindv1alpha2.APIServiceNamespaceStatus{ - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - }, - }, - st: state{}, - expectedState: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - AggregationRule: &rbacv1.AggregationRule{ - ClusterRoleSelectors: []metav1.LabelSelector{ - { - MatchLabels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - }, - }, - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowboys"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowgirls"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{}, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - roles: map[string]*rbacv1.Role{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{""}, - Resources: []string{"configmaps"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"secrets"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - }, - roleBindings: map[string]*rbacv1.RoleBinding{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "Role", - Name: "kube-binder-claims-my-export", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - }, - }, - "namespaced scoped with wrong pre-existing RBACs": { - scope: kubebindv1alpha2.NamespacedScope, - namespaces: map[string]*corev1.Namespace{ - "kube-binder-abcd1234": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - apiServiceNamespaces: map[types.NamespacedName]*kubebindv1alpha2.APIServiceNamespace{ - {Namespace: "kube-binder-abcd1234", Name: "consumer-ns-1"}: { - ObjectMeta: metav1.ObjectMeta{ - Name: "consumer-ns-1", - Namespace: "kube-binder-abcd1234", - }, - Status: kubebindv1alpha2.APIServiceNamespaceStatus{ - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - }, - }, - st: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - }, - Rules: []rbacv1.PolicyRule{}, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - }, - }, - roles: map[string]*rbacv1.Role{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - }, - }, - roleBindings: map[string]*rbacv1.RoleBinding{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "Role", - Name: "kube-binder-claims-my-export", - }, - }, - }, - }, - expectedState: state{ - clusterRoles: map[string]*rbacv1.ClusterRole{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - AggregationRule: &rbacv1.AggregationRule{ - ClusterRoleSelectors: []metav1.LabelSelector{ - { - MatchLabels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - }, - }, - }, - }, - "kube-binder-resources-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-resources-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowboys"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{"wildwest.dev"}, - Resources: []string{"cowgirls"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - "kube-binder-claims-kube-binder-abcd1234-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-kube-binder-abcd1234-my-export", - Labels: map[string]string{ - "rbac.kube-bind.io/aggregate-to-parent": "true", - }, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Namespace", - Name: "kube-binder-abcd1234", - UID: "uid-123", - }, - }, - }, - Rules: []rbacv1.PolicyRule{}, - }, - }, - clusterRoleBindings: map[string]*rbacv1.ClusterRoleBinding{ - "kube-binder-exports": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-exports", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder-exports", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - roles: map[string]*rbacv1.Role{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{""}, - Resources: []string{"configmaps"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"secrets"}, - Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, - }, - }, - }, - }, - roleBindings: map[string]*rbacv1.RoleBinding{ - "kube-binder-abcd1234-consumer-ns-1/kube-binder-claims-my-export": { - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder-claims-my-export", - Namespace: "kube-binder-abcd1234-consumer-ns-1", - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "Role", - Name: "kube-binder-claims-my-export", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: "kube-binder-abcd1234", - Name: "kube-binder", - }, - }, - }, - }, - }, - }, - } - - for tname, tt := range tests { - t.Run(tname, func(t *testing.T) { - r := newReconcilerWithState(tt.scope, tt.namespaces, tt.apiServiceNamespaces, &tt.st) - - normalizeState(&tt.st) - normalizeState(&tt.expectedState) - - err := r.reconcile(context.Background(), nil, nil, export) - - if tt.expectedErr != nil { - require.EqualError(t, err, tt.expectedErr.Error(), "reconcile should have failed") - } else { - require.NoError(t, err, "reconcile should have succeeded") - } - - compareMap(t, "ClusterRole", tt.expectedState.clusterRoles, tt.st.clusterRoles) - compareMap(t, "ClusterRoleBinding", tt.expectedState.clusterRoleBindings, tt.st.clusterRoleBindings) - compareMap(t, "Role", tt.expectedState.roles, tt.st.roles) - compareMap(t, "RoleBinding", tt.expectedState.roleBindings, tt.st.roleBindings) - }) - } -} - -func compareMap[V any](t *testing.T, kind string, a, b map[string]V) { - t.Helper() - require.Equal(t, slices.Sorted(maps.Keys(a)), slices.Sorted(maps.Keys(b)), "got unexpected entries after %s reconciliation", kind) - for k := range a { - require.Equal(t, a[k], b[k], "got unexpected content in %s %s", k, kind) - } -} diff --git a/backend/controllers/serviceexportrequest/serviceexportrequest_controller.go b/backend/controllers/serviceexportrequest/serviceexportrequest_controller.go deleted file mode 100644 index d6e3ab1e3..000000000 --- a/backend/controllers/serviceexportrequest/serviceexportrequest_controller.go +++ /dev/null @@ -1,271 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexportrequest - -import ( - "context" - "fmt" - "reflect" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-serviceexportrequest" -) - -// APIServiceExportRequestReconciler reconciles a APIServiceExportRequest object. -type APIServiceExportRequestReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - - informerScope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - reconciler reconciler -} - -// NewAPIServiceExportRequestReconciler returns a new APIServiceExportRequestReconciler to reconcile APIServiceExportRequests. -func NewAPIServiceExportRequestReconciler( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - scope kubebindv1alpha2.InformerScope, - isolation kubebindv1alpha2.Isolation, - schemaSource string, - schemaSyncInterval time.Duration, -) (*APIServiceExportRequestReconciler, error) { - // Set up field indexers for APIServiceExportRequests - if err := mgr.GetFieldIndexer().IndexField(ctx, &kubebindv1alpha2.APIServiceExportRequest{}, indexers.ServiceExportRequestByServiceExport, - indexers.IndexServiceExportRequestByServiceExport); err != nil { - return nil, fmt.Errorf("failed to setup ServiceExportRequestByServiceExport indexer: %w", err) - } - - if err := mgr.GetFieldIndexer().IndexField(ctx, &kubebindv1alpha2.APIServiceExportRequest{}, indexers.ServiceExportRequestByGroupResource, - indexers.IndexServiceExportRequestByGroupResource); err != nil { - return nil, fmt.Errorf("failed to setup ServiceExportRequestByGroupResource indexer: %w", err) - } - - r := &APIServiceExportRequestReconciler{ - manager: mgr, - opts: opts, - informerScope: scope, - isolation: isolation, - reconciler: reconciler{ - informerScope: scope, - isolation: isolation, - schemaSource: schemaSource, - schemaSyncInterval: schemaSyncInterval, - getBoundSchema: func(ctx context.Context, cl client.Client, namespace, name string) (*kubebindv1alpha2.BoundSchema, error) { - var schema kubebindv1alpha2.BoundSchema - key := types.NamespacedName{Namespace: namespace, Name: name} - if err := cl.Get(ctx, key, &schema); err != nil { - return nil, err - } - return &schema, nil - }, - getServiceExport: func(ctx context.Context, cache cache.Cache, ns, name string) (*kubebindv1alpha2.APIServiceExport, error) { - var export kubebindv1alpha2.APIServiceExport - key := types.NamespacedName{Namespace: ns, Name: name} - if err := cache.Get(ctx, key, &export); err != nil { - return nil, err - } - return &export, nil - }, - createServiceExport: func(ctx context.Context, cl client.Client, resource *kubebindv1alpha2.APIServiceExport) error { - return cl.Create(ctx, resource) - }, - createBoundSchema: func(ctx context.Context, cl client.Client, schema *kubebindv1alpha2.BoundSchema) error { - return cl.Create(ctx, schema) - }, - updateBoundSchema: func(ctx context.Context, cl client.Client, schema *kubebindv1alpha2.BoundSchema) error { - return cl.Update(ctx, schema) - }, - deleteServiceExportRequest: func(ctx context.Context, cl client.Client, ns, name string) error { - return cl.Delete(ctx, &kubebindv1alpha2.APIServiceExportRequest{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: ns, - Name: name, - }, - }) - }, - }, - } - - return r, nil -} - -// getServiceExportRequestMapper creates a mapping function for ServiceExport changes. -func getServiceExportRequestMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - serviceExport := obj.(*kubebindv1alpha2.APIServiceExport) - seKey := serviceExport.Namespace + "/" + serviceExport.Name - - c := cl.GetClient() - - var requests kubebindv1alpha2.APIServiceExportRequestList - if err := c.List(ctx, &requests, client.MatchingFields{indexers.ServiceExportRequestByServiceExport: seKey}); err != nil { - return []mcreconcile.Request{} - } - - var result []mcreconcile.Request - for _, req := range requests.Items { - result = append(result, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: req.Namespace, - Name: req.Name, - }, - }, - ClusterName: clusterName, - }) - } - - return result - }) -} - -// getBoundSchemaMapper creates a mapping function for BoundSchema changes. -func getBoundSchemaMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - boundSchema := obj.(*kubebindv1alpha2.BoundSchema) - boundSchemaKey := boundSchema.Spec.Names.Plural + "." + boundSchema.Spec.Group - c := cl.GetClient() - - var requests kubebindv1alpha2.APIServiceExportRequestList - if err := c.List(ctx, &requests, client.MatchingFields{indexers.ServiceExportRequestByGroupResource: boundSchemaKey}); err != nil { - return []mcreconcile.Request{} - } - - var result []mcreconcile.Request - for _, req := range requests.Items { - result = append(result, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: req.Namespace, - Name: req.Name, - }, - }, - ClusterName: clusterName, - }) - } - return result - }) -} - -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexportrequests,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexportrequests/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexportrequests/finalizers,verbs=update -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiresourceschemas,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiservicenamespaces,verbs=get;list;watch;create - -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -func (r *APIServiceExportRequestReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling APIServiceExportRequest", "cluster", req.ClusterName, "namespace", req.Namespace, "name", req.Name) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - // Fetch the APIServiceExportRequest instance - apiServiceExportRequest := &kubebindv1alpha2.APIServiceExportRequest{} - if err := client.Get(ctx, req.NamespacedName, apiServiceExportRequest); err != nil { - if errors.IsNotFound(err) { - // Request object not found, could have been deleted after reconcile request. - logger.Info("APIServiceExportRequest not found, ignoring") - return ctrl.Result{}, nil - } - // Error reading the object - requeue the request. - return ctrl.Result{}, fmt.Errorf("failed to get APIServiceExportRequest: %w", err) - } - - // Create a copy to modify - original := apiServiceExportRequest.DeepCopy() - - // Run the reconciliation logic - if err := r.reconciler.reconcile(ctx, client, cache, apiServiceExportRequest); err != nil { - logger.Error(err, "Failed to reconcile APIServiceExportRequest") - if !reflect.DeepEqual(original.Status.Phase, apiServiceExportRequest.Status.Phase) { - if err := client.Status().Update(ctx, apiServiceExportRequest); err != nil { - logger.Error(err, "Failed to update APIServiceExportRequest status") - return ctrl.Result{}, fmt.Errorf("failed to update APIServiceExportRequest status: %w", err) - } - logger.Info("APIServiceExportRequest status updated", "namespace", apiServiceExportRequest.Namespace, "name", apiServiceExportRequest.Name) - } - - return ctrl.Result{}, err - } - - // Update status if it has changed - if !reflect.DeepEqual(original.Status, apiServiceExportRequest.Status) { - if err := client.Status().Update(ctx, apiServiceExportRequest); err != nil { - logger.Error(err, "Failed to update APIServiceExportRequest status") - return ctrl.Result{}, fmt.Errorf("failed to update APIServiceExportRequest status: %w", err) - } - logger.Info("APIServiceExportRequest status updated", "namespace", apiServiceExportRequest.Namespace, "name", apiServiceExportRequest.Name) - } - - // When SchemaUpdatePolicy is Always, periodically re-reconcile to pick up - // source CRD changes and sync them into BoundSchemas. - if apiServiceExportRequest.Spec.SchemaUpdatePolicy == kubebindv1alpha2.SchemaUpdatePolicyAlways { - return ctrl.Result{RequeueAfter: r.reconciler.schemaSyncInterval}, nil - } - - return ctrl.Result{}, nil -} - -// SetupWithManager sets up the controller with the Manager. -func (r *APIServiceExportRequestReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.APIServiceExportRequest{}). - Watches( - &kubebindv1alpha2.APIServiceExport{}, - getServiceExportRequestMapper, - ). - Watches( - &kubebindv1alpha2.BoundSchema{}, - getBoundSchemaMapper, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/controllers/serviceexportrequest/serviceexportrequest_reconcile.go b/backend/controllers/serviceexportrequest/serviceexportrequest_reconcile.go deleted file mode 100644 index 42cebc800..000000000 --- a/backend/controllers/serviceexportrequest/serviceexportrequest_reconcile.go +++ /dev/null @@ -1,453 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexportrequest - -import ( - "context" - "fmt" - "strings" - "time" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - - "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2/helpers" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct { - informerScope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - schemaSource string - schemaSyncInterval time.Duration - - getBoundSchema func(ctx context.Context, cl client.Client, namespace, name string) (*kubebindv1alpha2.BoundSchema, error) - createBoundSchema func(ctx context.Context, cl client.Client, schema *kubebindv1alpha2.BoundSchema) error - updateBoundSchema func(ctx context.Context, cl client.Client, schema *kubebindv1alpha2.BoundSchema) error - - getServiceExport func(ctx context.Context, cache cache.Cache, ns, name string) (*kubebindv1alpha2.APIServiceExport, error) - createServiceExport func(ctx context.Context, cl client.Client, resource *kubebindv1alpha2.APIServiceExport) error - deleteServiceExportRequest func(ctx context.Context, cl client.Client, namespace, name string) error -} - -func (r *reconciler) reconcile(ctx context.Context, cl client.Client, cache cache.Cache, req *kubebindv1alpha2.APIServiceExportRequest) error { - export, err := r.getServiceExport(ctx, cache, req.Namespace, req.Name) - if err != nil && !apierrors.IsNotFound(err) { - return fmt.Errorf("failed to get APIServiceExport: %w", err) - } - // We must ensure schemas are created in form of boundSchemas first for the validation. - // Worst case scenario if validation fails, we will reuse schemas for same consumer once issues are fixed. - if err := r.ensureBoundSchemas(ctx, cl, export, req); err != nil { - conditions.SetSummary(req) - return fmt.Errorf("failed to ensure bound schemas: %w", err) - } - - if err := r.validate(ctx, cl, req); err != nil { - conditions.SetSummary(req) - return fmt.Errorf("failed to validate APIServiceExportRequest: %w", err) - } - - if err := r.ensureExports(ctx, cl, export, req); err != nil { - conditions.SetSummary(req) - return fmt.Errorf("failed to ensure exports: %w", err) - } - - if err := r.ensureAPIServiceNamespaces(ctx, cl, cache, req); err != nil { - conditions.SetSummary(req) - return fmt.Errorf("failed to ensure APIServiceNamespaces: %w", err) - } - - conditions.SetSummary(req) - - return nil -} - -// getExportedSchemas will list all schemas, exported by current backend. -// Important: getExportedSchemas is using client.Client to list resources, not cache. -// This is due to fact we use dynamic client and unstructured.Unstructured to get schemas and it -// does not quite work with dynamic cache informers: -// failed to get informer for *unstructured.UnstructuredList apis.kcp.io/v1alpha1, Kind=APIResourceSchemaList: failed to find newly started informer for apis.kcp.io/v1alpha1, Kind=APIResourceSchema"}. -func (r *reconciler) getExportedSchemas(ctx context.Context, cl client.Client) (kubebindv1alpha2.ExportedSchemas, error) { - parts := strings.SplitN(r.schemaSource, ".", 3) - if len(parts) != 3 { // We check this in validation, but just in case. - return nil, fmt.Errorf("malformed schema source: %q", r.schemaSource) - } - - gvk := schema.GroupVersionKind{ - Kind: parts[0], - Version: parts[1], - Group: parts[2], - } - - // Ensure we have the List kind - listGVK := gvk - if !strings.HasSuffix(listGVK.Kind, "List") { - listGVK.Kind += "List" - } - - list := &unstructured.UnstructuredList{} - list.SetGroupVersionKind(listGVK) - - // TODO(mjudeikis): This is hardcoded here and in handlers.go for now. - labelSelector := labels.Set{ - resources.ExportedCRDsLabel: "true", - } - - listOpts := make([]client.ListOption, 0, 1) - listOpts = append(listOpts, client.MatchingLabelsSelector{Selector: labelSelector.AsSelector()}) - - if err := cl.List(ctx, list, listOpts...); err != nil { - return nil, err - } - - boundSchemas := make(kubebindv1alpha2.ExportedSchemas, len(list.Items)) - for _, item := range list.Items { - boundSchema, err := helpers.UnstructuredToBoundSchema(item) - if err != nil { - return nil, err - } - boundSchemas[boundSchema.ResourceGroupName()] = boundSchema - } - - return boundSchemas, nil -} - -func (r *reconciler) ensureBoundSchemas(ctx context.Context, cl client.Client, export *kubebindv1alpha2.APIServiceExport, req *kubebindv1alpha2.APIServiceExportRequest) error { - exportedSchemas, err := r.getExportedSchemas(ctx, cl) - if err != nil { - return err - } - - for _, res := range req.Spec.Resources { - if len(res.Versions) == 0 { - continue - } - - for _, boundSchema := range exportedSchemas { - if boundSchema.Spec.Group == res.Group && boundSchema.Spec.Names.Plural == res.Resource { - boundSchema.Name = res.ResourceGroupName() - boundSchema.Namespace = req.Namespace - boundSchema.Spec.InformerScope = r.informerScope - boundSchema.ResourceVersion = "" - - if err := r.createOrUpdateBoundSchema(ctx, cl, export, boundSchema, req.Spec.SchemaUpdatePolicy); err != nil { - return err - } - } - } - } - - return nil -} - -func (r *reconciler) createOrUpdateBoundSchema(ctx context.Context, cl client.Client, export *kubebindv1alpha2.APIServiceExport, desired *kubebindv1alpha2.BoundSchema, schemaUpdatePolicy kubebindv1alpha2.SchemaUpdatePolicy) error { - logger := klog.FromContext(ctx) - - // If namespaced isolation is configured for cluster-scoped objects, - // we need to rewrite the BoundSchema's scope accordingly. - if desired.Spec.Scope == apiextensionsv1.NamespaceScoped && r.isolation == kubebindv1alpha2.IsolationNamespaced { - desired.Spec.Scope = apiextensionsv1.ClusterScoped - } - - hash, err := helpers.BoundSchemaSpecHash(&desired.Spec) - if err != nil { - return err - } - - existing, err := r.getBoundSchema(ctx, cl, desired.Namespace, desired.Name) - if err != nil && !apierrors.IsNotFound(err) && !strings.Contains(err.Error(), "no matches for kind") { - return err - } - - if existing != nil { - var needsUpdate bool - // When export is nil (APIServiceExport not yet created), we skip owner-reference - // management but still proceed with schema sync so BoundSchemas are ready - // before the export is created on the next reconcile pass. - // For policy=Never this is a no-op; for policy=Always - // it allows hash-based spec sync to run independently of export lifecycle. - if export != nil { - if !metav1.IsControlledBy(existing, export) { - if err := controllerutil.SetControllerReference(export, existing, cl.Scheme()); err != nil { - return fmt.Errorf("failed to set owner reference on BoundSchema %s: %w", desired.Name, err) - } - needsUpdate = true - } - } - - if schemaUpdatePolicy == kubebindv1alpha2.SchemaUpdatePolicyAlways { - if existing.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey] != hash { - existing.Spec = desired.Spec - if existing.Annotations == nil { - existing.Annotations = make(map[string]string) - } - existing.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey] = hash - needsUpdate = true - } - } - - if needsUpdate { - if err := r.updateBoundSchema(ctx, cl, existing); err != nil { - return fmt.Errorf("failed to update BoundSchema %s: %w", desired.Name, err) - } - logger.V(6).Info("Updated existing BoundSchema", - "boundSchema", desired.Name, - "namespace", desired.Namespace) - } - return nil - } - - // Create path: new BoundSchema. - if desired.Annotations == nil { - desired.Annotations = make(map[string]string) - } - desired.Annotations[kubebindv1alpha2.SourceSpecHashAnnotationKey] = hash - - return r.createBoundSchema(ctx, cl, desired) -} - -func (r *reconciler) ensureExports(ctx context.Context, cl client.Client, existingExport *kubebindv1alpha2.APIServiceExport, req *kubebindv1alpha2.APIServiceExportRequest) error { - logger := klog.FromContext(ctx) - - var schemas []*kubebindv1alpha2.BoundSchema - if req.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhasePending { - for _, res := range req.Spec.Resources { - name := res.ResourceGroupName() - boundSchema, err := r.getBoundSchema(ctx, cl, req.Namespace, name) - if err != nil { - if apierrors.IsNotFound(err) { - conditions.MarkFalse( - req, - kubebindv1alpha2.APIServiceExportRequestConditionExportsReady, - "BoundSchemaNotFound", - conditionsapi.ConditionSeverityError, - "BoundSchema %s in the service provider cluster not found", - name, - ) - return err - } - return err - } - - // Collect all schemas for hashing. - // TODO(mjudeikis) Scope is same for all crds so we keep stamping it over. We might want to change this - schemas = append(schemas, boundSchema) - } - - if existingExport != nil { - conditions.MarkTrue(req, kubebindv1alpha2.APIServiceExportRequestConditionExportsReady) - return nil - } - - hash, err := helpers.BoundSchemasSpecHash(schemas) - if err != nil { - return err - } - export := &kubebindv1alpha2.APIServiceExport{ - ObjectMeta: metav1.ObjectMeta{ - Name: req.Name, - Namespace: req.Namespace, - Annotations: map[string]string{ - kubebindv1alpha2.SourceSpecHashAnnotationKey: hash, - }, - }, - Spec: kubebindv1alpha2.APIServiceExportSpec{ - InformerScope: r.informerScope, - Isolation: r.isolation, - }, - } - - for _, res := range req.Spec.Resources { - export.Spec.Resources = append(export.Spec.Resources, kubebindv1alpha2.APIServiceExportResource{ - GroupResource: kubebindv1alpha2.GroupResource{ - Group: res.Group, - Resource: res.Resource, - }, - Versions: res.Versions, - }) - } - export.Spec.PermissionClaims = req.Spec.PermissionClaims - - logger.V(1).Info("Creating APIServiceExport", "name", export.Name, "namespace", export.Namespace) - if err := r.createServiceExport(ctx, cl, export); err != nil { - if apierrors.IsAlreadyExists(err) { - return nil - } - return err - } - - conditions.MarkTrue(req, kubebindv1alpha2.APIServiceExportRequestConditionExportsReady) - req.Status.Phase = kubebindv1alpha2.APIServiceExportRequestPhaseSucceeded - - if time.Since(req.CreationTimestamp.Time) > time.Minute { - req.Status.Phase = kubebindv1alpha2.APIServiceExportRequestPhaseFailed - req.Status.TerminalMessage = conditions.GetMessage(req, kubebindv1alpha2.APIServiceExportRequestConditionExportsReady) - } - } - - if time.Since(req.CreationTimestamp.Time) > 10*time.Minute { - logger.Info("Deleting service binding request %s/%s", req.Namespace, req.Name, "reason", "timeout", "age", time.Since(req.CreationTimestamp.Time)) - return r.deleteServiceExportRequest(ctx, cl, req.Namespace, req.Name) - } - - return nil -} - -// Validate validates if the APIServiceExportRequest is in a valid state. -// Currently it validates if all requested schemas are of the same scope and -// if claimable apis are allowed and valid. -// -// TODO: Move this to validatingAdmissionWebhook as this is not really part of reconciliation. -// https://github.com/kube-bind/kube-bind/issues/325 -func (r *reconciler) validate(ctx context.Context, cl client.Client, req *kubebindv1alpha2.APIServiceExportRequest) error { - exportedSchemas, err := r.getExportedSchemas(ctx, cl) - if err != nil { - return err - } - - if len(exportedSchemas) == 0 { - conditions.MarkFalse( - req, - kubebindv1alpha2.APIServiceExportRequestConditionExportsReady, - "SchemaNotFound", - conditionsapi.ConditionSeverityError, - "Schema not found", - ) - return fmt.Errorf("no exported schemas found") - } - - first := apiextensionsv1.ResourceScope("") - for _, res := range req.Spec.Resources { - boundSchema, ok := exportedSchemas[res.ResourceGroupName()] - if !ok { - conditions.MarkFalse( - req, - kubebindv1alpha2.APIServiceExportRequestConditionExportsReady, - "SchemaNotFound", - conditionsapi.ConditionSeverityError, - "Schema %s not found", - res.ResourceGroupName(), - ) - return fmt.Errorf("schema %s not found", res.ResourceGroupName()) - } - if first == apiextensionsv1.ResourceScope("") { - first = boundSchema.Spec.Scope - continue - } - if boundSchema.Spec.Scope != first { - conditions.MarkFalse(req, - kubebindv1alpha2.APIServiceExportRequestConditionExportsReady, - "DifferentScopes", - conditionsapi.ConditionSeverityError, - "Different scopes found: %v", - boundSchema.Spec.Scope, - ) - return fmt.Errorf("different scopes found for claimed resources: %v", boundSchema.Name) - } - } - - // Add validation if claimable apis are valid here - for _, claim := range req.Spec.PermissionClaims { - if !isClaimableAPI(claim) { - conditions.MarkFalse( - req, - kubebindv1alpha2.APIServiceExportConditionPermissionClaim, - "InvalidPermissionClaim", - conditionsapi.ConditionSeverityError, - "Resource %s is not a valid claimable API", - claim.GroupResource.String(), - ) - req.Status.Phase = kubebindv1alpha2.APIServiceExportRequestPhaseFailed - req.Status.TerminalMessage = conditions.GetMessage(req, kubebindv1alpha2.APIServiceExportConditionPermissionClaim) - return fmt.Errorf("resource %s is not a valid claimable API", claim.GroupResource.String()) - } - } - - // Add validation for duplicate group/resource combinations - seenGroupResources := make(map[string]bool) - for _, claim := range req.Spec.PermissionClaims { - key := claim.Group + "/" + claim.Resource - if seenGroupResources[key] { - conditions.MarkFalse( - req, - kubebindv1alpha2.APIServiceExportConditionPermissionClaim, - "DuplicatePermissionClaim", - conditionsapi.ConditionSeverityError, - "Duplicate permission claim found for group/resource %s", - claim.GroupResource.String(), - ) - req.Status.Phase = kubebindv1alpha2.APIServiceExportRequestPhaseFailed - req.Status.TerminalMessage = conditions.GetMessage(req, kubebindv1alpha2.APIServiceExportConditionPermissionClaim) - return fmt.Errorf("duplicate permission claim found for group/resource %s", claim.GroupResource.String()) - } - seenGroupResources[key] = true - } - - return nil -} - -// isClaimableAPI checks if a permission claim is for a claimable API. -func isClaimableAPI(claim kubebindv1alpha2.PermissionClaim) bool { - for _, api := range kubebindv1alpha2.ClaimableAPIs { - if claim.Group == api.GroupVersionResource.Group && claim.Resource == api.Names.Plural { - return true - } - } - return false -} - -func (r *reconciler) ensureAPIServiceNamespaces(ctx context.Context, cl client.Client, cache cache.Cache, req *kubebindv1alpha2.APIServiceExportRequest) error { - logger := klog.FromContext(ctx) - - // TODO(mjudeikis): We have this object above already, pass it down to avoid extra get. - export := &kubebindv1alpha2.APIServiceExport{} - if err := cl.Get(ctx, client.ObjectKeyFromObject(req), export); err != nil { - return fmt.Errorf("failed to get APIServiceExport %s/%s: %w", req.Namespace, req.Name, err) - } - - for _, ns := range req.Spec.Namespaces { - apiServiceNamespace := helpers.APIServiceNamespaceFromExport(export, ns.Name) - currentAPIServiceNamespace := &kubebindv1alpha2.APIServiceNamespace{} - err := cache.Get(ctx, client.ObjectKeyFromObject(apiServiceNamespace), currentAPIServiceNamespace) - if err != nil { - if apierrors.IsNotFound(err) { - logger.V(1).Info("Creating APIServiceNamespace", "name", apiServiceNamespace.Name, "namespace", apiServiceNamespace.Namespace) - if err := cl.Create(ctx, apiServiceNamespace); err != nil { - if apierrors.IsAlreadyExists(err) { - continue - } - return err - } - } else { - return err - } - } - } - - return nil -} diff --git a/backend/controllers/servicenamespace/servicenamespace_controller.go b/backend/controllers/servicenamespace/servicenamespace_controller.go deleted file mode 100644 index a5e5ab4d2..000000000 --- a/backend/controllers/servicenamespace/servicenamespace_controller.go +++ /dev/null @@ -1,292 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicenamespace - -import ( - "context" - "fmt" - "reflect" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-backend-servicenamespace" -) - -// APIServiceNamespaceReconciler reconciles a APIServiceNamespace object. -type APIServiceNamespaceReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - - informerScope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - reconciler reconciler -} - -// NewAPIServiceNamespaceReconciler returns a new APIServiceNamespaceReconciler to reconcile APIServiceNamespaces. -func NewAPIServiceNamespaceReconciler( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - scope kubebindv1alpha2.InformerScope, - isolation kubebindv1alpha2.Isolation, -) (*APIServiceNamespaceReconciler, error) { - // Set up field indexers for APIServiceNamespaces - if err := mgr.GetFieldIndexer().IndexField(ctx, &kubebindv1alpha2.APIServiceNamespace{}, indexers.ServiceNamespaceByNamespace, - indexers.IndexServiceNamespaceByNamespaceControllerRuntime); err != nil { - return nil, fmt.Errorf("failed to setup ServiceNamespaceByNamespace indexer: %w", err) - } - - r := &APIServiceNamespaceReconciler{ - manager: mgr, - opts: opts, - informerScope: scope, - isolation: isolation, - reconciler: reconciler{ - scope: scope, - isolation: isolation, - - getNamespace: func(ctx context.Context, cache cache.Cache, name string) (*corev1.Namespace, error) { - var ns corev1.Namespace - key := types.NamespacedName{Name: name} - if err := cache.Get(ctx, key, &ns); err != nil { - return nil, err - } - return &ns, nil - }, - createNamespace: func(ctx context.Context, client client.Client, ns *corev1.Namespace) error { - return client.Create(ctx, ns) - }, - deleteNamespace: func(ctx context.Context, client client.Client, name string) error { - var ns corev1.Namespace - key := types.NamespacedName{Name: name} - if err := client.Get(ctx, key, &ns); err != nil { - return err - } - return client.Delete(ctx, &ns) - }, - - getRoleBinding: func(ctx context.Context, cache cache.Cache, ns, name string) (*rbacv1.RoleBinding, error) { - var rb rbacv1.RoleBinding - key := types.NamespacedName{Namespace: ns, Name: name} - if err := cache.Get(ctx, key, &rb); err != nil { - return nil, err - } - return &rb, nil - }, - createRoleBinding: func(ctx context.Context, client client.Client, crb *rbacv1.RoleBinding) error { - return client.Create(ctx, crb) - }, - updateRoleBinding: func(ctx context.Context, client client.Client, crb *rbacv1.RoleBinding) error { - return client.Update(ctx, crb) - }, - }, - } - - return r, nil -} - -// getNamespaceMapper creates a mapping function for Namespace changes. -func getNamespaceMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation[client.Object, mcreconcile.Request](func(ctx context.Context, obj client.Object) []mcreconcile.Request { - namespace := obj.(*corev1.Namespace) - nsKey := namespace.Name - - c := cl.GetClient() - - var serviceNamespaces kubebindv1alpha2.APIServiceNamespaceList - if err := c.List(ctx, &serviceNamespaces, client.MatchingFields{indexers.ServiceNamespaceByNamespace: nsKey}); err != nil { - return []mcreconcile.Request{} - } - - var result []mcreconcile.Request - for _, sns := range serviceNamespaces.Items { - result = append(result, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: sns.Namespace, - Name: sns.Name, - }, - }, - ClusterName: clusterName, - }) - } - return result - }) -} - -// createClusterBindingMapper creates a mapping function for ClusterBinding changes. -func getClusterBindingMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation[client.Object, mcreconcile.Request](func(ctx context.Context, obj client.Object) []mcreconcile.Request { - clusterBinding := obj.(*kubebindv1alpha2.ClusterBinding) - ns := clusterBinding.Namespace - - c := cl.GetClient() - - var serviceNamespaces kubebindv1alpha2.APIServiceNamespaceList - if err := c.List(ctx, &serviceNamespaces, client.InNamespace(ns)); err != nil { - return []mcreconcile.Request{} - } - - var result []mcreconcile.Request - for _, sns := range serviceNamespaces.Items { - result = append(result, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: sns.Namespace, - Name: sns.Name, - }, - }, - ClusterName: clusterName, - }) - } - - return result - }) -} - -// getServiceExportMapper creates a mapping function for APIServiceExport changes. -func getServiceExportMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation[client.Object, mcreconcile.Request](func(ctx context.Context, obj client.Object) []mcreconcile.Request { - serviceExport := obj.(*kubebindv1alpha2.APIServiceExport) - ns := serviceExport.Namespace - - c := cl.GetClient() - - var serviceNamespaces kubebindv1alpha2.APIServiceNamespaceList - if err := c.List(ctx, &serviceNamespaces, client.InNamespace(ns)); err != nil { - return []mcreconcile.Request{} - } - - var result []mcreconcile.Request - for _, sns := range serviceNamespaces.Items { - result = append(result, mcreconcile.Request{ - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{ - Namespace: sns.Namespace, - Name: sns.Name, - }, - }, - ClusterName: clusterName, - }) - } - - return result - }) -} - -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiservicenamespaces,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiservicenamespaces/status,verbs=get;update;patch -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiservicenamespaces/finalizers,verbs=update -//+kubebuilder:rbac:groups=kube-bind.io,resources=clusterbindings,verbs=get;list;watch -//+kubebuilder:rbac:groups=kube-bind.io,resources=apiserviceexports,verbs=get;list;watch -//+kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch;create;update;patch;delete -//+kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=rolebindings,verbs=get;list;watch;create;update;patch;delete - -// Reconcile is part of the main kubernetes reconciliation loop which aims to -// move the current state of the cluster closer to the desired state. -func (r *APIServiceNamespaceReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling APIServiceNamespace", "cluster", req.ClusterName, "namespace", req.Namespace, "name", req.Name) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - client := cl.GetClient() - cache := cl.GetCache() - - // Fetch the APIServiceNamespace instance - apiServiceNamespace := &kubebindv1alpha2.APIServiceNamespace{} - if err := cache.Get(ctx, req.NamespacedName, apiServiceNamespace); err != nil { - if errors.IsNotFound(err) { - // Request object not found, could have been deleted after reconcile request. - // Handle deletion logic here - nsName := req.Namespace + "-" + req.Name - if err := r.reconciler.deleteNamespace(ctx, client, nsName); err != nil && !errors.IsNotFound(err) { - return ctrl.Result{}, fmt.Errorf("failed to delete namespace %q: %w", nsName, err) - } - logger.Info("APIServiceNamespace not found, ignoring") - return ctrl.Result{}, nil - } - // Error reading the object - requeue the request. - return ctrl.Result{}, fmt.Errorf("failed to get APIServiceNamespace: %w", err) - } - - // Create a copy to modify - original := apiServiceNamespace.DeepCopy() - - // Run the reconciliation logic - if err := r.reconciler.reconcile(ctx, client, cache, apiServiceNamespace); err != nil { - logger.Error(err, "Failed to reconcile APIServiceNamespace") - return ctrl.Result{}, err - } - - // Update status if it has changed - if !reflect.DeepEqual(original.Status, apiServiceNamespace.Status) { - err := client.Status().Update(ctx, apiServiceNamespace) - if err != nil { - logger.Error(err, "Failed to update APIServiceNamespace status") - return ctrl.Result{}, fmt.Errorf("failed to update APIServiceNamespace status: %w", err) - } - logger.Info("APIServiceNamespace status updated", "namespace", apiServiceNamespace.Namespace, "name", apiServiceNamespace.Name) - } - - return ctrl.Result{}, nil -} - -// SetupWithManager sets up the controller with the Manager. -func (r *APIServiceNamespaceReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.APIServiceNamespace{}). - Watches( - &corev1.Namespace{}, - getNamespaceMapper, - ). - Watches( - &kubebindv1alpha2.ClusterBinding{}, - getClusterBindingMapper, - ). - Watches( - &kubebindv1alpha2.APIServiceExport{}, - getServiceExportMapper, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/controllers/servicenamespace/servicenamespace_reconcile.go b/backend/controllers/servicenamespace/servicenamespace_reconcile.go deleted file mode 100644 index b5b058720..000000000 --- a/backend/controllers/servicenamespace/servicenamespace_reconcile.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicenamespace - -import ( - "context" - "fmt" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type reconciler struct { - scope kubebindv1alpha2.InformerScope - isolation kubebindv1alpha2.Isolation - - getNamespace func(ctx context.Context, cache cache.Cache, name string) (*corev1.Namespace, error) - createNamespace func(ctx context.Context, client client.Client, ns *corev1.Namespace) error - deleteNamespace func(ctx context.Context, client client.Client, name string) error - - getRoleBinding func(ctx context.Context, cache cache.Cache, ns, name string) (*rbacv1.RoleBinding, error) - createRoleBinding func(ctx context.Context, client client.Client, crb *rbacv1.RoleBinding) error - updateRoleBinding func(ctx context.Context, client client.Client, cr *rbacv1.RoleBinding) error -} - -func (c *reconciler) reconcile(ctx context.Context, client client.Client, cache cache.Cache, sns *kubebindv1alpha2.APIServiceNamespace) error { - var ns *corev1.Namespace - var nsName string - switch { - case sns.Status.Namespace != "": - // use existing namespace from status - nsName = sns.Status.Namespace - case c.isolation == kubebindv1alpha2.IsolationNone: - nsName = sns.Name - case c.isolation == kubebindv1alpha2.IsolationNamespaced || c.isolation == kubebindv1alpha2.IsolationPrefixed: - nsName = sns.Namespace + "-" + sns.Name - default: - return fmt.Errorf("unknown isolation strategy: %s", c.isolation) - } - ns, _ = c.getNamespace(ctx, cache, nsName) - - if ns == nil { - ns = &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: nsName, - Annotations: map[string]string{ - kubebindv1alpha2.APIServiceNamespaceAnnotationKey: sns.Namespace + "/" + sns.Name, - }, - }, - } - if err := c.createNamespace(ctx, client, ns); err != nil && !errors.IsAlreadyExists(err) { - return fmt.Errorf("failed to create namespace %q: %w", nsName, err) - } - } - - if sns.Status.Namespace != nsName { - sns.Status.Namespace = nsName - } - - return nil -} diff --git a/backend/deploy/01-clusterrole.yaml b/backend/deploy/01-clusterrole.yaml deleted file mode 100644 index 3488b382c..000000000 --- a/backend/deploy/01-clusterrole.yaml +++ /dev/null @@ -1,65 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: kube-binder -rules: -- apiGroups: - - "kube-bind.io" - resources: - - "apiserviceexportrequests" - verbs: ["create","delete","patch","update","get","list","watch"] -- apiGroups: - - "" - resources: - - "namespaces" - verbs: ["get"] -- apiGroups: - - "" - resources: - - "secrets" - verbs: ["get", "watch", "list"] -- apiGroups: - - "kube-bind.io" - resources: - - "clusterbindings" - verbs: ["get", "watch", "list"] -- apiGroups: - - "kube-bind.io" - resources: - - "clusterbindings/status" - verbs: ["get","patch","update"] -- apiGroups: - - "kube-bind.io" - resources: - - "apiserviceexports" - verbs: ["get", "watch", "list"] -- apiGroups: - - "kube-bind.io" - resources: - - "apiserviceexports/status" - verbs: ["get","patch","update"] -- apiGroups: - - "kube-bind.io" - resources: - - "apiservicenamespaces" - verbs: ["create","delete","patch","update","get","list","watch"] -- apiGroups: - - "kube-bind.io" - resources: - - "apiresourceschemas" - verbs: ["create","delete","patch","update","get","list","watch"] -- apiGroups: - - "kube-bind.io" - resources: - - "apiresourceschemas/status" - verbs: ["get","patch","update"] -- apiGroups: - - "kube-bind.io" - resources: - - "boundapiresourceschemas" - verbs: ["create","delete","patch","update","get","list","watch"] -- apiGroups: - - "kube-bind.io" - resources: - - "boundapiresourceschemas/status" - verbs: ["get","patch","update"] diff --git a/backend/deploy/bootstrap.go b/backend/deploy/bootstrap.go deleted file mode 100644 index 7593433b8..000000000 --- a/backend/deploy/bootstrap.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 deploy - -import ( - "context" - "embed" - - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" - - "github.com/kube-bind/kube-bind/pkg/bootstrap" -) - -//go:embed *.yaml -var raw embed.FS - -func Bootstrap(ctx context.Context, discoveryClient discovery.DiscoveryInterface, dynamicClient dynamic.Interface, batteriesIncluded sets.Set[string]) error { - return bootstrap.Bootstrap(ctx, discoveryClient, dynamicClient, batteriesIncluded, raw) -} diff --git a/backend/gateway/api/types.go b/backend/gateway/api/types.go new file mode 100644 index 000000000..baf1b4867 --- /dev/null +++ b/backend/gateway/api/types.go @@ -0,0 +1,213 @@ +/* +Copyright 2026 The kbind 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 api holds the gateway's wire types, shared by the server, the CLI +// and the UI. The protocol is deliberately thin: its terminal output is the +// core's one-apply bundle, nothing else — no request objects to poll, no +// phases. curl bind + pickup piped to kubectl apply is a complete client. +package api + +import ( + "encoding/json" + "time" +) + +// Provider is GET /api/provider: provider metadata + supported auth methods. +type Provider struct { + Name string `json:"name"` + Version string `json:"version,omitempty"` + AuthMethods []string `json:"authMethods"` + // ApplyEnabled reports whether the flag-gated POST /api/apply + // (browser-apply) path is available. + ApplyEnabled bool `json:"applyEnabled"` +} + +// Catalog is GET /api/catalog: the offerings visible to the caller. +type Catalog struct { + Exports []Export `json:"exports"` + Collections []Collection `json:"collections,omitempty"` +} + +// Export is one curated offering. +type Export struct { + Name string `json:"name"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + IconURL string `json:"iconURL,omitempty"` + Docs string `json:"docs,omitempty"` + APIs []string `json:"apis"` + // RelatedResources are the auxiliary objects (secrets/configmaps) a + // binding to this offering syncs alongside the APIs — a core concept + // (core.kbind.io relatedResources), surfaced here so consumers see what + // flows before they bind. + RelatedResources []RelatedResource `json:"relatedResources,omitempty"` +} + +// RelatedResource is one auxiliary-object rule of an offering. +type RelatedResource struct { + // Resource is "secrets" or "configmaps". + Resource string `json:"resource"` + // Direction is FromProvider or FromConsumer. + Direction string `json:"direction"` + // Selector is a human-readable summary of what is selected (labels + // and/or names); empty means everything in scope. + Selector string `json:"selector,omitempty"` +} + +// Collection is a grouping of exports for browsing. +type Collection struct { + Name string `json:"name"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + Exports []string `json:"exports"` +} + +// BindRequest is POST /api/bind's body. +type BindRequest struct { + // Export is the catalog Export to bind. + Export string `json:"export"` +} + +// BindResponse is POST /api/bind's result: a one-time pickup URL for the +// bundle. Single-use and short-TTL applies to the pickup URL, not the +// credential inside — a picked-up bundle stays valid until its Grant is +// revoked (GitOps-safe). +type BindResponse struct { + // Grant is the issuance record's name on the provider. + Grant string `json:"grant"` + // PickupURL is the single-use bundle pickup URL (relative to the + // gateway base unless absolute). + PickupURL string `json:"pickupURL"` + // ExpiresAt is when the pickup URL dies. + ExpiresAt time.Time `json:"expiresAt"` +} + +// Bundle is GET /api/bundle/ with Accept: application/json — the same +// objects the YAML multi-doc carries, in a thin envelope. +type Bundle struct { + Bundle []json.RawMessage `json:"bundle"` +} + +// ApplyRequest is POST /api/apply's body (flag-gated browser-apply): the +// gateway applies the bundle into a consumer cluster using a caller-supplied +// kubeconfig. Consumer credentials transit the gateway — deployments enable +// this consciously. +type ApplyRequest struct { + // Export is the catalog Export to bind. Optional when InstallKonnector + // is set: an export-less apply is a pure "connect a cluster" (konnector + // install only). + Export string `json:"export,omitempty"` + // Kubeconfig is the consumer cluster kubeconfig, base64-encoded. + Kubeconfig string `json:"kubeconfig"` + // InstallKonnector also installs/upgrades the konnector. + InstallKonnector bool `json:"installKonnector,omitempty"` +} + +// ApplyResponse reports what the gateway applied. +type ApplyResponse struct { + Applied []string `json:"applied"` +} + +// Clusters is GET /api/clusters: the consumer clusters known from konnector +// heartbeat Leases, and what each has bound. Grants whose bundle was never +// applied (no heartbeat yet) are listed separately as pending. +type Clusters struct { + Clusters []Cluster `json:"clusters"` + Pending []PendingGrant `json:"pending,omitempty"` +} + +// Cluster is one consumer cluster, identified by the cluster UID the +// konnector pins on its heartbeat Lease. +type Cluster struct { + // UID is the consumer cluster's stable identity. + UID string `json:"uid"` + // LastHeartbeat is the newest Lease renewal across the cluster's bindings. + LastHeartbeat time.Time `json:"lastHeartbeat"` + // Live is true when at least one binding's heartbeat is current. + Live bool `json:"live"` + // Bindings are the grants this cluster actively consumes. + Bindings []ClusterGrant `json:"bindings"` +} + +// ClusterGrant is one grant as consumed by one cluster. +type ClusterGrant struct { + Grant string `json:"grant"` + Export string `json:"export"` + Identity string `json:"identity,omitempty"` + Subject string `json:"subject,omitempty"` + BoundaryNamespace string `json:"boundaryNamespace,omitempty"` + LastHeartbeat time.Time `json:"lastHeartbeat"` + // Live is true while the heartbeat Lease is renewed within its grace + // window (2x the lease duration). + Live bool `json:"live"` + // APIs are the bound APIs with the number of objects currently synced + // onto the provider by this cluster (best-effort count). + APIs []SyncedAPI `json:"apis"` +} + +// SyncedAPI is one bound API and how many of its provider objects were +// written by the cluster. +type SyncedAPI struct { + Name string `json:"name"` + SyncedCount int `json:"syncedCount"` +} + +// ExportInstances is GET /api/catalog/{export}/instances: the provider-side +// objects consumers have synced under one catalog item. +type ExportInstances struct { + Export string `json:"export"` + Instances []Instance `json:"instances"` +} + +// Instance is one synced object on the provider, attributed to the consumer +// cluster (and, where a heartbeat links it, the identity) that wrote it. +type Instance struct { + // API is the CRD name (".") the instance belongs to — + // or "secrets"/"configmaps" for related resources. + API string `json:"api"` + // Related marks a related-resource row (a secret/configmap that flows + // alongside the APIs) rather than a bound-API instance. + Related bool `json:"related,omitempty"` + // Direction is set on related rows: FromProvider rows are the provider + // originals delivered to every bound cluster (the consumer-side copies + // are invisible to the provider by design); FromConsumer rows are copies + // consumers synced here, attributed like any synced instance. + Direction string `json:"direction,omitempty"` + // Namespace is empty for cluster-scoped instances. + Namespace string `json:"namespace,omitempty"` + Name string `json:"name"` + // ClusterUID is the consumer cluster that owns the object (from the + // sync engine's ownership marker). + ClusterUID string `json:"clusterUID,omitempty"` + // Identity is the human behind the grant whose connection heartbeats + // from that cluster, when the link can be made. + Identity string `json:"identity,omitempty"` + CreatedAt time.Time `json:"createdAt"` +} + +// PendingGrant is a grant whose credentials were issued but whose bundle has +// never heartbeated — bound, not (yet) connected. +type PendingGrant struct { + Grant string `json:"grant"` + Export string `json:"export"` + Identity string `json:"identity,omitempty"` + CreatedAt time.Time `json:"createdAt"` +} + +// Error is any non-2xx response body. +type Error struct { + Error string `json:"error"` +} diff --git a/backend/gateway/apply.go b/backend/gateway/apply.go new file mode 100644 index 000000000..1aad79a79 --- /dev/null +++ b/backend/gateway/apply.go @@ -0,0 +1,118 @@ +/* +Copyright 2026 The kbind 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 gateway + +import ( + "encoding/base64" + "encoding/json" + "net/http" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/tools/clientcmd" + + "github.com/kbind/kbind/backend/gateway/api" + "github.com/kbind/kbind/backend/issuer" + "github.com/kbind/kbind/pkg/konnectorinstall" + "github.com/kbind/kbind/pkg/kubeapply" +) + +// handleApply is the flag-gated browser-apply path: bind + apply the bundle +// (and optionally install the konnector) into a consumer cluster using a +// caller-supplied kubeconfig. Enabling it means consumer credentials transit +// the gateway — a deployment-level decision, off by default. +func (s *Server) handleApply(w http.ResponseWriter, r *http.Request) { + id, err := s.identity(r) + if err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + + var req api.ApplyRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Kubeconfig == "" { + writeError(w, http.StatusBadRequest, "body must be {\"export\": ..., \"kubeconfig\": }") + return + } + if req.Export == "" && !req.InstallKonnector { + writeError(w, http.StatusBadRequest, "nothing to do: set export and/or installKonnector") + return + } + kubeconfig, err := base64.StdEncoding.DecodeString(req.Kubeconfig) + if err != nil { + writeError(w, http.StatusBadRequest, "kubeconfig must be base64-encoded") + return + } + consumerCfg, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) + if err != nil { + writeError(w, http.StatusBadRequest, "parsing consumer kubeconfig: "+err.Error()) + return + } + + var objs []*unstructured.Unstructured + if req.InstallKonnector { + konnectorObjs, err := konnectorinstall.Objects(s.cfg.KonnectorImage) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + objs = append(objs, konnectorObjs...) + } else { + // The bundle's Secret lands in the konnector namespace; make sure it + // exists even when the konnector install is skipped. + objs = append(objs, kubeapply.NamespaceObject(issuer.KonnectorNamespace)) + } + + // With an export, run the same issuance path as bind — the terminal + // output is the same bundle. Without one this is a pure "connect a + // cluster": konnector install only. + if req.Export != "" { + grant, err := s.ensureGrant(r.Context(), id, req.Export) + if err != nil { + writeError(w, http.StatusBadGateway, err.Error()) + return + } + if err := s.waitGrantReady(r.Context(), grant); err != nil { + writeError(w, http.StatusGatewayTimeout, "credentials not provisioned yet: "+err.Error()) + return + } + bundleKubeconfig, err := s.bundle.Kubeconfig(r.Context(), grant) + if err != nil { + writeError(w, http.StatusBadGateway, "assembling kubeconfig: "+err.Error()) + return + } + for _, obj := range s.bundle.Objects(grant, bundleKubeconfig) { + content, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + objs = append(objs, &unstructured.Unstructured{Object: content}) + } + } + + applier, err := kubeapply.New(consumerCfg, "kbind-gateway") + if err != nil { + writeError(w, http.StatusBadRequest, "connecting to consumer cluster: "+err.Error()) + return + } + applied, err := applier.Apply(r.Context(), objs) + if err != nil { + writeError(w, http.StatusBadGateway, err.Error()) + return + } + writeJSON(w, http.StatusOK, api.ApplyResponse{Applied: applied}) +} diff --git a/backend/gateway/bind.go b/backend/gateway/bind.go new file mode 100644 index 000000000..3516e9bec --- /dev/null +++ b/backend/gateway/bind.go @@ -0,0 +1,268 @@ +/* +Copyright 2026 The kbind 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 gateway + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/yaml" + + "github.com/kbind/kbind/backend/auth" + "github.com/kbind/kbind/backend/gateway/api" + "github.com/kbind/kbind/backend/issuer" + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// errGone marks a pickup token that is used, expired or unknown. +var errGone = errors.New("bundle pickup token is invalid, expired or already used") + +// handleBind drives the issuer for the caller's identity and answers with a +// one-time pickup URL. There is no other handshake state: no request objects +// to poll, no phases. +func (s *Server) handleBind(w http.ResponseWriter, r *http.Request) { + id, err := s.identity(r) + if err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + + var req api.BindRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Export == "" { + writeError(w, http.StatusBadRequest, "body must be {\"export\": \"\"}") + return + } + + grant, err := s.ensureGrant(r.Context(), id, req.Export) + switch { + case apierrors.IsNotFound(err): + writeError(w, http.StatusNotFound, "unknown export "+req.Export) + return + case err != nil: + writeError(w, http.StatusBadGateway, err.Error()) + return + } + + if err := s.waitGrantReady(r.Context(), grant); err != nil { + writeError(w, http.StatusGatewayTimeout, "credentials not provisioned yet (is the issuer running?): "+err.Error()) + return + } + + token, expiry, err := s.mintPickup(r.Context(), grant) + if err != nil { + writeError(w, http.StatusBadGateway, "minting pickup token: "+err.Error()) + return + } + + writeJSON(w, http.StatusOK, api.BindResponse{ + Grant: grant.Name, + PickupURL: "/api/bundle/" + token, + ExpiresAt: expiry, + }) +} + +// ensureGrant creates or updates the Grant for (identity, export), resolving +// the export's APIs and defaults into the spec so issuance is a stable record. +func (s *Server) ensureGrant(ctx context.Context, id *auth.Identity, exportName string) (*iamv1alpha1.Grant, error) { + export := &catalogv1alpha1.Export{} + if err := s.client.Get(ctx, types.NamespacedName{Name: exportName}, export); err != nil { + return nil, err + } + if !apimeta.IsStatusConditionPresentAndEqual(export.Status.Conditions, catalogv1alpha1.ConditionReady, metav1.ConditionTrue) { + return nil, fmt.Errorf("export %s is not ready (its APIs are not all exported)", exportName) + } + + grant := &iamv1alpha1.Grant{ObjectMeta: metav1.ObjectMeta{Name: issuer.GrantName(exportName, id.Subject)}} + _, err := controllerutil.CreateOrUpdate(ctx, s.client, grant, func() error { + grant.Spec = iamv1alpha1.GrantSpec{ + Identity: iamv1alpha1.Identity{ + Subject: id.Subject, + DisplayName: id.DisplayName, + Groups: id.Groups, + }, + ExportName: exportName, + APIs: export.Spec.APIs, + ConflictPolicy: export.Spec.Defaults.ConflictPolicy, + RelatedResources: export.Spec.Defaults.RelatedResources, + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("recording grant: %w", err) + } + return grant, nil +} + +// waitGrantReady polls until the issuer reports provisioned credentials. +func (s *Server) waitGrantReady(ctx context.Context, grant *iamv1alpha1.Grant) error { + ctx, cancel := context.WithTimeout(ctx, s.cfg.bindTimeout()) + defer cancel() + return wait.PollUntilContextCancel(ctx, 500*time.Millisecond, true, func(ctx context.Context) (bool, error) { + if err := s.client.Get(ctx, types.NamespacedName{Name: grant.Name}, grant); err != nil { + return false, client.IgnoreNotFound(err) + } + return apimeta.IsStatusConditionPresentAndEqual(grant.Status.Conditions, iamv1alpha1.ConditionReady, metav1.ConditionTrue), nil + }) +} + +// mintPickup stamps a fresh one-time pickup token on the Grant. The token is +// "."; only sha256(random) is stored, as an +// annotation, so the gateway keeps zero state and any replica can serve the +// pickup. Re-binding replaces the previous (possibly unused) pickup. +func (s *Server) mintPickup(ctx context.Context, grant *iamv1alpha1.Grant) (string, time.Time, error) { + random := make([]byte, 24) + if _, err := rand.Read(random); err != nil { + return "", time.Time{}, err + } + secret := base64.RawURLEncoding.EncodeToString(random) + sum := sha256.Sum256([]byte(secret)) + expiry := time.Now().Add(s.cfg.pickupTTL()).UTC().Truncate(time.Second) + + err := retryConflict(func() error { + if err := s.client.Get(ctx, types.NamespacedName{Name: grant.Name}, grant); err != nil { + return err + } + if grant.Annotations == nil { + grant.Annotations = map[string]string{} + } + grant.Annotations[iamv1alpha1.AnnotationPickupSHA256] = hex.EncodeToString(sum[:]) + grant.Annotations[iamv1alpha1.AnnotationPickupExpiry] = expiry.Format(time.RFC3339) + return s.client.Update(ctx, grant) + }) + if err != nil { + return "", time.Time{}, err + } + token := base64.RawURLEncoding.EncodeToString([]byte(grant.Name)) + "." + secret + return token, expiry, nil +} + +// handleBundle is the single-use, short-TTL bundle pickup. The token is the +// auth; no session is required (curl-able, and the CLI redeems it directly). +// Content negotiation: application/json wraps the objects in {"bundle": [...]}, +// anything else gets the literal YAML multi-doc. +func (s *Server) handleBundle(w http.ResponseWriter, r *http.Request) { + grant, err := s.consumePickup(r.Context(), r.PathValue("token")) + if errors.Is(err, errGone) { + writeError(w, http.StatusGone, errGone.Error()) + return + } + if err != nil { + writeError(w, http.StatusBadGateway, err.Error()) + return + } + + kubeconfig, err := s.bundle.Kubeconfig(r.Context(), grant) + if err != nil { + writeError(w, http.StatusBadGateway, "assembling kubeconfig: "+err.Error()) + return + } + objs := s.bundle.Objects(grant, kubeconfig) + + if strings.Contains(r.Header.Get("Accept"), "application/json") { + out := api.Bundle{} + for _, obj := range objs { + raw, err := json.Marshal(obj) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + out.Bundle = append(out.Bundle, raw) + } + writeJSON(w, http.StatusOK, out) + return + } + + w.Header().Set("Content-Type", "application/yaml") + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", grant.Name+".yaml")) + for i, obj := range objs { + data, err := yaml.Marshal(obj) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + if i > 0 { + _, _ = w.Write([]byte("---\n")) + } + _, _ = w.Write(data) + } +} + +// consumePickup validates a pickup token and removes it from the Grant with +// optimistic concurrency — the API server enforces single-use, so two racing +// pickups (even on different gateway replicas) redeem exactly once. +func (s *Server) consumePickup(ctx context.Context, token string) (*iamv1alpha1.Grant, error) { + encodedName, secret, ok := strings.Cut(token, ".") + if !ok { + return nil, errGone + } + nameBytes, err := base64.RawURLEncoding.DecodeString(encodedName) + if err != nil { + return nil, errGone + } + sum := sha256.Sum256([]byte(secret)) + want := hex.EncodeToString(sum[:]) + + grant := &iamv1alpha1.Grant{} + err = retryConflict(func() error { + if err := s.client.Get(ctx, types.NamespacedName{Name: string(nameBytes)}, grant); err != nil { + if apierrors.IsNotFound(err) { + return errGone + } + return err + } + stored := grant.Annotations[iamv1alpha1.AnnotationPickupSHA256] + expiry, timeErr := time.Parse(time.RFC3339, grant.Annotations[iamv1alpha1.AnnotationPickupExpiry]) + if stored == "" || stored != want || timeErr != nil || time.Now().After(expiry) { + return errGone + } + delete(grant.Annotations, iamv1alpha1.AnnotationPickupSHA256) + delete(grant.Annotations, iamv1alpha1.AnnotationPickupExpiry) + return s.client.Update(ctx, grant) + }) + if err != nil { + return nil, err + } + return grant, nil +} + +// retryConflict retries fn on optimistic-concurrency conflicts. +func retryConflict(fn func() error) error { + var err error + for range 5 { + if err = fn(); !apierrors.IsConflict(err) { + return err + } + } + return err +} diff --git a/backend/gateway/catalog.go b/backend/gateway/catalog.go new file mode 100644 index 000000000..d3a54b27e --- /dev/null +++ b/backend/gateway/catalog.go @@ -0,0 +1,122 @@ +/* +Copyright 2026 The kbind 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 gateway + +import ( + "net/http" + "strings" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/kbind/kbind/backend/gateway/api" + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// handleCatalog lists the Exports and Collections visible to the caller. +// Exports that are not Ready (listing APIs that are not actually exported) +// are hidden — the export label stays the source of truth, the catalog is +// presentation. +func (s *Server) handleCatalog(w http.ResponseWriter, r *http.Request) { + if _, err := s.identity(r); err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + + var exports catalogv1alpha1.ExportList + if err := s.client.List(r.Context(), &exports); err != nil { + writeError(w, http.StatusBadGateway, "listing catalog: "+err.Error()) + return + } + var collections catalogv1alpha1.CollectionList + if err := s.client.List(r.Context(), &collections); err != nil { + writeError(w, http.StatusBadGateway, "listing collections: "+err.Error()) + return + } + + catalog := api.Catalog{Exports: []api.Export{}} + visible := map[string]bool{} + for i := range exports.Items { + e := &exports.Items[i] + if !apimeta.IsStatusConditionPresentAndEqual(e.Status.Conditions, catalogv1alpha1.ConditionReady, metav1.ConditionTrue) { + continue + } + apis := make([]string, 0, len(e.Spec.APIs)) + for _, a := range e.Spec.APIs { + apis = append(apis, a.Name) + } + out := api.Export{ + Name: e.Name, + Title: e.Spec.Title, + Description: e.Spec.Description, + Docs: e.Spec.Docs, + APIs: apis, + } + if e.Spec.Icon != nil { + out.IconURL = e.Spec.Icon.URL + } + for _, rr := range e.Spec.Defaults.RelatedResources { + out.RelatedResources = append(out.RelatedResources, api.RelatedResource{ + Resource: rr.Resource, + Direction: string(rr.Direction), + Selector: selectorSummary(rr), + }) + } + catalog.Exports = append(catalog.Exports, out) + visible[e.Name] = true + } + + for i := range collections.Items { + c := &collections.Items[i] + members := make([]string, 0, len(c.Spec.Exports)) + for _, ref := range c.Spec.Exports { + if visible[ref.Name] { + members = append(members, ref.Name) + } + } + if len(members) == 0 { + continue + } + catalog.Collections = append(catalog.Collections, api.Collection{ + Name: c.Name, + Title: c.Spec.Title, + Description: c.Spec.Description, + Exports: members, + }) + } + + writeJSON(w, http.StatusOK, catalog) +} + +// selectorSummary renders a related-resource selector for humans: label +// selector and/or names, empty when everything in scope is selected. +func selectorSummary(rr corev1alpha1.RelatedResource) string { + if rr.Selector == nil { + return "" + } + var parts []string + if rr.Selector.LabelSelector != nil { + if s := metav1.FormatLabelSelector(rr.Selector.LabelSelector); s != "" && s != "" { + parts = append(parts, s) + } + } + if len(rr.Selector.Names) > 0 { + parts = append(parts, "names: "+strings.Join(rr.Selector.Names, ", ")) + } + return strings.Join(parts, "; ") +} diff --git a/backend/gateway/clusters.go b/backend/gateway/clusters.go new file mode 100644 index 000000000..4b60ecd6a --- /dev/null +++ b/backend/gateway/clusters.go @@ -0,0 +1,179 @@ +/* +Copyright 2026 The kbind 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 gateway + +import ( + "context" + "net/http" + "sort" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kbind/kbind/backend/gateway/api" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// heartbeatGrace is how many missed lease durations still count as live. +const heartbeatGrace = 2 + +// handleClusters aggregates the konnector heartbeat Leases into a +// consumer-cluster view: each Lease is annotated with its Connection name +// (== the Grant name, since the bundle names the Connection after the Grant) +// and the consumer cluster UID — which cluster consumes which grant, how +// fresh its heartbeat is, and how many objects it has synced per API. +func (s *Server) handleClusters(w http.ResponseWriter, r *http.Request) { + if _, err := s.identity(r); err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + ctx := r.Context() + + var grants iamv1alpha1.GrantList + if err := s.client.List(ctx, &grants); err != nil { + writeError(w, http.StatusBadGateway, "listing grants: "+err.Error()) + return + } + + out := api.Clusters{Clusters: []api.Cluster{}} + clusters := map[string]*api.Cluster{} + leaseCache := map[string][]coordinationv1.Lease{} + // (api name, cluster UID) -> synced object count, filled lazily per API. + counts := map[string]map[string]int{} + + for i := range grants.Items { + grant := &grants.Items[i] + if grant.DeletionTimestamp != nil { + continue + } + + leases, err := s.boundaryLeases(ctx, leaseCache, grant.Status.Namespace) + if err != nil { + writeError(w, http.StatusBadGateway, "listing heartbeat leases: "+err.Error()) + return + } + matched := false + for j := range leases { + lease := &leases[j] + if lease.Annotations[corev1alpha1.AnnotationConnection] != grant.Name { + continue + } + uid := lease.Annotations[corev1alpha1.AnnotationConsumerClusterUID] + if uid == "" || lease.Spec.RenewTime == nil { + continue + } + matched = true + + binding := api.ClusterGrant{ + Grant: grant.Name, + Export: grant.Spec.ExportName, + Identity: grant.Spec.Identity.DisplayName, + Subject: grant.Spec.Identity.Subject, + BoundaryNamespace: grant.Status.Namespace, + LastHeartbeat: lease.Spec.RenewTime.Time.UTC(), + Live: leaseLive(lease), + } + for _, ref := range grant.Spec.APIs { + perCluster, err := s.syncedCounts(ctx, counts, ref.Name) + if err != nil { + // Best-effort: the view is about liveness first. + perCluster = nil + } + binding.APIs = append(binding.APIs, api.SyncedAPI{ + Name: ref.Name, + SyncedCount: perCluster[uid], + }) + } + + cluster, ok := clusters[uid] + if !ok { + cluster = &api.Cluster{UID: uid} + clusters[uid] = cluster + } + cluster.Bindings = append(cluster.Bindings, binding) + if binding.LastHeartbeat.After(cluster.LastHeartbeat) { + cluster.LastHeartbeat = binding.LastHeartbeat + } + cluster.Live = cluster.Live || binding.Live + } + + if !matched { + out.Pending = append(out.Pending, api.PendingGrant{ + Grant: grant.Name, + Export: grant.Spec.ExportName, + Identity: grant.Spec.Identity.DisplayName, + CreatedAt: grant.CreationTimestamp.Time.UTC(), + }) + } + } + + for _, cluster := range clusters { + sort.Slice(cluster.Bindings, func(a, b int) bool { return cluster.Bindings[a].Grant < cluster.Bindings[b].Grant }) + out.Clusters = append(out.Clusters, *cluster) + } + sort.Slice(out.Clusters, func(a, b int) bool { return out.Clusters[a].UID < out.Clusters[b].UID }) + sort.Slice(out.Pending, func(a, b int) bool { return out.Pending[a].Grant < out.Pending[b].Grant }) + + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) boundaryLeases(ctx context.Context, cache map[string][]coordinationv1.Lease, namespace string) ([]coordinationv1.Lease, error) { + if namespace == "" { + return nil, nil + } + if leases, ok := cache[namespace]; ok { + return leases, nil + } + var list coordinationv1.LeaseList + if err := s.client.List(ctx, &list, client.InNamespace(namespace), + client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + return nil, err + } + cache[namespace] = list.Items + return list.Items, nil +} + +func leaseLive(lease *coordinationv1.Lease) bool { + duration := 60 * time.Second + if lease.Spec.LeaseDurationSeconds != nil { + duration = time.Duration(*lease.Spec.LeaseDurationSeconds) * time.Second + } + return time.Since(lease.Spec.RenewTime.Time) <= heartbeatGrace*duration +} + +// syncedCounts counts, per consumer cluster UID, the provider objects of one +// bound API that the sync engine wrote (managed label + consumer-cluster-uid +// marker). One list per API per request, cached in counts. +func (s *Server) syncedCounts(ctx context.Context, counts map[string]map[string]int, apiName string) (map[string]int, error) { + if perCluster, ok := counts[apiName]; ok { + return perCluster, nil + } + items, err := s.listManaged(ctx, apiName) + if err != nil { + return nil, err + } + perCluster := map[string]int{} + for i := range items { + if uid := items[i].GetAnnotations()[corev1alpha1.AnnotationConsumerClusterUID]; uid != "" { + perCluster[uid]++ + } + } + counts[apiName] = perCluster + return perCluster, nil +} diff --git a/backend/gateway/instances.go b/backend/gateway/instances.go new file mode 100644 index 000000000..a71b7c80e --- /dev/null +++ b/backend/gateway/instances.go @@ -0,0 +1,246 @@ +/* +Copyright 2026 The kbind 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 gateway + +import ( + "context" + "net/http" + "sort" + + coordinationv1 "k8s.io/api/coordination/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kbind/kbind/backend/gateway/api" + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// handleExportInstances lists the provider-side objects consumers synced +// under one catalog item — the catalog's "what is actually running against +// this offering" view. Objects are attributed by the sync engine's ownership +// markers; identities are resolved through the heartbeat Lease → Grant link +// where one exists. +func (s *Server) handleExportInstances(w http.ResponseWriter, r *http.Request) { + if _, err := s.identity(r); err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + ctx := r.Context() + name := r.PathValue("export") + + export := &catalogv1alpha1.Export{} + if err := s.client.Get(ctx, types.NamespacedName{Name: name}, export); err != nil { + if apierrors.IsNotFound(err) { + writeError(w, http.StatusNotFound, "unknown export "+name) + return + } + writeError(w, http.StatusBadGateway, err.Error()) + return + } + + identityByCluster, err := s.identitiesForExport(ctx, name) + if err != nil { + writeError(w, http.StatusBadGateway, "resolving identities: "+err.Error()) + return + } + + out := api.ExportInstances{Export: name, Instances: []api.Instance{}} + for _, ref := range export.Spec.APIs { + items, err := s.listManaged(ctx, ref.Name) + if err != nil { + // The API may not be established (or readable) yet; the view is + // best-effort per API, like the clusters view's counts. + continue + } + for i := range items { + item := &items[i] + uid := item.GetAnnotations()[corev1alpha1.AnnotationConsumerClusterUID] + out.Instances = append(out.Instances, api.Instance{ + API: ref.Name, + Namespace: item.GetNamespace(), + Name: item.GetName(), + ClusterUID: uid, + Identity: identityByCluster[uid], + CreatedAt: item.GetCreationTimestamp().Time.UTC(), + }) + } + } + // Related resources flow alongside the APIs — show them too. + // FromConsumer copies exist here with sync markers; FromProvider rows + // are the provider originals matching the rule's selector. + for _, rr := range export.Spec.Defaults.RelatedResources { + items, err := s.listRelated(ctx, rr) + if err != nil { + continue // best-effort, like the bound-API listings + } + for i := range items { + item := &items[i] + uid := item.GetAnnotations()[corev1alpha1.AnnotationConsumerClusterUID] + out.Instances = append(out.Instances, api.Instance{ + API: rr.Resource, + Related: true, + Direction: string(rr.Direction), + Namespace: item.GetNamespace(), + Name: item.GetName(), + ClusterUID: uid, + Identity: identityByCluster[uid], + CreatedAt: item.GetCreationTimestamp().Time.UTC(), + }) + } + } + + sort.Slice(out.Instances, func(a, b int) bool { + x, y := out.Instances[a], out.Instances[b] + if x.Related != y.Related { + return !x.Related // bound-API instances first + } + if x.API != y.API { + return x.API < y.API + } + if x.Namespace != y.Namespace { + return x.Namespace < y.Namespace + } + return x.Name < y.Name + }) + writeJSON(w, http.StatusOK, out) +} + +// listRelated lists one related-resource rule's objects on the provider. +// FromConsumer: the managed copies consumers synced here. FromProvider: the +// unmanaged originals matching the rule's selector (label selector required; +// names-only rules additionally filter by name). +func (s *Server) listRelated(ctx context.Context, rr corev1alpha1.RelatedResource) ([]unstructured.Unstructured, error) { + kind := "Secret" + if rr.Resource == "configmaps" { + kind = "ConfigMap" + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: kind + "List"}) + + var opts []client.ListOption + if rr.Direction == corev1alpha1.FromConsumer { + opts = append(opts, client.MatchingLabels{corev1alpha1.LabelManaged: "true"}) + } else { + // Never list every secret on the provider: require a label selector + // for the originals view. + if rr.Selector == nil || rr.Selector.LabelSelector == nil { + return nil, nil + } + selector, err := metav1.LabelSelectorAsSelector(rr.Selector.LabelSelector) + if err != nil { + return nil, err + } + opts = append(opts, client.MatchingLabelsSelector{Selector: selector}) + } + if err := s.client.List(ctx, list, opts...); err != nil { + return nil, err + } + + names := map[string]bool{} + if rr.Selector != nil { + for _, n := range rr.Selector.Names { + names[n] = true + } + } + var out []unstructured.Unstructured + for i := range list.Items { + item := list.Items[i] + if len(names) > 0 && !names[item.GetName()] { + continue + } + if rr.Direction == corev1alpha1.FromConsumer { + // Only copies this layer's sync wrote, not issuer artifacts etc. + if item.GetAnnotations()[corev1alpha1.AnnotationRelatedBinding] == "" { + continue + } + } else if item.GetLabels()[corev1alpha1.LabelManaged] == "true" { + continue // a FromConsumer copy, not an original + } + out = append(out, item) + } + return out, nil +} + +// listManaged lists the provider objects of one bound API that the sync +// engine wrote (managed label). +func (s *Server) listManaged(ctx context.Context, apiName string) ([]unstructured.Unstructured, error) { + var crd apiextensionsv1.CustomResourceDefinition + if err := s.client.Get(ctx, types.NamespacedName{Name: apiName}, &crd); err != nil { + return nil, err + } + version := "" + for _, v := range crd.Spec.Versions { + if v.Storage { + version = v.Name + break + } + if v.Served && version == "" { + version = v.Name + } + } + if version == "" { + return nil, nil + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(schema.GroupVersionKind{ + Group: crd.Spec.Group, + Version: version, + Kind: crd.Spec.Names.Kind + "List", + }) + if err := s.client.List(ctx, list, client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + return nil, err + } + return list.Items, nil +} + +// identitiesForExport maps consumer cluster UIDs to the identity behind the +// export's grants, via the heartbeat Lease → Grant (connection name) link. +func (s *Server) identitiesForExport(ctx context.Context, exportName string) (map[string]string, error) { + var grants iamv1alpha1.GrantList + if err := s.client.List(ctx, &grants); err != nil { + return nil, err + } + identities := map[string]string{} + for i := range grants.Items { + grant := &grants.Items[i] + if grant.Spec.ExportName != exportName || grant.Status.Namespace == "" { + continue + } + var leases coordinationv1.LeaseList + if err := s.client.List(ctx, &leases, client.InNamespace(grant.Status.Namespace), + client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + continue + } + for j := range leases.Items { + lease := &leases.Items[j] + if lease.Annotations[corev1alpha1.AnnotationConnection] != grant.Name { + continue + } + if uid := lease.Annotations[corev1alpha1.AnnotationConsumerClusterUID]; uid != "" { + identities[uid] = grant.Spec.Identity.DisplayName + } + } + } + return identities, nil +} diff --git a/backend/gateway/server.go b/backend/gateway/server.go new file mode 100644 index 000000000..3863c95a3 --- /dev/null +++ b/backend/gateway/server.go @@ -0,0 +1,209 @@ +/* +Copyright 2026 The kbind 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 gateway is the kbind backend's HTTP API: catalog browsing, bind, +// one-time bundle pickup, and (flag-gated) browser-apply. It is stateless — +// sessions are encrypted tokens, and the only handshake state (one-time +// pickup) lives on the Grant via annotations — so any number of replicas +// works. One gateway fronts exactly one provider. +package gateway + +import ( + "encoding/json" + "errors" + "io/fs" + "net/http" + "time" + + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kbind/kbind/backend/auth" + "github.com/kbind/kbind/backend/gateway/api" + "github.com/kbind/kbind/backend/issuer" + "github.com/kbind/kbind/pkg/konnectorinstall" +) + +// Config is the gateway's static configuration. +type Config struct { + // ProviderName is the human-facing provider name in /api/provider. + ProviderName string + // Version is reported in /api/provider. + Version string + // ApplyEnabled turns on the POST /api/apply browser-apply path + // (--enable-apply). Off by default: consumer credentials transit the + // gateway when enabled. + ApplyEnabled bool + // PickupTTL is how long a bundle pickup URL lives. Default 5m. + PickupTTL time.Duration + // BindTimeout is how long POST /api/bind waits for the issuer to + // provision credentials before telling the caller to retry. Default 30s. + BindTimeout time.Duration + // KonnectorImage is the konnector image browser-apply installs. + KonnectorImage string +} + +func (c Config) pickupTTL() time.Duration { + if c.PickupTTL > 0 { + return c.PickupTTL + } + return 5 * time.Minute +} + +func (c Config) bindTimeout() time.Duration { + if c.BindTimeout > 0 { + return c.BindTimeout + } + return 30 * time.Second +} + +// Server is the gateway HTTP server. +type Server struct { + cfg Config + // client is a provider-cluster client (catalog, Grants, token Secrets). + client client.Client + bundle *issuer.BundleBuilder + auths []auth.Authenticator + mux *http.ServeMux +} + +// New assembles the gateway. ui is the embedded SPA filesystem (nil disables +// the UI routes). +func New(cfg Config, providerClient client.Client, bundle *issuer.BundleBuilder, auths []auth.Authenticator, ui fs.FS) *Server { + s := &Server{ + cfg: cfg, + client: providerClient, + bundle: bundle, + auths: auths, + mux: http.NewServeMux(), + } + + s.mux.HandleFunc("GET /api/provider", s.handleProvider) + s.mux.HandleFunc("GET /api/me", s.handleMe) + s.mux.HandleFunc("GET /api/catalog", s.handleCatalog) + s.mux.HandleFunc("GET /api/catalog/{export}/instances", s.handleExportInstances) + s.mux.HandleFunc("GET /api/clusters", s.handleClusters) + s.mux.HandleFunc("POST /api/bind", s.handleBind) + s.mux.HandleFunc("GET /api/bundle/{token}", s.handleBundle) + if cfg.ApplyEnabled { + s.mux.HandleFunc("POST /api/apply", s.handleApply) + } + s.mux.HandleFunc("GET /api/konnector", s.handleKonnectorManifests) + s.mux.HandleFunc("GET /api/healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) + }) + s.mux.HandleFunc("GET /api/auth/logout", s.handleLogout) + for _, a := range s.auths { + a.RegisterRoutes(s.mux) + } + if ui != nil { + s.mux.Handle("GET /", http.FileServerFS(ui)) + // The login page is separate from the app; the app redirects here + // when unauthenticated. + s.mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) { + http.ServeFileFS(w, r, ui, "login.html") + }) + } + return s +} + +// handleKonnectorManifests serves the konnector install (CRDs, RBAC, +// Deployment) as one apply-able YAML multi-doc — the "connect a cluster" +// counterpart of the bundle. No auth: it carries no credentials, so +// `curl … | kubectl apply -f -` stays a complete client. +func (s *Server) handleKonnectorManifests(w http.ResponseWriter, _ *http.Request) { + manifests, err := konnectorinstall.Manifests(s.cfg.KonnectorImage) + if err != nil { + writeError(w, http.StatusInternalServerError, err.Error()) + return + } + w.Header().Set("Content-Type", "application/yaml") + w.Header().Set("Content-Disposition", `attachment; filename="konnector.yaml"`) + _, _ = w.Write(manifests) +} + +// handleLogout clears the session cookie and lands on the login page. Bearer +// tokens are stateless and simply expire; logout is the browser story. +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: auth.SessionCookie, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + Secure: r.TLS != nil, + SameSite: http.SameSiteLaxMode, + }) + http.Redirect(w, r, "/login", http.StatusFound) +} + +// Handler returns the gateway's HTTP handler. +func (s *Server) Handler() http.Handler { return s.mux } + +// identity authenticates a request against the configured authenticators. +func (s *Server) identity(r *http.Request) (*auth.Identity, error) { + for _, a := range s.auths { + id, err := a.Authenticate(r) + if err == nil { + return id, nil + } + if !errors.Is(err, auth.ErrUnauthenticated) { + return nil, err + } + } + return nil, auth.ErrUnauthenticated +} + +// writeJSON writes v with the given status. +func writeJSON(w http.ResponseWriter, status int, v any) { + data, err := json.Marshal(v) + if err != nil { + http.Error(w, "encoding response", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(data) +} + +// writeError writes an api.Error. +func writeError(w http.ResponseWriter, status int, msg string) { + writeJSON(w, status, api.Error{Error: msg}) +} + +// handleMe reports the caller's identity (the UI's sidebar footer). +func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) { + id, err := s.identity(r) + if err != nil { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + writeJSON(w, http.StatusOK, id) +} + +// handleProvider serves provider metadata + auth methods (no auth required). +func (s *Server) handleProvider(w http.ResponseWriter, _ *http.Request) { + methods := make([]string, 0, len(s.auths)) + for _, a := range s.auths { + methods = append(methods, a.Name()) + } + writeJSON(w, http.StatusOK, api.Provider{ + Name: s.cfg.ProviderName, + Version: s.cfg.Version, + AuthMethods: methods, + ApplyEnabled: s.cfg.ApplyEnabled, + }) +} diff --git a/backend/http/handler.go b/backend/http/handler.go deleted file mode 100644 index 9e73238d7..000000000 --- a/backend/http/handler.go +++ /dev/null @@ -1,704 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 http - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/gorilla/mux" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - kjson "k8s.io/apimachinery/pkg/runtime/serializer/json" - componentbaseversion "k8s.io/component-base/version" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/backend/auth" - "github.com/kube-bind/kube-bind/backend/client" - "github.com/kube-bind/kube-bind/backend/kubernetes" - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - "github.com/kube-bind/kube-bind/backend/oidc" - "github.com/kube-bind/kube-bind/backend/session" - "github.com/kube-bind/kube-bind/backend/spaserver" - bindversion "github.com/kube-bind/kube-bind/pkg/version" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/web" -) - -// See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en -var noCacheHeaders = map[string]string{ - "Expires": time.Unix(0, 0).Format(time.RFC1123), - "Cache-Control": "no-cache, no-store, must-revalidate, max-age=0", - "X-Accel-Expires": "0", // https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/ -} - -// writeErrorResponse writes a structured error response to the HTTP response writer -func writeErrorResponse(w http.ResponseWriter, statusCode int, code, message, details string) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(statusCode) - - errorResponse := kubebindv1alpha2.NewError(code, message, details) - if err := json.NewEncoder(w).Encode(errorResponse); err != nil { - // Fallback to plain text if JSON encoding fails - http.Error(w, message, statusCode) - } -} - -// mapErrorToCode maps common errors to structured error codes -func mapErrorToCode(err error) (statusCode int, code string, details string) { - if apierrors.IsNotFound(err) { - return http.StatusNotFound, kubebindv1alpha2.ErrorCodeResourceNotFound, err.Error() - } - if apierrors.IsUnauthorized(err) { - return http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, err.Error() - } - if apierrors.IsForbidden(err) { - return http.StatusForbidden, kubebindv1alpha2.ErrorCodeAuthorizationFailed, err.Error() - } - if apierrors.IsBadRequest(err) { - return http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, err.Error() - } - // Default to internal server error - return http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, err.Error() -} - -type handler struct { - oidcProvider auth.OIDCProvider - authHandler auth.AuthHandlerInterface - authMiddleware *auth.AuthMiddleware - - scope kubebindv1alpha2.InformerScope - oidcAuthorizeURL string - backendCallbackURL string - providerPrettyName string - testingAutoSelect string - schemaSource string - - cookieEncryptionKey []byte - cookieSigningKey []byte - - client *http.Client - kubeManager *kubernetes.Manager - oidcServer *oidc.Server - - frontend string -} - -func NewHandler( - oidcProvider auth.OIDCProvider, - oidcServer *oidc.Server, - oidcAuthorizeURL, backendCallbackURL, providerPrettyName, testingAutoSelect string, - cookieSigningKey, cookieEncryptionKey []byte, - schemaSource string, - scope kubebindv1alpha2.InformerScope, - mgr *kubernetes.Manager, - frontend string, - tokenExpiry time.Duration, - sessionStore session.Store, -) (*handler, error) { - // Create JWT service for CLI authentication - jwtService, err := auth.NewJWTService("kube-bind-backend") - if err != nil { - return nil, fmt.Errorf("failed to create JWT service: %w", err) - } - - // Create auth middleware for request authentication - authMiddleware := auth.NewAuthMiddleware(jwtService, cookieSigningKey, cookieEncryptionKey, mgr, sessionStore) - - // Create auth handler with OIDC provider - authHandler := auth.NewAuthHandler(oidcProvider, jwtService, cookieSigningKey, cookieEncryptionKey, sessionStore, tokenExpiry) - - return &handler{ - oidcProvider: oidcProvider, - authHandler: authHandler, - authMiddleware: authMiddleware, - oidcAuthorizeURL: oidcAuthorizeURL, - backendCallbackURL: backendCallbackURL, - providerPrettyName: providerPrettyName, - testingAutoSelect: testingAutoSelect, - schemaSource: schemaSource, - frontend: frontend, - scope: scope, - client: http.DefaultClient, - kubeManager: mgr, - cookieSigningKey: cookieSigningKey, - cookieEncryptionKey: cookieEncryptionKey, - oidcServer: oidcServer, - }, nil -} - -func (h *handler) AddRoutes(mux *mux.Router) error { - // Public API routes (no authentication required) - mux.HandleFunc("/api/healthz", h.handleHealthz).Methods(http.MethodGet) - mux.HandleFunc("/api/bindable-resources", h.handleBindableResources).Methods(http.MethodGet) - // Intentionally unauthenticated: serves static, deterministic deployment YAML - // (konnector image tag is the only variable, derived from the server's own version). - // No secrets or cluster-specific data are included. - mux.HandleFunc("/api/konnector-manifests", h.handleKonnectorManifests).Methods(http.MethodGet) - - // Generic authentication routes (support both UI and CLI) - mux.HandleFunc("/api/authorize", h.authHandler.HandleAuthorize).Methods(http.MethodGet, http.MethodPost) - mux.HandleFunc("/api/callback", h.authHandler.HandleCallback).Methods(http.MethodGet) - mux.HandleFunc("/api/logout", h.handleLogout).Methods(http.MethodPost) - - mux.HandleFunc("/api/exports", h.handleServiceExport).Methods(http.MethodGet) - mux.HandleFunc("/exports", h.handleExportsRedirect).Methods(http.MethodGet) // This provides HTTP 302 redirects for backwards compatibility with older CLI versions and in general nicer UX. - - // Protected API routes (require authentication) - apiRouter := mux.PathPrefix("/api").Subrouter() - apiRouter.Use(h.authMiddleware.AuthenticateRequest) - - apiRouter.Handle("/templates", auth.RequireAuth(http.HandlerFunc(h.handleTemplates))).Methods(http.MethodGet) - apiRouter.Handle("/collections", auth.RequireAuth(http.HandlerFunc(h.handleCollections))).Methods(http.MethodGet) - apiRouter.Handle("/bind", auth.RequireAuth(http.HandlerFunc(h.handleBind))).Methods(http.MethodPost) - apiRouter.Handle("/ping", auth.RequireAuth(http.HandlerFunc(h.handlePing))).Methods(http.MethodGet) - apiRouter.Handle("/consumer-status", auth.RequireAuth(http.HandlerFunc(h.handleConsumerStatus))).Methods(http.MethodGet) - apiRouter.Handle("/apply-binding", auth.RequireAuth(http.HandlerFunc(h.handleApplyBinding))).Methods(http.MethodPost) - - if h.oidcServer != nil { - h.oidcServer.AddRoutes(mux) - } - - switch { - // Development mode: proxy to frontend dev server - case strings.HasPrefix(h.frontend, "http://"): - spaserver, err := spaserver.NewSPAReverseProxyServer(h.frontend) - if err != nil { - return err - } - mux.PathPrefix("/").Handler(spaserver) - default: - fs := web.GetFileSystem() - mux.PathPrefix("/").Handler(spaserver.NewSPAFileServer(fs)) - } - return nil -} - -func (h *handler) handleHealthz(w http.ResponseWriter, r *http.Request) { - prepareNoCache(w) - w.WriteHeader(http.StatusOK) -} - -func (h *handler) handlePing(w http.ResponseWriter, r *http.Request) { - prepareNoCache(w) - w.WriteHeader(http.StatusOK) - w.Write([]byte("pong")) //nolint:errcheck -} - -// handleKonnectorManifests returns the pre-rendered konnector YAML manifests -// that a consumer cluster needs to apply to deploy the konnector agent. -// The manifests are generated from the same Go structs used by the one-click -// apply flow (ensureKonnector) to avoid definition drift. -func (h *handler) handleKonnectorManifests(w http.ResponseWriter, r *http.Request) { - prepareNoCache(w) - - konnectorVersion, err := bindversion.BinaryVersion(componentbaseversion.Get().GitVersion) - if err != nil { - konnectorVersion = "latest" - } - konnectorImage := fmt.Sprintf("ghcr.io/kbind-dev/konnector:%s", konnectorVersion) - - manifests := kuberesources.NewKonnectorManifests(konnectorImage, h.kubeManager.GetKonnectorHostAliases()) - - // Serialize each object to YAML and join with document separators - s := runtime.NewScheme() - kuberesources.AddKonnectorSchemes(s) - encoder := kjson.NewSerializerWithOptions( - kjson.DefaultMetaFactory, - s, - s, - kjson.SerializerOptions{Yaml: true, Pretty: true, Strict: false}, - ) - codec := serializer.NewCodecFactory(s).EncoderForVersion(encoder, nil) - - var buf strings.Builder - objects := manifests.Objects() - for i, obj := range objects { - if i > 0 { - buf.WriteString("---\n") - } - if err := codec.Encode(obj, &buf); err != nil { - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to serialize konnector manifests", err.Error()) - return - } - } - - w.Header().Set("Content-Type", "text/yaml") - w.Header().Set("Content-Disposition", "attachment; filename=konnector.yaml") - w.Write([]byte(buf.String())) //nolint:errcheck -} - -func (h *handler) handleLogout(w http.ResponseWriter, r *http.Request) { - prepareNoCache(w) - - // Get cluster ID from query parameter if present - clusterID := r.URL.Query().Get("cluster_id") - - // Determine cookie name based on cluster ID - cookieName := "kube-bind" - if clusterID != "" { - cookieName = "kube-bind-" + clusterID - } - - // Create an expired cookie to clear the existing one - http.SetCookie(w, &http.Cookie{ - Name: cookieName, - Value: "", - Path: "/", - Domain: "", - Expires: time.Unix(0, 0), // Set to Unix epoch (Jan 1, 1970) to expire immediately - HttpOnly: true, - Secure: r.TLS != nil, // Set secure flag if HTTPS - SameSite: http.SameSiteLaxMode, - }) - - w.WriteHeader(http.StatusOK) - w.Write([]byte("logged out")) //nolint:errcheck -} - -func (h *handler) handleExportsRedirect(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - redirectURL := "/api/exports" - - // Preserve query parameters - if r.URL.RawQuery != "" { - redirectURL += "?" + r.URL.RawQuery - } - - logger.Info("redirecting CLI exports request", "from", r.URL.Path, "to", redirectURL) - http.Redirect(w, r, redirectURL, http.StatusFound) -} - -func (h *handler) handleServiceExport(w http.ResponseWriter, r *http.Request) { - logger := klog.FromContext(r.Context()).WithValues("method", r.Method, "url", r.URL.String()) - params := client.GetQueryParams(r) - - oidcAuthorizeURL := params.WithParams(fmt.Sprintf("http://%s/api/authorize", r.Host)) - - ver, err := bindversion.BinaryVersion(componentbaseversion.Get().GitVersion) - if err != nil { - logger.Error(err, "failed to parse version %q", componentbaseversion.Get().GitVersion) - ver = "v0.0.0" - } - prettyName := h.providerPrettyName - if prettyName == "" { - prettyName = "backend" - } - provider := &kubebindv1alpha2.BindingProvider{ - TypeMeta: metav1.TypeMeta{ - APIVersion: kubebindv1alpha2.GroupVersion, - Kind: "BindingProvider", - }, - Version: ver, - ProviderPrettyName: prettyName, - AuthenticationMethods: []kubebindv1alpha2.AuthenticationMethod{ - { - Method: "OAuth2CodeGrant", - OAuth2CodeGrant: &kubebindv1alpha2.OAuth2CodeGrant{ - AuthenticatedURL: oidcAuthorizeURL, - }, - }, - }, - } - - bs, err := json.Marshal(provider) - if err != nil { - logger.Error(err, "failed to marshal provider") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal provider information", err.Error()) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(bs) //nolint:errcheck -} - -func (h *handler) handleTemplates(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - prepareNoCache(w) - logger.Info("getting templates") - - authenticated := auth.GetAuthContext(r.Context()).IsValid - if !authenticated { - logger.Info("unauthenticated request to get templates") - writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid authentication credentials are required to access templates") - return - } - - params := client.GetQueryParams(r) - - templates, err := h.listTemplates(r.Context(), params.ClusterID) - if err != nil { - logger.Error(err, "failed to get template resources") - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to retrieve templates", details) - return - } - - w.Header().Set("Content-Type", "application/json") - // For UI, return direct result as before - if err := json.NewEncoder(w).Encode(templates); err != nil { - logger.Error(err, "failed to encode JSON response") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to encode response", err.Error()) - } -} - -func (h *handler) handleCollections(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - prepareNoCache(w) - logger.Info("getting collections") - - params := client.GetQueryParams(r) - - collections, err := h.listCollections(r.Context(), params.ClusterID) - if err != nil { - logger.Error(err, "failed to get collection resources") - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to retrieve collections", details) - return - } - - w.Header().Set("Content-Type", "application/json") - // For UI, return direct result as before - if err := json.NewEncoder(w).Encode(collections); err != nil { - logger.Error(err, "failed to encode JSON response") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to encode response", err.Error()) - } -} - -func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - params := client.GetQueryParams(r) - - prepareNoCache(w) - - // Get auth context (already verified by middleware) - authCtx := auth.GetAuthContext(r.Context()) - state := authCtx.SessionState - - // Parse JSON request body - const maxBodySize = 1 << 20 // 1 MB - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) - var bindRequest kubebindv1alpha2.BindableResourcesRequest - if err := json.NewDecoder(r.Body).Decode(&bindRequest); err != nil { - logger.Error(err, "failed to parse JSON request body") - var maxBytesError *http.MaxBytesError - if errors.As(err, &maxBytesError) { - writeErrorResponse(w, http.StatusRequestEntityTooLarge, kubebindv1alpha2.ErrorCodeBadRequest, "Request body too large", "The request body exceeds the maximum allowed size") - } else { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Invalid JSON request body", err.Error()) - } - return - } - - // Identity is always required. CLI provides the cluster identity (kube-system UID), - // and the UI sends the well-known "ui-identity" value. - identity := bindRequest.Spec.ClusterIdentity.Identity - if identity == "" { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Missing cluster identity", "spec.clusterIdentity.identity is required") - return - } - - // Resolve the UI sentinel to a real identity derived from the authenticated session. - isUIFlow := identity == auth.UIIdentity - if isUIFlow { - identity = state.Token.Issuer + "/" + state.Token.Subject - logger.Info("Resolved ui-identity from session", "identity", identity) - } - - consumerID := params.ConsumerID - if consumerID == "" { - consumerID = identity - } - - clusterPrettyName := bindRequest.Spec.ClusterIdentity.PrettyName - if clusterPrettyName == "" { - clusterPrettyName = bindRequest.Name - } - - handleResult, err := h.kubeManager.HandleResources(r.Context(), state.Token.Subject, consumerID, params.ClusterID, clusterPrettyName) - if err != nil { - logger.Error(err, "failed to handle resources") - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to handle cluster resources", details) - return - } - - // Module consist of many resources and permissionClaims. Read it and translate to - template, err := h.kubeManager.GetTemplates(r.Context(), params.ClusterID, bindRequest.Spec.TemplateRef.Name) - if err != nil { - logger.Error(err, "failed to get template", "template", bindRequest.Spec.TemplateRef.Name, "cluster", params.ClusterID) - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to retrieve template", details) - return - } - - request := kubebindv1alpha2.APIServiceExportRequestResponse{ - TypeMeta: metav1.TypeMeta{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "APIServiceExportRequest", - }, - ObjectMeta: kubebindv1alpha2.NameObjectMeta{ - Name: bindRequest.Name, - }, - Spec: kubebindv1alpha2.APIServiceExportRequestSpec{ - Resources: template.Spec.Resources, - PermissionClaims: template.Spec.PermissionClaims, - Namespaces: template.Spec.Namespaces, - SchemaUpdatePolicy: template.Spec.SchemaUpdatePolicy, - }, - } - - // For UI-only flow, create the APIServiceExportRequest on the provider cluster - // and wait for reconciliation. In CLI flow the konnector handles this instead. - var exportRequestName string - if isUIFlow { - exportRequest, err := h.kubeManager.CreateAPIServiceExportRequest( - r.Context(), - params.ClusterID, - handleResult.Namespace, - bindRequest.Name, - request.Spec, - ) - if err != nil { - logger.Error(err, "failed to create APIServiceExportRequest") - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to create API service export request", details) - return - } - exportRequestName = exportRequest.Name - } - - // callback response - requestBytes, err := json.Marshal(&request) - if err != nil { - logger.Error(err, "failed to marshal request") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal request", err.Error()) - return - } - - response := kubebindv1alpha2.BindingResourceResponse{ - TypeMeta: metav1.TypeMeta{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "BindingResponse", - }, - Authentication: kubebindv1alpha2.BindingResponseAuthentication{ - OAuth2CodeGrant: &kubebindv1alpha2.BindingResponseAuthenticationOAuth2CodeGrant{ - SessionID: state.SessionID, - ID: state.Token.Issuer + "/" + state.Token.Subject, - }, - }, - Kubeconfig: handleResult.Kubeconfig, - Requests: []runtime.RawExtension{{Raw: requestBytes}}, - ProviderNamespace: handleResult.Namespace, - BindingName: exportRequestName, - } - - payload, err := json.Marshal(&response) - if err != nil { - logger.Error(err, "failed to marshal binding response") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal binding response", err.Error()) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(payload) //nolint:errcheck -} - -// handleConsumerStatus returns whether the authenticated user already has a consumer -// namespace with existing APIServiceExports on the provider. -func (h *handler) handleConsumerStatus(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - params := client.GetQueryParams(r) - prepareNoCache(w) - - authCtx := auth.GetAuthContext(r.Context()) - state := authCtx.SessionState - identity := state.Token.Issuer + "/" + state.Token.Subject - - status, err := h.kubeManager.GetConsumerStatus(r.Context(), identity, params.ClusterID) - if err != nil { - logger.Error(err, "failed to get consumer status") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to get consumer status", err.Error()) - return - } - - payload, err := json.Marshal(status) - if err != nil { - logger.Error(err, "failed to marshal consumer status") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal consumer status", err.Error()) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(payload) //nolint:errcheck -} - -// applyBindingRequest is the JSON body for the apply-binding endpoint. -type applyBindingRequest struct { - // ConsumerKubeconfig is the base64-encoded kubeconfig for the consumer cluster. - ConsumerKubeconfig string `json:"consumerKubeconfig"` - // BindingName is the name for the binding (used for secret and bundle naming). - BindingName string `json:"bindingName"` - // HostAliases is an optional list of host alias entries for konnector pods, - // in the format "IP:hostname1,hostname2". Overrides the server-configured defaults. - HostAliases []string `json:"hostAliases,omitempty"` -} - -// handleApplyBinding receives a consumer kubeconfig and applies the konnector + binding -// bundle to the consumer cluster. -func (h *handler) handleApplyBinding(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - params := client.GetQueryParams(r) - prepareNoCache(w) - - authCtx := auth.GetAuthContext(r.Context()) - state := authCtx.SessionState - identity := state.Token.Issuer + "/" + state.Token.Subject - - // Parse request body - const maxBodySize = 1 << 20 // 1 MB - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) - var req applyBindingRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Invalid request body", err.Error()) - return - } - - if req.ConsumerKubeconfig == "" { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Missing consumer kubeconfig", "consumerKubeconfig is required") - return - } - if req.BindingName == "" { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Missing binding name", "bindingName is required") - return - } - - // Decode base64 consumer kubeconfig - consumerKubeconfigData, err := base64.StdEncoding.DecodeString(req.ConsumerKubeconfig) - if err != nil { - writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Invalid consumer kubeconfig encoding", "consumerKubeconfig must be base64 encoded") - return - } - - // Get the provider kubeconfig for this user's namespace - handleResult, err := h.kubeManager.HandleResources(r.Context(), state.Token.Subject, identity, params.ClusterID, req.BindingName) - if err != nil { - logger.Error(err, "failed to handle resources for apply-binding") - statusCode, code, details := mapErrorToCode(err) - writeErrorResponse(w, statusCode, code, "Failed to prepare provider resources", details) - return - } - - // Resolve konnector image - konnectorVersion, err := bindversion.BinaryVersion(componentbaseversion.Get().GitVersion) - if err != nil { - konnectorVersion = "latest" - } - konnectorImage := fmt.Sprintf("ghcr.io/kbind-dev/konnector:%s", konnectorVersion) - - // Parse optional host alias overrides from request - var overrideHostAliases []corev1.HostAlias - for _, entry := range req.HostAliases { - parts := strings.SplitN(entry, ":", 2) - if len(parts) == 2 && parts[0] != "" && parts[1] != "" { - overrideHostAliases = append(overrideHostAliases, corev1.HostAlias{ - IP: parts[0], - Hostnames: strings.Split(parts[1], ","), - }) - } - } - - // Apply to consumer cluster - result, err := h.kubeManager.ApplyToConsumer( - r.Context(), - consumerKubeconfigData, - handleResult.Kubeconfig, - req.BindingName, - konnectorImage, - overrideHostAliases, - ) - if err != nil { - logger.Error(err, "failed to apply binding to consumer cluster") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to apply binding to consumer cluster", err.Error()) - return - } - - payload, err := json.Marshal(result) - if err != nil { - logger.Error(err, "failed to marshal apply result") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal result", err.Error()) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(payload) //nolint:errcheck -} - -// if they are part of a Collection or not. -func (h *handler) listTemplates(ctx context.Context, cluster string) (*kubebindv1alpha2.APIServiceExportTemplateList, error) { - templates, err := h.kubeManager.ListTemplates(ctx, cluster) - if err != nil { - return nil, fmt.Errorf("failed to list collections: %w", err) - } - - return templates, nil -} - -// listCollections fetches the list of Collections from the backend cluster. -func (h *handler) listCollections(ctx context.Context, cluster string) (*kubebindv1alpha2.CollectionList, error) { - collections, err := h.kubeManager.ListCollections(ctx, cluster) - if err != nil { - return nil, fmt.Errorf("failed to list collections: %w", err) - } - - return collections, nil -} - -func (h *handler) handleBindableResources(w http.ResponseWriter, r *http.Request) { - logger := getLogger(r) - - bs, err := json.Marshal(&kubebindv1alpha2.ClaimableAPIs) - if err != nil { - logger.Error(err, "failed to marshal resources") - writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal bindable resources", err.Error()) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(bs) //nolint:errcheck -} - -// prepareNoCache prepares headers for preventing browser caching. -func prepareNoCache(w http.ResponseWriter) { - // Set NoCache headers - for k, v := range noCacheHeaders { - w.Header().Set(k, v) - } -} - -func getLogger(r *http.Request) klog.Logger { - return klog.FromContext(r.Context()).WithValues("method", r.Method, "url", r.URL.String()) -} diff --git a/backend/http/server.go b/backend/http/server.go deleted file mode 100644 index a7a5208ca..000000000 --- a/backend/http/server.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 http - -import ( - "context" - "log" - "net" - "net/http" - "time" - - "github.com/gorilla/mux" - - "github.com/kube-bind/kube-bind/backend/options" -) - -type Server struct { - options *options.Serve - listener net.Listener - Router *mux.Router -} - -func NewServer(options *options.Serve) (*Server, error) { - server := &Server{ - options: options, - Router: mux.NewRouter(), - listener: options.Listener, - } - - return server, nil -} - -func (s *Server) Addr() net.Addr { - return s.listener.Addr() -} - -func (s *Server) Start(ctx context.Context) error { - log.Println("Starting web server") - server := &http.Server{ - Handler: s.Router, - ReadHeaderTimeout: 1 * time.Minute, - } - go func() { - <-ctx.Done() - server.Close() - }() - - go func() { - if s.options.KeyFile == "" { - log.Println("Serving HTTP on", s.listener.Addr()) - server.Serve(s.listener) //nolint:errcheck - } else { - log.Println("Serving HTTPS on", s.listener.Addr()) - server.ServeTLS(s.listener, s.options.CertFile, s.options.KeyFile) //nolint:errcheck - } - }() - - return nil -} diff --git a/backend/issuer/bundle.go b/backend/issuer/bundle.go new file mode 100644 index 000000000..4c3477d5c --- /dev/null +++ b/backend/issuer/bundle.go @@ -0,0 +1,118 @@ +/* +Copyright 2026 The kbind 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 issuer + +import ( + "context" + "fmt" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// KonnectorNamespace is the consumer-side namespace the konnector runs in and +// where the bundle's kubeconfig Secret lands. +const KonnectorNamespace = "kbind" + +// BundleBuilder assembles the one-apply bundle for a Ready Grant. The bundle +// is never stored: it is (re)built on demand from the issuer's token Secret. +type BundleBuilder struct { + // Client is a provider-cluster client (reads the token Secret). + Client client.Client + // ExternalAddress is the provider API server URL consumers reach — + // what goes into issued kubeconfigs. + ExternalAddress string + // ExternalCA optionally overrides the CA bundle for issued kubeconfigs; + // nil uses the ca.crt from the SA token Secret. + ExternalCA []byte +} + +// Kubeconfig builds the consumer kubeconfig for a provisioned Grant. The +// context namespace is pinned to the boundary namespace — tenant RBAC allows +// Leases there, and the konnector homes its heartbeat in the kubeconfig's +// context namespace. +func (b *BundleBuilder) Kubeconfig(ctx context.Context, grant *iamv1alpha1.Grant) ([]byte, error) { + if grant.Status.Namespace == "" || grant.Status.TokenSecret == "" { + return nil, fmt.Errorf("grant %s is not provisioned yet", grant.Name) + } + var secret corev1.Secret + if err := b.Client.Get(ctx, types.NamespacedName{Namespace: grant.Status.Namespace, Name: grant.Status.TokenSecret}, &secret); err != nil { + return nil, fmt.Errorf("reading token secret: %w", err) + } + token := secret.Data[corev1.ServiceAccountTokenKey] + if len(token) == 0 { + return nil, fmt.Errorf("token secret %s/%s not yet populated", grant.Status.Namespace, grant.Status.TokenSecret) + } + ca := b.ExternalCA + if len(ca) == 0 { + ca = secret.Data[corev1.ServiceAccountRootCAKey] + } + + cfg := clientcmdapi.NewConfig() + cfg.Clusters["provider"] = &clientcmdapi.Cluster{ + Server: b.ExternalAddress, + CertificateAuthorityData: ca, + } + cfg.AuthInfos["kbind"] = &clientcmdapi.AuthInfo{Token: string(token)} + cfg.Contexts["provider"] = &clientcmdapi.Context{ + Cluster: "provider", + AuthInfo: "kbind", + Namespace: grant.Status.Namespace, + } + cfg.CurrentContext = "provider" + return clientcmd.Write(*cfg) +} + +// Objects returns the bundle's objects: Secret + Connection + ClusterBinding, +// all named after the Grant, exactly the core's one-apply contract. Every +// path through the service layer terminates here. +func (b *BundleBuilder) Objects(grant *iamv1alpha1.Grant, kubeconfig []byte) []client.Object { + secret := &corev1.Secret{ + TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Secret"}, + ObjectMeta: metav1.ObjectMeta{Namespace: KonnectorNamespace, Name: grant.Name}, + StringData: map[string]string{"kubeconfig": string(kubeconfig)}, + } + connection := &corev1alpha1.Connection{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.GroupVersion.String(), Kind: "Connection"}, + ObjectMeta: metav1.ObjectMeta{Name: grant.Name}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{ + Namespace: KonnectorNamespace, + Name: grant.Name, + Key: "kubeconfig", + }, + }, + } + binding := &corev1alpha1.ClusterBinding{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.GroupVersion.String(), Kind: "ClusterBinding"}, + ObjectMeta: metav1.ObjectMeta{Name: grant.Name}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: grant.Name}, + APIs: grant.Spec.APIs, + ConflictPolicy: grant.Spec.ConflictPolicy, + RelatedResources: grant.Spec.RelatedResources, + }, + } + return []client.Object{secret, connection, binding} +} diff --git a/backend/issuer/catalog_controller.go b/backend/issuer/catalog_controller.go new file mode 100644 index 000000000..698946543 --- /dev/null +++ b/backend/issuer/catalog_controller.go @@ -0,0 +1,108 @@ +/* +Copyright 2026 The kbind 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 issuer + +import ( + "context" + "fmt" + "strings" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// ExportReconciler keeps the catalog derived-from-core-truth: an Export +// listing an API that is not actually exported (missing the export label) +// gets Ready=False, and the gateway hides it. +type ExportReconciler struct { + Client client.Client +} + +// SetupWithManager registers the reconciler; CRD changes re-validate every +// Export (labels flipping is exactly the event that matters). +func (r *ExportReconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.Client == nil { + r.Client = mgr.GetClient() + } + return ctrl.NewControllerManagedBy(mgr). + For(&catalogv1alpha1.Export{}). + Watches(&apiextensionsv1.CustomResourceDefinition{}, handler.EnqueueRequestsFromMapFunc(r.allExports)). + Named("catalog-export"). + Complete(r) +} + +func (r *ExportReconciler) allExports(ctx context.Context, _ client.Object) []reconcile.Request { + var list catalogv1alpha1.ExportList + if err := r.Client.List(ctx, &list); err != nil { + return nil + } + reqs := make([]reconcile.Request, 0, len(list.Items)) + for i := range list.Items { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Name: list.Items[i].Name}}) + } + return reqs +} + +// Reconcile validates the Export's API list against the actually exported CRDs. +func (r *ExportReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + export := &catalogv1alpha1.Export{} + if err := r.Client.Get(ctx, req.NamespacedName, export); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + + var crds apiextensionsv1.CustomResourceDefinitionList + if err := r.Client.List(ctx, &crds, client.MatchingLabels{corev1alpha1.LabelExported: "true"}); err != nil { + return ctrl.Result{}, err + } + exported := make(map[string]bool, len(crds.Items)) + for i := range crds.Items { + exported[crds.Items[i].Name] = true + } + + var missing []string + for _, api := range export.Spec.APIs { + if !exported[api.Name] { + missing = append(missing, api.Name) + } + } + + cond := metav1.Condition{ + Type: catalogv1alpha1.ConditionReady, Status: metav1.ConditionTrue, + Reason: catalogv1alpha1.ReasonAsExpected, Message: "all listed APIs are exported", + ObservedGeneration: export.Generation, + } + if len(missing) > 0 { + cond.Status = metav1.ConditionFalse + cond.Reason = catalogv1alpha1.ReasonAPINotExported + cond.Message = fmt.Sprintf("not exported (missing the %s label): %s", corev1alpha1.LabelExported, strings.Join(missing, ", ")) + } + if apimeta.SetStatusCondition(&export.Status.Conditions, cond) { + if err := r.Client.Status().Update(ctx, export); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{}, nil +} diff --git a/backend/issuer/controller.go b/backend/issuer/controller.go new file mode 100644 index 000000000..2bbb2dc0c --- /dev/null +++ b/backend/issuer/controller.go @@ -0,0 +1,109 @@ +/* +Copyright 2026 The kbind 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 issuer + +import ( + "context" + "time" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// GrantReconciler drives Grants through the Issuer: provision on existence, +// revoke on deletion (cleanup finalizer). +type GrantReconciler struct { + Client client.Client + Issuer Issuer +} + +// SetupWithManager registers the reconciler with the provider-side manager. +func (r *GrantReconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.Client == nil { + r.Client = mgr.GetClient() + } + return ctrl.NewControllerManagedBy(mgr). + For(&iamv1alpha1.Grant{}). + Named("grant"). + Complete(r) +} + +// Reconcile provisions the Grant's credentials and reports them in status. +func (r *GrantReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + grant := &iamv1alpha1.Grant{} + if err := r.Client.Get(ctx, req.NamespacedName, grant); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + + if grant.DeletionTimestamp != nil { + if !controllerutil.ContainsFinalizer(grant, iamv1alpha1.FinalizerCleanup) { + return ctrl.Result{}, nil + } + if err := r.Issuer.Revoke(ctx, grant); err != nil { + return ctrl.Result{}, err + } + controllerutil.RemoveFinalizer(grant, iamv1alpha1.FinalizerCleanup) + return ctrl.Result{}, client.IgnoreNotFound(r.Client.Update(ctx, grant)) + } + + if controllerutil.AddFinalizer(grant, iamv1alpha1.FinalizerCleanup) { + if err := r.Client.Update(ctx, grant); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{}, nil + } + + result, err := r.Issuer.Provision(ctx, grant) + if err != nil { + return ctrl.Result{}, err + } + + orig := grant.DeepCopy() + grant.Status.Namespace = result.Namespace + grant.Status.ServiceAccount = result.ServiceAccount + grant.Status.TokenSecret = result.TokenSecret + if result.TokenReady { + apimeta.SetStatusCondition(&grant.Status.Conditions, metav1.Condition{ + Type: iamv1alpha1.ConditionReady, Status: metav1.ConditionTrue, + Reason: iamv1alpha1.ReasonAsExpected, Message: "credentials provisioned", + ObservedGeneration: grant.Generation, + }) + } else { + apimeta.SetStatusCondition(&grant.Status.Conditions, metav1.Condition{ + Type: iamv1alpha1.ConditionReady, Status: metav1.ConditionFalse, + Reason: iamv1alpha1.ReasonPending, Message: "waiting for the token controller to populate the token secret", + ObservedGeneration: grant.Generation, + }) + } + if !apimeta.IsStatusConditionPresentAndEqual(orig.Status.Conditions, iamv1alpha1.ConditionReady, metav1.ConditionTrue) || + orig.Status.Namespace != grant.Status.Namespace || orig.Status.TokenSecret != grant.Status.TokenSecret { + if err := r.Client.Status().Update(ctx, grant); err != nil { + return ctrl.Result{}, err + } + } + + if !result.TokenReady { + // The token controller populates the Secret out of band; poll briefly. + return ctrl.Result{RequeueAfter: 2 * time.Second}, nil + } + return ctrl.Result{}, nil +} diff --git a/backend/issuer/issuer.go b/backend/issuer/issuer.go new file mode 100644 index 000000000..6bd8accce --- /dev/null +++ b/backend/issuer/issuer.go @@ -0,0 +1,80 @@ +/* +Copyright 2026 The kbind 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 issuer provisions per-consumer credentials on the provider cluster: +// a tenancy boundary (namespace), a ServiceAccount with RBAC scoped to the +// granted APIs, and a long-lived SA token. The Grant (iam.kbind.io) is the +// issuance record; deleting it revokes. The in-tree implementation is plain +// Kubernetes only — a kcp issuer implements the same interface out of tree. +package issuer + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "strings" + + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// Issuer is the provisioning boundary of the service layer: make a Grant's +// credentials exist, and unwind them on revocation. +type Issuer interface { + // Provision ensures the Grant's boundary, ServiceAccount, RBAC and token + // exist, and reports what was provisioned. Idempotent. + Provision(ctx context.Context, grant *iamv1alpha1.Grant) (*ProvisionResult, error) + // Revoke removes the Grant's credentials (ServiceAccount, RBAC, token). + // It does NOT delete the boundary namespace or synced objects — that + // destructive step belongs to the reaper's explicit opt-in. + Revoke(ctx context.Context, grant *iamv1alpha1.Grant) error +} + +// ProvisionResult reports the artifacts of an issuance. +type ProvisionResult struct { + // Namespace is the per-consumer tenancy boundary. + Namespace string + // ServiceAccount is the issued ServiceAccount's name (in Namespace). + ServiceAccount string + // TokenSecret is the SA token Secret's name (in Namespace). + TokenSecret string + // TokenReady is true once the token controller populated the Secret. + TokenReady bool +} + +// IdentityHash is the stable tenancy key for a subject ("#"): +// same human, same boundary, on every re-bind. +func IdentityHash(subject string) string { + sum := sha256.Sum256([]byte(subject)) + return hex.EncodeToString(sum[:])[:10] +} + +// BoundaryNamespace is the per-identity provider namespace. +func BoundaryNamespace(subject string) string { + return "kbind-" + IdentityHash(subject) +} + +// GrantName is the deterministic Grant name for (export, identity), so a +// re-bind of the same export by the same human updates the existing record. +func GrantName(exportName, subject string) string { + return exportName + "-" + IdentityHash(subject) +} + +// SplitAPIName splits a CRD name "." into resource and group +// (group may be empty for core-group names, which do not occur in practice). +func SplitAPIName(name string) (resource, group string) { + resource, group, _ = strings.Cut(name, ".") + return resource, group +} diff --git a/backend/issuer/issuer_test.go b/backend/issuer/issuer_test.go new file mode 100644 index 000000000..90f5090b8 --- /dev/null +++ b/backend/issuer/issuer_test.go @@ -0,0 +1,65 @@ +/* +Copyright 2026 The kbind 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 issuer + +import ( + "testing" + + "github.com/stretchr/testify/require" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +func TestIdentityNamingIsStable(t *testing.T) { + subject := "https://issuer.example.com#alice" + + require.Equal(t, BoundaryNamespace(subject), BoundaryNamespace(subject), + "same human, same boundary") + require.Equal(t, GrantName("mangodb", subject), GrantName("mangodb", subject)) + + require.NotEqual(t, BoundaryNamespace(subject), BoundaryNamespace("https://issuer.example.com#bob")) + require.NotEqual(t, GrantName("mangodb", subject), GrantName("postgres", subject), + "one grant per (export, identity)") +} + +func TestSplitAPIName(t *testing.T) { + resource, group := SplitAPIName("mangodbs.mangodb.io") + require.Equal(t, "mangodbs", resource) + require.Equal(t, "mangodb.io", group) +} + +func TestGrantRulesEnumerateExactly(t *testing.T) { + issuer := &KubeIssuer{} + rules := issuer.grantRules(&iamv1alpha1.Grant{ + Spec: iamv1alpha1.GrantSpec{ + APIs: []corev1alpha1.APIRef{{Name: "widgets.example.org"}}, + RelatedResources: []corev1alpha1.RelatedResource{ + {Resource: "secrets", Direction: corev1alpha1.FromProvider}, + {Resource: "configmaps", Direction: corev1alpha1.FromConsumer}, + }, + }, + }) + + require.Len(t, rules, 3) + require.Equal(t, []string{"example.org"}, rules[0].APIGroups) + require.Equal(t, []string{"widgets", "widgets/status"}, rules[0].Resources) + require.Equal(t, []string{"get", "list", "watch"}, rules[1].Verbs, + "FromProvider related resources are read-only for the consumer credentials") + require.Contains(t, rules[2].Verbs, "create", + "FromConsumer related resources are written by the konnector") +} diff --git a/backend/issuer/kube.go b/backend/issuer/kube.go new file mode 100644 index 000000000..5d2970214 --- /dev/null +++ b/backend/issuer/kube.go @@ -0,0 +1,270 @@ +/* +Copyright 2026 The kbind 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 issuer + +import ( + "context" + "fmt" + + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// Scope selects how far the issued RBAC reaches for the granted resources. +type Scope string + +const ( + // ScopeCluster grants the exported resources in all namespaces (plus + // namespace creation), matching the core's identity-preserving sync: the + // consumer's namespace names are reproduced on the provider. Cross-consumer + // collisions are handled by the core's ownership markers (first-writer- + // wins). This is the default. + ScopeCluster Scope = "Cluster" + + // ScopeNamespace fences the credentials into the boundary namespace only — + // strict tenancy, with the honest consequence of identity-preserving sync: + // consumers must place bound objects in a namespace named like the + // boundary (the issued kubeconfig's context namespace). + ScopeNamespace Scope = "Namespace" +) + +// LabelIdentity marks the boundary namespace with the identity hash that owns +// it (the namespace is shared by all of that identity's Grants). +const LabelIdentity = "iam.kbind.io/identity" + +// KubeIssuer is the in-tree Issuer for plain Kubernetes providers. +// Credential mechanism: long-lived secret-based SA token (zero rotation +// friction accepted over security posture; revocation via Grant deletion). +type KubeIssuer struct { + // Client is a provider-cluster client. + Client client.Client + // Scope is the RBAC reach for granted resources. Default ScopeCluster. + Scope Scope +} + +func (i *KubeIssuer) scope() Scope { + if i.Scope == "" { + return ScopeCluster + } + return i.Scope +} + +// clusterRoleName namespaces the cluster-scoped RBAC objects per Grant. +func clusterRoleName(g *iamv1alpha1.Grant) string { return "kbind:grant:" + g.Name } + +// tokenSecretName is the SA token Secret for a Grant. +func tokenSecretName(g *iamv1alpha1.Grant) string { return g.Name + "-token" } + +// Provision implements Issuer for plain Kubernetes. +func (i *KubeIssuer) Provision(ctx context.Context, g *iamv1alpha1.Grant) (*ProvisionResult, error) { + ns := BoundaryNamespace(g.Spec.Identity.Subject) + + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, namespace, func() error { + setLabel(&namespace.ObjectMeta, corev1alpha1.LabelManaged, "true") + setLabel(&namespace.ObjectMeta, LabelIdentity, IdentityHash(g.Spec.Identity.Subject)) + return nil + }); err != nil { + return nil, fmt.Errorf("ensuring boundary namespace: %w", err) + } + + sa := &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, sa, func() error { + setLabel(&sa.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + return nil + }); err != nil { + return nil, fmt.Errorf("ensuring service account: %w", err) + } + + // Long-lived secret-based SA token; the token controller populates it. + token := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: tokenSecretName(g)}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, token, func() error { + setLabel(&token.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + if token.Annotations == nil { + token.Annotations = map[string]string{} + } + token.Annotations[corev1.ServiceAccountNameKey] = g.Name + token.Type = corev1.SecretTypeServiceAccountToken + return nil + }); err != nil { + return nil, fmt.Errorf("ensuring token secret: %w", err) + } + + if err := i.ensureRBAC(ctx, g, ns); err != nil { + return nil, err + } + + return &ProvisionResult{ + Namespace: ns, + ServiceAccount: g.Name, + TokenSecret: token.Name, + TokenReady: len(token.Data[corev1.ServiceAccountTokenKey]) > 0, + }, nil +} + +// ensureRBAC scopes the credentials to exactly the granted APIs (+ declared +// related resources). The split between ClusterRole and Role follows the +// issuance scope; the base ClusterRole (schema discovery + cluster identity) +// and the boundary-namespace Lease permissions (heartbeat) exist in both. +func (i *KubeIssuer) ensureRBAC(ctx context.Context, g *iamv1alpha1.Grant, ns string) error { + grantRules := i.grantRules(g) + + // Base cluster-wide reads every konnector needs: exported-CRD discovery + // + schema pull, and the kube-system namespace UID (cluster identity). + clusterRules := []rbacv1.PolicyRule{ + {APIGroups: []string{"apiextensions.k8s.io"}, Resources: []string{"customresourcedefinitions"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{""}, Resources: []string{"namespaces"}, Verbs: []string{"get"}, ResourceNames: []string{"kube-system"}}, + } + if i.scope() == ScopeCluster { + clusterRules = append(clusterRules, + rbacv1.PolicyRule{APIGroups: []string{""}, Resources: []string{"namespaces"}, Verbs: []string{"get", "list", "watch", "create"}}) + clusterRules = append(clusterRules, grantRules...) + } + + cr := &rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: clusterRoleName(g)}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, cr, func() error { + setLabel(&cr.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + cr.Rules = clusterRules + return nil + }); err != nil { + return fmt.Errorf("ensuring cluster role: %w", err) + } + + crb := &rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: clusterRoleName(g)}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, crb, func() error { + setLabel(&crb.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + crb.RoleRef = rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: cr.Name} + crb.Subjects = []rbacv1.Subject{{Kind: rbacv1.ServiceAccountKind, Namespace: ns, Name: g.Name}} + return nil + }); err != nil { + return fmt.Errorf("ensuring cluster role binding: %w", err) + } + + // Boundary-namespace Role: the heartbeat Lease home (the issued + // kubeconfig pins its context namespace here), plus the granted + // resources when the scope is Namespace. + roleRules := []rbacv1.PolicyRule{ + {APIGroups: []string{"coordination.k8s.io"}, Resources: []string{"leases"}, Verbs: []string{"get", "list", "watch", "create", "update", "patch"}}, + } + if i.scope() == ScopeNamespace { + roleRules = append(roleRules, grantRules...) + } + + role := &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, role, func() error { + setLabel(&role.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + role.Rules = roleRules + return nil + }); err != nil { + return fmt.Errorf("ensuring role: %w", err) + } + + rb := &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}} + if _, err := controllerutil.CreateOrUpdate(ctx, i.Client, rb, func() error { + setLabel(&rb.ObjectMeta, iamv1alpha1.LabelGrant, g.Name) + rb.RoleRef = rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "Role", Name: role.Name} + rb.Subjects = []rbacv1.Subject{{Kind: rbacv1.ServiceAccountKind, Namespace: ns, Name: g.Name}} + return nil + }); err != nil { + return fmt.Errorf("ensuring role binding: %w", err) + } + return nil +} + +// grantRules enumerates the granted APIs and related resources — an explicit, +// reviewable Role, not a wildcard. +func (i *KubeIssuer) grantRules(g *iamv1alpha1.Grant) []rbacv1.PolicyRule { + rules := make([]rbacv1.PolicyRule, 0, len(g.Spec.APIs)+len(g.Spec.RelatedResources)) + for _, api := range g.Spec.APIs { + resource, group := SplitAPIName(api.Name) + rules = append(rules, rbacv1.PolicyRule{ + APIGroups: []string{group}, + Resources: []string{resource, resource + "/status"}, + Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, + }) + } + for _, rr := range g.Spec.RelatedResources { + verbs := []string{"get", "list", "watch"} // FromProvider: konnector only reads + if rr.Direction == corev1alpha1.FromConsumer { + verbs = []string{"get", "list", "watch", "create", "update", "patch", "delete"} + } + rules = append(rules, rbacv1.PolicyRule{ + APIGroups: []string{rr.Group}, + Resources: []string{rr.Resource}, + Verbs: verbs, + }) + } + return rules +} + +// Revoke implements Issuer: remove the credentials, keep the boundary +// namespace and any synced objects (destructive cleanup is the reaper's +// explicit opt-in, see DeleteBoundary). +func (i *KubeIssuer) Revoke(ctx context.Context, g *iamv1alpha1.Grant) error { + ns := BoundaryNamespace(g.Spec.Identity.Subject) + for _, obj := range []client.Object{ + &rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: clusterRoleName(g)}}, + &rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: clusterRoleName(g)}}, + &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}}, + &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}}, + &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: tokenSecretName(g)}}, + &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: g.Name}}, + } { + if err := i.Client.Delete(ctx, obj); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("revoking %T %s: %w", obj, obj.GetName(), err) + } + } + return nil +} + +// DeleteBoundary deletes the Grant's boundary namespace (cascading synced +// objects inside it) — but only if no other live Grant shares the identity. +// Called by the reaper's destructive mode only, never by plain revocation. +func (i *KubeIssuer) DeleteBoundary(ctx context.Context, g *iamv1alpha1.Grant) error { + var grants iamv1alpha1.GrantList + if err := i.Client.List(ctx, &grants); err != nil { + return err + } + for idx := range grants.Items { + other := &grants.Items[idx] + if other.Name == g.Name || other.DeletionTimestamp != nil { + continue + } + if IdentityHash(other.Spec.Identity.Subject) == IdentityHash(g.Spec.Identity.Subject) { + return nil // boundary still in use + } + } + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: BoundaryNamespace(g.Spec.Identity.Subject)}} + if err := i.Client.Delete(ctx, ns); err != nil && !apierrors.IsNotFound(err) { + return err + } + return nil +} + +func setLabel(meta *metav1.ObjectMeta, key, value string) { + if meta.Labels == nil { + meta.Labels = map[string]string{} + } + meta.Labels[key] = value +} diff --git a/backend/kubernetes/indexers.go b/backend/kubernetes/indexers.go deleted file mode 100644 index 059af99ec..000000000 --- a/backend/kubernetes/indexers.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 kubernetes - -import ( - corev1 "k8s.io/api/core/v1" - "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/kube-bind/kube-bind/backend/kubernetes/resources" -) - -const ( - NamespacesByIdentity = "namespacesByIdentity" -) - -func IndexNamespacesByIdentity(obj client.Object) []string { - ns, ok := obj.(*corev1.Namespace) - if !ok { - return nil - } - - if id, found := ns.Annotations[resources.IdentityAnnotationKey]; found { - return []string{id} - } - - return nil -} diff --git a/backend/kubernetes/manager.go b/backend/kubernetes/manager.go deleted file mode 100644 index 2d30c7be6..000000000 --- a/backend/kubernetes/manager.go +++ /dev/null @@ -1,741 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 kubernetes - -import ( - "context" - "fmt" - "net" - "net/url" - "strings" - "time" - - appsv1 "k8s.io/api/apps/v1" - authzv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes/scheme" - authorizationv1 "k8s.io/client-go/kubernetes/typed/authorization/v1" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Manager struct { - namespacePrefix string - providerPrettyName string - scope kubebindv1alpha2.InformerScope - - externalAddressGenerator kuberesources.ExternalAddressGeneratorFunc - externalCA []byte - externalTLSServerName string - - manager mcmanager.Manager - embeddedOIDC bool - - // konnectorHostAliases are default host aliases injected into konnector - // pods deployed via the UI flow (configured via --konnector-host-alias flag). - konnectorHostAliases []corev1.HostAlias -} - -func NewKubernetesManager( - ctx context.Context, - namespacePrefix, providerPrettyName string, - externalAddressGenerator kuberesources.ExternalAddressGeneratorFunc, - scope kubebindv1alpha2.InformerScope, - externalCA []byte, - externalTLSServerName string, - manager mcmanager.Manager, - embeddedOIDC bool, - konnectorHostAliases []corev1.HostAlias, -) (*Manager, error) { - m := &Manager{ - namespacePrefix: namespacePrefix, - providerPrettyName: providerPrettyName, - scope: scope, - - externalAddressGenerator: externalAddressGenerator, - externalCA: externalCA, - externalTLSServerName: externalTLSServerName, - - manager: manager, - embeddedOIDC: embeddedOIDC, - konnectorHostAliases: konnectorHostAliases, - } - - if err := m.manager.GetFieldIndexer().IndexField(ctx, &corev1.Namespace{}, NamespacesByIdentity, - IndexNamespacesByIdentity); err != nil { - return nil, fmt.Errorf("failed to setup NamespacesByIdentity indexer: %w", err) - } - - return m, nil -} - -// HandleResourcesResult contains the result of HandleResources operation. -type HandleResourcesResult struct { - // Kubeconfig is the kubeconfig data for accessing the service provider cluster. - Kubeconfig []byte - // Namespace is the namespace assigned to this binding on the service provider cluster. - Namespace string -} - -func (m *Manager) HandleResources( - ctx context.Context, - author, identity, cluster, clusterPrettyName string, -) (*HandleResourcesResult, error) { - logger := klog.FromContext(ctx).WithValues("identity", identity) - ctx = klog.NewContext(ctx, logger) - - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - // try to find an existing namespace by annotation, or create a new one. - var nss corev1.NamespaceList - err = c.List(ctx, &nss, client.MatchingFields{NamespacesByIdentity: identity}) - if err != nil { - return nil, err - } - if len(nss.Items) > 1 { - logger.Error(fmt.Errorf("found multiple namespaces for identity %q", identity), "found multiple namespaces for identity") - return nil, fmt.Errorf("found multiple namespaces for identity %q", identity) - } - var ns string - if len(nss.Items) == 1 { - ns = nss.Items[0].Name - } else { - nsObj, err := kuberesources.CreateNamespace(ctx, c, m.namespacePrefix, identity, author) - if err != nil { - return nil, err - } - logger.Info("Created namespace", "namespace", nsObj.Name) - ns = nsObj.Name - } - logger = logger.WithValues("namespace", ns) - ctx = klog.NewContext(ctx, logger) - - // first look for ClusterBinding to get old secret name - kubeconfigSecretName := kuberesources.KubeconfigSecretName - var cb kubebindv1alpha2.ClusterBinding - err = c.Get(ctx, types.NamespacedName{Namespace: ns, Name: kuberesources.ClusterBindingName}, &cb) - switch { - case errors.IsNotFound(err): - if err := kuberesources.CreateClusterBinding(ctx, c, ns, "kubeconfig", m.providerPrettyName, identity, author, clusterPrettyName); err != nil { - return nil, err - } - case err != nil: - return nil, err - default: - logger.V(3).Info("Found existing ClusterBinding") - kubeconfigSecretName = cb.Spec.KubeconfigSecretRef.Name // reuse old name - } - - sa, err := kuberesources.CreateServiceAccount(ctx, c, ns, kuberesources.ServiceAccountName) - if err != nil { - return nil, err - } - - if err := kuberesources.EnsureBinderClusterRole(ctx, c); err != nil { - return nil, err - } - - saSecret, err := kuberesources.CreateSASecret(ctx, c, ns, sa.Name) - if err != nil { - return nil, err - } - - if err = kuberesources.EnsureBinderRoleBinding(ctx, c, ns, sa.Name); err != nil { - return nil, err - } - - kfgSecret, err := kuberesources.GenerateKubeconfig(ctx, c, cl.GetConfig(), m.externalAddressGenerator, m.externalCA, m.externalTLSServerName, saSecret.Name, ns, kubeconfigSecretName) - if err != nil { - return nil, err - } - - return &HandleResourcesResult{ - Kubeconfig: kfgSecret.Data["kubeconfig"], - Namespace: ns, - }, nil -} - -// CreateAPIServiceExportRequest creates an APIServiceExportRequest in the given namespace -// on the provider cluster and waits for it to be reconciled (Succeeded or Failed). -func (m *Manager) CreateAPIServiceExportRequest( - ctx context.Context, - cluster, namespace, name string, - spec kubebindv1alpha2.APIServiceExportRequestSpec, -) (*kubebindv1alpha2.APIServiceExportRequest, error) { - logger := klog.FromContext(ctx).WithValues("namespace", namespace, "name", name) - - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, fmt.Errorf("failed to get cluster client: %w", err) - } - c := cl.GetClient() - - exportRequest := &kubebindv1alpha2.APIServiceExportRequest{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: spec, - } - - // Create the APIServiceExportRequest, handling name conflicts - if err := c.Create(ctx, exportRequest); err != nil { - if !errors.IsAlreadyExists(err) { - return nil, fmt.Errorf("failed to create APIServiceExportRequest: %w", err) - } - // Name conflict: use generateName - exportRequest.Name = "" - exportRequest.GenerateName = name + "-" - if err := c.Create(ctx, exportRequest); err != nil { - return nil, fmt.Errorf("failed to create APIServiceExportRequest with generated name: %w", err) - } - } - - createdName := exportRequest.Name - logger = logger.WithValues("createdName", createdName) - logger.Info("Created APIServiceExportRequest, waiting for reconciliation") - - // Poll until reconciled. The client reads from cache, so the object may not - // be visible immediately after creation. Tolerate NotFound for an initial - // grace period before treating it as a real deletion. - var result *kubebindv1alpha2.APIServiceExportRequest - seenOnce := false - if err := wait.PollUntilContextTimeout(ctx, 1*time.Second, 60*time.Second, false, func(ctx context.Context) (bool, error) { - req := &kubebindv1alpha2.APIServiceExportRequest{} - if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: createdName}, req); err != nil { - if errors.IsNotFound(err) { - if seenOnce { - return false, fmt.Errorf("APIServiceExportRequest %s was deleted", createdName) - } - // Cache hasn't synced yet — keep polling. - return false, nil - } - return false, err - } - seenOnce = true - if req.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhaseSucceeded { - result = req - return true, nil - } - if req.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhaseFailed { - return false, fmt.Errorf("APIServiceExportRequest failed: %s", req.Status.TerminalMessage) - } - return false, nil - }); err != nil { - return nil, fmt.Errorf("waiting for APIServiceExportRequest: %w", err) - } - - logger.Info("APIServiceExportRequest reconciled successfully") - return result, nil -} - -func (m *Manager) ListCustomResourceDefinitions(ctx context.Context, cluster string, selector labels.Selector) (*apiextensionsv1.CustomResourceDefinitionList, error) { - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - var crds apiextensionsv1.CustomResourceDefinitionList - err = c.List(ctx, &crds, client.MatchingLabelsSelector{Selector: selector}) - if err != nil { - return nil, err - } - - return &crds, nil -} - -func (m *Manager) ListCollections(ctx context.Context, cluster string) (*kubebindv1alpha2.CollectionList, error) { - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - var collections kubebindv1alpha2.CollectionList - err = c.List(ctx, &collections) - if err != nil { - return nil, err - } - - return &collections, nil -} - -func (m *Manager) ListTemplates(ctx context.Context, cluster string) (*kubebindv1alpha2.APIServiceExportTemplateList, error) { - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - var templates kubebindv1alpha2.APIServiceExportTemplateList - err = c.List(ctx, &templates) - if err != nil { - return nil, err - } - - return &templates, nil -} - -func (m *Manager) GetTemplates(ctx context.Context, cluster, name string) (*kubebindv1alpha2.APIServiceExportTemplate, error) { - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - var template kubebindv1alpha2.APIServiceExportTemplate - err = c.Get(ctx, types.NamespacedName{Name: name}, &template) - if err != nil { - return nil, err - } - - return &template, nil -} - -func (m *Manager) ListDynamicResources(ctx context.Context, cluster string, gvk schema.GroupVersionKind, selector labels.Selector) (*unstructured.UnstructuredList, error) { - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - // Ensure we have the List kind - listGVK := gvk - if !strings.HasSuffix(listGVK.Kind, "List") { - listGVK.Kind += "List" - } - - list := &unstructured.UnstructuredList{} - list.SetGroupVersionKind(listGVK) - - listOpts := []client.ListOption{} - if selector != nil { - listOpts = append(listOpts, client.MatchingLabelsSelector{Selector: selector}) - } - - if err := c.List(ctx, list, listOpts...); err != nil { - return nil, err - } - - return list, nil -} - -func (m *Manager) AuthorizeRequest(ctx context.Context, subject string, groups []string, cluster, method, path string) error { - logger := klog.FromContext(ctx).WithValues("subject", subject, "cluster", cluster, "method", method, "path", path, "groups", groups) - - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return err - } - cfg := cl.GetConfig() - - // Create the authorization clientset - authClient, err := authorizationv1.NewForConfig(cfg) - if err != nil { - return err - } - - if m.embeddedOIDC { - groups = append(groups, "system:authenticated") - } - - // Check if user can bind (basic permission test) - sar := &authzv1.SubjectAccessReview{ - Spec: authzv1.SubjectAccessReviewSpec{ - User: subject, - Groups: groups, - ResourceAttributes: &authzv1.ResourceAttributes{ - Verb: "bind", - Group: "kube-bind.io", - }, - }, - } - // Perform the SubjectAccessReview using the specific clientset - sarResponse, err := authClient.SubjectAccessReviews().Create(ctx, sar, metav1.CreateOptions{}) - if err != nil { - logger.Error(err, "Failed to create SubjectAccessReview") - return err - } - - if !sarResponse.Status.Allowed { - logger.Info("User is not allowed to bind", "user", subject, "reason", sarResponse.Status) - // Return a structured authorization error - return errors.NewForbidden( - schema.GroupResource{Group: "kube-bind.io", Resource: "bind"}, - "", - fmt.Errorf("user %q is not authorized to bind resources: %s", subject, sarResponse.Status.Reason), - ) - } - logger.Info("User is allowed to bind", "user", subject) - return nil -} - -// ConsumerStatus describes the status of a consumer cluster relative to the provider. -type ConsumerStatus struct { - // Connected is true if the consumer has an existing provider namespace. - Connected bool `json:"connected"` - // Namespace is the provider namespace for this consumer. - Namespace string `json:"namespace,omitempty"` - // Exports is the list of APIServiceExport names in the consumer's namespace. - Exports []string `json:"exports,omitempty"` -} - -// GetConsumerStatus checks if the given identity already has a provider namespace -// with existing APIServiceExports. -func (m *Manager) GetConsumerStatus(ctx context.Context, identity, cluster string) (*ConsumerStatus, error) { - logger := klog.FromContext(ctx).WithValues("identity", identity) - - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName(cluster)) - if err != nil { - return nil, err - } - c := cl.GetClient() - - // Look up namespace by identity annotation - var nss corev1.NamespaceList - err = c.List(ctx, &nss, client.MatchingFields{NamespacesByIdentity: identity}) - if err != nil { - return nil, err - } - - if len(nss.Items) == 0 { - return &ConsumerStatus{Connected: false}, nil - } - - ns := nss.Items[0].Name - logger.Info("Found existing consumer namespace", "namespace", ns) - - // List APIServiceExports in the consumer namespace - var exports kubebindv1alpha2.APIServiceExportList - if err := c.List(ctx, &exports, client.InNamespace(ns)); err != nil { - return nil, fmt.Errorf("failed to list APIServiceExports: %w", err) - } - - exportNames := make([]string, 0, len(exports.Items)) - for _, e := range exports.Items { - exportNames = append(exportNames, e.Name) - } - - return &ConsumerStatus{ - Connected: len(exportNames) > 0, - Namespace: ns, - Exports: exportNames, - }, nil -} - -// ApplyToConsumerResult contains the result of ApplyToConsumer operation. -type ApplyToConsumerResult struct { - KonnectorDeployed bool `json:"konnectorDeployed"` - BundleCreated bool `json:"bundleCreated"` - Message string `json:"message"` -} - -// ApplyToConsumer applies konnector manifests and binding bundle to a consumer cluster -// using the provided consumer kubeconfig. -func (m *Manager) ApplyToConsumer( - ctx context.Context, - consumerKubeconfigData []byte, - providerKubeconfigData []byte, - bindingName string, - konnectorImage string, - overrideHostAliases []corev1.HostAlias, -) (*ApplyToConsumerResult, error) { - logger := klog.FromContext(ctx).WithValues("bindingName", bindingName) - - // Build a client from the consumer kubeconfig - consumerConfig, err := clientcmd.RESTConfigFromKubeConfig(consumerKubeconfigData) - if err != nil { - return nil, fmt.Errorf("invalid consumer kubeconfig: %w", err) - } - - s := scheme.Scheme - if err := kubebindv1alpha2.AddToScheme(s); err != nil { - return nil, fmt.Errorf("failed to add kube-bind scheme: %w", err) - } - if err := apiextensionsv1.AddToScheme(s); err != nil { - return nil, fmt.Errorf("failed to add apiextensions scheme: %w", err) - } - - consumerClient, err := client.New(consumerConfig, client.Options{Scheme: s}) - if err != nil { - return nil, fmt.Errorf("failed to create consumer client: %w", err) - } - - // 1. Ensure kube-bind namespace - ns := &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{Name: "kube-bind"}, - } - if err := consumerClient.Create(ctx, ns); err != nil && !errors.IsAlreadyExists(err) { - return nil, fmt.Errorf("failed to create kube-bind namespace: %w", err) - } - - // 2. Build host aliases: start with request overrides (if any), fall back to - // configured defaults, then merge any auto-resolved aliases from the provider kubeconfig. - var hostAliases []corev1.HostAlias - if len(overrideHostAliases) > 0 { - hostAliases = append(hostAliases, overrideHostAliases...) - } else { - hostAliases = append(hostAliases, m.konnectorHostAliases...) - } - if resolved := m.resolveProviderHostAliases(ctx, providerKubeconfigData); len(resolved) > 0 { - hostAliases = mergeHostAliases(hostAliases, resolved) - } - - // 3. Deploy konnector (idempotent) - konnectorDeployed, err := m.ensureKonnector(ctx, consumerClient, konnectorImage, hostAliases) - if err != nil { - return nil, fmt.Errorf("failed to deploy konnector: %w", err) - } - - // 3b. If konnector was newly deployed, wait for it to bootstrap CRDs - if konnectorDeployed { - logger.Info("Waiting for konnector to bootstrap CRDs on consumer cluster") - if err := m.waitForCRD(ctx, consumerClient, "apiservicebindingbundles.kube-bind.io"); err != nil { - return nil, fmt.Errorf("timed out waiting for konnector CRDs: %w", err) - } - } - - // 4. Create kubeconfig secret for the provider - secretName := fmt.Sprintf("kubeconfig-%s", bindingName) - kubeconfigSecret := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: secretName, - Namespace: "kube-bind", - }, - Type: corev1.SecretTypeOpaque, - Data: map[string][]byte{ - "kubeconfig": providerKubeconfigData, - }, - } - if err := consumerClient.Create(ctx, kubeconfigSecret); err != nil { - if errors.IsAlreadyExists(err) { - // Update existing secret - existing := &corev1.Secret{} - if err := consumerClient.Get(ctx, types.NamespacedName{Name: secretName, Namespace: "kube-bind"}, existing); err != nil { - return nil, fmt.Errorf("failed to get existing kubeconfig secret: %w", err) - } - existing.Data = kubeconfigSecret.Data - if err := consumerClient.Update(ctx, existing); err != nil { - return nil, fmt.Errorf("failed to update kubeconfig secret: %w", err) - } - } else { - return nil, fmt.Errorf("failed to create kubeconfig secret: %w", err) - } - } - - // 5. Create APIServiceBindingBundle - bundle := &kubebindv1alpha2.APIServiceBindingBundle{ - ObjectMeta: metav1.ObjectMeta{ - Name: bindingName, - }, - Spec: kubebindv1alpha2.APIServiceBindingBundleSpec{ - KubeconfigSecretRef: kubebindv1alpha2.ClusterSecretKeyRef{ - LocalSecretKeyRef: kubebindv1alpha2.LocalSecretKeyRef{ - Name: secretName, - Key: "kubeconfig", - }, - Namespace: "kube-bind", - }, - }, - } - if err := consumerClient.Create(ctx, bundle); err != nil { - if errors.IsAlreadyExists(err) { - logger.Info("APIServiceBindingBundle already exists, updating") - existing := &kubebindv1alpha2.APIServiceBindingBundle{} - if err := consumerClient.Get(ctx, types.NamespacedName{Name: bindingName}, existing); err != nil { - return nil, fmt.Errorf("failed to get existing bundle: %w", err) - } - existing.Spec = bundle.Spec - if err := consumerClient.Update(ctx, existing); err != nil { - return nil, fmt.Errorf("failed to update bundle: %w", err) - } - } else { - return nil, fmt.Errorf("failed to create APIServiceBindingBundle: %w", err) - } - } - - logger.Info("Successfully applied binding to consumer cluster") - return &ApplyToConsumerResult{ - KonnectorDeployed: konnectorDeployed, - BundleCreated: true, - Message: "Konnector and binding bundle applied successfully", - }, nil -} - -// resolveProviderHostAliases extracts the provider API server hostname from the -// kubeconfig and resolves it to IP addresses. This allows the konnector pods on -// the consumer cluster to reach the provider even when the hostname only resolves -// correctly from the backend pod's network (e.g., Kind/Docker environments). -func (m *Manager) resolveProviderHostAliases(ctx context.Context, providerKubeconfigData []byte) []corev1.HostAlias { - config, err := clientcmd.RESTConfigFromKubeConfig(providerKubeconfigData) - if err != nil { - return nil - } - - u, err := url.Parse(config.Host) - if err != nil { - return nil - } - - hostname := u.Hostname() - if hostname == "" { - return nil - } - - if net.ParseIP(hostname) != nil { - return nil - } - - ips, err := net.DefaultResolver.LookupHost(ctx, hostname) - if err != nil || len(ips) == 0 { - return nil - } - - var validIPs []string - for _, ip := range ips { - parsed := net.ParseIP(ip) - if parsed != nil && !parsed.IsLoopback() { - validIPs = append(validIPs, ip) - } - } - - if len(validIPs) == 0 { - return nil - } - - return []corev1.HostAlias{ - { - IP: validIPs[0], - Hostnames: []string{hostname}, - }, - } -} - -// ensureKonnector deploys the konnector agent to the consumer cluster. -// Returns true if the konnector was newly deployed, false if it already existed. -func (m *Manager) ensureKonnector(ctx context.Context, c client.Client, konnectorImage string, hostAliases []corev1.HostAlias) (bool, error) { - manifests := kuberesources.NewKonnectorManifests(konnectorImage, hostAliases) - - // Check if konnector deployment already exists - existing := &appsv1.Deployment{} - err := c.Get(ctx, types.NamespacedName{Name: kuberesources.KonnectorDeploymentName, Namespace: kuberesources.KonnectorNamespace}, existing) - if err == nil { - // Update the deployment if host aliases changed - existing.Spec.Template.Spec.HostAliases = hostAliases - existing.Spec.Template.Spec.Containers[0].Image = konnectorImage - if err := c.Update(ctx, existing); err != nil { - return false, fmt.Errorf("failed to update konnector deployment: %w", err) - } - return false, nil - } - if !errors.IsNotFound(err) { - return false, fmt.Errorf("failed to check for existing konnector: %w", err) - } - - if err := c.Create(ctx, manifests.ServiceAccount); err != nil && !errors.IsAlreadyExists(err) { - return false, fmt.Errorf("failed to create konnector service account: %w", err) - } - if err := c.Create(ctx, manifests.ClusterRole); err != nil && !errors.IsAlreadyExists(err) { - return false, fmt.Errorf("failed to create konnector cluster role: %w", err) - } - if err := c.Create(ctx, manifests.ClusterRoleBinding); err != nil && !errors.IsAlreadyExists(err) { - return false, fmt.Errorf("failed to create konnector cluster role binding: %w", err) - } - if err := c.Create(ctx, manifests.Deployment); err != nil { - return false, fmt.Errorf("failed to create konnector deployment: %w", err) - } - - return true, nil -} - -func (m *Manager) waitForCRD(ctx context.Context, c client.Client, crdName string) error { - return wait.PollUntilContextTimeout(ctx, 2*time.Second, 120*time.Second, true, func(ctx context.Context) (bool, error) { - crd := &apiextensionsv1.CustomResourceDefinition{} - err := c.Get(ctx, types.NamespacedName{Name: crdName}, crd) - if err != nil { - if errors.IsNotFound(err) { - return false, nil // keep polling - } - return false, nil // transient error, keep polling - } - // Check if the CRD is established - for _, cond := range crd.Status.Conditions { - if cond.Type == apiextensionsv1.Established && cond.Status == apiextensionsv1.ConditionTrue { - return true, nil - } - } - return false, nil - }) -} - -func (m *Manager) SeedDefaultCluster(ctx context.Context) error { - logger := klog.FromContext(ctx) - - cl, err := m.manager.GetCluster(ctx, multicluster.ClusterName("")) - if err != nil { - return err - } - c := cl.GetClient() - - _, err = kuberesources.CreateDefaultCluster(ctx, c) - if err != nil && !errors.IsAlreadyExists(err) { - logger.Error(err, "Failed to create default Cluster resource") - return err - } - logger.Info("Default Cluster resource ensured") - return nil -} - -// GetKonnectorHostAliases returns the configured default host aliases for konnector pods. -func (m *Manager) GetKonnectorHostAliases() []corev1.HostAlias { - return m.konnectorHostAliases -} - -// mergeHostAliases merges additional host aliases into existing ones, -// skipping entries whose IP is already present. -func mergeHostAliases(existing, additional []corev1.HostAlias) []corev1.HostAlias { - seen := make(map[string]bool, len(existing)) - for _, ha := range existing { - seen[ha.IP] = true - } - for _, ha := range additional { - if !seen[ha.IP] { - existing = append(existing, ha) - seen[ha.IP] = true - } - } - return existing -} diff --git a/backend/kubernetes/resources/cluster.go b/backend/kubernetes/resources/cluster.go deleted file mode 100644 index c449739ec..000000000 --- a/backend/kubernetes/resources/cluster.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 resources - -import ( - "context" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func CreateDefaultCluster(ctx context.Context, c client.Client) (*kubebindv1alpha2.Cluster, error) { - cluster := &kubebindv1alpha2.Cluster{ - ObjectMeta: metav1.ObjectMeta{ - Name: kubebindv1alpha2.DefaultClusterName, - }, - Spec: kubebindv1alpha2.ClusterSpec{}, - } - - err := c.Create(ctx, cluster) - if err != nil && !apierrors.IsAlreadyExists(err) { - return nil, err - } - - return cluster, nil -} diff --git a/backend/kubernetes/resources/cluster_binding.go b/backend/kubernetes/resources/cluster_binding.go deleted file mode 100644 index 99ea0569a..000000000 --- a/backend/kubernetes/resources/cluster_binding.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func CreateClusterBinding(ctx context.Context, client client.Client, ns, secretName, providerPrettyName, identity, author, clusterPrettyName string) error { - logger := klog.FromContext(ctx) - - annotations := map[string]string{} - if identity != "" { - annotations[IdentityAnnotationKey] = identity - } - if author != "" { - annotations[AuthorAnnotationKey] = author - } - if clusterPrettyName != "" { - annotations[PrettyNameAnnotationKey] = clusterPrettyName - } - - clusterBinding := &kubebindv1alpha2.ClusterBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: ClusterBindingName, - Namespace: ns, - Annotations: annotations, - }, - Spec: kubebindv1alpha2.ClusterBindingSpec{ - ProviderPrettyName: providerPrettyName, - KubeconfigSecretRef: kubebindv1alpha2.LocalSecretKeyRef{ - Name: secretName, - Key: "kubeconfig", - }, - }, - } - - logger.V(3).Info("Creating ClusterBinding") - err := client.Create(ctx, clusterBinding) - return err -} diff --git a/backend/kubernetes/resources/konnector.go b/backend/kubernetes/resources/konnector.go deleted file mode 100644 index dfa5879c9..000000000 --- a/backend/kubernetes/resources/konnector.go +++ /dev/null @@ -1,170 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 resources - -import ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/intstr" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -const ( - KonnectorNamespace = "kube-bind" - KonnectorServiceAccountName = "konnector" - KonnectorClusterRoleName = "kube-bind-konnector" - KonnectorDeploymentName = "konnector" - KonnectorReplicas = 2 - KonnectorHealthzPort = 8090 -) - -// KonnectorManifests holds typed Kubernetes objects for deploying the konnector agent. -type KonnectorManifests struct { - Namespace *corev1.Namespace - ServiceAccount *corev1.ServiceAccount - ClusterRole *rbacv1.ClusterRole - ClusterRoleBinding *rbacv1.ClusterRoleBinding - Deployment *appsv1.Deployment -} - -// NewKonnectorManifests returns the full set of Kubernetes objects needed to deploy -// the konnector agent to a consumer cluster. -func NewKonnectorManifests(konnectorImage string, hostAliases []corev1.HostAlias) *KonnectorManifests { - replicas := int32(KonnectorReplicas) - httpPort := intstr.FromInt(KonnectorHealthzPort) - - return &KonnectorManifests{ - Namespace: &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{Name: KonnectorNamespace}, - }, - ServiceAccount: &corev1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorServiceAccountName, - Namespace: KonnectorNamespace, - }, - }, - // Broad access is required because the konnector dynamically manages CRDs - // and syncs arbitrary resource types discovered from the provider. Scoping - // down would require knowing the bound resource types in advance, which - // defeats the auto-discovery model. - ClusterRole: &rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorClusterRoleName, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"*"}, - Resources: []string{"*"}, - Verbs: []string{"*"}, - }, - }, - }, - ClusterRoleBinding: &rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorClusterRoleName, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: "rbac.authorization.k8s.io", - Kind: "ClusterRole", - Name: KonnectorClusterRoleName, - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Name: KonnectorServiceAccountName, - Namespace: KonnectorNamespace, - }, - }, - }, - Deployment: &appsv1.Deployment{ - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorDeploymentName, - Namespace: KonnectorNamespace, - Labels: map[string]string{"app": "konnector"}, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &replicas, - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{"app": "konnector"}, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"app": "konnector"}, - }, - Spec: corev1.PodSpec{ - RestartPolicy: corev1.RestartPolicyAlways, - ServiceAccountName: KonnectorServiceAccountName, - HostAliases: hostAliases, - Containers: []corev1.Container{ - { - Name: "konnector", - Image: konnectorImage, - Env: []corev1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "POD_NAMESPACE", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, - }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/healthz", - Port: httpPort, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -// Objects returns all konnector manifests as a slice of runtime.Object for serialization. -func (m *KonnectorManifests) Objects() []runtime.Object { - return []runtime.Object{ - m.Namespace, - m.ServiceAccount, - m.ClusterRole, - m.ClusterRoleBinding, - m.Deployment, - } -} - -// AddKonnectorSchemes registers the schemes needed to serialize konnector manifests. -func AddKonnectorSchemes(s *runtime.Scheme) { - utilruntime.Must(corev1.AddToScheme(s)) - utilruntime.Must(appsv1.AddToScheme(s)) - utilruntime.Must(rbacv1.AddToScheme(s)) -} diff --git a/backend/kubernetes/resources/kubeconfig.go b/backend/kubernetes/resources/kubeconfig.go deleted file mode 100644 index 3ba6a7ded..000000000 --- a/backend/kubernetes/resources/kubeconfig.go +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - "fmt" - "os" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/client-go/util/retry" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func GenerateKubeconfig(ctx context.Context, - client client.Client, - clusterConfig *rest.Config, - externalAddressGenerator ExternalAddressGeneratorFunc, - externalCA []byte, - externalTLSServerName string, - saSecretName, ns, kubeconfigSecretName string, -) (*corev1.Secret, error) { - logger := klog.FromContext(ctx) - - externalAddress, err := externalAddressGenerator(ctx, clusterConfig) - if err != nil { - return nil, fmt.Errorf("failed to generate external address: %w", err) - } - - if externalCA == nil { - if len(clusterConfig.CAData) != 0 { - externalCA = clusterConfig.CAData - } else if len(clusterConfig.CAFile) != 0 { - ca, err := os.ReadFile(clusterConfig.CAFile) - if err != nil { - return nil, fmt.Errorf("failed to read CA file at %s: %w", clusterConfig.CAFile, err) - } - externalCA = ca - } - } - - var saSecret corev1.Secret - logger.V(2).Info("Waiting for service account secret to be updated with a token", "name", saSecretName) - if err := wait.PollUntilContextTimeout(ctx, 500*time.Millisecond, 10*time.Second, true, func(ctx context.Context) (done bool, err error) { - err = client.Get(ctx, types.NamespacedName{Namespace: ns, Name: saSecretName}, &saSecret) - if err != nil && !errors.IsNotFound(err) { - return false, err - } else if errors.IsNotFound(err) { - return false, nil - } - return saSecret.Data["token"] != nil && saSecret.Data["ca.crt"] != nil, nil - }); err != nil { - return nil, err - } - - cfg := clientcmdapi.Config{ - Clusters: map[string]*clientcmdapi.Cluster{ - "default": { - Server: externalAddress, - TLSServerName: externalTLSServerName, - CertificateAuthorityData: externalCA, - }, - }, - Contexts: map[string]*clientcmdapi.Context{ - "default": { - Cluster: "default", - Namespace: ns, - AuthInfo: "default", - }, - }, - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "default": { - Token: string(saSecret.Data["token"]), - }, - }, - CurrentContext: "default", - } - - kubeconfig, err := clientcmd.Write(cfg) - if err != nil { - return nil, fmt.Errorf("failed to encode kubeconfig: %w", err) - } - - kubeconfigSecret := &corev1.Secret{ - ObjectMeta: v1.ObjectMeta{ - Name: kubeconfigSecretName, - Namespace: ns, - }, - Data: map[string][]byte{ - "kubeconfig": kubeconfig, - }, - } - - logger.V(1).Info("Creating kubeconfig secret", "name", kubeconfigSecretName) - if err := client.Create(ctx, kubeconfigSecret); err != nil && !errors.IsAlreadyExists(err) { - return nil, err - } else if err == nil { - return kubeconfigSecret, nil - } - - var existing corev1.Secret - if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - err := client.Get(ctx, types.NamespacedName{Namespace: ns, Name: kubeconfigSecret.Name}, &existing) - if err != nil { - return err - } - existing.Data = kubeconfigSecret.Data - logger.V(1).Info("Updating kubeconfig secret", "name", kubeconfigSecretName) - err = client.Update(ctx, &existing) - return err - }); err != nil { - return nil, err - } - return &existing, nil -} - -// ExternalAddressGeneratorFunc is a function that generates the external address for a cluster based on the clusterConfig -// and is dependent on the provider. -type ExternalAddressGeneratorFunc func(ctx context.Context, clusterConfig *rest.Config) (string, error) - -// FixedExternalAddressGenerator returns an address generator uses the given address when available, -// otherwise falls back to the host of the provided rest config. -func NewFixedExternalAddressGenerator(address string) ExternalAddressGeneratorFunc { - return func(_ context.Context, clusterConfig *rest.Config) (string, error) { - if address == "" { - return clusterConfig.Host, nil - } - - return address, nil - } -} diff --git a/backend/kubernetes/resources/namespace.go b/backend/kubernetes/resources/namespace.go deleted file mode 100644 index 59b800088..000000000 --- a/backend/kubernetes/resources/namespace.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - "crypto/sha256" - "fmt" - "strings" - - "github.com/martinlindhe/base36" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -const ( - IdentityAnnotationKey = "backend.kube-bind.io/identity" - AuthorAnnotationKey = "backend.kube-bind.io/author" - PrettyNameAnnotationKey = "backend.kube-bind.io/cluster-pretty-name" - legacyIdentityAnnotationKey = "example-backend.kube-bind.io/identity" -) - -func handleLegacyAnnotations(ctx context.Context, cl client.Client, namespace *corev1.Namespace, id string) error { - if namespace.Annotations == nil { - return nil - } - - legacyValue, hasLegacy := namespace.Annotations[legacyIdentityAnnotationKey] - currentValue, hasCurrent := namespace.Annotations[IdentityAnnotationKey] - - if hasLegacy && (!hasCurrent || currentValue != id) && legacyValue == id { - original := namespace.DeepCopy() - if namespace.Annotations == nil { - namespace.Annotations = map[string]string{} - } - namespace.Annotations[IdentityAnnotationKey] = id - delete(namespace.Annotations, legacyIdentityAnnotationKey) - return cl.Patch(ctx, namespace, client.MergeFrom(original)) - } - - return nil -} - -func CreateNamespace(ctx context.Context, client client.Client, generateNamePrefix, identity, author string) (*corev1.Namespace, error) { - name := identityHash(identity) - namespace := &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%s%s", generateNamePrefix, name), - Annotations: map[string]string{ - IdentityAnnotationKey: identity, - AuthorAnnotationKey: author, - }, - }, - } - - err := client.Create(ctx, namespace) - if err != nil && !errors.IsAlreadyExists(err) { - return nil, err - } else if errors.IsAlreadyExists(err) { - err := client.Get(ctx, types.NamespacedName{Name: namespace.Name}, namespace) - if err != nil { - return nil, err - } - - if namespace.Annotations[IdentityAnnotationKey] != identity && namespace.Annotations[legacyIdentityAnnotationKey] != identity { - return nil, errors.NewAlreadyExists(corev1.Resource("namespace"), namespace.Name) - } - - if err := handleLegacyAnnotations(ctx, client, namespace, identity); err != nil { - return nil, err - } - } - - return namespace, nil -} - -func identityHash(userName string) string { - hash := sha256.Sum224([]byte(userName)) - return strings.ToLower(base36.EncodeBytes(hash[:8])) -} diff --git a/backend/kubernetes/resources/namespace_test.go b/backend/kubernetes/resources/namespace_test.go deleted file mode 100644 index 0db219ab6..000000000 --- a/backend/kubernetes/resources/namespace_test.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - "crypto/sha256" - "fmt" - "strings" - "testing" - - "github.com/martinlindhe/base36" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" -) - -func expectedIdentityHash(identity string) string { - hash := sha256.Sum224([]byte(identity)) - return strings.ToLower(base36.EncodeBytes(hash[:8])) -} - -func TestCreateNamespace(t *testing.T) { - scheme := runtime.NewScheme() - _ = corev1.AddToScheme(scheme) - - tests := []struct { - name string - generateName string - identity string - author string - wantErr bool - wantAnnotations map[string]string - }{ - { - name: "create new namespace with generateName", - generateName: "test-ns", - identity: "test-id-123", - author: "bob", - wantErr: false, - wantAnnotations: map[string]string{ - IdentityAnnotationKey: "test-id-123", - AuthorAnnotationKey: "bob", - }, - }, - { - name: "create new namespace with generateName already ending with dash", - generateName: "test-ns", - identity: "test-id-456", - author: "alice", - wantErr: false, - wantAnnotations: map[string]string{ - IdentityAnnotationKey: "test-id-456", - AuthorAnnotationKey: "alice", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() - cl := fake.NewClientBuilder().WithScheme(scheme).Build() - - result, err := CreateNamespace(ctx, cl, tt.generateName, tt.identity, tt.author) - - if tt.wantErr { - if err == nil { - t.Errorf("CreateNamespace() expected error but got none") - return - } - return - } - - if err != nil { - t.Errorf("CreateNamespace() unexpected error = %v", err) - return - } - - if result == nil { - t.Errorf("CreateNamespace() returned nil namespace") - return - } - - expectedPrefix := tt.generateName - expectedHash := expectedIdentityHash(tt.identity) - expectedName := fmt.Sprintf("%s%s", expectedPrefix, expectedHash) - - if result.Name != expectedName { - t.Errorf("CreateNamespace() name = %v, expected %v", result.Name, expectedName) - } - - if result.GenerateName != "" { - t.Errorf("CreateNamespace() generateName = %v, expected empty string", result.GenerateName) - } - - for key, expectedValue := range tt.wantAnnotations { - if actualValue, exists := result.Annotations[key]; !exists || actualValue != expectedValue { - t.Errorf("CreateNamespace() annotation %s = %v, expected %v (exists: %v)", key, actualValue, expectedValue, exists) - } - } - - var actualNamespace corev1.Namespace - if err := cl.Get(ctx, client.ObjectKey{Name: result.Name}, &actualNamespace); err != nil { - t.Fatalf("Failed to get created/updated namespace from client: %v", err) - } - - for key, expectedValue := range tt.wantAnnotations { - if actualValue, exists := actualNamespace.Annotations[key]; !exists || actualValue != expectedValue { - t.Errorf("CreateNamespace() stored annotation %s = %v, expected %v (exists: %v)", key, actualValue, expectedValue, exists) - } - } - }) - } -} diff --git a/backend/kubernetes/resources/rbac.go b/backend/kubernetes/resources/rbac.go deleted file mode 100644 index 9778e7172..000000000 --- a/backend/kubernetes/resources/rbac.go +++ /dev/null @@ -1,220 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - "reflect" - "slices" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func CreateServiceAccount(ctx context.Context, client client.Client, ns, name string) (*corev1.ServiceAccount, error) { - logger := klog.FromContext(ctx) - - var sa corev1.ServiceAccount - err := client.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, &sa) - if err != nil { - if errors.IsNotFound(err) { - sa = corev1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: ns, - }, - } - - logger.Info("Creating service account", "name", sa.Name) - err = client.Create(ctx, &sa) - return &sa, err - } - } - - return &sa, err -} - -// EnsureBinderClusterRole ensures that the binder cluster role is present in the cluster. This runs multiple times on bind. -func EnsureBinderClusterRole(ctx context.Context, client client.Client) error { - logger := klog.FromContext(ctx) - - // Define the ClusterRole rules based on the YAML specification - clusterRole := &rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder", - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"apiserviceexportrequests"}, - Verbs: []string{"create", "delete", "patch", "update", "get", "list", "watch"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"namespaces"}, - Verbs: []string{"get"}, - }, - { - APIGroups: []string{""}, - Resources: []string{"secrets"}, - Verbs: []string{"get", "watch", "list"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"clusterbindings"}, - Verbs: []string{"get", "watch", "list"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"clusterbindings/status"}, - Verbs: []string{"get", "patch", "update"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"apiserviceexports"}, - Verbs: []string{"get", "watch", "list"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"apiserviceexports/status"}, - Verbs: []string{"get", "patch", "update"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"apiservicenamespaces"}, - Verbs: []string{"create", "delete", "patch", "update", "get", "list", "watch"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"boundschemas"}, - Verbs: []string{"get", "list", "watch"}, - }, - { - APIGroups: []string{"kube-bind.io"}, - Resources: []string{"boundschemas/status"}, - Verbs: []string{"get", "list", "patch", "update"}, - }, - }, - } - - // Try to get existing ClusterRole - var existing rbacv1.ClusterRole - err := client.Get(ctx, types.NamespacedName{Name: "kube-binder"}, &existing) - if err != nil { - if errors.IsNotFound(err) { - // Create new ClusterRole - logger.Info("Creating kube-binder ClusterRole") - return client.Create(ctx, clusterRole) - } - return err - } - - // Update existing ClusterRole if rules have changed - if !rulesEqual(existing.Rules, clusterRole.Rules) { - logger.Info("Updating kube-binder ClusterRole") - existing.Rules = clusterRole.Rules - return client.Update(ctx, &existing) - } - - logger.V(2).Info("kube-binder ClusterRole already exists and is up to date") - return nil -} - -// EnsureBinderRoleBinding ensures that the binder cluster role is bound in the cluster. This runs multiple times on bind. -func EnsureBinderRoleBinding(ctx context.Context, client client.Client, namespace, saName string) error { - logger := klog.FromContext(ctx) - - expectedRoleBinding := rbacv1.RoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-binder", - Namespace: namespace, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.SchemeGroupVersion.Group, - Kind: "ClusterRole", - Name: "kube-binder", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Namespace: namespace, - Name: saName, - }, - }, - } - - var roleBinding rbacv1.RoleBinding - err := client.Get(ctx, types.NamespacedName{Namespace: expectedRoleBinding.Namespace, Name: expectedRoleBinding.Name}, &roleBinding) - if err != nil { - if !errors.IsNotFound(err) { - return err - } - logger.Info("Creating kube-binder RoleBinding", "namespace", namespace) - err = client.Create(ctx, &expectedRoleBinding) - if !errors.IsAlreadyExists(err) { - return err - } - roleBinding = expectedRoleBinding - } - - if !reflect.DeepEqual(expectedRoleBinding.Subjects, roleBinding.Subjects) { - roleBinding.Subjects = expectedRoleBinding.Subjects - return client.Update(ctx, &roleBinding) - } - - logger.V(2).Info("kube-binder RoleBinding already exists and is up to date", "namespace", namespace) - return nil -} - -// rulesEqual compares two PolicyRule slices for equality. -func rulesEqual(a, b []rbacv1.PolicyRule) bool { - if len(a) != len(b) { - return false - } - - for i := range a { - if !policyRuleEqual(a[i], b[i]) { - return false - } - } - return true -} - -// policyRuleEqual compares two PolicyRule structs for equality. -func policyRuleEqual(a, b rbacv1.PolicyRule) bool { - if !slices.Equal(a.APIGroups, b.APIGroups) { - return false - } - if !slices.Equal(a.Resources, b.Resources) { - return false - } - if !slices.Equal(a.Verbs, b.Verbs) { - return false - } - if !slices.Equal(a.ResourceNames, b.ResourceNames) { - return false - } - if !slices.Equal(a.NonResourceURLs, b.NonResourceURLs) { - return false - } - return true -} diff --git a/backend/kubernetes/resources/resources.go b/backend/kubernetes/resources/resources.go deleted file mode 100644 index 8d2b6f0bf..000000000 --- a/backend/kubernetes/resources/resources.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -const ( - //nolint:gosec - ServiceAccountTokenType = "kubernetes.io/service-account-token" - //nolint:gosec - ServiceAccountTokenAnnotation = "kubernetes.io/service-account.name" - ServiceAccountName = "kube-binder" - KubeconfigSecretName = "kubeconfig" - ClusterBindingName = "cluster" - - ExportedCRDsLabel = "kube-bind.io/exported" -) diff --git a/backend/kubernetes/resources/secret.go b/backend/kubernetes/resources/secret.go deleted file mode 100644 index 0cdf25a8b..000000000 --- a/backend/kubernetes/resources/secret.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 resources - -import ( - "context" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func CreateSASecret(ctx context.Context, client client.Client, ns, saName string) (*corev1.Secret, error) { - logger := klog.FromContext(ctx) - - var secret corev1.Secret - err := client.Get(ctx, types.NamespacedName{Namespace: ns, Name: saName}, &secret) - if err != nil { - if errors.IsNotFound(err) { - secret = corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: saName, - Namespace: ns, - Annotations: map[string]string{ - ServiceAccountTokenAnnotation: saName, - }, - }, - Type: ServiceAccountTokenType, - } - - logger.V(1).Info("Creating service account secret", "name", secret.Name) - err = client.Create(ctx, &secret) - return &secret, err - } - - return nil, err - } - - return &secret, nil -} diff --git a/backend/oidc/oidc.go b/backend/oidc/oidc.go deleted file mode 100644 index 568042545..000000000 --- a/backend/oidc/oidc.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 oidc - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "net" - "os" - "slices" - "time" - - "github.com/gorilla/mux" - "github.com/xrstf/mockoidc" -) - -type Server struct { - server *mockoidc.MockOIDC - tlsConfig *tls.Config -} - -func New(caBundleFile string, listener net.Listener, addrOverride string) (*Server, error) { - // Add offline_access to supported scopes for refresh token support - ensureOfflineAccessScope() - var tlsConfig *tls.Config - s := &Server{} - if caBundleFile != "" { - tlsConfig, err := LoadTLSConfig(caBundleFile) - if err != nil { - return nil, fmt.Errorf("failed to load CA bundle file: %w", err) - } - s.tlsConfig = tlsConfig - } - - staticUserProvider := NewStaticUserProvider() - staticUserProvider.Set(&mockoidc.MockUser{ - Subject: "kube-bind-embedded-user", - Email: "embedded@kube-bind.io", - PreferredUsername: "kube-bind", - Phone: "+1234567890", - Address: "123 Kube St, Bind City, KB 12345", - Groups: []string{"engineering", "devops"}, - EmailVerified: true, - }) - - server, err := mockoidc.NewServer(&mockoidc.ServerConfig{ - TLSConfig: tlsConfig, - Listener: listener, - AddrOverride: addrOverride, - UserProvider: staticUserProvider, - }) - if err != nil { - return nil, fmt.Errorf("failed to create mock OIDC server: %w", err) - } - s.server = server - - return s, nil -} - -// Config gives the configuration for clients to connect to the embedded OIDC server. -type Config struct { - ClientID string - ClientSecret string - Issuer string - - AccessTTL time.Duration - RefreshTTL time.Duration - - CodeChallengeMethodsSupported []string - - // CallbackURL and IssuerURL are kube-bind specific and must match API server endpoints. - CallbackURL string - IssuerURL string -} - -var ErrServerNotRunning = fmt.Errorf("embedded OIDC server is not running") - -func (s *Server) TLSConfig() *tls.Config { - return s.tlsConfig -} - -func (s *Server) AddRoutes(mux *mux.Router) { - s.server.AddRoutes(mux) -} - -// Config returns the OIDC configuration for clients to connect to the embedded OIDC server. -// It is partially auto-generated by mockoidc and partially overridden to match kube-bind specific URLs. -func (s *Server) Config(callbackURL, issuerURL string) (*Config, error) { - c := &Config{ - ClientID: s.server.Config().ClientID, - ClientSecret: s.server.Config().ClientSecret, - Issuer: issuerURL, // This overrides default fake OIDC issuer URL. Must match what it is served at. - - AccessTTL: s.server.Config().AccessTTL, - RefreshTTL: s.server.Config().RefreshTTL, - - CodeChallengeMethodsSupported: s.server.Config().CodeChallengeMethodsSupported, - CallbackURL: callbackURL, - IssuerURL: issuerURL, - } - return c, nil -} - -func LoadTLSConfig(caFile string) (*tls.Config, error) { - caCertPool := x509.NewCertPool() - caCert, err := os.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("failed to read CA file: %w", err) - } - if ok := caCertPool.AppendCertsFromPEM(caCert); !ok { - return nil, fmt.Errorf("failed to append CA certs from PEM") - } - return &tls.Config{ - RootCAs: caCertPool, - MinVersion: tls.VersionTLS13, - }, nil -} - -// ensureOfflineAccessScope adds "offline_access" to mockoidc's supported scopes if not already present -func ensureOfflineAccessScope() { - offlineAccess := "offline_access" - - // Check if offline_access is already in the supported scopes - if slices.Contains(mockoidc.ScopesSupported, offlineAccess) { - return // Already present - } - - // Add offline_access to the supported scopes - mockoidc.ScopesSupported = append(mockoidc.ScopesSupported, offlineAccess) -} diff --git a/backend/oidc/oidc_test.go b/backend/oidc/oidc_test.go deleted file mode 100644 index 65a7de9f9..000000000 --- a/backend/oidc/oidc_test.go +++ /dev/null @@ -1,284 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 oidc - -import ( - "crypto/x509" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/kcp-dev/sdk/testing/third_party/library-go/crypto" - "github.com/xrstf/mockoidc" -) - -func TestLoadTLSConfig_Success(t *testing.T) { - // Create a temporary CA file with the CA cert generated by the existing crypto package - tmpDir := t.TempDir() - caCertFile := filepath.Join(tmpDir, "test-ca.crt") - caKeyFile := filepath.Join(tmpDir, "test-ca.key") - - // Use the same crypto package that the main code uses - ca, _, err := crypto.EnsureCA(caCertFile, caKeyFile, "", "test-ca", 1) - if err != nil { - t.Fatalf("Failed to create test CA: %v", err) - } - - // Verify the CA file was created - if _, err := os.Stat(caCertFile); os.IsNotExist(err) { - t.Fatalf("CA file was not created: %v", err) - } - - // Test LoadTLSConfig - config, err := LoadTLSConfig(caCertFile) - if err != nil { - t.Fatalf("LoadTLSConfig failed: %v", err) - } - - // Verify the TLS config was created - if config == nil { - t.Fatal("Expected non-nil TLS config") - return - } - - if config.RootCAs == nil { - t.Fatal("Expected RootCAs to be set") - } - - // Verify the CA was loaded by checking that we can verify the CA cert itself - opts := x509.VerifyOptions{ - Roots: config.RootCAs, - } - - _, err = ca.Config.Certs[0].Verify(opts) - if err != nil { - t.Fatalf("Failed to verify CA cert with loaded TLS config: %v", err) - } -} - -func TestLoadTLSConfig_FileNotFound(t *testing.T) { - // Test with non-existent file - config, err := LoadTLSConfig("/non/existent/path.crt") - - if err == nil { - t.Fatal("Expected error for non-existent file") - } - - if config != nil { - t.Fatal("Expected nil config when error occurs") - } - - // Verify error message - expectedMsg := "failed to read CA file" - if !strings.Contains(err.Error(), expectedMsg) { - t.Errorf("Expected error to contain '%s', got: %v", expectedMsg, err) - } -} - -func TestLoadTLSConfig_InvalidPEM(t *testing.T) { - // Create a temporary file with invalid PEM content - tmpDir := t.TempDir() - caFile := filepath.Join(tmpDir, "invalid-ca.crt") - - invalidContent := "this is not a valid PEM certificate" - err := os.WriteFile(caFile, []byte(invalidContent), 0600) - if err != nil { - t.Fatalf("Failed to write invalid CA file: %v", err) - } - - // Test LoadTLSConfig with invalid PEM - config, err := LoadTLSConfig(caFile) - - if err == nil { - t.Fatal("Expected error for invalid PEM content") - } - - if config != nil { - t.Fatal("Expected nil config when error occurs") - } - - // Verify error message - expectedMsg := "failed to append CA certs from PEM" - if !strings.Contains(err.Error(), expectedMsg) { - t.Errorf("Expected error to contain '%s', got: %v", expectedMsg, err) - } -} - -func TestLoadTLSConfig_EmptyFile(t *testing.T) { - // Create a temporary empty file - tmpDir := t.TempDir() - caFile := filepath.Join(tmpDir, "empty-ca.crt") - - err := os.WriteFile(caFile, []byte(""), 0600) - if err != nil { - t.Fatalf("Failed to write empty CA file: %v", err) - } - - // Test LoadTLSConfig with empty file - config, err := LoadTLSConfig(caFile) - - if err == nil { - t.Fatal("Expected error for empty file") - } - - if config != nil { - t.Fatal("Expected nil config when error occurs") - } - - // Verify error message - expectedMsg := "failed to append CA certs from PEM" - if !strings.Contains(err.Error(), expectedMsg) { - t.Errorf("Expected error to contain '%s', got: %v", expectedMsg, err) - } -} - -func TestLoadTLSConfig_MultipleCerts(t *testing.T) { - // Create two different CA certificates - tmpDir := t.TempDir() - - // Create first CA - ca1CertFile := filepath.Join(tmpDir, "test-ca-1.crt") - ca1KeyFile := filepath.Join(tmpDir, "test-ca-1.key") - ca1, _, err := crypto.EnsureCA(ca1CertFile, ca1KeyFile, "", "test-ca-1", 1) - if err != nil { - t.Fatalf("Failed to create first test CA: %v", err) - } - - // Create second CA - ca2CertFile := filepath.Join(tmpDir, "test-ca-2.crt") - ca2KeyFile := filepath.Join(tmpDir, "test-ca-2.key") - ca2, _, err := crypto.EnsureCA(ca2CertFile, ca2KeyFile, "", "test-ca-2", 1) - if err != nil { - t.Fatalf("Failed to create second test CA: %v", err) - } - - // Read both CA certificates and combine them - ca1Data, err := os.ReadFile(ca1CertFile) - if err != nil { - t.Fatalf("Failed to read first CA file: %v", err) - } - - ca2Data, err := os.ReadFile(ca2CertFile) - if err != nil { - t.Fatalf("Failed to read second CA file: %v", err) - } - - // Write combined CA bundle - combinedCA, err := os.CreateTemp(tmpDir, "combined-ca-*.crt") - if err != nil { - t.Fatalf("Failed to create combined CA file: %v", err) - } - combinedCAFile := combinedCA.Name() - - ca1Data = append(ca1Data, ca2Data...) - if _, err = combinedCA.Write(ca1Data); err != nil { - t.Fatalf("Failed to write combined CA file: %v", err) - } - if err = combinedCA.Close(); err != nil { - t.Fatalf("Failed to close combined CA file: %v", err) - } - - // Test LoadTLSConfig with multiple certs - config, err := LoadTLSConfig(combinedCAFile) - if err != nil { - t.Fatalf("LoadTLSConfig failed with multiple certs: %v", err) - } - - // Verify the TLS config was created - if config == nil { - t.Fatal("Expected non-nil TLS config") - return - } - - if config.RootCAs == nil { - t.Fatal("Expected RootCAs to be set") - } - - // Verify both CAs were loaded by trying to verify both certificates - opts := x509.VerifyOptions{ - Roots: config.RootCAs, - } - - // Should be able to verify first CA cert - _, err = ca1.Config.Certs[0].Verify(opts) - if err != nil { - t.Fatalf("Failed to verify first CA cert: %v", err) - } - - // Should be able to verify second CA cert - _, err = ca2.Config.Certs[0].Verify(opts) - if err != nil { - t.Fatalf("Failed to verify second CA cert: %v", err) - } -} - -func TestEnsureOfflineAccessScope(t *testing.T) { - // Save original scopes - originalScopes := make([]string, len(mockoidc.ScopesSupported)) - copy(originalScopes, mockoidc.ScopesSupported) - - // Reset to original scopes after test - defer func() { - mockoidc.ScopesSupported = originalScopes - }() - - // Remove offline_access if it exists (to test adding) - var filteredScopes []string - for _, scope := range mockoidc.ScopesSupported { - if scope != "offline_access" { - filteredScopes = append(filteredScopes, scope) - } - } - mockoidc.ScopesSupported = filteredScopes - - // Verify offline_access is not present - hasOfflineAccess := false - for _, scope := range mockoidc.ScopesSupported { - if scope == "offline_access" { - hasOfflineAccess = true - break - } - } - if hasOfflineAccess { - t.Fatal("offline_access should not be present before calling ensureOfflineAccessScope") - } - - // Call ensureOfflineAccessScope - ensureOfflineAccessScope() - - // Verify offline_access is now present - hasOfflineAccess = false - for _, scope := range mockoidc.ScopesSupported { - if scope == "offline_access" { - hasOfflineAccess = true - break - } - } - if !hasOfflineAccess { - t.Fatal("offline_access should be present after calling ensureOfflineAccessScope") - } - - // Call again to test idempotency - originalLength := len(mockoidc.ScopesSupported) - ensureOfflineAccessScope() - - // Should not add it again - if len(mockoidc.ScopesSupported) != originalLength { - t.Fatal("ensureOfflineAccessScope should be idempotent") - } -} diff --git a/backend/oidc/user.go b/backend/oidc/user.go deleted file mode 100644 index f60c47c62..000000000 --- a/backend/oidc/user.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 oidc - -import "github.com/xrstf/mockoidc" - -var _ mockoidc.UserProvider = (*staticUserProvider)(nil) - -type staticUserProvider struct { - user mockoidc.User -} - -func (s *staticUserProvider) Get() mockoidc.User { - return s.user -} - -func (s *staticUserProvider) Set(user mockoidc.User) { - s.user = user -} - -func NewStaticUserProvider() *staticUserProvider { - return &staticUserProvider{ - user: &mockoidc.MockUser{}, - } -} diff --git a/backend/options/cookie.go b/backend/options/cookie.go deleted file mode 100644 index 11c3a29f7..000000000 --- a/backend/options/cookie.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 options - -import ( - "encoding/base64" - "fmt" - - "github.com/gorilla/securecookie" - "github.com/spf13/pflag" -) - -type Cookie struct { - SigningKey string - EncryptionKey string -} - -func NewCookie() *Cookie { - return &Cookie{} -} - -func (options *Cookie) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&options.SigningKey, "cookie-signing-key", options.SigningKey, "The key which is used to sign cookies, base64 encoded. Valid lengths are 32 or 64 bytes.") - fs.StringVar(&options.EncryptionKey, "cookie-encryption-key", options.EncryptionKey, "The key which is used to encrypt cookies, base64 encoded, optional. Valid lengths are 16, 24, or 32 bytes selecting AES-128, AES-192, or AES-256.") -} - -func (options *Cookie) Complete() error { - if options.SigningKey == "" { - options.SigningKey = base64.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)) - } - if options.EncryptionKey == "" { - options.EncryptionKey = base64.StdEncoding.EncodeToString(securecookie.GenerateRandomKey(32)) - } - return nil -} - -func (options *Cookie) Validate() error { - if options.SigningKey == "" { - return fmt.Errorf("cookie signing key must not be empty") - } - - if err := checkKey(options.SigningKey, 32, 64); err != nil { - return fmt.Errorf("invalid signing key: %w", err) - } - - if options.EncryptionKey != "" { - if err := checkKey(options.SigningKey, 16, 24, 32); err != nil { - return fmt.Errorf("invalid encryption key: %w", err) - } - } - - return nil -} - -func checkKey(key string, validLengths ...int) error { - b, err := base64.StdEncoding.DecodeString(key) - if err != nil { - return err - } - for _, validLength := range validLengths { - if len(b) == validLength { - return nil - } - } - - return fmt.Errorf("invalid key length: %d", len(b)) -} diff --git a/backend/options/oidc.go b/backend/options/oidc.go deleted file mode 100644 index 5797a2932..000000000 --- a/backend/options/oidc.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 options - -import ( - "crypto/tls" - "fmt" - "net" - "net/url" - "os" - "strings" - - "github.com/spf13/pflag" - - "github.com/kube-bind/kube-bind/backend/oidc" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type OIDC struct { - Type string - IssuerClientID string - IssuerClientSecret string - IssuerURL string - CallbackURL string - AuthorizeURL string - CAFile string - - // TLSConfig is set if an embedded OIDC server is used. - TLSConfig *tls.Config - OIDCServer *oidc.Server - - // If specified, bindings will be provisioned for these permissions in each cluster kube-bind manages. - // In additon, if type is embedded, embedded groups will added automatically. - - // AllowedGroups is a list of groups allowed to access bindings inside the cluster - AllowedGroups []string - // AllowedUsers is a list of users allowed to access bindings inside the cluster - AllowedUsers []string -} - -func NewOIDC() *OIDC { - return &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeExternal), - } -} - -func (options *OIDC) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&options.IssuerClientID, "oidc-issuer-client-id", options.IssuerClientID, "Issuer client ID") - fs.StringVar(&options.IssuerClientSecret, "oidc-issuer-client-secret", options.IssuerClientSecret, "OpenID client secret") - fs.StringVar(&options.IssuerURL, "oidc-issuer-url", options.IssuerURL, "Callback URL for OpenID responses.") - fs.StringVar(&options.CallbackURL, "oidc-callback-url", options.CallbackURL, "OpenID callback URL") - fs.StringVar(&options.AuthorizeURL, "oidc-authorize-url", options.AuthorizeURL, "OpenID authorize URL") - fs.StringVar(&options.CAFile, "oidc-ca-file", options.CAFile, "Path to a CA bundle to use when verifying the OIDC provider's TLS certificate.") - fs.StringVar(&options.Type, "oidc-type", options.Type, "Type of OIDC provider (embedded or external)") - fs.StringSliceVar(&options.AllowedGroups, "oidc-allowed-groups", options.AllowedGroups, "List of groups allowed to access bindings inside the cluster. If using embedded OIDC provider, system:authenticated will be added automatically.") - fs.StringSliceVar(&options.AllowedUsers, "oidc-allowed-users", options.AllowedUsers, "List of users allowed to access bindings inside the cluster") -} - -func (options *OIDC) Complete(listener net.Listener) error { - if options.Type == string(kubebindv1alpha2.OIDCProviderTypeEmbedded) { - oidcServer, err := oidc.New(options.CAFile, listener, options.IssuerURL) - if err != nil { - return err - } - options.OIDCServer = oidcServer - - cfg, err := oidcServer.Config(options.CallbackURL, options.IssuerURL) - if err != nil { - return err - } - - options.TLSConfig = oidcServer.TLSConfig() - options.IssuerURL = cfg.Issuer - options.IssuerClientID = cfg.ClientID - options.IssuerClientSecret = cfg.ClientSecret - // This should be provided from outside, but in embedded - we detect. - options.CallbackURL = cfg.CallbackURL - - options.AllowedGroups = append(options.AllowedGroups, "system:authenticated") - } - - if os.Getenv("OIDC_CLIENT_SECRET") != "" { - options.IssuerClientSecret = os.Getenv("OIDC_CLIENT_SECRET") - } - - if options.CAFile != "" { - tlsConfig, err := oidc.LoadTLSConfig(options.CAFile) - if err != nil { - return fmt.Errorf("failed to load OIDC CA file: %w", err) - } - options.TLSConfig = tlsConfig - } - - return nil -} - -func (options *OIDC) Validate() error { - if options.IssuerClientID == "" { - return fmt.Errorf("OIDC issuer client ID cannot be empty") - } - if os.Getenv("OIDC_CLIENT_SECRET") != "" && options.Type == string(kubebindv1alpha2.OIDCProviderTypeEmbedded) { - return fmt.Errorf("OIDC issuer client secret cannot be provided via environment variable when using embedded OIDC provider") - } - if options.IssuerURL == "" { - return fmt.Errorf("OIDC issuer URL cannot be empty") - } - if options.CallbackURL == "" { - return fmt.Errorf("OIDC callback URL cannot be empty") - } - - if options.CAFile != "" && options.TLSConfig != nil { - return fmt.Errorf("cannot use both CA file and embedded OIDC server") - } - - if options.Type != string(kubebindv1alpha2.OIDCProviderTypeEmbedded) && options.Type != string(kubebindv1alpha2.OIDCProviderTypeExternal) { - return fmt.Errorf("invalid OIDC provider type: %s", options.Type) - } - - issuerURL, err := url.Parse(options.IssuerURL) - if err != nil { - return fmt.Errorf("--oidc-issuer-url must be a valid URL: %w", err) - } - if issuerURL.Scheme != "http" && issuerURL.Scheme != "https" { - return fmt.Errorf("--oidc-issuer-url must use http or https scheme, got: %s", issuerURL.Scheme) - } - - callbackURL, err := url.Parse(options.CallbackURL) - if err != nil { - return fmt.Errorf("--oidc-callback-url must be a valid URL: %w", err) - } - if callbackURL.Scheme != "http" && callbackURL.Scheme != "https" { - return fmt.Errorf("--oidc-callback-url must use http or https scheme, got: %s", callbackURL.Scheme) - } - if !strings.HasSuffix(callbackURL.Path, "/api/callback") { - return fmt.Errorf("--oidc-callback-url must end with '/api/callback', got path: %s", callbackURL.Path) - } - - if options.Type == string(kubebindv1alpha2.OIDCProviderTypeEmbedded) && !strings.HasSuffix(options.IssuerURL, "/oidc") { - return fmt.Errorf("--oidc-issuer-url must end with '/oidc' when using embedded OIDC provider") - } - - if options.Type == string(kubebindv1alpha2.OIDCProviderTypeExternal) && len(options.AllowedGroups) == 0 && len(options.AllowedUsers) == 0 { - return fmt.Errorf("when using external OIDC provider, at least one of allowed groups or allowed users must be specified") - } - - return nil -} diff --git a/backend/options/oidc_test.go b/backend/options/oidc_test.go deleted file mode 100644 index 023f4d9bb..000000000 --- a/backend/options/oidc_test.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 options - -import ( - "testing" - - "github.com/stretchr/testify/require" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func TestOIDCValidate(t *testing.T) { - tests := []struct { - name string - options *OIDC - wantErr bool - errMsg string - }{ - { - name: "embedded OIDC with valid issuer URL ending in /oidc", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080/oidc", - CallbackURL: "http://localhost:8080/api/callback", - }, - wantErr: false, - }, - { - name: "embedded OIDC with invalid issuer URL not ending in /oidc", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080", - CallbackURL: "http://localhost:8080/api/callback", - }, - wantErr: true, - errMsg: "--oidc-issuer-url must end with '/oidc' when using embedded OIDC provider", - }, - { - name: "embedded OIDC with trailing slash /oidc/", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080/oidc/", - CallbackURL: "http://localhost:8080/api/callback", - }, - wantErr: true, - errMsg: "--oidc-issuer-url must end with '/oidc' when using embedded OIDC provider", - }, - { - name: "external OIDC does not require /oidc suffix", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeExternal), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080", - CallbackURL: "http://localhost:8080/api/callback", - AllowedGroups: []string{"admins"}, - }, - wantErr: false, - }, - { - name: "malformed issuer URL", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "not-a-valid-url", - CallbackURL: "http://localhost:8080/api/callback", - }, - wantErr: true, - errMsg: "--oidc-issuer-url must use http or https scheme, got: ", - }, - { - name: "malformed callback URL", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080/oidc", - CallbackURL: "not-a-valid-url", - }, - wantErr: true, - errMsg: "--oidc-callback-url must use http or https scheme, got: ", - }, - { - name: "callback URL with invalid scheme", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080/oidc", - CallbackURL: "ftp://localhost:8080/api/callback", - }, - wantErr: true, - errMsg: "--oidc-callback-url must use http or https scheme, got: ftp", - }, - { - name: "callback URL with only /callback (missing /api prefix)", - options: &OIDC{ - Type: string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - IssuerClientID: "test-client-id", - IssuerClientSecret: "test-client-secret", - IssuerURL: "http://localhost:8080/oidc", - CallbackURL: "http://localhost:8080/callback", - }, - wantErr: true, - errMsg: "--oidc-callback-url must end with '/api/callback', got path: /callback", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.options.Validate() - - if !tt.wantErr { - require.NoError(t, err) - return - } - - require.Error(t, err) - if tt.errMsg != "" { - require.EqualError(t, err, tt.errMsg) - } - }) - } -} diff --git a/backend/options/options.go b/backend/options/options.go deleted file mode 100644 index 3076dbf7f..000000000 --- a/backend/options/options.go +++ /dev/null @@ -1,341 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 options - -import ( - "fmt" - "net/url" - "os" - "strings" - "time" - - "github.com/spf13/pflag" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - providerkcp "github.com/kube-bind/kube-bind/backend/provider/kcp/options" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Options struct { - Logs *logs.Options - OIDC *OIDC - Cookie *Cookie - Serve *Serve - Session *Session - - ProviderKcp *providerkcp.Options - - ExtraOptions -} - -type ExtraOptions struct { - KubeConfig string - Context string - - Provider string - - NamespacePrefix string - PrettyName string - ConsumerScope string - Isolation string - ExternalAddress string - ExternalCAFile string - ExternalCA []byte - TLSExternalServerName string - // Defines the source of the schema for the bind screen. - // Options are: - // CustomResourceDefinition.v1.apiextensions.k8s.io - // APIResourceSchema.v1alpha1.apis.kcp.io - SchemaSource string - - TestingAutoSelect string - TestingSkipNameValidation bool - - // If ControllerFrontend starts with http:// it is treated as a URL to a SPA server - // Else - it is treated as a path to static files to be served. - Frontend string - // FrontendDisabled indicates that no frontend should be served at all, including oidc and api. - // This is useful for backend-only deployments. - FrontendDisabled bool - - TokenExpiry time.Duration - - // SchemaSyncInterval is how often the serviceexportrequest controller re-reconciles - // to detect source schema changes when SchemaUpdatePolicy is Always. - SchemaSyncInterval time.Duration - - // KonnectorHostAlias is a list of host alias entries for konnector pods - // deployed via the UI flow, in the format IP:hostname1,hostname2. - KonnectorHostAlias []string -} - -type completedOptions struct { - Logs *logs.Options - OIDC *OIDC - Cookie *Cookie - Serve *Serve - Session *Session - - // Provider specific options - ProviderKcp *providerkcp.CompletedOptions - - ExtraOptions -} - -type CompletedOptions struct { - *completedOptions -} - -func NewOptions() *Options { - // Default to -v=2 - logs := logs.NewOptions() - logs.Verbosity = logsv1.VerbosityLevel(2) - - opts := &Options{ - Logs: logs, - OIDC: NewOIDC(), - Cookie: NewCookie(), - Serve: NewServe(), - Session: NewSession(), - ProviderKcp: providerkcp.NewOptions(), - - ExtraOptions: ExtraOptions{ - Provider: "kubernetes", - NamespacePrefix: "cluster-", - PrettyName: "Backend", - ConsumerScope: string(kubebindv1alpha2.NamespacedScope), - Isolation: string(kubebindv1alpha2.IsolationPrefixed), - SchemaSource: CustomResourceDefinitionSource.String(), - Frontend: "embedded", // Not used, but indicates to use embedded frontend using SPA. - TokenExpiry: 1 * time.Hour, - FrontendDisabled: false, - SchemaSyncInterval: 5 * time.Minute, - }, - } - return opts -} - -var providerAliases = map[string]string{ - "kcp": "kcp", - "kubernetes": "kubernetes", - "": "kubernetes", -} - -type SchemaSource string - -func (s SchemaSource) String() string { - return string(s) -} - -var ( - KCPAPIResourceSchemaSource = SchemaSource("APIResourceSchema.v1alpha1.apis.kcp.io") - CustomResourceDefinitionSource = SchemaSource("CustomResourceDefinition.v1.apiextensions.k8s.io") -) - -// TODO(mjudeikis): https://github.com/kube-bind/kube-bind/issues/298 -// We should relax these once we happy they work with any schema. -var schemaSourceAliases = map[string]string{ - CustomResourceDefinitionSource.String(): CustomResourceDefinitionSource.String(), // mostrly for e2e tests - "customresourcedefinitions": CustomResourceDefinitionSource.String(), - "apiresourceschemas": KCPAPIResourceSchemaSource.String(), - KCPAPIResourceSchemaSource.String(): KCPAPIResourceSchemaSource.String(), -} - -func (options *Options) AddFlags(fs *pflag.FlagSet) { - logsv1.AddFlags(options.Logs, fs) - options.OIDC.AddFlags(fs) - options.Cookie.AddFlags(fs) - options.Serve.AddFlags(fs) - options.Session.AddFlags(fs) - options.ProviderKcp.AddFlags(fs) - - fs.StringVar(&options.KubeConfig, "kubeconfig", options.KubeConfig, "path to a kubeconfig. Only required if out-of-cluster") - fs.StringVar(&options.Context, "context", options.Context, "The name of the kubeconfig context to use.") - fs.StringVar(&options.NamespacePrefix, "namespace-prefix", options.NamespacePrefix, "The prefix to use for cluster namespaces") - fs.StringVar(&options.PrettyName, "pretty-name", options.PrettyName, "Pretty name for the backend") - fs.StringVar(&options.ConsumerScope, "consumer-scope", options.ConsumerScope, "How consumers access the service provider cluster. In Kubernetes, \"namespaced\" allows namespace isolation. In kcp, \"cluster\" allows workspace isolation, and with that allows cluster-scoped resources to bind and it is generally more performant.") - // TODO(mjudeikis): remove deprecated flag in future release - fs.StringVar(&options.Isolation, "cluster-scoped-isolation", options.Isolation, "How cluster scoped service objects are isolated between multiple consumers on the provider side. Among the choices, \"prefixed\" prepends the name of the cluster namespace to an object's name; \"namespaced\" maps a consumer side object into a namespaced object inside the corresponding cluster namespace; \"none\" is used for the case of a dedicated provider where isolation is not necessary.") - _ = fs.MarkDeprecated("cluster-scoped-isolation", "use --isolation instead") - fs.StringVar(&options.Isolation, "isolation", options.Isolation, "How cluster scoped service objects are isolated between multiple consumers on the provider side. Among the choices, \"prefixed\" prepends the name of the cluster namespace to an object's name; \"namespaced\" maps a consumer side object into a namespaced object inside the corresponding cluster namespace; \"none\" is used for the case of a dedicated provider where isolation is not necessary.") - fs.StringVar(&options.ExternalAddress, "external-address", options.ExternalAddress, "The external address for the service provider cluster, including https:// and port. If not specified, service account's hosts are used.") - fs.StringVar(&options.ExternalCAFile, "external-ca-file", options.ExternalCAFile, "The external CA file for the service provider cluster. If not specified, service account's CA is used.") - fs.StringVar(&options.TLSExternalServerName, "external-server-name", options.TLSExternalServerName, "The external (TLS) server name used by consumers to talk to the service provider cluster. This can be useful to select the right certificate via SNI.") - fs.StringVar(&options.Frontend, "frontend", options.Frontend, "If starts with http:// it is treated as a URL to a SPA server Else - it is treated as a path to static files to be served.") - fs.BoolVarP(&options.FrontendDisabled, "frontend-disabled", "", false, "If set, will run in backend only mode without API and oidc.") - fs.DurationVar(&options.TokenExpiry, "token-expiry", options.TokenExpiry, "The duration for which tokens are valid. Default is 1h.") - - fs.StringVar(&options.Provider, "multicluster-runtime-provider", options.Provider, - fmt.Sprintf("The multicluster runtime provider. Possible values are: %v", sets.List(sets.Set[string](sets.StringKeySet(providerAliases)))), - ) - - values := make([]string, 0, len(schemaSourceAliases)) - for _, v := range schemaSourceAliases { - values = append(values, v) - } - - fs.StringVar(&options.SchemaSource, "schema-source", options.SchemaSource, - fmt.Sprintf("Defines the source of the schema in Kind.Version.Group format for the bind screen. Defaults to CustomResourceDefinition.v1.apiextensions.k8s.io. Possible values are: %v", - values), - ) - - fs.DurationVar(&options.SchemaSyncInterval, "schema-sync-interval", options.SchemaSyncInterval, "How often to re-sync BoundSchemas when SchemaUpdatePolicy is Always. Default is 5m.") - - fs.StringVar(&options.TestingAutoSelect, "testing-auto-select", options.TestingAutoSelect, ". that is automatically selected on th bind screen for testing") - fs.MarkHidden("testing-auto-select") //nolint:errcheck - fs.StringSliceVar(&options.KonnectorHostAlias, "konnector-host-alias", options.KonnectorHostAlias, "Add host aliases to konnector pods deployed via the UI flow, in the format IP:hostname1,hostname2. Can be specified multiple times.") -} - -func (options *Options) Complete() (*CompletedOptions, error) { - // Serve must complete first as OIDC may depend on it - // to reuse the listener. The web server is always started - // (at minimum for the healthz endpoint), so the listener - // is required even when the frontend is disabled. - if err := options.Serve.Complete(); err != nil { - return nil, err - } - - if !options.FrontendDisabled { - if err := options.OIDC.Complete(options.Serve.Listener); err != nil { - return nil, err - } - if err := options.Cookie.Complete(); err != nil { - return nil, err - } - if err := options.Session.Complete(); err != nil { - return nil, err - } - } - - // normalize the scope and the isolation - if strings.ToLower(options.ConsumerScope) == "namespaced" { - options.ConsumerScope = string(kubebindv1alpha2.NamespacedScope) - } - if strings.ToLower(options.ConsumerScope) == "cluster" { - options.ConsumerScope = string(kubebindv1alpha2.ClusterScope) - } - switch strings.ToLower(options.Isolation) { - case "prefixed": - options.Isolation = string(kubebindv1alpha2.IsolationPrefixed) - case "namespaced": - options.Isolation = string(kubebindv1alpha2.IsolationNamespaced) - case "none": - options.Isolation = string(kubebindv1alpha2.IsolationNone) - default: - options.Isolation = string(kubebindv1alpha2.IsolationNone) - } - - if options.ExternalCAFile != "" && options.ExternalCA != nil { - return nil, fmt.Errorf("cannot specify both --external-ca-file and set ExternalCA") - } - if options.ExternalCAFile != "" { - ca, err := os.ReadFile(options.ExternalCAFile) - if err != nil { - return nil, fmt.Errorf("error reading external CA file: %v", err) - } - options.ExternalCA = ca - } - co := &CompletedOptions{ - completedOptions: &completedOptions{ - Logs: options.Logs, - OIDC: options.OIDC, - Cookie: options.Cookie, - Serve: options.Serve, - Session: options.Session, - ExtraOptions: options.ExtraOptions, - }, - } - - if options.Provider == "kcp" { - opts, err := options.ProviderKcp.Complete() - if err != nil { - return nil, err - } - co.completedOptions.ProviderKcp = opts - } - return co, nil -} - -func (options *CompletedOptions) Validate() error { - if options.NamespacePrefix == "" { - return fmt.Errorf("namespace prefix cannot be empty") - } - if options.PrettyName == "" { - return fmt.Errorf("pretty name cannot be empty") - } - - if !options.FrontendDisabled { - if err := options.Serve.Validate(); err != nil { - return err - } - - if err := options.OIDC.Validate(); err != nil { - return err - } - if err := options.Cookie.Validate(); err != nil { - return err - } - if err := options.Session.Validate(); err != nil { - return err - } - } - - if options.ConsumerScope != string(kubebindv1alpha2.NamespacedScope) && options.ConsumerScope != string(kubebindv1alpha2.ClusterScope) { - return fmt.Errorf("consumer scope must be either %q or %q", kubebindv1alpha2.NamespacedScope, kubebindv1alpha2.ClusterScope) - } - - if options.ExternalAddress != "" { - if !strings.HasPrefix(options.ExternalAddress, "https://") { - return fmt.Errorf("external hostname must start with https://") - } - _, err := url.Parse(options.ExternalAddress) - if err != nil { - return fmt.Errorf("invalid external hostname: %v", err) - } - } - - provider := providerAliases[options.Provider] - if provider == "" { - return fmt.Errorf("unknown provider %q, must be one of %v", options.Provider, sets.List(sets.Set[string](sets.StringKeySet(providerAliases)))) - } - options.Provider = provider - - schemaSource := schemaSourceAliases[options.SchemaSource] - if schemaSource == "" { - return fmt.Errorf("unknown schema source %q, must be one of %v", options.SchemaSource, sets.List(sets.Set[string](sets.StringKeySet(schemaSourceAliases)))) - } - options.SchemaSource = schemaSource - parts := strings.SplitN(options.SchemaSource, ".", 3) - if len(parts) != 3 { // We check this in validation, but just in case. - return fmt.Errorf("invalid schema source: %q", options.SchemaSource) - } - - if options.SchemaSyncInterval < 10*time.Second { - return fmt.Errorf("--schema-sync-interval must be at least 10s, got %v", options.SchemaSyncInterval) - } - - for _, entry := range options.KonnectorHostAlias { - parts := strings.SplitN(entry, ":", 2) - if len(parts) != 2 || parts[0] == "" || parts[1] == "" { - return fmt.Errorf("invalid --konnector-host-alias %q, expected format IP:hostname1,hostname2", entry) - } - } - - return nil -} diff --git a/backend/options/serve.go b/backend/options/serve.go deleted file mode 100644 index 75b65303a..000000000 --- a/backend/options/serve.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 options - -import ( - "context" - "fmt" - "net" - "strconv" - - "github.com/spf13/pflag" -) - -type Serve struct { - ListenIP string - ListenPort int - ListenAddress string - CertFile, KeyFile string - - // Listener is used to pre-wire a port zero listener for testing. - Listener net.Listener -} - -func NewServe() *Serve { - return &Serve{ - ListenAddress: "127.0.0.1:8080", - } -} - -func (options *Serve) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&options.ListenIP, "listen-ip", options.ListenIP, "The host IP where the backend is running") - fs.MarkDeprecated("listen-ip", "Use listen-address instead") //nolint:errcheck - fs.IntVar(&options.ListenPort, "listen-port", options.ListenPort, "The host port where the backend is running") - fs.MarkDeprecated("listen-port", "Use listen-address instead") //nolint:errcheck - fs.StringVar(&options.ListenAddress, "listen-address", options.ListenAddress, "The address where the backend should be listening on, defaults to 127.0.0.1:8080.") - fs.StringVar(&options.CertFile, "tls-cert-file", options.CertFile, "The TLS certificate file the webserver will use.") - fs.StringVar(&options.KeyFile, "tls-key-file", options.KeyFile, "The TLS private key file the webserver will use.") -} - -func (options *Serve) Complete() error { - if options.Listener == nil { - var err error - addr := options.ListenAddress - if options.ListenIP != "" { - addr = net.JoinHostPort(options.ListenIP, strconv.Itoa(options.ListenPort)) - } - // We only support TCP4 for now to avoid dual stack complications in embedded OIDC server tests. - var lc net.ListenConfig - options.Listener, err = lc.Listen(context.Background(), "tcp4", addr) - if err != nil { - return err - } - } - return nil -} - -func (options *Serve) Validate() error { - if options.ListenIP == "" && options.ListenAddress == "" { - return fmt.Errorf("either listen-ip or listen-address must be provided") - } - if options.CertFile == "" && options.KeyFile != "" { - return fmt.Errorf("TLS key file cannot be specified without TLS cert file") - } - if options.CertFile != "" && options.KeyFile == "" { - return fmt.Errorf("TLS cert file cannot be specified without TLS key file") - } - - return nil -} diff --git a/backend/options/session.go b/backend/options/session.go deleted file mode 100644 index de8603707..000000000 --- a/backend/options/session.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 options - -import ( - "github.com/spf13/pflag" - - redisoptions "github.com/kube-bind/kube-bind/backend/options/session/redis" -) - -type Session struct { - Redis *redisoptions.Options -} - -func NewSession() *Session { - return &Session{ - Redis: redisoptions.NewOptions(), - } -} - -func (options *Session) AddFlags(fs *pflag.FlagSet) { - options.Redis.AddFlags(fs) -} - -func (options *Session) Complete() error { - return options.Redis.Complete() -} - -func (options *Session) Validate() error { - return options.Redis.Validate() -} diff --git a/backend/options/session/redis/options.go b/backend/options/session/redis/options.go deleted file mode 100644 index 1edc53b93..000000000 --- a/backend/options/session/redis/options.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 redis - -import ( - "fmt" - "os" - - "github.com/spf13/pflag" -) - -type Options struct { - Address string - Password string -} - -func NewOptions() *Options { - return &Options{} -} - -func (options *Options) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&options.Address, "redis-addr", options.Address, "The redis address (e.g. localhost:6379) to connect to if storing sessions in Redis. If empty, the in-memory provider is used.") -} - -func (options *Options) Complete() error { - if pwd := os.Getenv("REDIS_PASSWORD"); pwd != "" { - options.Password = pwd - } - return nil -} - -func (options *Options) Validate() error { - if options.Password != "" && options.Address == "" { - return fmt.Errorf("redis-addr must be specified when using redis-password") - } - return nil -} diff --git a/backend/provider/kcp/controllers/apibindingtemplate/controller.go b/backend/provider/kcp/controllers/apibindingtemplate/controller.go deleted file mode 100644 index 8e2d45515..000000000 --- a/backend/provider/kcp/controllers/apibindingtemplate/controller.go +++ /dev/null @@ -1,182 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 apibindingtemplate contains a kcp-specific controller that watches -// APIBindings in provider/backend workspaces and automatically creates or -// updates APIServiceExportTemplates based on the APIResourceSchemas exposed by -// each bound APIExport. -package apibindingtemplate - -import ( - "context" - "fmt" - "strings" - - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/controller-runtime/pkg/controller" - crhandler "sigs.k8s.io/controller-runtime/pkg/handler" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/reconcile" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mchandler "sigs.k8s.io/multicluster-runtime/pkg/handler" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/shared" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const controllerName = "kube-bind-kcp-apibinding-template" - -// APIBindingTemplateReconciler watches APIBindings and ensures an -// APIServiceExportTemplate exists for every bound APIExport. -type APIBindingTemplateReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - ignorePrefixes []string - scheme *runtime.Scheme - vwCache *shared.VWClientCache -} - -// New returns a new APIBindingTemplateReconciler. -func New( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - ignorePrefixes []string, - baseConfig *rest.Config, - scheme *runtime.Scheme, -) (*APIBindingTemplateReconciler, error) { - r := &APIBindingTemplateReconciler{ - manager: mgr, - opts: opts, - ignorePrefixes: ignorePrefixes, - scheme: scheme, - vwCache: shared.NewVWClientCache(baseConfig), - } - - return r, nil -} - -// shouldIgnore returns true if the APIBinding name matches any of the -// configured ignore prefixes. -func (r *APIBindingTemplateReconciler) shouldIgnore(name string) bool { - for _, prefix := range r.ignorePrefixes { - if strings.HasPrefix(name, prefix) { - return true - } - } - return false -} - -// Reconcile implements reconcile.Reconciler for multicluster-runtime. -func (r *APIBindingTemplateReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - - if r.shouldIgnore(req.Name) { - logger.V(4).Info("Ignoring APIBinding matching ignore prefix", "name", req.Name) - return ctrl.Result{}, nil - } - - logger.Info("Reconciling APIBinding", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - - c := cl.GetClient() - clusterConfig := cl.GetConfig() - - binding := &apisv1alpha2.APIBinding{} - if err := c.Get(ctx, req.NamespacedName, binding); err != nil { - if errors.IsNotFound(err) { - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to get APIBinding %q: %w", req.Name, err) - } - - // Build the schema getter with VW fallback using the shared cache. - getSchema := shared.SchemaGetterWithFallback(c, clusterConfig, r.vwCache) - - rec := reconciler{ - client: c, - scheme: r.scheme, - getAPIResourceSchema: getSchema, - } - - if err := rec.reconcile(ctx, binding); err != nil { - logger.Error(err, "Failed to reconcile APIBinding", "name", req.Name) - return ctrl.Result{}, err - } - - return ctrl.Result{}, nil -} - -// getTemplateMapper returns a mapper that enqueues the owning APIBinding when -// an APIServiceExportTemplate changes. -// -// This function has the signature func(clusterName string, cl cluster.Cluster) handler.TypedEventHandler -// because multicluster-runtime's mcbuilder.Watches accepts a "per-cluster event handler factory" -// rather than a plain handler — it calls this factory for each cluster that is engaged. -func getTemplateMapper(clusterName multicluster.ClusterName, cl cluster.Cluster) crhandler.TypedEventHandler[client.Object, mcreconcile.Request] { - return mchandler.TypedEnqueueRequestsFromMapFuncWithClusterPreservation(func(ctx context.Context, obj client.Object) []mcreconcile.Request { - annotations := obj.GetAnnotations() - if annotations == nil { - return nil - } - ownerName, ok := annotations[shared.AnnotationOwnerBinding] - if !ok { - return nil - } - - c := cl.GetClient() - var binding apisv1alpha2.APIBinding - if err := c.Get(ctx, client.ObjectKey{Name: ownerName}, &binding); err != nil { - return nil - } - - return []mcreconcile.Request{ - { - Request: reconcile.Request{ - NamespacedName: types.NamespacedName{Name: ownerName}, - }, - ClusterName: clusterName, - }, - } - }) -} - -// SetupWithManager registers the controller with the multicluster-runtime Manager. -func (r *APIBindingTemplateReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&apisv1alpha2.APIBinding{}). - Watches( - &kubebindv1alpha2.APIServiceExportTemplate{}, - getTemplateMapper, - ). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/provider/kcp/controllers/apibindingtemplate/reconcile.go b/backend/provider/kcp/controllers/apibindingtemplate/reconcile.go deleted file mode 100644 index 67456f366..000000000 --- a/backend/provider/kcp/controllers/apibindingtemplate/reconcile.go +++ /dev/null @@ -1,236 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 apibindingtemplate - -import ( - "context" - "fmt" - - apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1" - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/shared" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// templateNameForBinding derives a deterministic APIServiceExportTemplate name -// from the APIBinding name and scope. The naming convention is: -// -// -cluster for ClusterScope -// -namespaced for NamespacedScope -// -// Note: if a binding name already ends in "-cluster" or "-namespaced", this -// could theoretically collide with another binding's template name. In practice -// kcp APIBinding names are generated and unlikely to hit this edge case. -func templateNameForBinding(bindingName string, scope kubebindv1alpha2.InformerScope) string { - switch scope { - case kubebindv1alpha2.ClusterScope: - return bindingName + "-cluster" - default: - return bindingName + "-namespaced" - } -} - -type reconciler struct { - client client.Client - scheme *runtime.Scheme - getAPIResourceSchema func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) -} - -func (r *reconciler) reconcile(ctx context.Context, binding *apisv1alpha2.APIBinding) error { - logger := klog.FromContext(ctx) - - if binding.Status.Phase != apisv1alpha2.APIBindingPhaseBound { - return nil - } - if len(binding.Status.BoundResources) == 0 { - logger.V(4).Info("APIBinding has no bound resources yet, skipping", "binding", binding.Name) - return nil - } - - // Build separate templates per scope. - templates, err := r.buildTemplates(ctx, binding) - if err != nil { - return err - } - - desiredNames := make(map[string]bool, len(templates)) - for _, desired := range templates { - desiredNames[desired.Name] = true - - // Set owner reference: APIBinding owns the template. - if err := controllerutil.SetOwnerReference(binding, desired, r.scheme); err != nil { - return fmt.Errorf("failed to set owner reference on APIServiceExportTemplate %q: %w", desired.Name, err) - } - - if err := r.ensureTemplate(ctx, binding, desired); err != nil { - return err - } - } - - // Prune orphaned templates: if a binding used to have resources of a - // given scope but no longer does, the old template must be deleted. - return r.pruneOrphanedTemplates(ctx, binding, desiredNames) -} - -// pruneOrphanedTemplates lists templates owned by this binding and deletes any -// that are no longer in the desired set. -func (r *reconciler) pruneOrphanedTemplates(ctx context.Context, binding *apisv1alpha2.APIBinding, desiredNames map[string]bool) error { - logger := klog.FromContext(ctx) - - var allTemplates kubebindv1alpha2.APIServiceExportTemplateList - if err := r.client.List(ctx, &allTemplates); err != nil { - return fmt.Errorf("failed to list APIServiceExportTemplates: %w", err) - } - - for i := range allTemplates.Items { - tmpl := &allTemplates.Items[i] - ann := tmpl.Annotations - if ann == nil || ann[shared.AnnotationOwnerBinding] != binding.Name { - continue - } - if desiredNames[tmpl.Name] { - continue - } - logger.Info("Deleting orphaned APIServiceExportTemplate", "name", tmpl.Name, "binding", binding.Name) - if err := r.client.Delete(ctx, tmpl); err != nil && !errors.IsNotFound(err) { - return fmt.Errorf("failed to delete orphaned APIServiceExportTemplate %q: %w", tmpl.Name, err) - } - } - - return nil -} - -func (r *reconciler) ensureTemplate(ctx context.Context, binding *apisv1alpha2.APIBinding, desired *kubebindv1alpha2.APIServiceExportTemplate) error { - logger := klog.FromContext(ctx) - - existing := &kubebindv1alpha2.APIServiceExportTemplate{} - err := r.client.Get(ctx, types.NamespacedName{Name: desired.Name}, existing) - if errors.IsNotFound(err) { - logger.Info("Creating APIServiceExportTemplate", "name", desired.Name, "binding", binding.Name) - if err := r.client.Create(ctx, desired); err != nil { - return fmt.Errorf("failed to create APIServiceExportTemplate %q: %w", desired.Name, err) - } - return nil - } - if err != nil { - return fmt.Errorf("failed to get APIServiceExportTemplate %q: %w", desired.Name, err) - } - - needsUpdate := false - - if !equality.Semantic.DeepEqual(existing.Spec, desired.Spec) { - existing.Spec = desired.Spec - needsUpdate = true - } - - // Ensure owner reference is set. - if !metav1.IsControlledBy(existing, binding) { - if err := controllerutil.SetOwnerReference(binding, existing, r.scheme); err != nil { - return fmt.Errorf("failed to set owner reference on APIServiceExportTemplate %q: %w", desired.Name, err) - } - needsUpdate = true - } - - if !needsUpdate { - return nil - } - - logger.Info("Updating APIServiceExportTemplate", "name", desired.Name, "binding", binding.Name) - if err := r.client.Update(ctx, existing); err != nil { - return fmt.Errorf("failed to update APIServiceExportTemplate %q: %w", desired.Name, err) - } - - return nil -} - -// buildTemplates constructs one APIServiceExportTemplate per scope from the -// APIBinding's bound resources. Resources are grouped by scope so that each -// template contains only resources of the same scope (Namespaced or Cluster). -func (r *reconciler) buildTemplates(ctx context.Context, binding *apisv1alpha2.APIBinding) ([]*kubebindv1alpha2.APIServiceExportTemplate, error) { - type scopedResource struct { - scope kubebindv1alpha2.InformerScope - resource kubebindv1alpha2.APIServiceExportResource - } - - grouped := make([]scopedResource, 0, len(binding.Status.BoundResources)) - for _, boundRes := range binding.Status.BoundResources { - schema, err := r.getAPIResourceSchema(ctx, boundRes.Schema.Name) - if err != nil { - return nil, fmt.Errorf("failed to get APIResourceSchema %q for binding %q: %w", - boundRes.Schema.Name, binding.Name, err) - } - - var versions []string - for _, v := range schema.Spec.Versions { - if v.Served { - versions = append(versions, v.Name) - } - } - - scope := kubebindv1alpha2.NamespacedScope - if schema.Spec.Scope == apiextensionsv1.ClusterScoped { - scope = kubebindv1alpha2.ClusterScope - } - - grouped = append(grouped, scopedResource{ - scope: scope, - resource: kubebindv1alpha2.APIServiceExportResource{ - GroupResource: kubebindv1alpha2.GroupResource{ - Group: boundRes.Group, - Resource: boundRes.Resource, - }, - Versions: versions, - }, - }) - } - - // Group resources by scope. - byScope := map[kubebindv1alpha2.InformerScope][]kubebindv1alpha2.APIServiceExportResource{} - for _, sr := range grouped { - byScope[sr.scope] = append(byScope[sr.scope], sr.resource) - } - - templates := make([]*kubebindv1alpha2.APIServiceExportTemplate, 0, len(byScope)) - for scope, resources := range byScope { - templateName := templateNameForBinding(binding.Name, scope) - tmpl := &kubebindv1alpha2.APIServiceExportTemplate{ - ObjectMeta: metav1.ObjectMeta{ - Name: templateName, - Annotations: map[string]string{ - shared.AnnotationOwnerBinding: binding.Name, - }, - }, - Spec: kubebindv1alpha2.APIServiceExportTemplateSpec{ - Scope: scope, - Resources: resources, - }, - } - templates = append(templates, tmpl) - } - - return templates, nil -} diff --git a/backend/provider/kcp/controllers/apiresourceschema/controller.go b/backend/provider/kcp/controllers/apiresourceschema/controller.go deleted file mode 100644 index 7bbaeaa3f..000000000 --- a/backend/provider/kcp/controllers/apiresourceschema/controller.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 apiresourceschema contains a kcp-specific controller that watches -// APIServiceExportTemplates and copies the corresponding APIResourceSchemas -// into the workspace so that the serviceexportrequest controller can find them. -package apiresourceschema - -import ( - "context" - "fmt" - - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/log" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/shared" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const controllerName = "kube-bind-kcp-apiresourceschema" - -// APIResourceSchemaReconciler watches APIServiceExportTemplates and ensures -// that the APIResourceSchemas referenced by the owning APIBinding are copied -// into the workspace with the kube-bind.io/exported=true label. -type APIResourceSchemaReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - scheme *runtime.Scheme - vwCache *shared.VWClientCache -} - -// New returns a new APIResourceSchemaReconciler. -func New( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - baseConfig *rest.Config, - scheme *runtime.Scheme, -) (*APIResourceSchemaReconciler, error) { - return &APIResourceSchemaReconciler{ - manager: mgr, - opts: opts, - scheme: scheme, - vwCache: shared.NewVWClientCache(baseConfig), - }, nil -} - -// Reconcile implements reconcile.Reconciler for multicluster-runtime. -func (r *APIResourceSchemaReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx) - logger.Info("Reconciling APIServiceExportTemplate for schema copy", "request", req) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get cluster %q: %w", req.ClusterName, err) - } - - c := cl.GetClient() - clusterConfig := cl.GetConfig() - - // Get the template. - tmpl := &kubebindv1alpha2.APIServiceExportTemplate{} - if err := c.Get(ctx, req.NamespacedName, tmpl); err != nil { - if errors.IsNotFound(err) { - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to get APIServiceExportTemplate %q: %w", req.Name, err) - } - - // Find the owning APIBinding via annotation. - bindingName, ok := tmpl.Annotations[shared.AnnotationOwnerBinding] - if !ok { - logger.V(4).Info("Template has no owner-binding annotation, skipping", "name", tmpl.Name) - return ctrl.Result{}, nil - } - - binding := &apisv1alpha2.APIBinding{} - if err := c.Get(ctx, types.NamespacedName{Name: bindingName}, binding); err != nil { - if errors.IsNotFound(err) { - logger.Info("Owning APIBinding not found, skipping", "binding", bindingName) - return ctrl.Result{}, nil - } - return ctrl.Result{}, fmt.Errorf("failed to get APIBinding %q: %w", bindingName, err) - } - - if binding.Status.Phase != apisv1alpha2.APIBindingPhaseBound { - return ctrl.Result{}, nil - } - - // Build schema getter with VW fallback using the shared cache. - getSchema := shared.SchemaGetterWithFallback(c, clusterConfig, r.vwCache) - - rec := reconciler{ - client: c, - scheme: r.scheme, - getAPIResourceSchema: getSchema, - } - - if err := rec.reconcile(ctx, tmpl, binding); err != nil { - logger.Error(err, "Failed to reconcile schemas for template", "name", tmpl.Name) - return ctrl.Result{}, err - } - - return ctrl.Result{}, nil -} - -// SetupWithManager registers the controller with the multicluster-runtime Manager. -func (r *APIResourceSchemaReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&kubebindv1alpha2.APIServiceExportTemplate{}). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/provider/kcp/controllers/apiresourceschema/reconcile.go b/backend/provider/kcp/controllers/apiresourceschema/reconcile.go deleted file mode 100644 index b617654ba..000000000 --- a/backend/provider/kcp/controllers/apiresourceschema/reconcile.go +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 apiresourceschema - -import ( - "context" - "fmt" - - apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1" - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/klog/v2" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - - "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type reconciler struct { - client client.Client - scheme *runtime.Scheme - getAPIResourceSchema func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) -} - -func (r *reconciler) reconcile(ctx context.Context, tmpl *kubebindv1alpha2.APIServiceExportTemplate, binding *apisv1alpha2.APIBinding) error { - logger := klog.FromContext(ctx) - - // Build a set of resources listed in this template so we only copy - // schemas that match this template's scope. - templateResources := make(map[string]bool, len(tmpl.Spec.Resources)) - for _, res := range tmpl.Spec.Resources { - templateResources[res.Group+"/"+res.Resource] = true - } - - for _, boundRes := range binding.Status.BoundResources { - if !templateResources[boundRes.Group+"/"+boundRes.Resource] { - continue - } - - schema, err := r.getAPIResourceSchema(ctx, boundRes.Schema.Name) - if err != nil { - return fmt.Errorf("failed to get APIResourceSchema %q for binding %q: %w", - boundRes.Schema.Name, binding.Name, err) - } - - if err := r.ensureSchema(ctx, tmpl, schema); err != nil { - logger.Error(err, "Failed to ensure APIResourceSchema copy", - "schema", schema.Name, "template", tmpl.Name) - return err - } - } - - return nil -} - -// ensureSchema creates or updates a local copy of the APIResourceSchema, -// owned by the template and labeled for discovery by serviceexportrequest. -func (r *reconciler) ensureSchema(ctx context.Context, tmpl *kubebindv1alpha2.APIServiceExportTemplate, source *apisv1alpha1.APIResourceSchema) error { - logger := klog.FromContext(ctx) - - desired := &apisv1alpha1.APIResourceSchema{ - ObjectMeta: metav1.ObjectMeta{ - Name: source.Name, - Labels: map[string]string{ - resources.ExportedCRDsLabel: "true", - }, - }, - Spec: *source.Spec.DeepCopy(), - } - - // Set owner reference: template owns the schema copy. - if err := controllerutil.SetOwnerReference(tmpl, desired, r.scheme); err != nil { - return fmt.Errorf("failed to set owner reference on APIResourceSchema %q: %w", desired.Name, err) - } - - existing := &apisv1alpha1.APIResourceSchema{} - err := r.client.Get(ctx, client.ObjectKey{Name: desired.Name}, existing) - if errors.IsNotFound(err) { - logger.Info("Creating APIResourceSchema copy", "name", desired.Name, "template", tmpl.Name) - if err := r.client.Create(ctx, desired); err != nil { - return fmt.Errorf("failed to create APIResourceSchema %q: %w", desired.Name, err) - } - return nil - } - if err != nil { - return fmt.Errorf("failed to get APIResourceSchema %q: %w", desired.Name, err) - } - - // Check if spec or labels need updating. - needsUpdate := false - - if !equality.Semantic.DeepEqual(existing.Spec, desired.Spec) { - existing.Spec = desired.Spec - needsUpdate = true - } - - if existing.Labels == nil || existing.Labels[resources.ExportedCRDsLabel] != "true" { - if existing.Labels == nil { - existing.Labels = make(map[string]string) - } - existing.Labels[resources.ExportedCRDsLabel] = "true" - needsUpdate = true - } - - // Ensure owner reference is set. - if !metav1.IsControlledBy(existing, tmpl) { - if err := controllerutil.SetOwnerReference(tmpl, existing, r.scheme); err != nil { - return fmt.Errorf("failed to set owner reference on APIResourceSchema %q: %w", existing.Name, err) - } - needsUpdate = true - } - - if needsUpdate { - logger.Info("Updating APIResourceSchema copy", "name", existing.Name, "template", tmpl.Name) - if err := r.client.Update(ctx, existing); err != nil { - return fmt.Errorf("failed to update APIResourceSchema %q: %w", existing.Name, err) - } - } - - return nil -} diff --git a/backend/provider/kcp/controllers/shared/vw.go b/backend/provider/kcp/controllers/shared/vw.go deleted file mode 100644 index 90379a41e..000000000 --- a/backend/provider/kcp/controllers/shared/vw.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 shared provides utilities shared across kcp controllers. -package shared - -import ( - "context" - "fmt" - "net/url" - "strings" - "sync" - - apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1" - apisv1alpha1client "github.com/kcp-dev/sdk/client/clientset/versioned/typed/apis/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/log" -) - -// AnnotationOwnerBinding is the annotation key used to link an -// APIServiceExportTemplate back to the APIBinding that owns it. -const AnnotationOwnerBinding = "apibindingtemplate.kube-bind.io/owner-binding" - -// ExtractClusterID extracts the cluster ID from an apiexport virtual workspace -// URL. The expected URL format (as of kcp v0.26+) is: -// -// https://host:port/services/apiexport///clusters/ -// -// where path segments 0-3 are /services/apiexport//, -// segment 4 is "clusters", and segment 5 is the cluster ID. -func ExtractClusterID(clusterConfig *rest.Config) (string, error) { - u, err := url.Parse(clusterConfig.Host) - if err != nil { - return "", fmt.Errorf("failed to parse cluster host URL: %w", err) - } - - pathParts := strings.Split(strings.Trim(u.Path, "/"), "/") - if len(pathParts) < 6 || pathParts[4] != "clusters" { - return "", fmt.Errorf("unexpected apiexport URL format: %s", u.Path) - } - - return pathParts[5], nil -} - -// VWClientCache caches typed apis.kcp.io clients keyed by cluster ID. The -// clients target the apiresourceschema virtual workspace and skip discovery -// (which the VW does not fully serve), so we use the typed kcp REST client -// rather than controller-runtime's client.Client. -type VWClientCache struct { - mu sync.RWMutex - clients map[string]apisv1alpha1client.ApisV1alpha1Interface - baseConfig *rest.Config -} - -// NewVWClientCache creates a new VWClientCache. -func NewVWClientCache(baseConfig *rest.Config) *VWClientCache { - return &VWClientCache{ - clients: make(map[string]apisv1alpha1client.ApisV1alpha1Interface), - baseConfig: baseConfig, - } -} - -// GetClient returns a cached client for the given cluster ID, creating one if -// necessary. -func (c *VWClientCache) GetClient(clusterID string) (apisv1alpha1client.ApisV1alpha1Interface, error) { - c.mu.RLock() - if cl, ok := c.clients[clusterID]; ok { - c.mu.RUnlock() - return cl, nil - } - c.mu.RUnlock() - - c.mu.Lock() - defer c.mu.Unlock() - - // Double-check after acquiring write lock. - if cl, ok := c.clients[clusterID]; ok { - return cl, nil - } - - cl, err := newVWClient(c.baseConfig, clusterID) - if err != nil { - return nil, err - } - c.clients[clusterID] = cl - return cl, nil -} - -// newVWClient creates a typed apis.kcp.io client pointing at the -// apiresourceschema virtual workspace for the given cluster ID: -// -// https://host:port/services/apiresourceschema/{clusterID}/clusters/{clusterID} -// -// Two important details: -// -// 1. We replace the path on baseConfig.Host (which typically points at a -// workspace such as .../clusters/) rather than appending — otherwise -// the URL ends up with two /clusters/ segments and never matches the VW root. -// -// 2. The kcp VW resolver accepts either "*" or the literal consumer cluster -// name in the /clusters// segment (see kcp pkg/virtual/apiresourceschema/ -// builder/build.go digestURL). We use the literal name because client-go's -// REST request builder percent-encodes "*" to "%2A" when constructing the -// final URL, and the resolver compares the path segment against the literal -// string "*" — so a wildcard never matches in practice. -func newVWClient(baseConfig *rest.Config, clusterID string) (apisv1alpha1client.ApisV1alpha1Interface, error) { - cfg := rest.CopyConfig(baseConfig) - u, err := url.Parse(baseConfig.Host) - if err != nil { - return nil, fmt.Errorf("failed to parse base config host: %w", err) - } - cfg.Host = fmt.Sprintf("%s://%s/services/apiresourceschema/%s/clusters/%s", u.Scheme, u.Host, clusterID, clusterID) - - return apisv1alpha1client.NewForConfig(cfg) -} - -// SchemaGetterWithFallback returns a function that first tries to get an -// APIResourceSchema from the workspace client, and if not found, falls back to -// the apiresourceschema virtual workspace via the cached VW client. -func SchemaGetterWithFallback( - workspaceClient client.Client, - clusterConfig *rest.Config, - vwCache *VWClientCache, -) func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) { - return func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) { - logger := log.FromContext(ctx) - - // 1. Try the current workspace first. - var schema apisv1alpha1.APIResourceSchema - err := workspaceClient.Get(ctx, client.ObjectKey{Name: name}, &schema) - if err == nil { - return &schema, nil - } - if !errors.IsNotFound(err) { - return nil, err - } - - // 2. Fallback: try the apiresourceschema virtual workspace. - logger.V(2).Info("APIResourceSchema not found in workspace, trying VW fallback", "schema", name) - - clusterID, err := ExtractClusterID(clusterConfig) - if err != nil { - return nil, fmt.Errorf("cannot build VW fallback client: %w", err) - } - - vwClient, err := vwCache.GetClient(clusterID) - if err != nil { - return nil, fmt.Errorf("failed to get VW client for cluster %q: %w", clusterID, err) - } - - vwSchema, err := vwClient.APIResourceSchemas().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return nil, fmt.Errorf("APIResourceSchema %q not found in workspace or VW: %w", name, err) - } - - return vwSchema, nil - } -} diff --git a/backend/provider/kcp/controllers/vwrbac/controller.go b/backend/provider/kcp/controllers/vwrbac/controller.go deleted file mode 100644 index b895d9db0..000000000 --- a/backend/provider/kcp/controllers/vwrbac/controller.go +++ /dev/null @@ -1,296 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 vwrbac is a TEMPORARY controller that bootstraps RBAC required by -// the kcp apiresourceschema virtual workspace into every consumer workspace -// that has a kube-bind APIBinding. The VW authorizer requires the caller to -// have read access to apibindings.apis.kcp.io in the consumer workspace -// before it will return APIResourceSchemas (see -// kcp/pkg/virtual/apiresourceschema/authorizer/authorizer.go). The kube-bind -// backend SA does not have that by default, so we plant a ClusterRole + -// ClusterRoleBinding once per consumer workspace. -// -// This package should be removed once kcp grants apiresourceschema VW access -// directly to the APIExport owner identity. -package vwrbac - -import ( - "context" - "fmt" - "strings" - - apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - authenticationv1 "k8s.io/api/authentication/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/controller" - "sigs.k8s.io/controller-runtime/pkg/log" - mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" - mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" -) - -// kcpClusterNameExtraKey is the extra-key kcp injects on requests authenticated -// as a kcp-native ServiceAccount. Its value is the SA's home logical cluster -// name. It's the marker that lets us turn the bare SA username into the kcp -// "global SA" identity used for cross-workspace RBAC. -const kcpClusterNameExtraKey = "authentication.kcp.io/cluster-name" - -const ( - controllerName = "kube-bind-kcp-vwrbac" - - // roleName is the deterministic name for the ClusterRole + ClusterRoleBinding - // installed in every consumer workspace. - roleName = "kube-bind-vw-apibinding-reader" -) - -// VWRBACReconciler watches APIBindings across consumer workspaces and ensures -// each workspace has a ClusterRole + ClusterRoleBinding allowing the kube-bind -// backend identity to read apibindings.apis.kcp.io. This is what unlocks the -// kcp apiresourceschema VW for the backend. -type VWRBACReconciler struct { - manager mcmanager.Manager - opts controller.TypedOptions[mcreconcile.Request] - subject rbacv1.Subject -} - -// New returns a new VWRBACReconciler. It performs a SelfSubjectReview against -// baseConfig to discover the identity the backend will use against consumer -// workspaces, so the bootstrapped RBAC binds the right user. -func New( - ctx context.Context, - mgr mcmanager.Manager, - opts controller.TypedOptions[mcreconcile.Request], - baseConfig *rest.Config, -) (*VWRBACReconciler, error) { - subject, err := discoverSubject(ctx, baseConfig) - if err != nil { - return nil, fmt.Errorf("vwrbac: failed to discover backend identity: %w", err) - } - - log.FromContext(ctx).Info("vwrbac: bootstrapping consumer-workspace RBAC for identity", - "kind", subject.Kind, "name", subject.Name) - - return &VWRBACReconciler{ - manager: mgr, - opts: opts, - subject: subject, - }, nil -} - -// discoverSubject calls SelfSubjectReview against the supplied config and maps -// the resulting identity into the RBAC subject that consumer-workspace -// ClusterRoleBindings must use. -// -// Two cases: -// -// 1. kcp-native ServiceAccount (the recommended setup): the JWT carries the -// SA's home logical cluster, which kcp surfaces as the -// "authentication.kcp.io/cluster-name" extra. Cross-workspace RBAC binds -// it via the "global SA" identity: -// -// system:kcp:serviceaccount::: -// -// bound with Kind: User. See kcp e2e -// test/e2e/virtual/apiresourceschema/virtualworkspace_test.go. -// -// 2. Foreign identity (e.g. a local Kubernetes SA presented via OIDC, or any -// other User): use the bare username as Kind: User. kcp will not resolve -// it as a ServiceAccount object — `Kind: ServiceAccount` would never -// match. -func discoverSubject(ctx context.Context, cfg *rest.Config) (rbacv1.Subject, error) { - kc, err := kubernetes.NewForConfig(cfg) - if err != nil { - return rbacv1.Subject{}, err - } - rev, err := kc.AuthenticationV1().SelfSubjectReviews().Create( - ctx, &authenticationv1.SelfSubjectReview{}, metav1.CreateOptions{}) - if err != nil { - return rbacv1.Subject{}, fmt.Errorf("SelfSubjectReview: %w", err) - } - - user := rev.Status.UserInfo.Username - if user == "" { - return rbacv1.Subject{}, fmt.Errorf("SelfSubjectReview returned empty username") - } - - name := user - const saPrefix = "system:serviceaccount:" - if clusters := rev.Status.UserInfo.Extra[kcpClusterNameExtraKey]; len(clusters) > 0 && strings.HasPrefix(user, saPrefix) { - nsName := strings.TrimPrefix(user, saPrefix) // ":" - name = fmt.Sprintf("system:kcp:serviceaccount:%s:%s", clusters[0], nsName) - } - - return rbacv1.Subject{ - Kind: rbacv1.UserKind, - APIGroup: rbacv1.GroupName, - Name: name, - }, nil -} - -// Reconcile ensures the bootstrap ClusterRole + ClusterRoleBinding exist in -// the consumer workspace where the APIBinding lives. It does not need to read -// the binding's contents — the existence of any binding in the cluster is the -// trigger. -func (r *VWRBACReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { - logger := log.FromContext(ctx).WithValues("cluster", req.ClusterName, "binding", req.Name) - - cl, err := r.manager.GetCluster(ctx, req.ClusterName) - if err != nil { - return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) - } - c := cl.GetClient() - - if err := ensureClusterRole(ctx, c); err != nil { - return ctrl.Result{}, err - } - if err := ensureClusterRoleBinding(ctx, c, r.subject); err != nil { - return ctrl.Result{}, err - } - - logger.V(2).Info("vwrbac: bootstrap RBAC ensured") - return ctrl.Result{}, nil -} - -func ensureClusterRole(ctx context.Context, c client.Client) error { - desired := &rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{Name: roleName}, - Rules: []rbacv1.PolicyRule{ - { - // Workspace access — required by kcp's workspaceContentAuthorizer - // for foreign / cross-workspace SAs to even enter the workspace. - NonResourceURLs: []string{"/"}, - Verbs: []string{"access"}, - }, - { - // The "invitation" the apiresourceschema VW authorizer checks. - APIGroups: []string{apisv1alpha2.SchemeGroupVersion.Group}, - Resources: []string{"apibindings"}, - Verbs: []string{"get", "list", "watch"}, - }, - }, - } - - existing := &rbacv1.ClusterRole{} - err := c.Get(ctx, client.ObjectKey{Name: roleName}, existing) - if errors.IsNotFound(err) { - if cerr := c.Create(ctx, desired); cerr != nil && !errors.IsAlreadyExists(cerr) { - return fmt.Errorf("create ClusterRole %q: %w", roleName, cerr) - } - return nil - } - if err != nil { - return fmt.Errorf("get ClusterRole %q: %w", roleName, err) - } - - // Update only if rules drifted. - if rulesEqual(existing.Rules, desired.Rules) { - return nil - } - existing.Rules = desired.Rules - if err := c.Update(ctx, existing); err != nil { - return fmt.Errorf("update ClusterRole %q: %w", roleName, err) - } - return nil -} - -func ensureClusterRoleBinding(ctx context.Context, c client.Client, subject rbacv1.Subject) error { - desired := &rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{Name: roleName}, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.GroupName, - Kind: "ClusterRole", - Name: roleName, - }, - Subjects: []rbacv1.Subject{subject}, - } - - existing := &rbacv1.ClusterRoleBinding{} - err := c.Get(ctx, client.ObjectKey{Name: roleName}, existing) - if errors.IsNotFound(err) { - if cerr := c.Create(ctx, desired); cerr != nil && !errors.IsAlreadyExists(cerr) { - return fmt.Errorf("create ClusterRoleBinding %q: %w", roleName, cerr) - } - return nil - } - if err != nil { - return fmt.Errorf("get ClusterRoleBinding %q: %w", roleName, err) - } - - // RoleRef is immutable; only fix subjects if they drifted. - if subjectsEqual(existing.Subjects, desired.Subjects) { - return nil - } - existing.Subjects = desired.Subjects - if err := c.Update(ctx, existing); err != nil { - return fmt.Errorf("update ClusterRoleBinding %q: %w", roleName, err) - } - return nil -} - -func rulesEqual(a, b []rbacv1.PolicyRule) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if !stringSliceEqual(a[i].APIGroups, b[i].APIGroups) || - !stringSliceEqual(a[i].Resources, b[i].Resources) || - !stringSliceEqual(a[i].Verbs, b[i].Verbs) || - !stringSliceEqual(a[i].NonResourceURLs, b[i].NonResourceURLs) || - !stringSliceEqual(a[i].ResourceNames, b[i].ResourceNames) { - return false - } - } - return true -} - -func subjectsEqual(a, b []rbacv1.Subject) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -func stringSliceEqual(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -// SetupWithManager registers the controller with the multicluster-runtime Manager. -func (r *VWRBACReconciler) SetupWithManager(mgr mcmanager.Manager) error { - return mcbuilder.ControllerManagedBy(mgr). - For(&apisv1alpha2.APIBinding{}). - WithOptions(r.opts). - Named(controllerName). - Complete(r) -} diff --git a/backend/provider/kcp/options/options.go b/backend/provider/kcp/options/options.go deleted file mode 100644 index 1f1f1a4cf..000000000 --- a/backend/provider/kcp/options/options.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 options - -import ( - "github.com/spf13/pflag" -) - -type Options struct { - ExtraOptions -} - -type ExtraOptions struct { - APIExportEndpointSliceName string - - // APIBindingIgnorePrefixes is a list of name prefixes for APIBindings - // that should be ignored by the APIBindingTemplate controller. System - // bindings like "kube-bind.io", "tenancy.kcp.io-*", "topology.kcp.io-*" - // should typically be excluded. - APIBindingIgnorePrefixes []string -} - -type completedOptions struct { - ExtraOptions -} - -type CompletedOptions struct { - *completedOptions -} - -func NewOptions() *Options { - return &Options{ - ExtraOptions: ExtraOptions{ - APIExportEndpointSliceName: "kube-bind.io", - APIBindingIgnorePrefixes: []string{ - "kube-bind.io", - "tenancy.kcp.io", - "topology.kcp.io", - }, - }, - } -} - -func (options *Options) AddFlags(fs *pflag.FlagSet) { - fs.StringVar(&options.ExtraOptions.APIExportEndpointSliceName, "apiexport-endpoint-slice-name", options.ExtraOptions.APIExportEndpointSliceName, "name of the APIExport EndpointSlice to watch") - fs.StringSliceVar(&options.ExtraOptions.APIBindingIgnorePrefixes, "apibinding-ignore-prefixes", options.ExtraOptions.APIBindingIgnorePrefixes, "name prefixes of APIBindings to ignore when generating APIServiceExportTemplates") -} - -func (options *Options) Complete() (*CompletedOptions, error) { - return &CompletedOptions{ - completedOptions: &completedOptions{ - ExtraOptions: options.ExtraOptions, - }, - }, nil -} - -func (options *CompletedOptions) Validate() error { - return nil -} diff --git a/backend/provider/kcp/provider.go b/backend/provider/kcp/provider.go deleted file mode 100644 index 8e8a95ce5..000000000 --- a/backend/provider/kcp/provider.go +++ /dev/null @@ -1,175 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 kcp - -import ( - "context" - "fmt" - "math" - "net/url" - "strings" - "time" - - provider "github.com/kcp-dev/multicluster-provider/apiexport" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/cluster" - "sigs.k8s.io/multicluster-runtime/pkg/multicluster" - - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -var _ multicluster.Provider = &Provider{} -var _ multicluster.ProviderRunnable = &Provider{} - -// Provider is a [sigs.k8s.io/multicluster-runtime/pkg/multicluster.Provider] that represents each [logical cluster] -// (in the kcp sense) exposed via a APIExport virtual workspace as a cluster in the [sigs.k8s.io/multicluster-runtime] sense. -// -// Core functionality is delegated to the apiexport.Provider, this wrapper just adds best effort path-awareness index to it via hooks. -// -// [logical cluster]: https://docs.kcp.io/kcp/latest/concepts/terminology/#logical-cluster -type Provider struct { - *provider.Provider -} - -// New is simple provider wrapper for kcp. -func New(cfg *rest.Config, endpointSliceName string, options provider.Options) (*Provider, error) { - p, err := provider.New(cfg, endpointSliceName, options) - if err != nil { - return nil, err - } - - return &Provider{ - Provider: p, - }, nil -} - -// Get returns the cluster with the given name as a cluster.Cluster. -func (p *Provider) Get(ctx context.Context, clusterName multicluster.ClusterName) (cluster.Cluster, error) { - return p.Provider.Get(ctx, clusterName) -} - -// IndexField adds an indexer to the clusters managed by this provider. -func (p *Provider) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error { - return p.Provider.IndexField(ctx, obj, field, extractValue) -} - -// Start starts the provider and blocks. -func (p *Provider) Start(ctx context.Context, aware multicluster.Aware) error { - return p.Provider.Start(ctx, &awareWrapper{Aware: aware}) -} - -// awareWrapper wraps a multicluster.Aware to create kube-bind Cluster objects -// so we could bootstrap RBAC for them. -type awareWrapper struct { - multicluster.Aware -} - -func (a *awareWrapper) Engage(ctx context.Context, name multicluster.ClusterName, cluster cluster.Cluster) error { - ctx, cancel := context.WithCancel(ctx) //nolint:govet // cancel is called in the error case only. - - err := a.Aware.Engage(ctx, name, cluster) - if err != nil { - cancel() - return err - } - - cl := cluster.GetClient() - - obj := &kubebindv1alpha2.Cluster{ - ObjectMeta: metav1.ObjectMeta{ - Name: kubebindv1alpha2.DefaultClusterName, - }, - Spec: kubebindv1alpha2.ClusterSpec{}, - } - - const maxRetries = 3 - for attempt := 0; attempt < maxRetries; attempt++ { - err = cl.Create(ctx, obj) - if err == nil || apierrors.IsAlreadyExists(err) { - break - } - - if !apierrors.IsForbidden(err) { - cancel() - return err - } - - if attempt < maxRetries-1 { - backoff := time.Duration(math.Pow(2, float64(attempt))) * time.Second - select { - case <-time.After(backoff): - case <-ctx.Done(): - cancel() - return ctx.Err() - } - } - } - - if err != nil && !apierrors.IsAlreadyExists(err) { - cancel() - return err - } - - return nil //nolint:govet // cancel is called in the error case only. -} - -// NewKCPExternalAddressGenerator returns an ExternalAddressGeneratorFunc -// suitable for kcp-based clusters. -func NewKCPExternalAddressGenerator(externalAddress string) (kuberesources.ExternalAddressGeneratorFunc, error) { - var extURL *url.URL - if externalAddress != "" { - var err error - - extURL, err = url.Parse(externalAddress) - if err != nil { - return nil, fmt.Errorf("invalid --external-address: %w", err) - } - } - - return func(_ context.Context, clusterConfig *rest.Config) (string, error) { - // In kcp case, we are talking via apiexport so clientconfig will be pointing to - // https://192.168.2.166:6443/services/apiexport/root:org:ws//clusters/2p0rtkf7b697s6mj - // We need to extract host and /clusters/... part - u, err := url.Parse(clusterConfig.Host) - if err != nil { - return "", err - } - - // Extract cluster ID from the path - // Path format: /services/apiexport/root:org:ws//clusters/{cluster-id} - pathParts := strings.Split(strings.Trim(u.Path, "/"), "/") - if len(pathParts) < 6 || pathParts[4] != "clusters" { - return "", fmt.Errorf("invalid apiexport URL format") - } - - clusterID := pathParts[5] - - // Construct new URL with cluster path - var finalURL = u - if extURL != nil { - finalURL = extURL - } - - finalURL.Path = "/clusters/" + clusterID - - return finalURL.String(), nil - }, nil -} diff --git a/backend/reaper/reaper.go b/backend/reaper/reaper.go new file mode 100644 index 000000000..b137ee5ec --- /dev/null +++ b/backend/reaper/reaper.go @@ -0,0 +1,226 @@ +/* +Copyright 2026 The kbind 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 reaper detects consumers that stopped coming, keyed off the +// heartbeat Lease the konnector maintains in each Grant's boundary namespace. +// Conservative by default: it marks Grants stale (condition + annotation) and +// only revokes/deletes when explicitly enabled. +package reaper + +import ( + "context" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kbind/kbind/backend/issuer" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +// Reaper periodically sweeps Grants against their boundary namespaces' +// heartbeat Leases. +type Reaper struct { + // Client is a provider-cluster client. + Client client.Client + // Issuer performs the destructive boundary deletion (opt-in). + Issuer *issuer.KubeIssuer + // TTL is how long a Lease may be unrenewed (or a Ready Grant may sit + // without any Lease) before the Grant is considered stale. Default 30m. + TTL time.Duration + // Revoke deletes stale Grants (the issuer finalizer removes the + // credentials). Off by default. + Revoke bool + // DeleteBoundary additionally deletes the boundary namespace (cascading + // the synced objects inside it) when revoking, if no other Grant shares + // it. Off by default; requires Revoke. + DeleteBoundary bool + // Interval is the sweep cadence. Default 1m. + Interval time.Duration +} + +func (r *Reaper) ttl() time.Duration { + if r.TTL > 0 { + return r.TTL + } + return 30 * time.Minute +} + +func (r *Reaper) interval() time.Duration { + if r.Interval > 0 { + return r.Interval + } + return time.Minute +} + +// Start implements manager.Runnable (needs leader election: destructive-ish, +// single sweeper is enough). +func (r *Reaper) Start(ctx context.Context) error { + ticker := time.NewTicker(r.interval()) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + if err := r.sweep(ctx); err != nil { + ctrl.LoggerFrom(ctx).Error(err, "reaper sweep failed") + } + } + } +} + +// NeedLeaderElection makes the manager run the reaper only on the leader. +func (r *Reaper) NeedLeaderElection() bool { return true } + +func (r *Reaper) sweep(ctx context.Context) error { + log := ctrl.LoggerFrom(ctx).WithName("reaper") + var grants iamv1alpha1.GrantList + if err := r.Client.List(ctx, &grants); err != nil { + return err + } + for i := range grants.Items { + grant := &grants.Items[i] + if grant.DeletionTimestamp != nil || grant.Status.Namespace == "" { + continue + } + if err := r.sweepGrant(ctx, log, grant); err != nil { + log.Error(err, "sweeping grant", "grant", grant.Name) + } + } + return nil +} + +func (r *Reaper) sweepGrant(ctx context.Context, log logr, grant *iamv1alpha1.Grant) error { + stale, reason, since, err := r.staleness(ctx, grant) + if err != nil { + return err + } + + if !stale { + // Heartbeat is healthy (or the grant is too young to judge): clear + // any previous stale marking. + if grant.Annotations[iamv1alpha1.AnnotationStaleSince] != "" || + apimeta.IsStatusConditionTrue(grant.Status.Conditions, iamv1alpha1.ConditionStale) { + delete(grant.Annotations, iamv1alpha1.AnnotationStaleSince) + if err := r.Client.Update(ctx, grant); err != nil { + return err + } + apimeta.SetStatusCondition(&grant.Status.Conditions, metav1.Condition{ + Type: iamv1alpha1.ConditionStale, Status: metav1.ConditionFalse, + Reason: iamv1alpha1.ReasonAsExpected, Message: "consumer heartbeat is current", + }) + return r.Client.Status().Update(ctx, grant) + } + return nil + } + + // Mark first, destroy (optionally) after. + if grant.Annotations[iamv1alpha1.AnnotationStaleSince] == "" { + if grant.Annotations == nil { + grant.Annotations = map[string]string{} + } + grant.Annotations[iamv1alpha1.AnnotationStaleSince] = since.UTC().Format(time.RFC3339) + if err := r.Client.Update(ctx, grant); err != nil { + return err + } + } + if apimeta.SetStatusCondition(&grant.Status.Conditions, metav1.Condition{ + Type: iamv1alpha1.ConditionStale, Status: metav1.ConditionTrue, + Reason: reason, Message: "consumer stopped renewing its heartbeat Lease (or never applied the bundle)", + }) { + if err := r.Client.Status().Update(ctx, grant); err != nil { + return err + } + log.Info("grant marked stale", "grant", grant.Name, "reason", reason) + } + + if !r.Revoke { + return nil + } + if r.DeleteBoundary { + if err := r.Issuer.DeleteBoundary(ctx, grant); err != nil { + return err + } + } + log.Info("revoking stale grant", "grant", grant.Name, "reason", reason) + return client.IgnoreNotFound(r.Client.Delete(ctx, grant)) +} + +// staleness inspects the boundary namespace's heartbeat Leases. The konnector +// annotates each Lease with its Connection name, and the bundle names the +// Connection after the Grant — so a Grant is judged **per-grant** by the +// Leases matching its own name. Fallback for hand-edited bundles (renamed +// Connection): with no matching Lease, any fresh Lease in the boundary keeps +// the Grant alive (conservative), and only a fully silent boundary goes stale. +func (r *Reaper) staleness(ctx context.Context, grant *iamv1alpha1.Grant) (bool, string, time.Time, error) { + var leases coordinationv1.LeaseList + if err := r.Client.List(ctx, &leases, client.InNamespace(grant.Status.Namespace), + client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + return false, "", time.Time{}, err + } + + var newestMatching, newestAny time.Time + for i := range leases.Items { + lease := &leases.Items[i] + if lease.Spec.RenewTime == nil { + continue + } + renewed := lease.Spec.RenewTime.Time + if renewed.After(newestAny) { + newestAny = renewed + } + if lease.Annotations[corev1alpha1.AnnotationConnection] == grant.Name && renewed.After(newestMatching) { + newestMatching = renewed + } + } + + now := time.Now() + if !newestMatching.IsZero() { + // Per-grant precision: this Grant's own Connection heartbeats. + if now.Sub(newestMatching) > r.ttl() { + return true, iamv1alpha1.ReasonLeaseExpired, newestMatching, nil + } + return false, "", time.Time{}, nil + } + if !newestAny.IsZero() && now.Sub(newestAny) <= r.ttl() { + // Someone in this boundary is alive but not under this Grant's name + // (renamed Connection) — conservative: not stale. + return false, "", time.Time{}, nil + } + if !newestAny.IsZero() { + return true, iamv1alpha1.ReasonLeaseExpired, newestAny, nil + } + + ready := apimeta.FindStatusCondition(grant.Status.Conditions, iamv1alpha1.ConditionReady) + if ready == nil || ready.Status != metav1.ConditionTrue { + return false, "", time.Time{}, nil + } + if readySince := ready.LastTransitionTime.Time; now.Sub(readySince) > r.ttl() { + return true, iamv1alpha1.ReasonNoLease, readySince, nil + } + return false, "", time.Time{}, nil +} + +// logr is the narrow logging interface the reaper needs. +type logr interface { + Info(msg string, keysAndValues ...any) + Error(err error, msg string, keysAndValues ...any) +} diff --git a/backend/reaper/reaper_test.go b/backend/reaper/reaper_test.go new file mode 100644 index 000000000..5146b8136 --- /dev/null +++ b/backend/reaper/reaper_test.go @@ -0,0 +1,143 @@ +/* +Copyright 2026 The kbind 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 reaper + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + coordinationv1 "k8s.io/api/coordination/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apimachineryruntime "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" +) + +const boundary = "kbind-abc123" + +func testScheme(t *testing.T) *apimachineryruntime.Scheme { + t.Helper() + scheme := apimachineryruntime.NewScheme() + utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + utilruntime.Must(iamv1alpha1.AddToScheme(scheme)) + return scheme +} + +func lease(name, connection string, renewedAgo time.Duration) *coordinationv1.Lease { + renew := metav1.NewMicroTime(time.Now().Add(-renewedAgo)) + return &coordinationv1.Lease{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: boundary, + Name: name, + Labels: map[string]string{corev1alpha1.LabelManaged: "true"}, + Annotations: map[string]string{corev1alpha1.AnnotationConnection: connection}, + }, + Spec: coordinationv1.LeaseSpec{ + HolderIdentity: ptr.To("consumer-uid"), + RenewTime: &renew, + }, + } +} + +func grant(name string, readyAgo time.Duration) *iamv1alpha1.Grant { + return &iamv1alpha1.Grant{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Status: iamv1alpha1.GrantStatus{ + Namespace: boundary, + Conditions: []metav1.Condition{{ + Type: iamv1alpha1.ConditionReady, + Status: metav1.ConditionTrue, + Reason: iamv1alpha1.ReasonAsExpected, + LastTransitionTime: metav1.NewTime(time.Now().Add(-readyAgo)), + }}, + }, + } +} + +func TestStalenessIsPerGrant(t *testing.T) { + ttl := time.Minute + for _, tc := range []struct { + name string + leases []client.Object + grant *iamv1alpha1.Grant + wantStale bool + wantReason string + }{ + { + name: "own lease fresh -> alive", + leases: []client.Object{lease("g1-uid", "g1", time.Second)}, + grant: grant("g1", time.Hour), + wantStale: false, + }, + { + name: "own lease expired -> stale, even though a sibling grant in the same boundary is alive", + leases: []client.Object{ + lease("g1-uid", "g1", time.Hour), + lease("g2-uid", "g2", time.Second), + }, + grant: grant("g1", time.Hour), + wantStale: true, + wantReason: iamv1alpha1.ReasonLeaseExpired, + }, + { + name: "no matching lease but a fresh foreign one (renamed Connection) -> conservative, alive", + leases: []client.Object{lease("renamed-uid", "renamed", time.Second)}, + grant: grant("g1", time.Hour), + wantStale: false, + }, + { + name: "no matching lease, all foreign leases expired -> stale", + leases: []client.Object{lease("renamed-uid", "renamed", time.Hour)}, + grant: grant("g1", time.Hour), + wantStale: true, + wantReason: iamv1alpha1.ReasonLeaseExpired, + }, + { + name: "no lease at all, Ready beyond TTL -> stale (bundle never applied)", + leases: nil, + grant: grant("g1", time.Hour), + wantStale: true, + wantReason: iamv1alpha1.ReasonNoLease, + }, + { + name: "no lease at all, freshly Ready -> not judged yet", + leases: nil, + grant: grant("g1", time.Second), + wantStale: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(tc.leases...).Build() + r := &Reaper{Client: c, TTL: ttl} + + stale, reason, _, err := r.staleness(context.Background(), tc.grant) + require.NoError(t, err) + require.Equal(t, tc.wantStale, stale) + if tc.wantStale { + require.Equal(t, tc.wantReason, reason) + } + }) + } +} diff --git a/backend/server.go b/backend/server.go deleted file mode 100644 index bd8b2fbf4..000000000 --- a/backend/server.go +++ /dev/null @@ -1,439 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 backend - -import ( - "context" - "encoding/base64" - "fmt" - "net" - nethttp "net/http" - "strings" - "sync" - - corev1 "k8s.io/api/core/v1" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - "sigs.k8s.io/controller-runtime/pkg/controller" - mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" - - "github.com/kube-bind/kube-bind/backend/auth" - "github.com/kube-bind/kube-bind/backend/controllers/bindableresourcesrequest" - "github.com/kube-bind/kube-bind/backend/controllers/cluster" - "github.com/kube-bind/kube-bind/backend/controllers/clusterbinding" - "github.com/kube-bind/kube-bind/backend/controllers/serviceexport" - "github.com/kube-bind/kube-bind/backend/controllers/serviceexportrbac" - "github.com/kube-bind/kube-bind/backend/controllers/serviceexportrequest" - "github.com/kube-bind/kube-bind/backend/controllers/servicenamespace" - http "github.com/kube-bind/kube-bind/backend/http" - kube "github.com/kube-bind/kube-bind/backend/kubernetes" - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/apibindingtemplate" - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/apiresourceschema" - "github.com/kube-bind/kube-bind/backend/provider/kcp/controllers/vwrbac" - "github.com/kube-bind/kube-bind/backend/session/memory" - "github.com/kube-bind/kube-bind/backend/session/redis" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Server struct { - Config *Config - - OIDC *auth.OIDCServiceProvider - oidcOnce sync.Once - oidcErr error - Kubernetes *kube.Manager - WebServer *http.Server - - Controllers -} - -type Controllers struct { - ServiceExportRBAC *serviceexportrbac.APIServiceExportRBACReconciler - ClusterBinding *clusterbinding.ClusterBindingReconciler - ServiceExport *serviceexport.APIServiceExportReconciler - ServiceExportRequest *serviceexportrequest.APIServiceExportRequestReconciler - ServiceNamespace *servicenamespace.APIServiceNamespaceReconciler - Cluster *cluster.ClusterReconciler - BindableResourcesRequest *bindableresourcesrequest.BindableResourcesRequestReconciler - - // Provider specific controllers - only set when provider is "kcp" - APIBindingTemplate *apibindingtemplate.APIBindingTemplateReconciler - APIResourceSchema *apiresourceschema.APIResourceSchemaReconciler - VWRBAC *vwrbac.VWRBACReconciler -} - -func NewServer(ctx context.Context, c *Config) (*Server, error) { - logger := klog.FromContext(ctx) - - s := &Server{ - Config: c, - } - - // Parse konnector host aliases from flag - var konnectorHostAliases []corev1.HostAlias - for _, entry := range c.Options.KonnectorHostAlias { - parts := strings.SplitN(entry, ":", 2) - if len(parts) == 2 && parts[0] != "" && parts[1] != "" { - konnectorHostAliases = append(konnectorHostAliases, corev1.HostAlias{ - IP: parts[0], - Hostnames: strings.Split(parts[1], ","), - }) - } - } - - var err error - s.Kubernetes, err = kube.NewKubernetesManager( - ctx, - c.Options.NamespacePrefix, - c.Options.PrettyName, - c.ExternalAddressGenerator, - kubebindv1alpha2.InformerScope(c.Options.ExtraOptions.ConsumerScope), - c.Options.ExternalCA, - c.Options.TLSExternalServerName, - s.Config.Manager, - c.Options.OIDC.Type == string(kubebindv1alpha2.OIDCProviderTypeEmbedded), - konnectorHostAliases, - ) - if err != nil { - return nil, fmt.Errorf("error setting up Kubernetes Manager: %w", err) - } - - // Always create the web server for health check endpoints - s.WebServer, err = http.NewServer(c.Options.Serve) - if err != nil { - return nil, fmt.Errorf("error setting up HTTP Server: %w", err) - } - - // Register health check endpoint - s.WebServer.Router.HandleFunc("/healthz", func(w nethttp.ResponseWriter, r *nethttp.Request) { - w.WriteHeader(nethttp.StatusOK) - w.Write([]byte("ok")) //nolint:errcheck - }).Methods("GET") - - if c.Options.FrontendDisabled { - logger.Info("Frontend is disabled; running in backend only mode") - } else { - // setup oidc backend - callback := c.Options.OIDC.CallbackURL - if callback == "" { - callback = fmt.Sprintf("http://%s/api/callback", s.WebServer.Addr().String()) - } - - // Use lazy initialization for embedded OIDC to avoid circular dependency - if c.Options.OIDC.OIDCServer != nil { - logger.Info("Using embedded OIDC server; will initialize lazily") - } else { - // External OIDC provider - initialize immediately - s.OIDC, err = s.initializeOIDCProvider(ctx, callback) - if err != nil { - return nil, fmt.Errorf("error setting up OIDC: %w", err) - } - } - - signingKey, err := base64.StdEncoding.DecodeString(c.Options.Cookie.SigningKey) - if err != nil { - return nil, fmt.Errorf("error creating signing key: %w", err) - } - - var encryptionKey []byte - if c.Options.Cookie.EncryptionKey != "" { - var err error - encryptionKey, err = base64.StdEncoding.DecodeString(c.Options.Cookie.EncryptionKey) - if err != nil { - return nil, fmt.Errorf("error creating encryption key: %w", err) - } - } - - sessionStore := memory.New() - - if addr := c.Options.Session.Redis.Address; addr != "" { - redisStore, err := redis.New(addr, c.Options.Session.Redis.Password) - if err != nil { - return nil, fmt.Errorf("error setting up Redis session store: %w", err) - } - sessionStore = redisStore - } - - handler, err := http.NewHandler( - s, - s.Config.Options.OIDC.OIDCServer, - c.Options.OIDC.AuthorizeURL, - callback, - c.Options.PrettyName, - c.Options.TestingAutoSelect, - signingKey, - encryptionKey, - c.Options.SchemaSource, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - s.Kubernetes, - c.Options.Frontend, - c.Options.TokenExpiry, - sessionStore, - ) - if err != nil { - return nil, fmt.Errorf("error setting up HTTP Handler: %w", err) - } - if err := handler.AddRoutes(s.WebServer.Router); err != nil { - return nil, fmt.Errorf("error adding routes to HTTP Server: %w", err) - } - } - - opts := controller.TypedOptions[mcreconcile.Request]{ - SkipNameValidation: ptr.To(c.Options.TestingSkipNameValidation), - } - - s.ClusterBinding, err = clusterbinding.NewClusterBindingReconciler( - ctx, - s.Config.Manager, - opts, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - ) - if err != nil { - return nil, fmt.Errorf("error setting up ClusterBinding Controller: %w", err) - } - - // Register the ClusterBinding controller with the manager - if err := s.ClusterBinding.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up ClusterBinding controller with manager: %w", err) - } - - s.ServiceExportRBAC, err = serviceexportrbac.NewAPIServiceExportRBACReconciler( - ctx, - s.Config.Manager, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - opts, - ) - if err != nil { - return nil, fmt.Errorf("error setting up RBAC Controller: %w", err) - } - // Register the APIServiceExport RBAC controller with the manager - if err := s.ServiceExportRBAC.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up RBAC controller with manager: %w", err) - } - - // construct APIServiceExport controller with multicluster-runtime - s.ServiceExport, err = serviceexport.NewAPIServiceExportReconciler( - ctx, - s.Config.Manager, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - opts, - ) - if err != nil { - return nil, fmt.Errorf("error setting up APIServiceExport Controller: %w", err) - } - - // Register the APIServiceExport controller with the manager - if err := s.ServiceExport.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up APIServiceExport controller with manager: %w", err) - } - - s.ServiceNamespace, err = servicenamespace.NewAPIServiceNamespaceReconciler( - ctx, - s.Config.Manager, - opts, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - kubebindv1alpha2.Isolation(c.Options.Isolation), - ) - if err != nil { - return nil, fmt.Errorf("error setting up APIServiceNamespace Controller: %w", err) - } - - // Register the APIServiceNamespace controller with the manager - if err := s.ServiceNamespace.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up APIServiceNamespace controller with manager: %w", err) - } - - s.ServiceExportRequest, err = serviceexportrequest.NewAPIServiceExportRequestReconciler( - ctx, - s.Config.Manager, - opts, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - kubebindv1alpha2.Isolation(c.Options.Isolation), - c.Options.SchemaSource, - c.Options.SchemaSyncInterval, - ) - if err != nil { - return nil, fmt.Errorf("error setting up ServiceExportRequest Controller: %w", err) - } - if err := s.ServiceExportRequest.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up ServiceExportRequest controller with manager: %w", err) - } - - s.Cluster, err = cluster.NewClusterReconciler( - ctx, - s.Config.Manager, - opts, - c.Options.OIDC.AllowedGroups, - c.Options.OIDC.AllowedUsers, - ) - if err != nil { - return nil, fmt.Errorf("error setting up LogicalCluster Controller: %w", err) - } - if err := s.Cluster.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up LogicalCluster controller with manager: %w", err) - } - - // Setup BindableResourcesRequest controller - this handles direct CRD-based binding - // when the frontend is disabled (no HTTP API/OIDC flow) - if c.Options.FrontendDisabled { - s.BindableResourcesRequest, err = bindableresourcesrequest.NewBindableResourcesRequestReconciler( - ctx, - s.Config.Manager, - opts, - kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), - kubebindv1alpha2.Isolation(c.Options.Isolation), - s.Kubernetes, - ) - if err != nil { - return nil, fmt.Errorf("error setting up BindableResourcesRequest Controller: %w", err) - } - if err := s.BindableResourcesRequest.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up BindableResourcesRequest controller with manager: %w", err) - } - logger.Info("BindableResourcesRequest controller enabled for CRD-based binding") - } - - // Setup kcp-specific controllers. Only active when provider is kcp - // (APIBindings and APIResourceSchemas only exist in kcp workspaces). - if c.Options.Provider == "kcp" { - s.APIBindingTemplate, err = apibindingtemplate.New(ctx, s.Config.Manager, opts, c.Options.ProviderKcp.APIBindingIgnorePrefixes, c.ClientConfig, c.Scheme) - if err != nil { - return nil, fmt.Errorf("error setting up APIBindingTemplate Controller: %w", err) - } - if err := s.APIBindingTemplate.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up APIBindingTemplate controller with manager: %w", err) - } - logger.Info("APIBindingTemplate controller enabled for kcp provider") - - s.APIResourceSchema, err = apiresourceschema.New(ctx, s.Config.Manager, opts, c.ClientConfig, c.Scheme) - if err != nil { - return nil, fmt.Errorf("error setting up APIResourceSchema Controller: %w", err) - } - if err := s.APIResourceSchema.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up APIResourceSchema controller with manager: %w", err) - } - logger.Info("APIResourceSchema controller enabled for kcp provider") - - s.VWRBAC, err = vwrbac.New(ctx, s.Config.Manager, opts, c.ClientConfig) - if err != nil { - return nil, fmt.Errorf("error setting up VWRBAC Controller: %w", err) - } - if err := s.VWRBAC.SetupWithManager(s.Config.Manager); err != nil { - return nil, fmt.Errorf("error setting up VWRBAC controller with manager: %w", err) - } - logger.Info("VWRBAC controller enabled (temporary; bootstraps consumer-workspace RBAC for kcp apiresourceschema VW)") - } - - return s, nil -} - -func (s *Server) initializeOIDCProvider(ctx context.Context, callback string) (*auth.OIDCServiceProvider, error) { - logger := klog.FromContext(ctx) - logger.Info("Initializing OIDC Service Provider", "issuerURL", s.Config.Options.OIDC.IssuerURL) - - clientID := s.Config.Options.OIDC.IssuerClientID - clientSecret := s.Config.Options.OIDC.IssuerClientSecret - issuerURL := s.Config.Options.OIDC.IssuerURL - tlsConfig := s.Config.Options.OIDC.TLSConfig - - if clientSecret != "" { - logger.Info("WARNING: OIDC client secret is configured. For CLI applications, consider using PKCE.") - } - - if tlsConfig != nil { - return auth.NewOIDCServiceProviderWithTLS( - ctx, - clientID, - clientSecret, - callback, - issuerURL, - tlsConfig, - ) - } - - return auth.NewOIDCServiceProvider( - ctx, - clientID, - clientSecret, - callback, - issuerURL, - ) -} - -func (s *Server) ensureOIDC(ctx context.Context) error { - logger := klog.FromContext(ctx) - if s.Config.Options.OIDC.OIDCServer == nil { - // External OIDC - already initialized - return nil - } - - s.oidcOnce.Do(func() { - callback := s.Config.Options.OIDC.CallbackURL - if callback == "" { - callback = fmt.Sprintf("http://%s/api/callback", s.WebServer.Addr().String()) - } - - s.OIDC, s.oidcErr = s.initializeOIDCProvider(ctx, callback) - if s.oidcErr == nil { - logger.Info("Successfully initialized embedded OIDC provider") - } - }) - return s.oidcErr -} - -func (s *Server) GetOIDCProvider(ctx context.Context) (*auth.OIDCServiceProvider, error) { - if err := s.ensureOIDC(ctx); err != nil { - return nil, err - } - return s.OIDC, nil -} - -func (s *Server) Addr() net.Addr { - if s.WebServer == nil { - return nil - } - return s.WebServer.Addr() -} - -func (s *Server) Run(ctx context.Context) error { - logger := klog.FromContext(ctx) - - // start controller-runtime manager after bootstrap completes - go func() { - if err := s.Config.Manager.Start(ctx); err != nil { - logger.Error(err, "Failed to start controller manager") - } - }() - - go func() { - // When using native k8s provider/singelton cluster - provider is set to nil - // so we need to seed the default cluster. If provider is set - it is provider responsibility - // to seed the default cluster in each managed cluster either via provider machinery or via provider - // wrapper (see kcp example). - if s.Config.Provider == nil { - if err := s.seedCluster(ctx); err != nil { - logger.Error(err, "Failed to seed default cluster") - } - } - }() - - return s.WebServer.Start(ctx) -} - -func (s *Server) seedCluster(ctx context.Context) error { - return s.Kubernetes.SeedDefaultCluster(ctx) -} diff --git a/backend/session/cookie.go b/backend/session/cookie.go deleted file mode 100644 index 4fb905ea2..000000000 --- a/backend/session/cookie.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 session - -import ( - "net/http" - "time" -) - -func MakeCookie(req *http.Request, name string, value string, secure bool, expiration time.Duration) *http.Cookie { - return &http.Cookie{ - Name: name, - Value: value, - Path: "/", // TODO: make configurable - Domain: "", // TODO: add domain support - Expires: time.Now().Add(expiration), - HttpOnly: true, - Secure: secure, - SameSite: http.SameSiteLaxMode, - } -} diff --git a/backend/session/memory/memory.go b/backend/session/memory/memory.go deleted file mode 100644 index c19c80bf5..000000000 --- a/backend/session/memory/memory.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 memory - -import ( - "context" - "errors" - "sync" - "time" - - "github.com/kube-bind/kube-bind/backend/session" -) - -type pkceEntry struct { - verifier string - expiresAt time.Time -} - -type Store struct { - lock sync.RWMutex - sessions map[string]*session.State - pkceVerifiers map[string]pkceEntry -} - -func New() session.Store { - return &Store{ - sessions: make(map[string]*session.State), - pkceVerifiers: make(map[string]pkceEntry), - } -} - -func (s *Store) Save(ctx context.Context, state *session.State) error { - s.lock.Lock() - defer s.lock.Unlock() - s.sessions[state.SessionID] = state - return nil -} - -func (s *Store) Load(ctx context.Context, sessionID string) (*session.State, error) { - s.lock.RLock() - defer s.lock.RUnlock() - state, exists := s.sessions[sessionID] - if !exists { - return nil, session.ErrSessionNotFound - } - return state, nil -} - -func (s *Store) Delete(ctx context.Context, sessionID string) error { - s.lock.Lock() - defer s.lock.Unlock() - delete(s.sessions, sessionID) - return nil -} - -func (s *Store) SavePKCEVerifier(ctx context.Context, sessionID, verifier string) error { - if sessionID == "" || verifier == "" { - return errors.New("sessionID and verifier cannot be empty") - } - s.lock.Lock() - defer s.lock.Unlock() - s.pkceVerifiers[sessionID] = pkceEntry{ - verifier: verifier, - expiresAt: time.Now().Add(session.PKCEVerifierTTL), - } - return nil -} - -func (s *Store) LoadAndDeletePKCEVerifier(ctx context.Context, sessionID string) (string, error) { - if sessionID == "" { - return "", session.ErrPKCEVerifierNotFound - } - s.lock.Lock() - defer s.lock.Unlock() - entry, ok := s.pkceVerifiers[sessionID] - if !ok { - return "", session.ErrPKCEVerifierNotFound - } - - delete(s.pkceVerifiers, sessionID) - - if time.Now().After(entry.expiresAt) { - return "", session.ErrPKCEVerifierNotFound - } - - return entry.verifier, nil -} diff --git a/backend/session/provider.go b/backend/session/provider.go deleted file mode 100644 index 0fc693430..000000000 --- a/backend/session/provider.go +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 session - -import ( - "context" - "fmt" - "time" -) - -const PKCEVerifierTTL = 10 * time.Minute - -var ErrSessionNotFound = fmt.Errorf("session not found") -var ErrPKCEVerifierNotFound = fmt.Errorf("pkce verifier not found") - -type Store interface { - Save(ctx context.Context, state *State) error - Load(ctx context.Context, sessionID string) (*State, error) - Delete(ctx context.Context, sessionID string) error - SavePKCEVerifier(ctx context.Context, sessionID, verifier string) error - LoadAndDeletePKCEVerifier(ctx context.Context, sessionID string) (string, error) -} diff --git a/backend/session/redis/redis.go b/backend/session/redis/redis.go deleted file mode 100644 index a3a14913f..000000000 --- a/backend/session/redis/redis.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 redis - -import ( - "context" - "errors" - "fmt" - "time" - - goredis "github.com/redis/go-redis/v9" - "github.com/vmihailenco/msgpack/v4" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/backend/session" -) - -func getSessionKey(sessionID string) string { - return fmt.Sprintf("session:%s", sessionID) -} - -func getPKCEKey(sessionID string) string { - return fmt.Sprintf("pkce:%s", sessionID) -} - -type store struct { - client *goredis.Client -} - -func New(redisAddr string, redisPassword string) (session.Store, error) { - client := goredis.NewClient(&goredis.Options{ - Addr: redisAddr, - Password: redisPassword, - DB: 0, - }) - - if err := client.Ping(context.Background()).Err(); err != nil { - return nil, fmt.Errorf("failed to connect to redis: %w", err) - } - - return &store{ - client: client, - }, nil -} - -func (s *store) Save(ctx context.Context, state *session.State) error { - encoded, err := state.Encode() - if err != nil { - return fmt.Errorf("failed to encode state: %w", err) - } - - key := getSessionKey(state.SessionID) - - var ttl time.Duration - if !state.ExpiresAt.IsZero() { - ttl = time.Until(state.ExpiresAt) - if ttl <= 0 { - klog.FromContext(context.Background()).V(4).Info("Session already expired, skipping saving to redis", "sessionID", state.SessionID) - return nil - } - } - - err = s.client.Set(ctx, key, encoded, ttl).Err() - if err != nil { - return fmt.Errorf("failed to save session to redis: %w", err) - } - return nil -} - -func (s *store) Load(ctx context.Context, sessionID string) (*session.State, error) { - key := getSessionKey(sessionID) - - val, err := s.client.Get(ctx, key).Bytes() - if err != nil { - if errors.Is(err, goredis.Nil) { - return nil, session.ErrSessionNotFound - } - return nil, fmt.Errorf("failed to load session from redis: %w", err) - } - - var state session.State - err = msgpack.Unmarshal(val, &state) - if err != nil { - return nil, fmt.Errorf("failed to decode state from redis: %w", err) - } - - return &state, nil -} - -func (s *store) Delete(ctx context.Context, sessionID string) error { - key := getSessionKey(sessionID) - err := s.client.Del(ctx, key).Err() - if err != nil { - return fmt.Errorf("failed to delete session from redis: %w", err) - } - return nil -} - -func (s *store) SavePKCEVerifier(ctx context.Context, sessionID, verifier string) error { - if sessionID == "" || verifier == "" { - return errors.New("sessionID and verifier cannot be empty") - } - - key := getPKCEKey(sessionID) - - err := s.client.Set(ctx, key, verifier, session.PKCEVerifierTTL).Err() - if err != nil { - return fmt.Errorf("failed to save pkce to redis: %w", err) - } - return nil -} - -func (s *store) LoadAndDeletePKCEVerifier(ctx context.Context, sessionID string) (string, error) { - if sessionID == "" { - return "", session.ErrPKCEVerifierNotFound - } - - key := getPKCEKey(sessionID) - - val, err := s.client.Get(ctx, key).Result() - if err != nil { - if errors.Is(err, goredis.Nil) { - return "", session.ErrPKCEVerifierNotFound - } - return "", fmt.Errorf("failed to load pkce from redis: %w", err) - } - - _ = s.client.Del(ctx, key).Err() - - return val, nil -} diff --git a/backend/session/redis/redis_test.go b/backend/session/redis/redis_test.go deleted file mode 100644 index 5d26c27f6..000000000 --- a/backend/session/redis/redis_test.go +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 redis - -import ( - "context" - "testing" - "time" - - "github.com/alicebob/miniredis/v2" - "github.com/stretchr/testify/require" - - "github.com/kube-bind/kube-bind/backend/session" -) - -func TestRedisStore(t *testing.T) { - s := miniredis.RunT(t) - defer s.Close() - - store, err := New(s.Addr(), "") - require.NoError(t, err) - - ctx := context.Background() - - t.Run("Save and Load Session", func(t *testing.T) { - state := &session.State{ - SessionID: "sess-123", - ClusterID: "clus-456", - } - state.SetExpiration(1 * time.Hour) - - err := store.Save(ctx, state) - require.NoError(t, err) - - loaded, err := store.Load(ctx, "sess-123") - require.NoError(t, err) - require.Equal(t, "clus-456", loaded.ClusterID) - }) - - t.Run("Load nonexistent Session", func(t *testing.T) { - _, err := store.Load(ctx, "sess-nonexistent") - require.ErrorIs(t, err, session.ErrSessionNotFound) - }) - - t.Run("Delete Session", func(t *testing.T) { - state := &session.State{ - SessionID: "sess-delete-123", - } - err := store.Save(ctx, state) - require.NoError(t, err) - - err = store.Delete(ctx, "sess-delete-123") - require.NoError(t, err) - - _, err = store.Load(ctx, "sess-delete-123") - require.ErrorIs(t, err, session.ErrSessionNotFound) - }) - - t.Run("Save and Load PKCE", func(t *testing.T) { - err := store.SavePKCEVerifier(ctx, "sess-pkce", "my-verifier") - require.NoError(t, err) - - val, err := store.LoadAndDeletePKCEVerifier(ctx, "sess-pkce") - require.NoError(t, err) - require.Equal(t, "my-verifier", val) - - _, err = store.LoadAndDeletePKCEVerifier(ctx, "sess-pkce") - require.ErrorIs(t, err, session.ErrPKCEVerifierNotFound) - }) - - t.Run("Save Expired Session should not store", func(t *testing.T) { - state := &session.State{ - SessionID: "sess-expired", - } - - state.SetExpiration(-1 * time.Hour) - - err := store.Save(ctx, state) - require.NoError(t, err) - - _, err = store.Load(ctx, "sess-expired") - require.ErrorIs(t, err, session.ErrSessionNotFound) - }) -} diff --git a/backend/session/session.go b/backend/session/session.go deleted file mode 100644 index 4ab0d5e38..000000000 --- a/backend/session/session.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 session - -import ( - "time" - - "github.com/vmihailenco/msgpack/v4" -) - -// State is the data stored on the clientside as a browser cookie. -// To be independent of the OIDC token sizes, it only stores the absolute minimum -// information required for this particular backend implementation. Especially -// when lots of groups and claims are involved, the tokens can grow to a size -// larger than allowed by browsers for cookies, and even compression would only -// be a small adhesive strip, not a solution. -type State struct { - Token TokenInfo `msgpack:"tok,omitempty"` - SessionID string `msgpack:"sid,omitempty"` - ClusterID string `msgpack:"cid,omitempty"` - RedirectURL string `msgpack:"red,omitempty"` - CreatedAt time.Time `msgpack:"cat,omitempty"` - ExpiresAt time.Time `msgpack:"eat,omitempty"` -} - -type TokenInfo struct { - Subject string `msgpack:"sub,omitempty"` - Issuer string `msgpack:"iss,omitempty"` - Groups []string `msgpack:"grp,omitempty"` -} - -func (s *State) Encode() ([]byte, error) { - return msgpack.Marshal(s) -} - -// IsExpired checks if the session has expired -func (s *State) IsExpired() bool { - return s.ExpiresAt.IsZero() || time.Now().After(s.ExpiresAt) -} - -// SetExpiration sets the session expiration time -func (s *State) SetExpiration(duration time.Duration) { - s.CreatedAt = time.Now() - s.ExpiresAt = s.CreatedAt.Add(duration) -} diff --git a/backend/spaserver/spaserver.go b/backend/spaserver/spaserver.go deleted file mode 100644 index 92dbb9c33..000000000 --- a/backend/spaserver/spaserver.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 spaserver - -import ( - "net/http" - "net/http/httputil" - "net/url" - "os" - "path/filepath" - "strings" -) - -type SPAFileServer struct { - fileSystem http.FileSystem - fileServer http.Handler -} - -func NewSPAFileServer(fileSystem http.FileSystem) *SPAFileServer { - return &SPAFileServer{ - fileSystem: fileSystem, - fileServer: http.FileServer(fileSystem), - } -} - -func (s *SPAFileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - path, err := filepath.Abs(r.URL.Path) - if err != nil { - http.Error(w, "Bad request", http.StatusBadRequest) - return - } - - // Try to serve the file directly first - if f, err := s.fileSystem.Open(path); err == nil { - if err = f.Close(); err != nil { - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - s.fileServer.ServeHTTP(w, r) - return - } else if !os.IsNotExist(err) { - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - - // File not found - check if it's a static asset - if isStaticAsset(path) { - if f, err := s.fileSystem.Open(path); err == nil { - if err = f.Close(); err != nil { - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - return - } - r.URL.Path = path - s.fileServer.ServeHTTP(w, r) - return - } - // Asset not found even with clean path, return 404 - http.NotFound(w, r) - return - } - - // For navigation routes, serve index.html - r.URL.Path = "/" - s.fileServer.ServeHTTP(w, r) -} - -// isStaticAsset checks if the path is for a static asset. -func isStaticAsset(path string) bool { - return strings.Contains(path, "/assets/") || - strings.HasSuffix(path, ".js") || - strings.HasSuffix(path, ".css") || - strings.HasSuffix(path, ".png") || - strings.HasSuffix(path, ".jpg") || - strings.HasSuffix(path, ".jpeg") || - strings.HasSuffix(path, ".gif") || - strings.HasSuffix(path, ".svg") || - strings.HasSuffix(path, ".ico") || - strings.HasSuffix(path, ".woff") || - strings.HasSuffix(path, ".woff2") || - strings.HasSuffix(path, ".ttf") || - strings.HasSuffix(path, ".eot") -} - -// SPAReverseProxyServer is used for local development or in theory it could be used. -type SPAReverseProxyServer struct { - reverseProxy *httputil.ReverseProxy -} - -func NewSPAReverseProxyServer(frontend string) (*SPAReverseProxyServer, error) { - u, err := url.Parse(frontend) - if err != nil { - return nil, err - } - - return &SPAReverseProxyServer{ - reverseProxy: httputil.NewSingleHostReverseProxy(u), - }, nil -} - -func (s *SPAReverseProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { - s.reverseProxy.ServeHTTP(w, r) -} diff --git a/backend/template/files.go b/backend/template/files.go deleted file mode 100644 index 96179b5d9..000000000 --- a/backend/template/files.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 template - -import ( - "embed" -) - -//go:embed * -var Files embed.FS diff --git a/backend/template/icon/github-icon.svg b/backend/template/icon/github-icon.svg deleted file mode 100644 index 5d6072823..000000000 --- a/backend/template/icon/github-icon.svg +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/backend/template/icon/google-icon.svg b/backend/template/icon/google-icon.svg deleted file mode 100644 index d667afdf5..000000000 --- a/backend/template/icon/google-icon.svg +++ /dev/null @@ -1,16 +0,0 @@ - - - - logo_googleg_48dp - Created with Sketch. - - - - - - - - - - - \ No newline at end of file diff --git a/backend/template/icon/microsoft-icon.svg b/backend/template/icon/microsoft-icon.svg deleted file mode 100644 index 739c395ab..000000000 --- a/backend/template/icon/microsoft-icon.svg +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/backend/template/resources.gohtml b/backend/template/resources.gohtml deleted file mode 100644 index 67db1f76a..000000000 --- a/backend/template/resources.gohtml +++ /dev/null @@ -1,232 +0,0 @@ - - - - - - - - - - - - - Services - Kube Bind - - - -
- - -
- {{range $serviceIdx, $schema := .Schemas}} -
-
-
-
{{$schema.Name}}
- {{if $schema.Description}}{{$schema.Description}}{{end}} -
-
    -
  • - Scope: {{$schema.Scope}} -
  • -
  • - Resources ({{len $schema.Resources}}): -
    - {{range $schema.Resources}} - {{.Resource}}.{{.Group}} - {{end}} -
    -
  • - {{if $schema.PermissionClaims}} -
  • - Permissions ({{len $schema.PermissionClaims}}): - {{range $i, $claim := $schema.PermissionClaims}} -
    - - {{$claim.Resource}}{{if $claim.Group}}.{{$claim.Group}}{{end}} - {{if $claim.Selector.NamedResources}} ({{len $claim.Selector.NamedResources}}){{end}} - {{if $claim.Selector.LabelSelector}} (labels){{end}} - - {{if or $claim.Selector.NamedResources $claim.Selector.LabelSelector}} -
    - -
    - {{if $claim.Selector.NamedResources}} -
    - Named: - {{range $claim.Selector.NamedResources}} -
    {{.Name}}{{if .Namespace}} ({{.Namespace}}){{end}} - {{end}} -
    - {{end}} - {{if $claim.Selector.LabelSelector}} -
    - Labels: - {{if $claim.Selector.LabelSelector.MatchLabels}} - {{range $key, $value := $claim.Selector.LabelSelector.MatchLabels}} -
    {{$key}}: {{$value}} - {{end}} - {{end}} - {{if $claim.Selector.LabelSelector.MatchExpressions}} - {{range $claim.Selector.LabelSelector.MatchExpressions}} -
    {{.Key}} {{.Operator}} {{range $idx, $val := .Values}}{{if $idx}}, {{end}}{{$val}}{{end}} - {{end}} - {{end}} -
    - {{end}} -
    - {{end}} -
    - {{end}} -
  • - {{end}} - {{if $schema.Namespaces}} -
  • - Namespaces ({{len $schema.Namespaces}}): -
    - {{range $schema.Namespaces}} - {{.Name}} - {{end}} -
    -
  • - {{end}} -
- -
-
- {{end}} -
-
- - - - - diff --git a/backend/template/styles.css b/backend/template/styles.css deleted file mode 100644 index 743b6fe99..000000000 --- a/backend/template/styles.css +++ /dev/null @@ -1,252 +0,0 @@ - -@import url('https://fonts.googleapis.com/css?family=Montserrat:400,800'); - -* { - box-sizing: border-box; -} - -body { - background: #f6f5f7; - display: flex; - justify-content: center; - align-items: center; - flex-direction: column; - font-family: 'Montserrat', sans-serif; - height: 100vh; - margin: -20px 0 50px; -} - -h1 { - font-weight: bold; - margin: 0; -} - -h2 { - text-align: center; -} - -p { - font-size: 14px; - font-weight: 100; - line-height: 20px; - letter-spacing: 0.5px; - margin: 20px 0 30px; -} - -span { - font-size: 12px; -} - -a { - color: #333; - font-size: 14px; - text-decoration: none; - margin: 15px 0; -} - -button { - border-radius: 20px; - border: 1px solid #138D75; - background-color: #138D75; - color: #FFFFFF; - font-size: 12px; - font-weight: bold; - padding: 12px 45px; - letter-spacing: 1px; - text-transform: uppercase; - transition: transform 80ms ease-in; -} - -button:active { - transform: scale(0.95); -} - -button:focus { - outline: none; -} - -button.ghost { - background-color: transparent; - border-color: #FFFFFF; -} - -form { - background-color: #FFFFFF; - display: flex; - align-items: center; - justify-content: center; - flex-direction: column; - padding: 0 50px; - height: 100%; - text-align: center; -} - -input { - background-color: #eee; - border: none; - padding: 12px 15px; - margin: 8px 0; - width: 100%; -} - -.container { - background-color: #fff; - border-radius: 10px; - box-shadow: 0 14px 28px rgba(0,0,0,0.25), - 0 10px 10px rgba(0,0,0,0.22); - position: relative; - overflow: hidden; - width: 768px; - max-width: 100%; - min-height: 480px; -} - -.form-container { - position: absolute; - top: 0; - height: 100%; - transition: all 0.6s ease-in-out; -} - -.sign-in-container { - left: 0; - width: 50%; - z-index: 2; -} - -.container.right-panel-active .sign-in-container { - transform: translateX(100%); -} - -.right-side-container { - left: 0; - width: 50%; - opacity: 0; - z-index: 1; -} - -.container.right-panel-active .right-side-container { - transform: translateX(100%); - opacity: 1; - z-index: 5; - animation: show 0.6s; -} - -@keyframes show { - 0%, 49.99% { - opacity: 0; - z-index: 1; - } - - 50%, 100% { - opacity: 1; - z-index: 5; - } -} - -.overlay-container { - position: absolute; - top: 0; - left: 50%; - width: 50%; - height: 100%; - overflow: hidden; - transition: transform 0.6s ease-in-out; - z-index: 100; -} - -.container.right-panel-active .overlay-container{ - transform: translateX(-100%); -} - -.overlay { - background: #0B5345; - /*background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);*/ - /*background: linear-gradient(to right, #FF4B2B, #FF416C);*/ - background-repeat: no-repeat; - background-size: cover; - background-position: 0 0; - color: #FFFFFF; - position: relative; - left: -100%; - height: 100%; - width: 200%; - transform: translateX(0); - transition: transform 0.6s ease-in-out; -} - -.container.right-panel-active .overlay { - transform: translateX(50%); -} - -.overlay-panel { - position: absolute; - display: flex; - align-items: center; - justify-content: center; - flex-direction: column; - padding: 0 40px; - text-align: center; - top: 0; - height: 100%; - width: 50%; - transform: translateX(0); - transition: transform 0.6s ease-in-out; -} - -.overlay-left { - transform: translateX(-20%); -} - -.container.right-panel-active .overlay-left { - transform: translateX(0); -} - -.overlay-right { - right: 0; - transform: translateX(0); -} - -.container.right-panel-active .overlay-right { - transform: translateX(20%); -} - -.social-container { - margin: 20px 0; -} - -.social-container a { - border: 0px solid #DDDDDD; - border-radius: 50%; - display: inline-flex; - justify-content: center; - align-items: center; - margin: 0 5px; - height: 40px; - width: 40px; -} - -footer { - background-color: #222; - color: #fff; - font-size: 14px; - bottom: 0; - position: fixed; - left: 0; - right: 0; - text-align: center; - z-index: 999; -} - -footer p { - margin: 10px 0; -} - -footer i { - color: red; -} - -footer a { - color: #3c97bf; - text-decoration: none; -} \ No newline at end of file diff --git a/cli/client.go b/cli/client.go new file mode 100644 index 000000000..165b4ac69 --- /dev/null +++ b/cli/client.go @@ -0,0 +1,177 @@ +/* +Copyright 2026 The kbind 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 cli + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" + + "github.com/kbind/kbind/backend/gateway/api" +) + +// ErrLoginRequired asks the user to run bind login. +var ErrLoginRequired = errors.New("not logged in to this gateway — run: kubectl bind login ") + +// Client talks to one gateway. +type Client struct { + // Server is the gateway base URL. + Server string + // Token is the session bearer token (empty = unauthenticated). + Token string + + HTTP *http.Client +} + +// NewClient builds a gateway client. +func NewClient(server, token string) *Client { + return &Client{ + Server: server, + Token: token, + HTTP: &http.Client{Timeout: 60 * time.Second}, + } +} + +func (c *Client) do(ctx context.Context, method, path string, body, out any) error { + var reader io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return err + } + reader = bytes.NewReader(data) + } + req, err := http.NewRequestWithContext(ctx, method, c.Server+path, reader) + if err != nil { + return err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.Token != "" { + req.Header.Set("Authorization", "Bearer "+c.Token) + } + res, err := c.HTTP.Do(req) + if err != nil { + return err + } + defer func() { _ = res.Body.Close() }() + + if res.StatusCode == http.StatusUnauthorized { + return ErrLoginRequired + } + data, err := io.ReadAll(res.Body) + if err != nil { + return err + } + if res.StatusCode/100 != 2 { + var apiErr api.Error + if json.Unmarshal(data, &apiErr) == nil && apiErr.Error != "" { + return errors.New(apiErr.Error) + } + return fmt.Errorf("%s %s: %s", method, path, res.Status) + } + if out != nil { + return json.Unmarshal(data, out) + } + return nil +} + +// Provider fetches gateway metadata (no auth needed). +func (c *Client) Provider(ctx context.Context) (*api.Provider, error) { + var p api.Provider + if err := c.do(ctx, http.MethodGet, "/api/provider", nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// Catalog fetches the visible exports and collections. +func (c *Client) Catalog(ctx context.Context) (*api.Catalog, error) { + var cat api.Catalog + if err := c.do(ctx, http.MethodGet, "/api/catalog", nil, &cat); err != nil { + return nil, err + } + return &cat, nil +} + +// Clusters fetches the consumer clusters known from konnector heartbeats. +func (c *Client) Clusters(ctx context.Context) (*api.Clusters, error) { + var clusters api.Clusters + if err := c.do(ctx, http.MethodGet, "/api/clusters", nil, &clusters); err != nil { + return nil, err + } + return &clusters, nil +} + +// Instances fetches the provider-side objects synced under one catalog item. +func (c *Client) Instances(ctx context.Context, export string) (*api.ExportInstances, error) { + var instances api.ExportInstances + if err := c.do(ctx, http.MethodGet, "/api/catalog/"+url.PathEscape(export)+"/instances", nil, &instances); err != nil { + return nil, err + } + return &instances, nil +} + +// Bind requests a binding and returns the pickup handle. +func (c *Client) Bind(ctx context.Context, export string) (*api.BindResponse, error) { + var res api.BindResponse + if err := c.do(ctx, http.MethodPost, "/api/bind", api.BindRequest{Export: export}, &res); err != nil { + return nil, err + } + return &res, nil +} + +// Pickup redeems a one-time pickup URL and returns the literal YAML bundle. +func (c *Client) Pickup(ctx context.Context, pickupURL string) ([]byte, error) { + u, err := url.Parse(pickupURL) + if err != nil { + return nil, err + } + full := pickupURL + if !u.IsAbs() { + full = c.Server + pickupURL + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, full, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/yaml") + res, err := c.HTTP.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = res.Body.Close() }() + data, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + if res.StatusCode/100 != 2 { + var apiErr api.Error + if json.Unmarshal(data, &apiErr) == nil && apiErr.Error != "" { + return nil, errors.New(apiErr.Error) + } + return nil, fmt.Errorf("bundle pickup: %s", res.Status) + } + return data, nil +} diff --git a/cli/cmd/bind.go b/cli/cmd/bind.go new file mode 100644 index 000000000..7740324cb --- /dev/null +++ b/cli/cmd/bind.go @@ -0,0 +1,127 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + + "github.com/kbind/kbind/backend/issuer" + "github.com/kbind/kbind/pkg/konnectorinstall" + "github.com/kbind/kbind/pkg/kubeapply" +) + +// newExportCmd binds a catalog Export: `kubectl bind export ` fetches +// the one-apply bundle and applies it (or prints it with -o yaml). +func newExportCmd() *cobra.Command { + var ( + output string + kubeconfig string + installKonnector bool + konnectorImage string + ) + cmd := &cobra.Command{ + Use: "export ", + Short: "Bind a catalog Export: fetch the one-apply bundle and apply it", + Long: `Bind requests credentials for an Export, picks up the one-apply bundle +(Secret + Connection + ClusterBinding) and applies it to your current cluster. + +With -o yaml the bundle is printed instead of applied — commit it to git and +your GitOps pipeline is the client (the credentials inside stay valid until +the provider revokes the grant).`, + Args: cobra.ExactArgs(1), + } + cmd.RunE = func(cmd *cobra.Command, args []string) error { + client, _, err := resolveClient() + if err != nil { + return err + } + + res, err := client.Bind(cmd.Context(), args[0]) + if err != nil { + return err + } + bundle, err := client.Pickup(cmd.Context(), res.PickupURL) + if err != nil { + return err + } + + if output == "yaml" { + _, err = cmd.OutOrStdout().Write(bundle) + return err + } + if output != "" { + return fmt.Errorf("unsupported output format %q (only yaml)", output) + } + + cfg, err := consumerRestConfig(kubeconfig) + if err != nil { + return err + } + if installKonnector { + if _, err := konnectorinstall.Apply(cmd.Context(), cfg, konnectorImage); err != nil { + return err + } + fmt.Fprintln(cmd.OutOrStdout(), "konnector installed") + } + applied, err := applyBundle(cmd.Context(), cfg, bundle, !installKonnector) + if err != nil { + return err + } + for _, a := range applied { + fmt.Fprintf(cmd.OutOrStdout(), "applied %s\n", a) + } + fmt.Fprintf(cmd.OutOrStdout(), "bound %s — watch it: kubectl get connections,clusterbindings\n", args[0]) + return nil + } + cmd.Flags().StringVarP(&output, "output", "o", "", "print the bundle instead of applying (yaml)") + cmd.Flags().StringVar(&kubeconfig, "kubeconfig", "", "consumer cluster kubeconfig (default: usual kubectl resolution)") + cmd.Flags().BoolVar(&installKonnector, "install-konnector", true, "install/upgrade the konnector before applying the bundle") + cmd.Flags().StringVar(&konnectorImage, "konnector-image", konnectorinstall.DefaultImage, "konnector image to install") + return cmd +} + +// consumerRestConfig resolves the consumer cluster the way kubectl would. +func consumerRestConfig(explicit string) (*rest.Config, error) { + rules := clientcmd.NewDefaultClientConfigLoadingRules() + if explicit != "" { + rules.ExplicitPath = explicit + } + return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{}).ClientConfig() +} + +// applyBundle applies the YAML bundle; ensureNamespace also creates the +// konnector namespace (needed when the konnector install was skipped). +func applyBundle(ctx context.Context, cfg *rest.Config, bundle []byte, ensureNamespace bool) ([]string, error) { + objs, err := kubeapply.DecodeYAML(bundle) + if err != nil { + return nil, err + } + if ensureNamespace { + objs = append([]*unstructured.Unstructured{kubeapply.NamespaceObject(issuer.KonnectorNamespace)}, objs...) + } + applier, err := kubeapply.New(cfg, "kbind-cli") + if err != nil { + return nil, err + } + return applier.Apply(ctx, objs) +} diff --git a/cli/cmd/catalog.go b/cli/cmd/catalog.go new file mode 100644 index 000000000..7a33a10da --- /dev/null +++ b/cli/cmd/catalog.go @@ -0,0 +1,62 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "fmt" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" +) + +func newCatalogCmd() *cobra.Command { + return &cobra.Command{ + Use: "catalog", + Short: "List the provider's offerings (Exports and Collections)", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, _, err := resolveClient() + if err != nil { + return err + } + catalog, err := client.Catalog(cmd.Context()) + if err != nil { + return err + } + if len(catalog.Exports) == 0 { + fmt.Fprintln(cmd.OutOrStdout(), "The catalog is empty.") + return nil + } + + collectionsOf := map[string][]string{} + for _, col := range catalog.Collections { + for _, name := range col.Exports { + collectionsOf[name] = append(collectionsOf[name], col.Title) + } + } + + w := tabwriter.NewWriter(cmd.OutOrStdout(), 2, 8, 2, ' ', 0) + fmt.Fprintln(w, "NAME\tTITLE\tAPIS\tCOLLECTIONS") + for _, e := range catalog.Exports { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", + e.Name, e.Title, strings.Join(e.APIs, ","), strings.Join(collectionsOf[e.Name], ",")) + } + return w.Flush() + }, + } +} diff --git a/cli/cmd/clusters.go b/cli/cmd/clusters.go new file mode 100644 index 000000000..5f1bdb126 --- /dev/null +++ b/cli/cmd/clusters.go @@ -0,0 +1,99 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "fmt" + "strings" + "text/tabwriter" + "time" + + "github.com/spf13/cobra" + + "github.com/kbind/kbind/backend/gateway/api" +) + +func newClustersCmd() *cobra.Command { + return &cobra.Command{ + Use: "clusters", + Short: "List the consumer clusters connected to this provider", + Long: `Clusters shows which consumer clusters are heartbeating against the +provider (from the konnector's Leases), what each has bound, and how many +objects it is syncing.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + client, _, err := resolveClient() + if err != nil { + return err + } + clusters, err := client.Clusters(cmd.Context()) + if err != nil { + return err + } + if len(clusters.Clusters) == 0 && len(clusters.Pending) == 0 { + fmt.Fprintln(cmd.OutOrStdout(), "No consumer clusters yet.") + return nil + } + + w := tabwriter.NewWriter(cmd.OutOrStdout(), 2, 8, 2, ' ', 0) + fmt.Fprintln(w, "CLUSTER\tSTATUS\tEXPORT\tIDENTITY\tHEARTBEAT\tSYNCED") + for _, cluster := range clusters.Clusters { + for _, b := range cluster.Bindings { + status := "Live" + if !b.Live { + status = "Stale" + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", + shortUID(cluster.UID), status, b.Export, b.Identity, + ago(b.LastHeartbeat), syncedSummary(b.APIs)) + } + } + for _, p := range clusters.Pending { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", + "-", "NeverConnected", p.Export, p.Identity, "bound "+ago(p.CreatedAt), "-") + } + return w.Flush() + }, + } +} + +func shortUID(uid string) string { + if len(uid) > 13 { + return uid[:13] + } + return uid +} + +func ago(t time.Time) string { + d := time.Since(t) + switch { + case d < 90*time.Second: + return fmt.Sprintf("%ds ago", int(d.Seconds())) + case d < 90*time.Minute: + return fmt.Sprintf("%dm ago", int(d.Minutes())) + default: + return fmt.Sprintf("%dh ago", int(d.Hours())) + } +} + +func syncedSummary(apis []api.SyncedAPI) string { + parts := make([]string, 0, len(apis)) + for _, a := range apis { + parts = append(parts, fmt.Sprintf("%s=%d", a.Name, a.SyncedCount)) + } + return strings.Join(parts, ",") +} diff --git a/cli/cmd/connect.go b/cli/cmd/connect.go new file mode 100644 index 000000000..c3e9e72e9 --- /dev/null +++ b/cli/cmd/connect.go @@ -0,0 +1,60 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/kbind/kbind/pkg/konnectorinstall" +) + +func newConnectCmd() *cobra.Command { + var ( + kubeconfig string + konnectorImage string + ) + cmd := &cobra.Command{ + Use: "connect", + Short: "Connect a cluster: install/upgrade the konnector", + Long: `Connect installs the konnector (CRDs, RBAC, Deployment) into your current +cluster — the only kbind component that ever runs on the consumer side. Bind +services afterwards with "kubectl bind export ". + +Reproducible by hand: curl -fsS /api/konnector | kubectl apply -f -`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + cfg, err := consumerRestConfig(kubeconfig) + if err != nil { + return err + } + applied, err := konnectorinstall.Apply(cmd.Context(), cfg, konnectorImage) + if err != nil { + return err + } + for _, a := range applied { + fmt.Fprintf(cmd.OutOrStdout(), "applied %s\n", a) + } + fmt.Fprintln(cmd.OutOrStdout(), "konnector installed — bind a service: kubectl bind export ") + return nil + }, + } + cmd.Flags().StringVar(&kubeconfig, "kubeconfig", "", "consumer cluster kubeconfig (default: usual kubectl resolution)") + cmd.Flags().StringVar(&konnectorImage, "konnector-image", konnectorinstall.DefaultImage, "konnector image to install") + return cmd +} diff --git a/cli/cmd/instances.go b/cli/cmd/instances.go new file mode 100644 index 000000000..5a93c60dc --- /dev/null +++ b/cli/cmd/instances.go @@ -0,0 +1,75 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "fmt" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" +) + +func newInstancesCmd() *cobra.Command { + return &cobra.Command{ + Use: "instances [export]", + Short: "List the objects consumers synced under a catalog item (all items when omitted)", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client, _, err := resolveClient() + if err != nil { + return err + } + + // No export named: sweep the whole catalog. + exports := args + if len(exports) == 0 { + catalog, err := client.Catalog(cmd.Context()) + if err != nil { + return err + } + for _, e := range catalog.Exports { + exports = append(exports, e.Name) + } + if len(exports) == 0 { + fmt.Fprintln(cmd.OutOrStdout(), "The catalog is empty.") + return nil + } + } + + w := tabwriter.NewWriter(cmd.OutOrStdout(), 2, 8, 2, ' ', 0) + fmt.Fprintln(w, "EXPORT\tAPI\tNAMESPACE\tNAME\tCLUSTER\tIDENTITY\tAGE") + total := 0 + for _, export := range exports { + res, err := client.Instances(cmd.Context(), export) + if err != nil { + return err + } + for _, inst := range res.Instances { + total++ + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", + export, inst.API, inst.Namespace, inst.Name, shortUID(inst.ClusterUID), inst.Identity, ago(inst.CreatedAt)) + } + } + if total == 0 { + fmt.Fprintf(cmd.OutOrStdout(), "Nothing synced under %s yet.\n", strings.Join(exports, ", ")) + return nil + } + return w.Flush() + }, + } +} diff --git a/cli/cmd/kubectl-bind/cmd/kubectlBind.go b/cli/cmd/kubectl-bind/cmd/kubectlBind.go deleted file mode 100644 index 4140a784f..000000000 --- a/cli/cmd/kubectl-bind/cmd/kubectlBind.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2024 The Kube Bind 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 cmd - -import ( - goflags "flag" - "fmt" - "os" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/component-base/version" - "k8s.io/klog/v2" - - apiservicecmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/cmd" - collectionscmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-collections/cmd" - deploycmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-deploy/cmd" - logincmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-login/cmd" - templatescmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-templates/cmd" - bindcmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind/cmd" - clusteridentitycmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/cluster-identity/cmd" - devcmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/dev/cmd" -) - -func KubectlBindCommand() *cobra.Command { - rootCmd, err := bindcmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - // setup klog - fs := goflags.NewFlagSet("klog", goflags.PanicOnError) - klog.InitFlags(fs) - rootCmd.PersistentFlags().AddGoFlagSet(fs) - - if v := version.Get().String(); len(v) == 0 { - rootCmd.Version = "" - } else { - rootCmd.Version = v - } - - apiserviceCmd, err := apiservicecmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(apiserviceCmd) - - deployCmd, err := deploycmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(deployCmd) - - loginCmd, err := logincmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(loginCmd) - - templatesCmd, err := templatescmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(templatesCmd) - - collectionsCmd, err := collectionscmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(collectionsCmd) - - devCmd, err := devcmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(devCmd) - - clusterIdentityCmd, err := clusteridentitycmd.New(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v", err) - os.Exit(1) - } - rootCmd.AddCommand(clusterIdentityCmd) - - return rootCmd -} diff --git a/cli/cmd/kubectl-bind/cmd/kubectlBind_test.go b/cli/cmd/kubectl-bind/cmd/kubectlBind_test.go deleted file mode 100644 index c937e46c3..000000000 --- a/cli/cmd/kubectl-bind/cmd/kubectlBind_test.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - bindcmd "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind/cmd" -) - -func TestKubectlBindCommand(t *testing.T) { - rootCmd := KubectlBindCommand() - - require.Equal(t, "kubectl-bind", rootCmd.Use, "Unexpected one-line command description") - require.Equal(t, "kubectl plugin for kube-bind, bind different remote types into the current cluster.", rootCmd.Short, "Unexpected short command description") - require.Contains(t, rootCmd.Long, "To bind a remote service, use the 'kubectl bind' command.", "Unexpected long command") - require.Equal(t, rootCmd.Example, fmt.Sprintf(bindcmd.BindExampleUses, "kubectl"), "Unexpected command Example") -} - -func TestKubectlBindArgs(t *testing.T) { - tests := []struct { - name string - args []string - wantErr bool - }{ - {"Valid URL", []string{"https://example.com"}, false}, - {"Invalid argument", []string{"invalid-arg"}, true}, - {"Mixed valid and invalid", []string{"https://example.com", "invalid-arg"}, true}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - rootCmd := KubectlBindCommand() - err := rootCmd.Args(rootCmd, tt.args) - if tt.wantErr { - require.Error(t, err, "Expected error but got none") - } else { - require.NoError(t, err, "Unexpected error") - } - }) - } -} diff --git a/cli/cmd/login.go b/cli/cmd/login.go new file mode 100644 index 000000000..846915d88 --- /dev/null +++ b/cli/cmd/login.go @@ -0,0 +1,66 @@ +/* +Copyright 2026 The kbind 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 cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/kbind/kbind/cli" +) + +func newLoginCmd() *cobra.Command { + var noBrowser bool + cmd := &cobra.Command{ + Use: "login ", + Short: "Authenticate against a kbind gateway and cache the session", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + server := cli.NormalizeServer(args[0]) + + // Surface the provider before the dance, so a typo'd URL fails fast. + probe := cli.NewClient(server, "") + provider, err := probe.Provider(cmd.Context()) + if err != nil { + return fmt.Errorf("reaching gateway %s: %w", server, err) + } + fmt.Fprintf(cmd.OutOrStdout(), "Logging in to %s (%s)\n", provider.Name, server) + + token, err := cli.Login(cmd.Context(), server, !noBrowser, func(msg string) { + fmt.Fprintln(cmd.OutOrStdout(), msg) + }) + if err != nil { + return err + } + + cfg, err := cli.LoadConfig() + if err != nil { + return err + } + cfg.Server = server + cfg.Tokens[server] = token + if err := cfg.Save(); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Logged in. Try: kubectl bind catalog\n") + return nil + }, + } + cmd.Flags().BoolVar(&noBrowser, "no-browser", false, "print the login URL instead of opening a browser") + return cmd +} diff --git a/cli/cmd/root.go b/cli/cmd/root.go new file mode 100644 index 000000000..96d6a424b --- /dev/null +++ b/cli/cmd/root.go @@ -0,0 +1,71 @@ +/* +Copyright 2026 The kbind 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 cmd wires the bind CLI commands. +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/kbind/kbind/cli" +) + +// Version is stamped via -ldflags at release time. +var Version = "dev" + +var serverFlag string + +// New builds the bind root command. Binding an export IS the root command +// (`kubectl bind `); everything else is a subcommand. +func New() *cobra.Command { + root := &cobra.Command{ + Use: "bind", + Short: "Bind a provider's APIs into your cluster", + Long: `bind is a thin client over a kbind gateway. Everything it does is +reproducible by hand: binding returns a one-apply YAML bundle that a plain +"kubectl apply -f" (or GitOps) consumes just as well. + + kubectl bind login https://provider.example.com + kubectl bind connect # install the konnector + kubectl bind catalog + kubectl bind export mangodb # bind a service + kubectl bind export mangodb -o yaml # GitOps mode: print, don't apply`, + Version: Version, + SilenceUsage: true, + SilenceErrors: true, + } + root.PersistentFlags().StringVar(&serverFlag, "server", "", "gateway base URL (default: the last login)") + root.AddCommand(newLoginCmd(), newConnectCmd(), newCatalogCmd(), newExportCmd(), newClustersCmd(), newInstancesCmd()) + return root +} + +// resolveClient builds a gateway client from --server / stored config. +func resolveClient() (*cli.Client, *cli.Config, error) { + cfg, err := cli.LoadConfig() + if err != nil { + return nil, nil, err + } + server := cli.NormalizeServer(serverFlag) + if server == "" { + server = cfg.Server + } + if server == "" { + return nil, nil, fmt.Errorf("no gateway configured — run: kubectl bind login ") + } + return cli.NewClient(server, cfg.Tokens[server]), cfg, nil +} diff --git a/cli/config.go b/cli/config.go new file mode 100644 index 000000000..8c1d71517 --- /dev/null +++ b/cli/config.go @@ -0,0 +1,95 @@ +/* +Copyright 2026 The kbind 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 cli implements the bind CLI: a thin client over the gateway. +// Everything it does is reproducible by hand with curl + kubectl. +package cli + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Config is the CLI's stored state: the current gateway and a session token +// per gateway. +type Config struct { + // Server is the current gateway base URL. + Server string `json:"server,omitempty"` + // Tokens maps gateway base URLs to session bearer tokens. + Tokens map[string]string `json:"tokens,omitempty"` +} + +// configPath is ~/.config/kbind/config.json (or the platform equivalent). +func configPath() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "kbind", "config.json"), nil +} + +// LoadConfig reads the CLI config; a missing file is an empty config. +func LoadConfig() (*Config, error) { + path, err := configPath() + if err != nil { + return nil, err + } + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + return &Config{Tokens: map[string]string{}}, nil + } + if err != nil { + return nil, err + } + var cfg Config + if err := json.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("parsing %s: %w", path, err) + } + if cfg.Tokens == nil { + cfg.Tokens = map[string]string{} + } + return &cfg, nil +} + +// Save writes the config (0600 — it holds session tokens). +func (c *Config) Save() error { + path, err := configPath() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + return os.WriteFile(path, data, 0o600) +} + +// NormalizeServer canonicalizes a gateway URL flag/arg. +func NormalizeServer(server string) string { + server = strings.TrimSuffix(strings.TrimSpace(server), "/") + // Tolerate a pasted API URL: the base is the gateway root. + server = strings.TrimSuffix(server, "/api") + if server != "" && !strings.Contains(server, "://") { + server = "https://" + server + } + return server +} diff --git a/cli/go.mod b/cli/go.mod deleted file mode 100644 index 59509958e..000000000 --- a/cli/go.mod +++ /dev/null @@ -1,163 +0,0 @@ -module github.com/kube-bind/kube-bind/cli - -go 1.26.9 - -replace ( - github.com/kube-bind/kube-bind => ../ - github.com/kube-bind/kube-bind/sdk => ../sdk -) - -require ( - github.com/MakeNowJust/heredoc v1.0.0 - github.com/blang/semver/v4 v4.0.0 - github.com/fatih/color v1.19.0 - github.com/kube-bind/kube-bind v0.7.1 - github.com/kube-bind/kube-bind/sdk v0.7.1 - github.com/moby/moby/client v0.4.1 - github.com/muesli/reflow v0.3.0 - github.com/spf13/cobra v1.10.2 - github.com/spf13/pflag v1.0.10 - github.com/stretchr/testify v1.11.1 - helm.sh/helm/v3 v3.20.2 - k8s.io/api v0.36.0 - k8s.io/apiextensions-apiserver v0.35.1 - k8s.io/apimachinery v0.36.0 - k8s.io/cli-runtime v0.36.0 - k8s.io/client-go v0.36.0 - k8s.io/component-base v0.36.0 - k8s.io/klog/v2 v2.140.0 - sigs.k8s.io/controller-runtime v0.23.3 - sigs.k8s.io/kind v0.31.0 - sigs.k8s.io/yaml v1.6.0 -) - -require ( - al.essio.dev/pkg/shellescape v1.6.0 // indirect - dario.cat/mergo v1.0.2 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/BurntSushi/toml v1.6.0 // indirect - github.com/Masterminds/goutils v1.1.1 // indirect - github.com/Masterminds/semver/v3 v3.4.0 // indirect - github.com/Masterminds/sprig/v3 v3.3.0 // indirect - github.com/Masterminds/squirrel v1.5.4 // indirect - github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/chai2010/gettext-go v1.0.3 // indirect - github.com/clipperhouse/uax29/v2 v2.7.0 // indirect - github.com/containerd/containerd v1.7.36 // indirect - github.com/containerd/errdefs v1.0.0 // indirect - github.com/containerd/errdefs/pkg v0.3.0 // indirect - github.com/containerd/log v0.1.0 // indirect - github.com/containerd/platforms v0.2.1 // indirect - github.com/cyphar/filepath-securejoin v0.6.1 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/distribution/reference v0.6.0 // indirect - github.com/docker/go-connections v0.7.0 // indirect - github.com/docker/go-units v0.5.0 // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch v5.9.11+incompatible // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect - github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-errors/errors v1.5.1 // indirect - github.com/go-gorp/gorp/v3 v3.1.0 // indirect - github.com/go-logr/logr v1.4.4 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.5 // indirect - github.com/go-openapi/swag v0.26.0 // indirect - github.com/go-openapi/swag/cmdutils v0.26.0 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.26.0 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect - github.com/gobwas/glob v0.2.3 // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/gnostic-models v0.7.1 // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/gosuri/uitable v0.0.4 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/huandu/xstrings v1.5.0 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jmoiron/sqlx v1.4.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.18.5 // indirect - github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect - github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect - github.com/lib/pq v1.12.3 // indirect - github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-isatty v0.0.21 // indirect - github.com/mattn/go-runewidth v0.0.23 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/go-wordwrap v1.0.1 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/moby/moby/api v1.54.2 // indirect - github.com/moby/term v0.5.2 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect - github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/onsi/gomega v1.39.1 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.1 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.20.1 // indirect - github.com/rubenv/sql-migrate v1.8.1 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect - github.com/shopspring/decimal v1.4.0 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect - github.com/spf13/cast v1.10.0 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xlab/treeprint v1.2.0 // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect - go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.23.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/time v0.15.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect - google.golang.org/grpc v1.83.1 // indirect - google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect - gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect - gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - k8s.io/apiserver v0.36.0 // indirect - k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f // indirect - k8s.io/kubectl v0.36.0 // indirect - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 // indirect - oras.land/oras-go/v2 v2.6.2 // indirect - sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect - sigs.k8s.io/kustomize/api v0.21.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect - sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.0 // indirect -) diff --git a/cli/go.sum b/cli/go.sum deleted file mode 100644 index e95e91175..000000000 --- a/cli/go.sum +++ /dev/null @@ -1,463 +0,0 @@ -al.essio.dev/pkg/shellescape v1.6.0 h1:NxFcEqzFSEVCGN2yq7Huv/9hyCEGVa/TncnOOBBeXHA= -al.essio.dev/pkg/shellescape v1.6.0/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= -dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= -dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= -github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= -github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= -github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= -github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= -github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= -github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= -github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= -github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= -github.com/bshuster-repo/logrus-logstash-hook v1.0.0/go.mod h1:zsTqEiSzDgAa/8GZR7E1qaXrhYNDKBYy5/dWPTIflbk= -github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= -github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= -github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chai2010/gettext-go v1.0.3 h1:9liNh8t+u26xl5ddmWLmsOsdNLwkdRTg5AG+JnTiM80= -github.com/chai2010/gettext-go v1.0.3/go.mod h1:y+wnP2cHYaVj19NZhYKAwEMH2CI1gNHeQQ+5AjwawxA= -github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= -github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/containerd/containerd v1.7.36 h1:HyMsOG5kmp1LQsGzqwI6Ts06T4VpYZbszfDZYB0bW5w= -github.com/containerd/containerd v1.7.36/go.mod h1:ozI//0TomTCLPhQREnx0IXDIQMg+Fk7yTtg9fNvU8EQ= -github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= -github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= -github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= -github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= -github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= -github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= -github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= -github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= -github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= -github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= -github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= -github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= -github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE= -github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/distribution/distribution/v3 v3.0.0 h1:q4R8wemdRQDClzoNNStftB2ZAfqOiN6UX90KJc4HjyM= -github.com/distribution/distribution/v3 v3.0.0/go.mod h1:tRNuFoZsUdyRVegq8xGNeds4KLjwLCRin/tTo6i1DhU= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo= -github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M= -github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= -github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= -github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8= -github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= -github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= -github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= -github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= -github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= -github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f h1:Wl78ApPPB2Wvf/TIe2xdyJxTlb6obmF18d8QdkxNDu4= -github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f/go.mod h1:OSYXu++VVOHnXeitef/D8n/6y4QV8uLHSFXX4NeXMGc= -github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= -github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/foxcpp/go-mockdns v1.2.0 h1:omK3OrHRD1IWJz1FuFBCFquhXslXoF17OvBS6JPzZF0= -github.com/foxcpp/go-mockdns v1.2.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk= -github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= -github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= -github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs= -github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= -github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= -github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= -github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= -github.com/go-openapi/swag v0.26.0 h1:GVDXCmfvhfu1BxiHo8/FA+BbKmhecHnG3varjON5/RI= -github.com/go-openapi/swag v0.26.0/go.mod h1:82g3193sZJRbocs7bNCqGfIgq8pkuwVwCfhKIRlEQF0= -github.com/go-openapi/swag/cmdutils v0.26.0 h1:iowihOcvq7y4egO8cOq0dmfohz6wfeQ63U1EnuhO2TU= -github.com/go-openapi/swag/cmdutils v0.26.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.26.0 h1:CmZp+ZT7HrmFwrC3GdGsXBq2+42T1bjKBapcqVpIs3c= -github.com/go-openapi/swag/netutils v0.26.0/go.mod h1:5iK+Ok3ZohWWex1C50BFTPexi03UaPwjW4Oj8kgrpwo= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= -github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= -github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= -github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= -github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= -github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= -github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= -github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gosuri/uitable v0.0.4 h1:IG2xLKRvErL3uhY6e1BylFzG+aJiwQviDDTfOKeKTpY= -github.com/gosuri/uitable v0.0.4/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/golang-lru/arc/v2 v2.0.5 h1:l2zaLDubNhW4XO3LnliVj0GXO3+/CGNJAg1dcN2Fpfw= -github.com/hashicorp/golang-lru/arc/v2 v2.0.5/go.mod h1:ny6zBSQZi2JxIeYcv7kt2sH2PXJtirBN7RDhRpxPkxU= -github.com/hashicorp/golang-lru/v2 v2.0.5 h1:wW7h1TG88eUIJ2i69gaE3uNVtEPIagzhGvHgwfx2Vm4= -github.com/hashicorp/golang-lru/v2 v2.0.5/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= -github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= -github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= -github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= -github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -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= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= -github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= -github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= -github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= -github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= -github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= -github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= -github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= -github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw= -github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= -github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= -github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= -github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM= -github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= -github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= -github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg= -github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= -github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY= -github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ= -github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= -github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= -github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= -github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= -github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= -github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= -github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= -github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= -github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= -github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5 h1:Ii+DKncOVM8Cu1Hc+ETb5K+23HdAMvESYE3ZJ5b5cMI= -github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0/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/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= -github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= -github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= -github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5 h1:EaDatTxkdHG+U3Bk4EUr+DZ7fOGwTfezUiUJMaIcaho= -github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5/go.mod h1:fyalQWdtzDBECAQFBJuQe5bzQ02jGd5Qcbgb97Flm7U= -github.com/redis/go-redis/extra/redisotel/v9 v9.0.5 h1:EfpWLLCyXw8PSM2/XNJLjI3Pb27yVE+gIAfeqp8LUCc= -github.com/redis/go-redis/extra/redisotel/v9 v9.0.5/go.mod h1:WZjPDy7VNzn77AAfnAfVjZNvfJTYfPetfZk5yoSTLaQ= -github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= -github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/rubenv/sql-migrate v1.8.1 h1:EPNwCvjAowHI3TnZ+4fQu3a915OpnQoPAjTXCGOy2U0= -github.com/rubenv/sql-migrate v1.8.1/go.mod h1:BTIKBORjzyxZDS6dzoiw6eAFYJ1iNlGAtjn4LGeVjS8= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= -github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= -github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= -github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= -github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= -github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= -github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= -github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= -github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= -github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= -go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/bridges/prometheus v0.57.0 h1:UW0+QyeyBVhn+COBec3nGhfnFe5lwB0ic1JBVjzhk0w= -go.opentelemetry.io/contrib/bridges/prometheus v0.57.0/go.mod h1:ppciCHRLsyCio54qbzQv0E4Jyth/fLWDTJYfvWpcSVk= -go.opentelemetry.io/contrib/exporters/autoexport v0.57.0 h1:jmTVJ86dP60C01K3slFQa2NQ/Aoi7zA+wy7vMOKD9H4= -go.opentelemetry.io/contrib/exporters/autoexport v0.57.0/go.mod h1:EJBheUMttD/lABFyLXhce47Wr6DPWYReCzaZiXadH7g= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.8.0 h1:WzNab7hOOLzdDF/EoWCt4glhrbMPVMOO5JYTmpz36Ls= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.8.0/go.mod h1:hKvJwTzJdp90Vh7p6q/9PAOd55dI6WA6sWj62a/JvSs= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.8.0 h1:S+LdBGiQXtJdowoJoQPEtI52syEP/JYBUpjO49EQhV8= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.8.0/go.mod h1:5KXybFvPGds3QinJWQT7pmXf+TN5YIa7CNYObWRkj50= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.32.0 h1:j7ZSD+5yn+lo3sGV69nW04rRR0jhYnBwjuX3r0HvnK0= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.32.0/go.mod h1:WXbYJTUaZXAbYd8lbgGuvih0yuCfOFC5RJoYnoLcGz8= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.32.0 h1:t/Qur3vKSkUCcDVaSumWF2PKHt85pc7fRvFuoVT8qFU= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.32.0/go.mod h1:Rl61tySSdcOJWoEgYZVtmnKdA0GeKrSqkHC1t+91CH8= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0 h1:cMyu9O88joYEaI47CnQkxO1XZdpoTF9fEnW2duIddhw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0/go.mod h1:6Am3rn7P9TVVeXYG+wtcGE7IE1tsQ+bP3AuWcKt/gOI= -go.opentelemetry.io/otel/exporters/prometheus v0.54.0 h1:rFwzp68QMgtzu9PgP3jm9XaMICI6TsofWWPcBDKwlsU= -go.opentelemetry.io/otel/exporters/prometheus v0.54.0/go.mod h1:QyjcV9qDP6VeK5qPyKETvNjmaaEc7+gqjh4SS0ZYzDU= -go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.8.0 h1:CHXNXwfKWfzS65yrlB2PVds1IBZcdsX8Vepy9of0iRU= -go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.8.0/go.mod h1:zKU4zUgKiaRxrdovSS2amdM5gOc59slmo/zJwGX+YBg= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.32.0 h1:SZmDnHcgp3zwlPBS2JX2urGYe/jBKEIT6ZedHRUyCz8= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.32.0/go.mod h1:fdWW0HtZJ7+jNpTKUR0GpMEDP69nR8YBJQxNiVCE3jk= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.32.0 h1:cC2yDI3IQd0Udsux7Qmq8ToKAx1XCilTQECZ0KDZyTw= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.32.0/go.mod h1:2PD5Ex6z8CFzDbTdOlwyNIUywRr1DN0ospafJM1wJ+s= -go.opentelemetry.io/otel/log v0.8.0 h1:egZ8vV5atrUWUbnSsHn6vB8R21G2wrKqNiDt3iWertk= -go.opentelemetry.io/otel/log v0.8.0/go.mod h1:M9qvDdUTRCopJcGRKg57+JSQ9LgLBrwwfC32epk5NX8= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/log v0.8.0 h1:zg7GUYXqxk1jnGF/dTdLPrK06xJdrXgqgFLnI4Crxvs= -go.opentelemetry.io/otel/sdk/log v0.8.0/go.mod h1:50iXr0UVwQrYS45KbruFrEt4LvAdCaWWgIrsN3ZQggo= -go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= -go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= -go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= -go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -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/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -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/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -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/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= -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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= -google.golang.org/genproto v0.0.0-20231211222908-989df2bf70f3 h1:1hfbdAfFbkmpg41000wDVqr7jUpK/Yo+LPnIxxGzmkg= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= -google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= -gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= -gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= -gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= -helm.sh/helm/v3 v3.20.2 h1:binM4rvPx5DcNsa1sIt7UZi55lRbu3pZUFmQkSoRh48= -helm.sh/helm/v3 v3.20.2/go.mod h1:Fl1kBaWCpkUrM6IYXPjQ3bdZQfFrogKArqptvueZ6Ww= -k8s.io/api v0.36.0 h1:SgqDhZzHdOtMk40xVSvCXkP9ME0H05hPM3p9AB1kL80= -k8s.io/api v0.36.0/go.mod h1:m1LVrGPNYax5NBHdO+QuAedXyuzTt4RryI/qnmNvs34= -k8s.io/apiextensions-apiserver v0.35.1 h1:p5vvALkknlOcAqARwjS20kJffgzHqwyQRM8vHLwgU7w= -k8s.io/apiextensions-apiserver v0.35.1/go.mod h1:2CN4fe1GZ3HMe4wBr25qXyJnJyZaquy4nNlNmb3R7AQ= -k8s.io/apimachinery v0.36.0 h1:jZyPzhd5Z+3h9vJLt0z9XdzW9VzNzWAUw+P1xZ9PXtQ= -k8s.io/apimachinery v0.36.0/go.mod h1:FklypaRJt6n5wUIwWXIP6GJlIpUizTgfo1T/As+Tyxc= -k8s.io/apiserver v0.36.0 h1:Jg5OFAENUACByUCg15CmhZAYrr5ZyJ+jodyA1mHl3YE= -k8s.io/apiserver v0.36.0/go.mod h1:mHvwdHf+qKEm+1/hYm756SV+oREOKSPnsjagOpx6Vho= -k8s.io/cli-runtime v0.36.0 h1:HNxciQpQMMOKS0/GiUXcKDyA6J2FDILJj9NmP2BZrTg= -k8s.io/cli-runtime v0.36.0/go.mod h1:KObkknK9Ro5LYX+1RdiKc7C8CvGg4aX+V/Zv+E8WPHA= -k8s.io/client-go v0.36.0 h1:pOYi7C4RHChYjMiHpZSpSbIM6ZxVbRXBy7CuiIwqA3c= -k8s.io/client-go v0.36.0/go.mod h1:ZKKcpwF0aLYfkHFCjillCKaTK/yBkEDHTDXCFY6AS9Y= -k8s.io/component-base v0.36.0 h1:hFjEktssxiJhrK1zfybkH4kJOi8iZuF+mIDCqS5+jRo= -k8s.io/component-base v0.36.0/go.mod h1:JZvIfcNHk+uck+8LhJzhSBtydWXaZNQwX2OdL+Mnwsk= -k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= -k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f h1:4Qiq0YAoQATdgmHALJWz9rJ4fj20pB3xebpB4CFNhYM= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/kubectl v0.36.0 h1:hEGr8NvIm2Wjqs2Xy48Uzmvo6lpHdGKlLyMvau2gTms= -k8s.io/kubectl v0.36.0/go.mod h1:iDe8aV5BEi45W8k+5n71I2pJ/nwE0PHDu+/2cejzYoo= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -oras.land/oras-go/v2 v2.6.2 h1:N04RXngAp1LJKTG6ifz3xHPipasEkWr+hFmInja5YKo= -oras.land/oras-go/v2 v2.6.2/go.mod h1:PlTtg4JTDJkDe8yVHpM2wz7/YDc00GVas+i4jAW2TZ4= -pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= -pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/controller-runtime v0.23.3 h1:VjB/vhoPoA9l1kEKZHBMnQF33tdCLQKJtydy4iqwZ80= -sigs.k8s.io/controller-runtime v0.23.3/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kind v0.31.0 h1:UcT4nzm+YM7YEbqiAKECk+b6dsvc/HRZZu9U0FolL1g= -sigs.k8s.io/kind v0.31.0/go.mod h1:FSqriGaoTPruiXWfRnUXNykF8r2t+fHtK0P0m1AbGF8= -sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= -sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= -sigs.k8s.io/kustomize/kyaml v0.21.1 h1:IVlbmhC076nf6foyL6Taw4BkrLuEsXUXNpsE+ScX7fI= -sigs.k8s.io/kustomize/kyaml v0.21.1/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= -sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= -sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0 h1:qmp2e3ZfFi1/jJbDGpD4mt3wyp6PE1NfKHCYLqgNQJo= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= -sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= -sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/cli/login.go b/cli/login.go new file mode 100644 index 000000000..aa101ff1c --- /dev/null +++ b/cli/login.go @@ -0,0 +1,82 @@ +/* +Copyright 2026 The kbind 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 cli + +import ( + "context" + "fmt" + "net" + "net/http" + "net/url" + "os/exec" + "runtime" + "time" +) + +// Login runs the browser login dance: a localhost callback listener catches +// the session token the gateway appends after the OIDC flow finishes. Returns +// the token. When openBrowser is false the URL is only printed. +func Login(ctx context.Context, server string, openBrowser bool, out func(string)) (string, error) { + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") + if err != nil { + return "", err + } + defer func() { _ = listener.Close() }() + + callback := fmt.Sprintf("http://127.0.0.1:%d/callback", listener.Addr().(*net.TCPAddr).Port) + loginURL := server + "/api/auth/oidc/login?redirect=" + url.QueryEscape(callback) + + tokens := make(chan string, 1) + srv := &http.Server{ReadHeaderTimeout: 10 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := r.URL.Query().Get("token") + if token == "" { + http.Error(w, "missing token", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte("

Logged in to kbind.

You can close this tab and return to the terminal.")) + tokens <- token + })} + go func() { _ = srv.Serve(listener) }() + defer func() { _ = srv.Close() }() + + out("Opening " + loginURL) + out("(if the browser does not open, visit the URL manually)") + if openBrowser { + _ = browse(ctx, loginURL) + } + + select { + case token := <-tokens: + return token, nil + case <-ctx.Done(): + return "", ctx.Err() + case <-time.After(5 * time.Minute): + return "", fmt.Errorf("login timed out after 5 minutes") + } +} + +func browse(ctx context.Context, url string) error { + switch runtime.GOOS { + case "darwin": + return exec.CommandContext(ctx, "open", url).Start() + case "windows": + return exec.CommandContext(ctx, "rundll32", "url.dll,FileProtocolHandler", url).Start() + default: + return exec.CommandContext(ctx, "xdg-open", url).Start() + } +} diff --git a/cli/pkg/client/client.go b/cli/pkg/client/client.go deleted file mode 100644 index 9571b4838..000000000 --- a/cli/pkg/client/client.go +++ /dev/null @@ -1,255 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 client - -import ( - "bytes" - "context" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "strings" - "time" - - "github.com/kube-bind/kube-bind/cli/pkg/config" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Client interface { - GetTemplates(context.Context) (*kubebindv1alpha2.APIServiceExportTemplateList, error) - GetCollections(context.Context) (*kubebindv1alpha2.CollectionList, error) - Bind(context.Context, *kubebindv1alpha2.BindableResourcesRequest) (*kubebindv1alpha2.BindingResourceResponse, error) - - Get(string) (*http.Response, error) - Post(string, io.Reader) (*http.Response, error) - Do(*http.Request) (*http.Response, error) -} - -// authenticatedClient provides an HTTP client with automatic authentication -type authenticatedClient struct { - client *http.Client - server config.Server - - insecure bool -} - -type ClientOption func(*authenticatedClient) - -// WithInsecure configures the client to skip TLS certificate verification -// WARNING: This should only be used for testing or development environments -func WithInsecure(insecure bool) ClientOption { - return func(c *authenticatedClient) { - c.insecure = insecure - } -} - -// NewClient creates a new authenticated HTTP client -func NewClient(server config.Server, opts ...ClientOption) (Client, error) { - authClient := &authenticatedClient{ - server: server, - } - for _, opt := range opts { - opt(authClient) - } - - if authClient.client == nil { - authClient.client = &http.Client{} - } - - // Create an insecure HTTP client if needed - if authClient.insecure { - authClient.client.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - }, - } - } - - return authClient, nil -} - -func (c *authenticatedClient) GetTemplates(ctx context.Context) (*kubebindv1alpha2.APIServiceExportTemplateList, error) { - url, err := c.buildEndpointURL("templates") - if err != nil { - return nil, fmt.Errorf("failed to build templates URL: %w", err) - } - - resp, err := c.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result kubebindv1alpha2.APIServiceExportTemplateList - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return nil, fmt.Errorf("failed to decode templates response: %w", err) - } - - return &result, nil -} - -func (c *authenticatedClient) GetCollections(ctx context.Context) (*kubebindv1alpha2.CollectionList, error) { - url, err := c.buildEndpointURL("collections") - if err != nil { - return nil, fmt.Errorf("failed to build collections URL: %w", err) - } - - resp, err := c.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var result kubebindv1alpha2.CollectionList - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return nil, fmt.Errorf("failed to decode collections response: %w", err) - } - - return &result, nil -} - -func (c *authenticatedClient) Bind(ctx context.Context, request *kubebindv1alpha2.BindableResourcesRequest) (*kubebindv1alpha2.BindingResourceResponse, error) { - url, err := c.buildEndpointURL("bind") - if err != nil { - return nil, fmt.Errorf("failed to build bind URL: %w", err) - } - - reqBody, err := json.Marshal(request) - if err != nil { - return nil, fmt.Errorf("failed to marshal bind request: %w", err) - } - - resp, err := c.Post(url, io.NopCloser(bytes.NewReader(reqBody))) - if err != nil { - return nil, fmt.Errorf("failed to send bind request: %w", err) - } - defer resp.Body.Close() - - var result kubebindv1alpha2.BindingResourceResponse - if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { - return nil, fmt.Errorf("failed to decode bind response: %w", err) - } - - return &result, nil -} - -// Get performs an authenticated GET request -func (c *authenticatedClient) Get(url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - - if err := c.addAuthHeaders(req); err != nil { - return nil, err - } - - return c.client.Do(req) -} - -// Post performs an authenticated POST request -func (c *authenticatedClient) Post(url string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - - if err := c.addAuthHeaders(req); err != nil { - return nil, err - } - - return c.client.Do(req) -} - -// Do performs an authenticated HTTP request -func (c *authenticatedClient) Do(req *http.Request) (*http.Response, error) { - if err := c.addAuthHeaders(req); err != nil { - return nil, err - } - - return c.client.Do(req) -} - -// addAuthHeaders adds authentication headers to the request -func (c *authenticatedClient) addAuthHeaders(req *http.Request) error { - s := c.server - // Check if we have stored authentication for this server - if !c.isTokenValid() { - err := fmt.Errorf("no valid authentication found for server %s. Please run 'kubectl bind login %s' first", s.URL, s.URL) - if s.Cluster != "" { - err = fmt.Errorf("no valid authentication found for server %s with cluster %s. Please run 'kubectl bind login %s --cluster %s' first", s.URL, s.Cluster, s.URL, s.Cluster) - } - return err - } - - req.Header.Set("Authorization", c.getAuthorizationHeader()) - req.Header.Set("User-Agent", "kubectl-bind-cli") - req.Header.Set("Accept", "application/json") - - return nil -} - -// isTokenValid checks if the token for the given server is still valid -func (c *authenticatedClient) isTokenValid() bool { - - if c.server.AccessToken == "" { - return false - } - - // Check if token has expired (with 5 minute buffer) - if !c.server.ExpiresAt.IsZero() && time.Now().Add(5*time.Minute).After(c.server.ExpiresAt) { - return false - } - - return true -} - -// buildEndpointURL constructs an endpoint URL based on server config and cluster context -func (c *authenticatedClient) buildEndpointURL(endpoint string) (string, error) { - baseURL, err := url.Parse(c.server.URL) - if err != nil { - return "", fmt.Errorf("invalid server URL %q: %w", c.server.URL, err) - } - if baseURL.Scheme == "" || baseURL.Host == "" { - return "", fmt.Errorf("invalid server URL %q: missing scheme or host", c.server.URL) - } - - baseURL.Path = path.Join(baseURL.Path, "api", strings.TrimPrefix(endpoint, "/")) - - if c.server.Cluster != "" { - query := baseURL.Query() - query.Set("cluster_id", c.server.Cluster) - baseURL.RawQuery = query.Encode() - } - - return baseURL.String(), nil -} - -// getAuthorizationHeader returns the authorization header value for the given server -func (c *authenticatedClient) getAuthorizationHeader() string { - tokenType := c.server.TokenType - if tokenType == "" { - tokenType = "Bearer" - } - - return fmt.Sprintf("%s %s", tokenType, c.server.AccessToken) -} diff --git a/cli/pkg/config/config.go b/cli/pkg/config/config.go deleted file mode 100644 index 3f3b31af9..000000000 --- a/cli/pkg/config/config.go +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 config - -import ( - "encoding/json" - "fmt" - "os" - "path" - "strings" - "time" -) - -// Config represents the kube-bind CLI configuration -type Config struct { - APIVersion string `json:"apiVersion"` - Kind string `json:"kind"` - Servers map[string]*Server `json:"servers,omitempty"` - Current string `json:"current,omitempty"` - - // configFile is the path to the kube-bind configuration file - configFile string `json:"-"` -} - -// Server represents authentication details for a kube-bind server -type Server struct { - URL string `json:"url"` - Cluster string `json:"cluster,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - TokenType string `json:"tokenType,omitempty"` - ExpiresAt time.Time `json:"expiresAt,omitempty"` - Username string `json:"username,omitempty"` -} - -// NewConfig creates a new empty configuration -func NewConfig(configFile string) *Config { - // if configFile is empty, use default location - if configFile == "" { - configFile = GetDefaultConfigFilePath() - } - return &Config{ - APIVersion: "v1", - Kind: "Config", - Servers: make(map[string]*Server), - configFile: configFile, - } -} - -// GetDefaultConfigFilePath returns the default path to the kube-bind config file -func GetDefaultConfigFilePath() string { - homeDir, err := os.UserHomeDir() - if err != nil { - return path.Join(".", "config") - } - return path.Join(homeDir, ".kube-bind", "config") -} - -// GetConfigPath returns the path to the kube-bind config file -func (c *Config) GetConfigPath() (string, error) { - return c.configFile, nil -} - -// LoadConfig loads the kube-bind configuration from file -func LoadConfigFromFile(configFile string) (*Config, error) { - // If config file doesn't exist, return empty config - if _, err := os.Stat(configFile); os.IsNotExist(err) { - return NewConfig(configFile), nil - } - - data, err := os.ReadFile(configFile) - if err != nil { - return nil, fmt.Errorf("unable to read config file: %w", err) - } - - var config Config - if err := json.Unmarshal(data, &config); err != nil { - return nil, fmt.Errorf("unable to parse config file: %w", err) - } - config.configFile = configFile - - // Initialize servers map if nil - if config.Servers == nil { - config.Servers = make(map[string]*Server) - } - - return &config, nil -} - -// SaveConfig saves the kube-bind configuration to file -func (c *Config) SaveConfig() error { - data, err := json.MarshalIndent(c, "", " ") - if err != nil { - return fmt.Errorf("unable to marshal config: %w", err) - } - - configFile, err := c.GetConfigPath() - if err != nil { - return fmt.Errorf("unable to get config file path: %w", err) - } - - if err := os.WriteFile(configFile, data, 0600); err != nil { - return fmt.Errorf("unable to write config file %s: %w", configFile, err) - } - - return nil -} - -func (c *Config) Get(serverURL, clusterID string) (*Server, bool) { - key := buildServerKey(serverURL, clusterID) - server, exists := c.Servers[key] - return server, exists -} - -// AddServerWithCluster adds or updates server configuration with cluster ID -func (c *Config) AddServerWithCluster(serverURL, clusterID string, server *Server) { - key := buildServerKey(serverURL, clusterID) - c.addServer(key, server) -} - -// addServer adds or updates server configuration -func (c *Config) addServer(name string, server *Server) { - if c.Servers == nil { - c.Servers = make(map[string]*Server) - } - c.Servers[name] = server - c.Current = name -} - -// FindServersByURL finds all servers for a given URL (across all clusters) -func (c *Config) FindServersByURL(serverURL string) map[string]*Server { - matches := make(map[string]*Server) - for key, server := range c.Servers { - keyServerURL, _ := parseServerKey(key) - if keyServerURL == serverURL { - matches[key] = server - } - } - return matches -} - -// RemoveServer removes a server from the configuration -func (c *Config) RemoveServer(name, cluster string) { - delete(c.Servers, buildServerKey(name, cluster)) - if c.Current == name { - c.Current = "" - // Set current to first available server - for serverName := range c.Servers { - c.Current = serverName - break - } - } -} - -// GetCurrentServer returns the currently active server configuration. -func (c *Config) GetCurrentServer() (*Server, string, error) { - if c.Current == "" { - return nil, "", fmt.Errorf("no current server set") - } - - server, exists := c.Servers[c.Current] - if !exists { - return nil, "", fmt.Errorf("current server %q not found in config", c.Current) - } - - return server, c.Current, nil -} - -// SetCurrentServer sets the current active server -func (c *Config) SetCurrentServer(serverName, cluster string) error { - if _, exists := c.Servers[buildServerKey(serverName, cluster)]; !exists { - return fmt.Errorf("server %q does not exist", serverName) - } - - c.Current = buildServerKey(serverName, cluster) - return nil -} - -// buildServerKey creates a unique key for server+cluster combination -func buildServerKey(serverURL, clusterID string) string { - if clusterID == "" { - return serverURL - } - - // Use @ separator to combine server and cluster (similar to user@host pattern) - return fmt.Sprintf("%s@%s", clusterID, serverURL) -} - -// parseServerKey parses a server key back into serverURL and clusterID. -func parseServerKey(key string) (serverURL, clusterID string) { - if parts := strings.SplitN(key, "@", 2); len(parts) == 2 { - return parts[1], parts[0] - } - return key, "" -} diff --git a/cli/pkg/help/help.go b/cli/pkg/help/help.go deleted file mode 100644 index e7478fe75..000000000 --- a/cli/pkg/help/help.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2024 The Kube Bind 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 help - -import ( - "fmt" - "strings" - - "github.com/MakeNowJust/heredoc" - "github.com/muesli/reflow/indent" -) - -func Doc(s string) string { - return RemoveIndentation(s) -} - -func Examples(s string) string { - s = RemoveIndentation(s) - - // apply a consistent, nice-looking indentation - s = indent.String(s, 2) - - return s -} - -func Examplesf(s string, args ...any) string { - return Examples(fmt.Sprintf(s, args...)) -} - -func RemoveIndentation(s string) string { - s = strings.TrimSpace(s) - s = heredoc.Doc(s) - - return s -} diff --git a/cli/pkg/kubectl/base/browser.go b/cli/pkg/kubectl/base/browser.go deleted file mode 100644 index e0e8aa7d6..000000000 --- a/cli/pkg/kubectl/base/browser.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 base - -import ( - "context" - "os/exec" - "runtime" -) - -// openBrowser opens the given URL in the default browser -func OpenBrowser(url string) error { - var cmd *exec.Cmd - - // Determine the command based on the operating system - switch runtime.GOOS { - case "windows": - cmd = exec.CommandContext(context.Background(), "cmd", "/c", "start", url) - case "darwin": - cmd = exec.CommandContext(context.Background(), "open", url) - default: // Linux and other Unix-like systems - cmd = exec.CommandContext(context.Background(), "xdg-open", url) - } - - return cmd.Run() -} diff --git a/cli/pkg/kubectl/base/client.go b/cli/pkg/kubectl/base/client.go deleted file mode 100644 index 18fea8bb1..000000000 --- a/cli/pkg/kubectl/base/client.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 base - -import ( - "github.com/kube-bind/kube-bind/cli/pkg/client" -) - -// GetAuthenticatedClientWithLogin returns an authenticated client for the configured server. -func (o *Options) GetAuthenticatedClient() (client.Client, error) { - // First try to create an authenticated client - // Now use authenticated client - return client.NewClient(*o.server, - client.WithInsecure(o.SkipInsecure), - ) -} diff --git a/cli/pkg/kubectl/base/identity.go b/cli/pkg/kubectl/base/identity.go deleted file mode 100644 index e467c64c8..000000000 --- a/cli/pkg/kubectl/base/identity.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 base - -import ( - "context" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func GetClusterIdentityFromNamespace(ctx context.Context, rest *rest.Config, namespaceName string) (string, error) { - cl, err := client.New(rest, client.Options{}) - if err != nil { - return "", err - } - - var namespace corev1.Namespace - err = cl.Get(ctx, types.NamespacedName{Name: namespaceName}, &namespace) - if err != nil { - return "", err - } - - return string(namespace.UID), nil -} diff --git a/cli/pkg/kubectl/base/kubeconfig.go b/cli/pkg/kubectl/base/kubeconfig.go deleted file mode 100644 index be1e9f321..000000000 --- a/cli/pkg/kubectl/base/kubeconfig.go +++ /dev/null @@ -1,202 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 base - -import ( - "context" - "fmt" - "os" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/client-go/util/retry" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func ParseRemoteKubeconfig(kubeconfig []byte) (host string, ns string, err error) { - config, err := clientcmd.Load(kubeconfig) - if err != nil { - return "", "", err - } - if _, found := config.Contexts[config.CurrentContext]; !found { - return "", "", fmt.Errorf("current context %q of remote kubeconfig not found", config.CurrentContext) - } - cluster, found := config.Clusters[config.Contexts[config.CurrentContext].Cluster] - if !found { - return "", "", fmt.Errorf("cluster %q in current context %q of remote kubeconfig not found", config.Contexts[config.CurrentContext].Cluster, config.CurrentContext) - } - - return cluster.Server, config.Contexts[config.CurrentContext].Namespace, nil -} - -func FindRemoteKubeconfig(ctx context.Context, kubeClient *kubernetes.Clientset, remoteNamespace string, remoteHost string) (string, error) { - logger := klog.FromContext(ctx) - - secrets, err := kubeClient.CoreV1().Secrets("kube-bind").List(ctx, v1.ListOptions{}) - if err != nil { - return "", err - } - for _, s := range secrets.Items { - logger := logger.WithValues("namespace", "kube-bind", "name", s.Name) - bs, found := s.Data["kubeconfig"] - if !found { - logger.V(6).Info("secret does not contain kubeconfig") - continue - } - host, ns, err := ParseRemoteKubeconfig(bs) - if err != nil { - logger.V(6).Info("failed to parse kubeconfig", "error", err) - continue - } - if ns != remoteNamespace { - logger.V(6).Info("secret current context namespace not set") - continue - } - if host != remoteHost { - logger.V(6).Info("secret current context host mismatch") - continue - } - - return s.Name, nil - } - return "", nil -} - -// EnsureKubeconfigSecret creates a secret which contains the service binding authenticated data such as -// the binding session id and the kubeconfig of the service provider cluster. If it is pre-existing, the kubeconfig -// is updated. -// -// If name is provided, the secret will be created with that name or updated if it already exists. -// If name is empty, a new secret with a generated name (kubeconfig-) will be created. -// -// It does special checking that only kubeconfigs with the same host and default namespace are updated. -func EnsureKubeconfigSecret(ctx context.Context, kubeconfig, name string, client kubernetes.Interface) (*corev1.Secret, bool, error) { - remoteHost, remoteNamespace, err := ParseRemoteKubeconfig([]byte(kubeconfig)) - if err != nil { - return nil, false, err - } - - // If no name provided, create with generated name - if name == "" { - secret := &corev1.Secret{ - ObjectMeta: v1.ObjectMeta{ - Namespace: "kube-bind", - GenerateName: "kubeconfig-", - Labels: map[string]string{ - kubebindv1alpha2.LabelProviderKubeconfig: "true", - }, - }, - Data: map[string][]byte{ - "kubeconfig": []byte(kubeconfig), - }, - } - - secret, err := client.CoreV1().Secrets("kube-bind").Create(ctx, secret, v1.CreateOptions{}) - if err != nil { - return nil, false, err - } - return secret, true, nil - } - - // Name provided - try to get existing secret - _, err = client.CoreV1().Secrets("kube-bind").Get(ctx, name, v1.GetOptions{}) - if err != nil && !errors.IsNotFound(err) { - return nil, false, err - } - - // Secret doesn't exist - create with the provided name - if errors.IsNotFound(err) { - secret := &corev1.Secret{ - ObjectMeta: v1.ObjectMeta{ - Namespace: "kube-bind", - Name: name, - Labels: map[string]string{ - kubebindv1alpha2.LabelProviderKubeconfig: "true", - }, - }, - Data: map[string][]byte{ - "kubeconfig": []byte(kubeconfig), - }, - } - - secret, err := client.CoreV1().Secrets("kube-bind").Create(ctx, secret, v1.CreateOptions{}) - if err != nil { - return nil, false, err - } - return secret, true, nil - } - - // Secret exists - update it - var secret *corev1.Secret - if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - var err error - secret, err = client.CoreV1().Secrets("kube-bind").Get(ctx, name, v1.GetOptions{}) - if err != nil { - return err - } - bs, found := secret.Data["kubeconfig"] - if !found { - return fmt.Errorf("secret %s/%s does not contain a kubeconfig", "kube-bind", name) - } - existingHost, existingNamespace, err := ParseRemoteKubeconfig(bs) - if err != nil { - return err - } - if existingHost != remoteHost || existingNamespace != remoteNamespace { - return errors.NewAlreadyExists(corev1.Resource("secret"), secret.Name) - } - secret.Data["kubeconfig"] = []byte(kubeconfig) - // Ensure label is set on existing secrets - if secret.Labels == nil { - secret.Labels = make(map[string]string) - } - secret.Labels[kubebindv1alpha2.LabelProviderKubeconfig] = "true" - if _, err := client.CoreV1().Secrets("kube-bind").Update(ctx, secret, v1.UpdateOptions{}); err != nil { - return err - } - return nil - }); err != nil { - return nil, false, err - } - - return secret, false, nil -} - -// LoadRestConfigFromString loads a kubeconfig string and returns a rest.Config -func LoadRestConfigFromString(kubeconfig string) (*rest.Config, error) { - config, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig)) - if err != nil { - return nil, fmt.Errorf("failed to build config from kubeconfig: %w", err) - } - return config, nil -} - -// LoadRestConfigFromFile loads a kubeconfig file and returns a rest.Config -func LoadRestConfigFromFile(kubeconfig string) (*rest.Config, error) { - content, err := os.ReadFile(kubeconfig) - if err != nil { - return nil, fmt.Errorf("failed to load kubeconfig: %w", err) - } - - return LoadRestConfigFromString(string(content)) -} diff --git a/cli/pkg/kubectl/base/options.go b/cli/pkg/kubectl/base/options.go deleted file mode 100644 index 066cc43db..000000000 --- a/cli/pkg/kubectl/base/options.go +++ /dev/null @@ -1,204 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 base - -import ( - "fmt" - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/tools/clientcmd" - - "github.com/kube-bind/kube-bind/cli/pkg/config" -) - -// Options contains options common to most CLI plugins. -type Options struct { - genericclioptions.IOStreams - // OptOutOfDefaultKubectlFlags indicates that the standard kubectl/kubeconfig-related flags should not be bound - // by default. - OptOutOfDefaultKubectlFlags bool - // Kubeconfig specifies kubeconfig file(s). - Kubeconfig string - // KubectlOverrides stores the extra client connection fields, such as context, user, etc. - KubectlOverrides *clientcmd.ConfigOverrides - // ServerName is the kube-bind server name to use (overrides kube-bind config current server) - ServerName string - // ClusterName is the kube-bind cluster name to use (overrides kube-bind config current cluster) - ClusterName string - // SkipInsecure skips TLS verification (for development) - SkipInsecure bool - // ConfigFile is the path to the kube-bind configuration file - ConfigFile string - // ClientConfig is the resolved cliendcmd.ClientConfig based on the client connection flags. This is only valid - // after calling Complete. - ClientConfig clientcmd.ClientConfig - - // config is config struct. Used only for login process. - config *config.Config - // Server is the loaded kube-bind server used by the plugins. - server *config.Server -} - -// NewOptions provides an instance of Options with default values. -func NewOptions(streams genericclioptions.IOStreams) *Options { - return &Options{ - KubectlOverrides: &clientcmd.ConfigOverrides{}, - IOStreams: streams, - } -} - -// BindFlags binds options fields to cmd's flagset. -func (o *Options) BindFlags(cmd *cobra.Command) { - if o.OptOutOfDefaultKubectlFlags { - return - } - - cmd.Flags().StringVar(&o.Kubeconfig, "kubeconfig", o.Kubeconfig, "Path to the kubeconfig file") - - // We add only a subset of kubeconfig-related flags to the plugin. - // All those with LongName == "" will be ignored. - kubectlConfigOverrideFlags := clientcmd.RecommendedConfigOverrideFlags("") - kubectlConfigOverrideFlags.AuthOverrideFlags.ClientCertificate.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.ClientKey.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.Impersonate.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.ImpersonateGroups.LongName = "" - kubectlConfigOverrideFlags.ContextOverrideFlags.ClusterName.LongName = "" - kubectlConfigOverrideFlags.Timeout.LongName = "" - - clientcmd.BindOverrideFlags(o.KubectlOverrides, cmd.PersistentFlags(), kubectlConfigOverrideFlags) - - // Add common kube-bind flags - cmd.Flags().StringVar(&o.ServerName, "server", o.ServerName, "The kube-bind server name to use (overrides kube-bind config current server)") - cmd.Flags().StringVar(&o.ClusterName, "cluster", o.ClusterName, "The kube-bind cluster name to use (overrides kube-bind config current cluster)") - cmd.Flags().BoolVar(&o.SkipInsecure, "insecure-skip-tls-verify", false, "Skip TLS certificate verification (not recommended)") - cmd.Flags().StringVar(&o.ConfigFile, "config-file", "", "Path to the kube-bind configuration file") -} - -// Complete initializes ClientConfig based on Kubeconfig and KubectlOverrides, and resolves server configuration. -func (o *Options) Complete(skipValidate bool) error { - loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() - loadingRules.ExplicitPath = o.Kubeconfig - - startingConfig, err := loadingRules.GetStartingConfig() - if err != nil { - return err - } - - o.ClientConfig = clientcmd.NewDefaultClientConfig(*startingConfig, o.KubectlOverrides) - - if o.ConfigFile == "" { - o.ConfigFile = config.GetDefaultConfigFilePath() - } - - // Create directory if it doesn't exist - if err := os.MkdirAll(filepath.Dir(o.ConfigFile), 0700); err != nil { - return fmt.Errorf("unable to create config directory: %w", err) - } - - if _, err := os.Stat(o.ConfigFile); os.IsNotExist(err) { - // Create empty config file - emptyConfig := config.NewConfig(o.ConfigFile) - if err := emptyConfig.SaveConfig(); err != nil { - return fmt.Errorf("unable to create config file: %w", err) - } - } - - switch { - case o.ServerName != "" && o.ClusterName != "": - // Both server and cluster specified separately - do nothing - case o.ServerName != "" && strings.Contains(o.ServerName, "@"): - // Server specified in server@cluster format - parts := strings.SplitN(o.ServerName, "@", 2) - o.ServerName = parts[0] - o.ClusterName = parts[1] - case o.ServerName != "" && o.ClusterName == "": - // Only server specified - do nothing. Cluster is empty - case o.ServerName == "": - // No server specified - do nothing. Will be resolved from config - } - - // If server name is not specified, use current server from config. - // Server should always be set either with cluster or without. - // So if its empty here, we need to resolve it. - var s *config.Server - var c *config.Config - if o.ServerName == "" { - c, err = config.LoadConfigFromFile(o.ConfigFile) - if err != nil { - return fmt.Errorf("failed to load config: %w", err) - } - - s, _, err = c.GetCurrentServer() - if err != nil && !skipValidate { - return fmt.Errorf("no current server configured. Use 'kubectl bind-login {--cluster }' to login first: %w", err) - } - } else { - // Validate that the specified server exists in config - c, err = config.LoadConfigFromFile(o.ConfigFile) - if err != nil { - return fmt.Errorf("failed to load config: %w", err) - } - - var exists bool - s, exists = c.Get(o.ServerName, o.ClusterName) - if !exists && !skipValidate { - err := fmt.Errorf("server %q not found in config", o.ServerName) - if o.ClusterName != "" { - err = fmt.Errorf("server %q with cluster %q not found in config", o.ServerName, o.ClusterName) - } - return err - } - } - if (s == nil && !skipValidate) || c == nil { - // This should never happen. This is programming error. - return fmt.Errorf("failed to resolve server configuration") - } - - if s != nil { - o.ServerName = s.URL - o.ClusterName = s.Cluster - } - o.server = s - o.config = c - - return nil -} - -// Validate validates the configured options. -func (o *Options) Validate() error { - if o.ServerName != "" && strings.Contains(o.ServerName, "@") && o.ClusterName != "" { - return fmt.Errorf("cannot specify both server in 'server@cluster' format and --cluster flag") - } - - if o.ClusterName != "" && o.ServerName == "" { - return fmt.Errorf("cannot specify --cluster without --server") - } - if _, err := url.Parse(o.ServerName); err != nil { - return fmt.Errorf("invalid server URL: %w", err) - } - - return nil -} - -func (o *Options) GetConfig() *config.Config { - return o.config -} diff --git a/cli/pkg/kubectl/bind-apiservice/cmd/cmd.go b/cli/pkg/kubectl/bind-apiservice/cmd/cmd.go deleted file mode 100644 index 5522aa67f..000000000 --- a/cli/pkg/kubectl/bind-apiservice/cmd/cmd.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 cmd - -import ( - "fmt" - - "github.com/fatih/color" - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/plugin" - - _ "k8s.io/client-go/plugin/pkg/client/auth/exec" - _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" -) - -var ( - bindAPIServiceExampleUses = ` - # bind to a remote API service. Use kubectl bind to create the APIServiceExportRequest interactively. - %[1]s apiservice --remote-kubeconfig file -f apiservice-export-request.yaml - - # bind to a remote API using template name - %[1]s apiservice --name my-api --template-name database-service - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewBindAPIServiceOptions(streams) - cmd := &cobra.Command{ - Use: "apiservice https://|-f ", - Short: "Bind to a remote API service", - Long: help.Doc(` - Bind to a remote API service by creating an APIServiceExportRequest. - - This command allows you to bind remote services into your cluster by either: - - - Providing a URL to an APIServiceExportRequest resource - - Providing a file containing an APIServiceExportRequest manifest - - Using a template name to interactively create the binding - - The command will authenticate with the remote service provider, create the necessary - APIServiceExportRequest, and deploy a konnector to establish the connection between - your cluster and the remote service. - `), - Example: fmt.Sprintf(bindAPIServiceExampleUses, "kubectl bind"), - SilenceUsage: true, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if len(args) > 1 { - return cmd.Help() - } - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - if !opts.NoBanner { - yellow := color.New(color.BgRed, color.FgBlack).SprintFunc() - fmt.Fprintf(streams.ErrOut, "%s\n\n", yellow("DISCLAIMER: This is a prototype. It will change in incompatible ways at any time.")) - } - - if err := opts.Run(cmd.Context()); err != nil { - fmt.Fprintf(streams.ErrOut, "Error: %v\n", err) - return nil - } - return nil - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/bind.go b/cli/pkg/kubectl/bind-apiservice/plugin/bind.go deleted file mode 100644 index 9559261d1..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/bind.go +++ /dev/null @@ -1,401 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/spf13/cobra" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/cli-runtime/pkg/printers" - kubeclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// BindAPIServiceOptions are the options for the kubectl-bind-apiservice command. -type BindAPIServiceOptions struct { - *base.Options - Logs *logs.Options - - JSONYamlPrintFlags *genericclioptions.JSONYamlPrintFlags - OutputFormat string - Print *genericclioptions.PrintFlags - printer printers.ResourcePrinter - - remoteKubeconfigFile string - remoteKubeconfigNamespace string - remoteKubeconfigName string - remoteNamespace string - file string - - // skipKonnector skips the deployment of the konnector. - SkipKonnector bool - KonnectorImageOverride string - DowngradeKonnector bool - // KonnectorHostAlias is a list of host alias entries to add to the konnector pods. - KonnectorHostAlias []string - // KonnectorHostAliasParsed is the parsed version of KonnectorHostAlias. - KonnectorHostAliasParsed []corev1.HostAlias - - NoBanner bool - DryRun bool - Template string - Name string - - // ClusterIdentity is a unique identity for the cluster. - ClusterIdentity string - // clusterIdentityNamespaceName is the namespace name, from which the cluster identity will be generated. - clusterIdentityNamespaceName string -} - -// NewBindAPIServiceOptions returns new BindAPIServiceOptions. -func NewBindAPIServiceOptions(streams genericclioptions.IOStreams) *BindAPIServiceOptions { - return &BindAPIServiceOptions{ - Options: base.NewOptions(streams), - Logs: logs.NewOptions(), - Print: genericclioptions.NewPrintFlags("kubectl-bind-apiservice"), - clusterIdentityNamespaceName: "kube-system", - } -} - -// AddCmdFlags binds fields to cmd's flagset. -func (b *BindAPIServiceOptions) AddCmdFlags(cmd *cobra.Command) { - b.Options.BindFlags(cmd) - logsv1.AddFlags(b.Logs, cmd.Flags()) - b.Print.AddFlags(cmd) - - // First block of flags are common with bind/plugin/bind.go, keep them in sync. - cmd.Flags().BoolVar(&b.SkipKonnector, "skip-konnector", b.SkipKonnector, "Skip the deployment of the konnector") - cmd.Flags().BoolVarP(&b.DryRun, "dry-run", "d", b.DryRun, "If true, only print the requests that would be sent to the service provider after authentication, without actually binding.") - cmd.Flags().StringVar(&b.KonnectorImageOverride, "konnector-image", b.KonnectorImageOverride, "The konnector image to use") - cmd.Flags().MarkHidden("konnector-image") //nolint:errcheck - cmd.Flags().StringSliceVarP(&b.KonnectorHostAlias, "konnector-host-alias", "", []string{}, "Add a host alias to the konnector pods in the format IP:hostname1,hostname2") - cmd.Flags().MarkHidden("konnector-host-alias") //nolint:errcheck - cmd.Flags().StringVarP(&b.ClusterIdentity, "cluster-identity", "", b.ClusterIdentity, "A unique identity for the cluster. If not provided, it will be generated based on the local cluster information. ") - cmd.Flags().StringVarP(&b.clusterIdentityNamespaceName, "cluster-identity-namespace", "", b.clusterIdentityNamespaceName, "The namespace name from which the cluster identity will be generated. Only used if cluster-identity is not provided.") - - // Second block of flags specific to bind-apiservice. - cmd.Flags().StringVar(&b.Template, "template-name", b.Template, "A template name to use for binding") - cmd.Flags().StringVar(&b.Name, "name", b.Name, "The name of the BindableResourcesRequest to create") - cmd.Flags().StringVar(&b.remoteKubeconfigFile, "remote-kubeconfig", b.remoteKubeconfigFile, "A file path for a kubeconfig file to connect to the service provider cluster") - cmd.Flags().StringVar(&b.remoteKubeconfigNamespace, "remote-kubeconfig-namespace", b.remoteKubeconfigNamespace, "The namespace of the remote kubeconfig secret to read from") - cmd.Flags().StringVar(&b.remoteKubeconfigName, "remote-kubeconfig-name", b.remoteKubeconfigNamespace, "The name of the remote kubeconfig secret to read from") - cmd.Flags().StringVarP(&b.file, "file", "f", b.file, "A file with an APIServiceExportRequest manifest. Use - to read from stdin") - cmd.Flags().StringVar(&b.remoteNamespace, "remote-namespace", b.remoteNamespace, "The namespace in the remote cluster where the konnector is deployed") - cmd.Flags().BoolVar(&b.DowngradeKonnector, "downgrade-konnector", b.DowngradeKonnector, "Downgrade the konnector to the version of the kubectl-bind-apiservice binary") - cmd.Flags().BoolVar(&b.NoBanner, "no-banner", b.NoBanner, "Do not show the red banner") - cmd.Flags().MarkHidden("no-banner") //nolint:errcheck -} - -// Complete ensures all fields are initialized. -func (b *BindAPIServiceOptions) Complete(args []string) error { - if len(args) > 0 { - b.Name = args[0] - } - if err := b.Options.Complete(false); err != nil { - return err - } - - printer, err := b.Print.ToPrinter() - if err != nil { - return err - } - - b.printer = printer - - // parse konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - hostnames := strings.Split(parts[1], ",") - b.KonnectorHostAliasParsed = append(b.KonnectorHostAliasParsed, corev1.HostAlias{ - IP: parts[0], - Hostnames: hostnames, - }) - } - return nil -} - -// Validate validates the BindAPIServiceOptions are complete and usable. -func (b *BindAPIServiceOptions) Validate() error { - if b.file == "" && b.Template == "" { - return errors.New("file, template-name or --file are required") - } - - if allowed := sets.NewString(b.Print.AllowedFormats()...); *b.Print.OutputFormat != "" && !allowed.Has(*b.Print.OutputFormat) { - return fmt.Errorf("invalid output format %q (allowed: %s)", *b.Print.OutputFormat, strings.Join(allowed.List(), ", ")) - } - - if b.Template == "" { - if (b.remoteKubeconfigNamespace == "" && b.remoteKubeconfigName != "") || - (b.remoteKubeconfigNamespace != "" && b.remoteKubeconfigName == "") { - return errors.New("remote-kubeconfig-namespace and remote-kubeconfig-name must be specified together") - } - if b.remoteKubeconfigFile == "" && b.remoteKubeconfigNamespace == "" && b.remoteKubeconfigName == "" { - return errors.New("remote-kubeconfig or remote-kubeconfig-namespace and remote-kubeconfig-name are required") - } - } - // Name is required unless reading from file, where name will be read from the file. - if b.Name == "" && b.file == "" { - return errors.New("name is required") - } - - // TODO(mjudeikis): This code is duplicate fromn bind/plugin/bind.go. Unify. - // validate konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid konnector-host-alias entry %q, expected format IP:hostname1,hostname2", hostAlias) - } - if parts[0] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, IP address is empty", hostAlias) - } - if parts[1] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, hostnames are empty", hostAlias) - } - } - - return b.Options.Validate() -} - -// Run starts the binding process. -func (b *BindAPIServiceOptions) Run(ctx context.Context) error { - fmt.Fprintf(b.Options.ErrOut, "Starting binding process...\n") - - config, err := b.Options.ClientConfig.ClientConfig() - if err != nil { - return err - } - - // Use the shared binder to create bindings - binderOpts := &BinderOptions{ - IOStreams: b.Options.IOStreams, - SkipKonnector: b.SkipKonnector, - KonnectorImageOverride: b.KonnectorImageOverride, - KonnectorHostAliasParsed: b.KonnectorHostAliasParsed, - DowngradeKonnector: b.DowngradeKonnector, - RemoteKubeconfigFile: b.remoteKubeconfigFile, - RemoteKubeconfigNamespace: b.remoteKubeconfigNamespace, - RemoteKubeconfigName: b.remoteKubeconfigName, - RemoteNamespace: b.remoteNamespace, - ClusterIdentity: b.ClusterIdentity, - ClusterIdentityNamespaceName: b.clusterIdentityNamespaceName, - DryRun: b.DryRun, - File: b.file, - } - binder := NewBinder(config, binderOpts) - - var bindings []*kubebindv1alpha2.APIServiceBinding - if b.Template != "" { - r, err := b.bindTemplate(ctx) - if err != nil { - return err - } - bindings, err = binder.BindFromResponse(ctx, r.response) - if err != nil { - return fmt.Errorf("failed to create bindings: %w", err) - } - } else if b.file != "" { - bindings, err = binder.BindFromFile(ctx) - if err != nil { - return fmt.Errorf("failed to create bindings: %w", err) - } - } - - fmt.Fprintln(b.Options.ErrOut) - return b.printTable(ctx, config, bindings) -} - -func (b *BindAPIServiceOptions) getRemoteKubeconfig(ctx context.Context, config *rest.Config, namespace, name string) (kubeconfig, ns string, remoteConfig *rest.Config, err error) { - var remoteKubeConfig *clientcmdapi.Config - - switch { - case b.remoteKubeconfigFile != "": - remoteKubeConfig, err = clientcmd.LoadFromFile(b.remoteKubeconfigFile) - if err != nil { - return "", "", nil, err - } - case b.remoteKubeconfigNamespace != "" && b.remoteKubeconfigName != "": - name = b.remoteKubeconfigName - namespace = b.remoteKubeconfigNamespace - fallthrough - default: - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return "", "", nil, err - } - secret, err := kubeClient.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return "", "", nil, err - } - bs, found := secret.Data["kubeconfig"] - if !found { - return "", "", nil, fmt.Errorf("secret %s/%s does not contain a kubeconfig", namespace, name) - } - remoteKubeConfig, err = clientcmd.Load(bs) - if err != nil { - return "", "", nil, err - } - } - - c, found := remoteKubeConfig.Contexts[remoteKubeConfig.CurrentContext] - if !found { - return "", "", nil, fmt.Errorf("current context %q not found in remote kubeconfig", remoteKubeConfig.CurrentContext) - } - if b.remoteNamespace != "" { - c.Namespace = b.remoteNamespace - } - if c.Namespace == "" { - return "", "", nil, fmt.Errorf("remote namespace is required, either as flag or in the passed remote kubeconfig") - } - remoteConfig, err = clientcmd.NewDefaultClientConfig(*remoteKubeConfig, &clientcmd.ConfigOverrides{}).ClientConfig() - if err != nil { - return "", "", nil, err - } - - remoteKubeconfig, err := clientcmd.Write(*remoteKubeConfig) - if err != nil { - return "", "", nil, err - } - return string(remoteKubeconfig), c.Namespace, remoteConfig, nil -} - -func (b *BindAPIServiceOptions) ensureClientSideNamespaceExists(ctx context.Context, config *rest.Config) error { - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return err - } - - _, err = kubeClient.CoreV1().Namespaces().Get(ctx, "kube-bind", metav1.GetOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return err - } else if apierrors.IsNotFound(err) { - ns := &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-bind", - }, - } - if _, err = kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}); err != nil { - return err - } else { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Created kube-bind namespace.\n") - } - } - return nil -} - -type bindTemplateResult struct { - response *kubebindv1alpha2.BindingResourceResponse - namespace string - name string -} - -func (b *BindAPIServiceOptions) bindTemplate(ctx context.Context) (*bindTemplateResult, error) { - config, err := b.Options.ClientConfig.ClientConfig() - if err != nil { - return nil, err - } - - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return nil, fmt.Errorf("failed to create kube client: %w", err) - } - - // Get authenticated client with auto-login - client, err := b.Options.GetAuthenticatedClient() - if err != nil { - return nil, fmt.Errorf("failed to create authenticated client: %w", err) - } - - if b.ClusterIdentity == "" { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "⚠️ Warning: Cluster identity not provided, it will be generated based on the local cluster information which may lead to unexpected results if same identity is re-used. Be warrned of the dragons! \n") - ns, err := kubeClient.CoreV1().Namespaces().Get(ctx, b.clusterIdentityNamespaceName, metav1.GetOptions{}) // just to trigger possible errors early - if err != nil { - if apierrors.IsNotFound(err) { - return nil, fmt.Errorf("namespace %q not found for cluster identity generation: %w. You can override default identity namespace with --cluster-identity-namespace flag", b.clusterIdentityNamespaceName, err) - } - return nil, fmt.Errorf("failed to get namespace %q for cluster identity generation: %w", b.clusterIdentityNamespaceName, err) - } - fmt.Fprintf(b.Options.IOStreams.ErrOut, " Using namespace %q with UID %q for cluster identity generation.\n", ns.Name, ns.UID) - b.ClusterIdentity = string(ns.UID) - } - - bindRequest := &kubebindv1alpha2.BindableResourcesRequest{ - ObjectMeta: metav1.ObjectMeta{ - Name: b.Name, - }, - Spec: kubebindv1alpha2.BindableResourcesRequestSpec{ - TemplateRef: kubebindv1alpha2.APIServiceExportTemplateRef{ - Name: b.Template, - }, - ClusterIdentity: kubebindv1alpha2.ClusterIdentity{ - Identity: b.ClusterIdentity, - }, - }, - } - - bindResponse, err := client.Bind(ctx, bindRequest) - if err != nil { - return nil, fmt.Errorf("failed to bind to template %q: %w", b.Template, err) - } - - if bindResponse.Authentication.OAuth2CodeGrant == nil { - return nil, fmt.Errorf("unexpected response: authentication.oauth2CodeGrant is nil") - } - - err = b.ensureClientSideNamespaceExists(ctx, config) - if err != nil { - return nil, fmt.Errorf("failed to ensure kube-bind namespace exists: %w", err) - } - - // copy kubeconfig into local cluster - remoteHost, remoteNamespace, err := base.ParseRemoteKubeconfig(bindResponse.Kubeconfig) - if err != nil { - return nil, err - } - secretName, err := base.FindRemoteKubeconfig(ctx, kubeClient, remoteNamespace, remoteHost) - if err != nil { - return nil, err - } - secret, created, err := base.EnsureKubeconfigSecret(ctx, string(bindResponse.Kubeconfig), secretName, kubeClient) - if err != nil { - return nil, err - } - if created { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "🔒 Created secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } else { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "🔒 Updated secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } - return &bindTemplateResult{ - response: bindResponse, - namespace: secret.Namespace, - name: secret.Name, - }, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/binder.go b/cli/pkg/kubectl/bind-apiservice/plugin/binder.go deleted file mode 100644 index c903b4391..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/binder.go +++ /dev/null @@ -1,342 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "encoding/json" - "fmt" - "io" - "os" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/cli-runtime/pkg/genericclioptions" - kubeclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "sigs.k8s.io/yaml" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// BinderOptions contains the configuration for the shared binder -type BinderOptions struct { - IOStreams genericclioptions.IOStreams - SkipKonnector bool - KonnectorImageOverride string - KonnectorHostAliasParsed []corev1.HostAlias - DowngradeKonnector bool - RemoteKubeconfigFile string - RemoteKubeconfigNamespace string - RemoteKubeconfigName string - RemoteNamespace string - ClusterIdentity string - ClusterIdentityNamespaceName string - File string - DryRun bool -} - -// Binder provides shared binding functionality for both bind and bind-apiservice commands -type Binder struct { - opts *BinderOptions - config *rest.Config -} - -// NewBinder creates a new shared binder instance -func NewBinder(config *rest.Config, opts *BinderOptions) *Binder { - return &Binder{ - config: config, - opts: opts, - } -} - -// TODO: bindFromFile and bindFromResponse can likely share a lot of code. This slow is bit repetitive -// but keeps the two paths separate for clarity. But it needs love. -// https://github.com/kube-bind/kube-bind/issues/360 - -func (b *Binder) BindFromFile(ctx context.Context) ([]*kubebindv1alpha2.APIServiceBinding, error) { - // Generate the kubectl command that would be equivalent - remoteFlags := "" - if b.opts.RemoteKubeconfigFile != "" { - remoteFlags = fmt.Sprintf("--remote-kubeconfig %s", b.opts.RemoteKubeconfigFile) - } else if b.opts.RemoteKubeconfigNamespace != "" && b.opts.RemoteKubeconfigName != "" { - remoteFlags = fmt.Sprintf("--remote-kubeconfig-namespace %s --remote-kubeconfig-name %s", b.opts.RemoteKubeconfigNamespace, b.opts.RemoteKubeconfigName) - } - fmt.Fprintf(b.opts.IOStreams.ErrOut, "🚀 Executing: kubectl bind apiservice %s -f -\n", remoteFlags) - fmt.Fprintf(b.opts.IOStreams.ErrOut, "✨ Use \"-o yaml\" and \"--dry-run\" to get the APIServiceExportRequest.\n") - fmt.Fprintf(b.opts.IOStreams.ErrOut, " and pass it to \"kubectl bind apiservice\" directly. Great for automation.\n") - - // Ensure client side namespace exists - err := b.ensureClientSideNamespaceExists(ctx) - if err != nil { - return nil, fmt.Errorf("failed to ensure kube-bind namespace exists: %w", err) - } - - remoteKubeconfig, _, _, err := b.getRemoteKubeconfig(ctx, "", "") - if err != nil { - return nil, err - } - - // Copy kubeconfig into local cluster - remoteHost, remoteNamespace, err := base.ParseRemoteKubeconfig([]byte(remoteKubeconfig)) - if err != nil { - return nil, err - } - - kubeClient, err := kubeclient.NewForConfig(b.config) - if err != nil { - return nil, fmt.Errorf("failed to create kube client: %w", err) - } - - secretName, err := base.FindRemoteKubeconfig(ctx, kubeClient, remoteNamespace, remoteHost) - if err != nil { - return nil, err - } - - secret, created, err := base.EnsureKubeconfigSecret(ctx, remoteKubeconfig, secretName, kubeClient) - if err != nil { - return nil, err - } - - if created { - fmt.Fprintf(b.opts.IOStreams.ErrOut, "🔒 Created secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } else { - fmt.Fprintf(b.opts.IOStreams.ErrOut, "🔒 Updated secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } - - if b.opts.DryRun { - return nil, nil - } - - // Get remote kubeconfig - remoteKubeconfig, remoteNamespaceActual, remoteConfig, err := b.getRemoteKubeconfig(ctx, secret.Namespace, secret.Name) - if err != nil { - return nil, fmt.Errorf("failed to get remote kubeconfig: %w", err) - } - - data, err := b.getRequestManifest() - if err != nil { - return nil, fmt.Errorf("failed to get request manifest: %w", err) - } - - request, err := b.unmarshalManifest(data) - if err != nil { - return nil, fmt.Errorf("failed to unmarshal request manifest: %w", err) - } - - // Deploy konnector if needed - if err := b.deployKonnector(ctx); err != nil { - return nil, fmt.Errorf("failed to deploy konnector: %w", err) - } - - // Create bindings for all requests - result, err := b.createServiceExportRequest(ctx, remoteConfig, remoteNamespaceActual, request) - if err != nil { - return nil, fmt.Errorf("failed to create service export request: %w", err) - } - - secretName, err = b.createKubeconfigSecret(ctx, remoteConfig.Host, remoteNamespaceActual, remoteKubeconfig) - if err != nil { - return nil, fmt.Errorf("failed to create kubeconfig secret: %w", err) - } - - results, err := b.createAPIServiceBindings(ctx, result, secretName) - if err != nil { - return nil, fmt.Errorf("failed to create API service bindings: %w", err) - } - - return results, nil -} - -// BindFromResponse processes a BindingResourceResponse and creates all necessary bindings -func (b *Binder) BindFromResponse(ctx context.Context, response *kubebindv1alpha2.BindingResourceResponse) ([]*kubebindv1alpha2.APIServiceBinding, error) { - if response == nil || response.Authentication.OAuth2CodeGrant == nil { - return nil, fmt.Errorf("unexpected response: authentication.oauth2CodeGrant is nil") - } - - // Ensure client side namespace exists - err := b.ensureClientSideNamespaceExists(ctx) - if err != nil { - return nil, fmt.Errorf("failed to ensure kube-bind namespace exists: %w", err) - } - - // Copy kubeconfig into local cluster - remoteHost, remoteNamespace, err := base.ParseRemoteKubeconfig(response.Kubeconfig) - if err != nil { - return nil, err - } - - kubeClient, err := kubeclient.NewForConfig(b.config) - if err != nil { - return nil, fmt.Errorf("failed to create kube client: %w", err) - } - - secretName, err := base.FindRemoteKubeconfig(ctx, kubeClient, remoteNamespace, remoteHost) - if err != nil { - return nil, err - } - - secret, created, err := base.EnsureKubeconfigSecret(ctx, string(response.Kubeconfig), secretName, kubeClient) - if err != nil { - return nil, err - } - - if created { - fmt.Fprintf(b.opts.IOStreams.ErrOut, "🔒 Created secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } else { - fmt.Fprintf(b.opts.IOStreams.ErrOut, "🔒 Updated secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } - - if b.opts.DryRun { - return nil, nil - } - - // Get remote kubeconfig - remoteKubeconfig, remoteNamespaceActual, remoteConfig, err := b.getRemoteKubeconfig(ctx, secret.Namespace, secret.Name) - if err != nil { - return nil, fmt.Errorf("failed to get remote kubeconfig: %w", err) - } - - // Extract the requests - apiRequests := make([]*kubebindv1alpha2.APIServiceExportRequest, len(response.Requests)) - for i, request := range response.Requests { - var meta metav1.TypeMeta - if err := json.Unmarshal(request.Raw, &meta); err != nil { - return nil, fmt.Errorf("unexpected response: failed to unmarshal request #%d: %v", i, err) - } - if got, expected := meta.APIVersion, kubebindv1alpha2.SchemeGroupVersion.String(); got != expected { - return nil, fmt.Errorf("unexpected response: request #%d is not %s, got %s", i, expected, got) - } - var apiRequest kubebindv1alpha2.APIServiceExportRequest - if err := json.Unmarshal(request.Raw, &apiRequest); err != nil { - return nil, fmt.Errorf("failed to unmarshal api request #%d: %v", i+1, err) - } - apiRequests[i] = &apiRequest - } - - // Deploy konnector if needed - if err := b.deployKonnector(ctx); err != nil { - return nil, fmt.Errorf("failed to deploy konnector: %w", err) - } - - // Create bindings for all requests - bindings := make([]*kubebindv1alpha2.APIServiceBinding, 0, len(apiRequests)) - for _, request := range apiRequests { - result, err := b.createServiceExportRequest(ctx, remoteConfig, remoteNamespaceActual, request) - if err != nil { - return nil, fmt.Errorf("failed to create service export request: %w", err) - } - - secretName, err := b.createKubeconfigSecret(ctx, remoteConfig.Host, remoteNamespaceActual, remoteKubeconfig) - if err != nil { - return nil, fmt.Errorf("failed to create kubeconfig secret: %w", err) - } - - results, err := b.createAPIServiceBindings(ctx, result, secretName) - if err != nil { - return nil, fmt.Errorf("failed to create API service bindings: %w", err) - } - bindings = append(bindings, results...) - } - - return bindings, nil -} - -// Helper methods - these delegate to existing methods from BindAPIServiceOptions -func (b *Binder) ensureClientSideNamespaceExists(ctx context.Context) error { - // Create a temporary BindAPIServiceOptions to reuse existing logic - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - } - return tempOpts.ensureClientSideNamespaceExists(ctx, b.config) -} - -func (b *Binder) getRemoteKubeconfig(ctx context.Context, namespace, name string) (kubeconfig, ns string, remoteConfig *rest.Config, err error) { - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - remoteKubeconfigFile: b.opts.RemoteKubeconfigFile, - remoteKubeconfigNamespace: b.opts.RemoteKubeconfigNamespace, - remoteKubeconfigName: b.opts.RemoteKubeconfigName, - } - return tempOpts.getRemoteKubeconfig(ctx, b.config, namespace, name) -} - -func (b *Binder) deployKonnector(ctx context.Context) error { - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - SkipKonnector: b.opts.SkipKonnector, - KonnectorImageOverride: b.opts.KonnectorImageOverride, - DowngradeKonnector: b.opts.DowngradeKonnector, - DryRun: b.opts.DryRun, - KonnectorHostAliasParsed: b.opts.KonnectorHostAliasParsed, - } - return tempOpts.DeployKonnector(ctx, b.config) -} - -func (b *Binder) createServiceExportRequest(ctx context.Context, remoteConfig *rest.Config, remoteNamespace string, request *kubebindv1alpha2.APIServiceExportRequest) (*kubebindv1alpha2.APIServiceExportRequest, error) { - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - remoteNamespace: b.opts.RemoteNamespace, - } - return tempOpts.createServiceExportRequest(ctx, remoteConfig, remoteNamespace, request) -} - -func (b *Binder) createKubeconfigSecret(ctx context.Context, remoteHost, remoteNamespace, remoteKubeconfig string) (string, error) { - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - } - - return tempOpts.createKubeconfigSecret(ctx, b.config, remoteHost, remoteNamespace, remoteKubeconfig) -} - -func (b *Binder) createAPIServiceBindings(ctx context.Context, request *kubebindv1alpha2.APIServiceExportRequest, secretName string) ([]*kubebindv1alpha2.APIServiceBinding, error) { - tempOpts := &BindAPIServiceOptions{ - Options: &base.Options{IOStreams: b.opts.IOStreams}, - } - return tempOpts.createAPIServiceBindings(ctx, b.config, request, secretName) -} - -func (b *Binder) getRequestManifest() ([]byte, error) { - if b.opts.File == "-" { - body, err := io.ReadAll(b.opts.IOStreams.In) - if err != nil { - return nil, fmt.Errorf("failed to read from stdin: %w", err) - } - return body, nil - } - - body, err := os.ReadFile(b.opts.File) - if err != nil { - return nil, fmt.Errorf("failed to read file %s: %w", b.opts.File, err) - } - return body, nil -} - -func (b *Binder) unmarshalManifest(bs []byte) (*kubebindv1alpha2.APIServiceExportRequest, error) { - var request kubebindv1alpha2.APIServiceExportRequest - if err := yaml.Unmarshal(bs, &request); err != nil { - return nil, fmt.Errorf("failed to unmarshal manifest: %w", err) - } - if request.APIVersion != kubebindv1alpha2.SchemeGroupVersion.String() { - return nil, fmt.Errorf("invalid apiVersion %q", request.APIVersion) - } - if request.Kind != "APIServiceExportRequest" { - return nil, fmt.Errorf("invalid kind %q", request.Kind) - } - return &request, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/deploy_konnector.go b/cli/pkg/kubectl/bind-apiservice/plugin/deploy_konnector.go deleted file mode 100644 index 0707dc518..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/deploy_konnector.go +++ /dev/null @@ -1,299 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" -) - -const ( - KonnectorNamespace = "kube-bind" - KonnectorAppName = "konnector" - KonnectorServiceAccount = "konnector" - KonnectorClusterRole = "kube-bind-konnector" - KonnectorClusterRoleBinding = "kube-bind-konnector" -) - -func bootstrapKonnector( - ctx context.Context, - discoveryClient discovery.DiscoveryInterface, - dynamicClient dynamic.Interface, - image string, - hostAliases []corev1.HostAlias, -) error { - resources := getAllKonnectorResources(image, hostAliases) - - for _, resource := range resources { - if err := applyResource(ctx, dynamicClient, discoveryClient, resource); err != nil { - return err - } - } - - return nil -} - -// getAllKonnectorResources returns all konnector resources needed for deployment -func getAllKonnectorResources(image string, hostAliases []corev1.HostAlias) []interface{} { - return []interface{}{ - getKonnectorNamespace(), - getKonnectorServiceAccount(), - getKonnectorClusterRole(), - getKonnectorClusterRoleBinding(), - getKonnectorDeployment(image, hostAliases), - } -} - -// getKonnectorNamespace returns the namespace for konnector deployment -func getKonnectorNamespace() *corev1.Namespace { - return &corev1.Namespace{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "v1", - Kind: "Namespace", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorNamespace, - }, - } -} - -// getKonnectorServiceAccount returns the service account for konnector -func getKonnectorServiceAccount() *corev1.ServiceAccount { - return &corev1.ServiceAccount{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "v1", - Kind: "ServiceAccount", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorServiceAccount, - Namespace: KonnectorNamespace, - }, - } -} - -// getKonnectorClusterRole returns the cluster role for konnector -func getKonnectorClusterRole() *rbacv1.ClusterRole { - return &rbacv1.ClusterRole{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "rbac.authorization.k8s.io/v1", - Kind: "ClusterRole", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorClusterRole, - }, - Rules: []rbacv1.PolicyRule{ - { - APIGroups: []string{"*"}, - Resources: []string{"*"}, - Verbs: []string{"*"}, - }, - }, - } -} - -// getKonnectorClusterRoleBinding returns the cluster role binding for konnector -func getKonnectorClusterRoleBinding() *rbacv1.ClusterRoleBinding { - return &rbacv1.ClusterRoleBinding{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "rbac.authorization.k8s.io/v1", - Kind: "ClusterRoleBinding", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorClusterRoleBinding, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: "rbac.authorization.k8s.io", - Kind: "ClusterRole", - Name: KonnectorClusterRole, - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - Name: KonnectorServiceAccount, - Namespace: KonnectorNamespace, - }, - }, - } -} - -// getKonnectorDeployment returns the deployment for konnector -func getKonnectorDeployment(image string, hostAliases []corev1.HostAlias) *appsv1.Deployment { - replicas := int32(2) - - return &appsv1.Deployment{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apps/v1", - Kind: "Deployment", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: KonnectorAppName, - Namespace: KonnectorNamespace, - Labels: map[string]string{ - "app": KonnectorAppName, - }, - }, - Spec: appsv1.DeploymentSpec{ - Replicas: &replicas, - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": KonnectorAppName, - }, - }, - Template: corev1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "app": KonnectorAppName, - }, - }, - Spec: corev1.PodSpec{ - RestartPolicy: corev1.RestartPolicyAlways, - ServiceAccountName: KonnectorServiceAccount, - HostAliases: hostAliases, - Containers: []corev1.Container{ - { - Name: KonnectorAppName, - Image: image, - Env: []corev1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "POD_NAMESPACE", - ValueFrom: &corev1.EnvVarSource{ - FieldRef: &corev1.ObjectFieldSelector{ - FieldPath: "metadata.namespace", - }, - }, - }, - }, - ReadinessProbe: &corev1.Probe{ - ProbeHandler: corev1.ProbeHandler{ - HTTPGet: &corev1.HTTPGetAction{ - Path: "/healthz", - Port: intstr.FromInt(8090), - }, - }, - }, - }, - }, - }, - }, - }, - } -} - -func applyResource(ctx context.Context, dynamicClient dynamic.Interface, discoveryClient discovery.DiscoveryInterface, obj interface{}) error { - runtimeObj, ok := obj.(runtime.Object) - if !ok { - return nil - } - - // Convert to unstructured - unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(runtimeObj) - if err != nil { - return err - } - - // Extract metadata - metadata, ok := unstructuredObj["metadata"].(map[string]interface{}) - if !ok { - return nil - } - - name, _ := metadata["name"].(string) - namespace, _ := metadata["namespace"].(string) - - // Get GVK information - gvk := runtimeObj.GetObjectKind().GroupVersionKind() - - // Get GVR from discovery - gvr := getGVRFromGVK(gvk) - - // Apply the resource - var resourceClient dynamic.ResourceInterface - if namespace != "" { - resourceClient = dynamicClient.Resource(gvr).Namespace(namespace) - } else { - resourceClient = dynamicClient.Resource(gvr) - } - - // Try to get existing resource - _, err = resourceClient.Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if errors.IsNotFound(err) { - // Create new resource - _, err = resourceClient.Create(ctx, &unstructured.Unstructured{Object: unstructuredObj}, metav1.CreateOptions{}) - return err - } - return err - } - - // Update existing resource - _, err = resourceClient.Update(ctx, &unstructured.Unstructured{Object: unstructuredObj}, metav1.UpdateOptions{}) - return err -} - -func getGVRFromGVK(gvk schema.GroupVersionKind) schema.GroupVersionResource { - gvkMap := map[schema.GroupVersionKind]schema.GroupVersionResource{ - {Group: "", Version: "v1", Kind: "Namespace"}: { - Group: "", - Version: "v1", - Resource: "namespaces", - }, - {Group: "", Version: "v1", Kind: "ServiceAccount"}: { - Group: "", - Version: "v1", - Resource: "serviceaccounts", - }, - {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"}: { - Group: "rbac.authorization.k8s.io", - Version: "v1", - Resource: "clusterroles", - }, - {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}: { - Group: "rbac.authorization.k8s.io", - Version: "v1", - Resource: "clusterrolebindings", - }, - {Group: "apps", Version: "v1", Kind: "Deployment"}: { - Group: "apps", - Version: "v1", - Resource: "deployments", - }, - } - if gvr, found := gvkMap[gvk]; found { - return gvr - } - - return schema.GroupVersionResource{} -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/konnector.go b/cli/pkg/kubectl/bind-apiservice/plugin/konnector.go deleted file mode 100644 index 2614d2b64..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/konnector.go +++ /dev/null @@ -1,148 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/blang/semver/v4" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" - kubeclient "k8s.io/client-go/kubernetes" - clientgoversion "k8s.io/client-go/pkg/version" - "k8s.io/client-go/rest" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/version" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" -) - -const ( - konnectorImage = "ghcr.io/kbind-dev/konnector" -) - -// DeployKonnector deploys the konnector to the cluster. -func (b *BindAPIServiceOptions) DeployKonnector(ctx context.Context, config *rest.Config) error { - logger := klog.FromContext(ctx) - - dynamicClient, err := dynamic.NewForConfig(config) - if err != nil { - return err - } - discoveryClient, err := discovery.NewDiscoveryClientForConfig(config) - if err != nil { - return err - } - bindClient, err := bindclient.NewForConfig(config) - if err != nil { - return err - } - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return err - } - - bindVersion, err := version.BinaryVersion(clientgoversion.Get().GitVersion) - if err != nil { - return err - } - - if b.KonnectorImageOverride != "" { - fmt.Fprintf(b.Options.ErrOut, "🚀 Deploying konnector %s to namespace kube-bind with custom image %q.\n", bindVersion, b.KonnectorImageOverride) - if err := bootstrapKonnector(ctx, discoveryClient, dynamicClient, b.KonnectorImageOverride, b.KonnectorHostAliasParsed); err != nil { - return err - } - } else if !b.SkipKonnector { - konnectorVersion, installed, err := currentKonnectorVersion(ctx, kubeClient) - if err != nil { - return fmt.Errorf("failed to check current konnector version in the cluster: %w", err) - } - - konnectorImage := fmt.Sprintf("%s:%s", konnectorImage, bindVersion) - - if installed { - if konnectorVersion == "unknown" || konnectorVersion == "latest" || konnectorVersion == "main" { - fmt.Fprintf(b.Options.ErrOut, "konnector of %s version already installed, skipping\n", konnectorVersion) - // fall through to CRD test - } else { - konnectorSemVer, konnectorErr := semver.Parse(strings.TrimLeft(konnectorVersion, "v")) - bindSemVer, bindErr := semver.Parse(strings.TrimLeft(bindVersion, "v")) - - // If either version is not a valid SemVer (e.g., a git hash), skip version comparison - switch { - case konnectorErr != nil || bindErr != nil: - fmt.Fprintf(b.Options.ErrOut, "konnector version %s or bind version %s is not a valid SemVer, skipping version comparison\n", konnectorVersion, bindVersion) - // fall through to CRD test - case bindSemVer.GT(konnectorSemVer): - fmt.Fprintf(b.Options.ErrOut, "Updating konnector from %s to %s.\n", konnectorVersion, bindVersion) - if err := bootstrapKonnector(ctx, discoveryClient, dynamicClient, konnectorImage, b.KonnectorHostAliasParsed); err != nil { - return err - } - case bindSemVer.LT(konnectorSemVer): - fmt.Fprintf(b.Options.ErrOut, "Newer konnector %s installed. To downgrade to %s use --downgrade-konnector.\n", konnectorVersion, bindVersion) - } - } - } else { - fmt.Fprintf(b.Options.ErrOut, "🚀 Deploying konnector %s to namespace kube-bind.\n", bindVersion) - if err := bootstrapKonnector(ctx, discoveryClient, dynamicClient, konnectorImage, b.KonnectorHostAliasParsed); err != nil { - return err - } - } - } - first := true - return wait.PollUntilContextCancel(ctx, 1*time.Second, true, func(ctx context.Context) (bool, error) { - _, err := bindClient.KubeBindV1alpha2().APIServiceBindings().List(ctx, metav1.ListOptions{}) - if err == nil { - if !first { - fmt.Fprintln(b.Options.IOStreams.ErrOut) - } - return true, nil - } - - logger.V(2).Info("Waiting for APIServiceBindings to be served", "error", err, "host", config.Host) - if first { - fmt.Fprint(b.Options.IOStreams.ErrOut, " Waiting for the konnector to be ready") - first = false - } else { - fmt.Fprint(b.Options.IOStreams.ErrOut, ".") - } - return false, nil - }) -} - -func currentKonnectorVersion(ctx context.Context, kubeClient kubeclient.Interface) (string, bool, error) { - deployment, err := kubeClient.AppsV1().Deployments("kube-bind").Get(ctx, "konnector", metav1.GetOptions{}) - if err != nil && !errors.IsNotFound(err) { - return "", false, err - } else if errors.IsNotFound(err) { - return "", false, nil - } - - img := deployment.Spec.Template.Spec.Containers[0].Image - if !strings.HasPrefix(img, konnectorImage+":") { - return "unknown", true, nil - } - - version := strings.TrimPrefix(img, konnectorImage+":") - return version, true, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/secret.go b/cli/pkg/kubectl/bind-apiservice/plugin/secret.go deleted file mode 100644 index 26645f77d..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/secret.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubeclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" -) - -func (b *BindAPIServiceOptions) createKubeconfigSecret(ctx context.Context, config *rest.Config, remoteHost, remoteNamespace, kubeconfig string) (string, error) { - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return "", err - } - - // create kube-bind namespace - if _, err := kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-bind", - }, - }, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) { - return "", err - } else if err == nil { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "📦 Created kube-binding namespace.\n") - } - - // look for secret of the given identity - secretName, err := base.FindRemoteKubeconfig(ctx, kubeClient, remoteNamespace, remoteHost) - if err != nil { - return "", err - } else if secretName != "" { - return secretName, nil - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Creating secret for host %s, namespace %s\n", remoteHost, remoteNamespace) - secretName, err = b.ensureKubeconfigSecretWithLogging(ctx, kubeconfig, "", kubeClient) - if err != nil { - return "", err - } - - return secretName, nil -} - -func (b *BindAPIServiceOptions) ensureKubeconfigSecretWithLogging(ctx context.Context, kubeconfig, name string, client kubeclient.Interface) (string, error) { - secret, created, err := base.EnsureKubeconfigSecret(ctx, kubeconfig, name, client) - if err != nil { - return "", err - } - - remoteHost, remoteNamespace, err := base.ParseRemoteKubeconfig([]byte(kubeconfig)) - if err != nil { - return "", err - } - - if b.remoteKubeconfigFile != "" { - if created { - fmt.Fprintf(b.Options.ErrOut, "🔒 Created secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } else { - fmt.Fprintf(b.Options.ErrOut, "🔒 Updated secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } - } - - return secret.Name, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/servicebindings.go b/cli/pkg/kubectl/bind-apiservice/plugin/servicebindings.go deleted file mode 100644 index b539c8b64..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/servicebindings.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - "time" - - apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2/helpers" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" -) - -func (b *BindAPIServiceOptions) createAPIServiceBindings(ctx context.Context, config *rest.Config, request *kubebindv1alpha2.APIServiceExportRequest, secretName string) ([]*kubebindv1alpha2.APIServiceBinding, error) { - bindClient, err := bindclient.NewForConfig(config) - if err != nil { - return nil, err - } - apiextensionsClient, err := apiextensionsclientset.NewForConfig(config) - if err != nil { - return nil, err - } - - // Use request name as the single binding name - bindingName := request.ObjectMeta.Name - existing, err := bindClient.KubeBindV1alpha2().APIServiceBindings().Get(ctx, bindingName, metav1.GetOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return nil, err - } else if err == nil { - // Validate existing binding - if existing.Spec.KubeconfigSecretRef.Namespace != "kube-bind" || existing.Spec.KubeconfigSecretRef.Name != secretName { - return nil, fmt.Errorf("found existing APIServiceBinding %s not from this service provider", bindingName) - } - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Reusing existing APIServiceBinding %s.\n", existing.Name) - - // Validate all CRDs are owned by this binding - for _, resource := range request.Spec.Resources { - crd, err := apiextensionsClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, resource.ResourceGroupName(), metav1.GetOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return nil, err - } else if err == nil { - if !helpers.IsOwnedByBinding(existing.Name, existing.UID, crd.OwnerReferences) { - return nil, fmt.Errorf("CustomResourceDefinition %s exists, but is not owned by kube-bind", crd.Name) - } - } - } - - return []*kubebindv1alpha2.APIServiceBinding{existing}, nil - } - - // Create new APIServiceBinding - var created *kubebindv1alpha2.APIServiceBinding - if err := wait.PollUntilContextCancel(ctx, 1*time.Second, false, func(ctx context.Context) (bool, error) { - created, err = bindClient.KubeBindV1alpha2().APIServiceBindings().Create(ctx, &kubebindv1alpha2.APIServiceBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: bindingName, - }, - Spec: kubebindv1alpha2.APIServiceBindingSpec{ - KubeconfigSecretRef: kubebindv1alpha2.ClusterSecretKeyRef{ - LocalSecretKeyRef: kubebindv1alpha2.LocalSecretKeyRef{ - Name: secretName, - Key: "kubeconfig", - }, - Namespace: "kube-bind", - }, - }, - }, metav1.CreateOptions{}) - if err != nil { - return false, err - } - - // Best effort status update to have "Pending" in the Ready condition - conditions.MarkFalse(created, - conditionsapi.ReadyCondition, - "Pending", - conditionsapi.ConditionSeverityInfo, - "Pending", - ) - _, _ = bindClient.KubeBindV1alpha2().APIServiceBindings().UpdateStatus(ctx, created, metav1.UpdateOptions{}) - - return true, nil - }); err != nil { - return nil, err - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "✅ Created APIServiceBinding %s for %d resources\n", bindingName, len(request.Spec.Resources)) - return []*kubebindv1alpha2.APIServiceBinding{created}, nil -} diff --git a/cli/pkg/kubectl/bind-apiservice/plugin/serviceexportrequest.go b/cli/pkg/kubectl/bind-apiservice/plugin/serviceexportrequest.go deleted file mode 100644 index b28562e63..000000000 --- a/cli/pkg/kubectl/bind-apiservice/plugin/serviceexportrequest.go +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - "time" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/cli-runtime/pkg/printers" - "k8s.io/client-go/rest" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" -) - -func (b *BindAPIServiceOptions) createServiceExportRequest( - ctx context.Context, - remoteConfig *rest.Config, - ns string, - request *kubebindv1alpha2.APIServiceExportRequest, -) (*kubebindv1alpha2.APIServiceExportRequest, error) { - bindRemoteClient, err := bindclient.NewForConfig(remoteConfig) - if err != nil { - return nil, err - } - - // create request in the service provider cluster - if request.Name == "" { - request.GenerateName = "export-" - } - created, err := bindRemoteClient.KubeBindV1alpha2().APIServiceExportRequests(ns).Create(ctx, request, metav1.CreateOptions{}) - if err != nil { - if !apierrors.IsAlreadyExists(err) { - return nil, err - } - if request.Name == "" { - return nil, err - } - request.GenerateName = request.Name + "-" - request.Name = "" - created, err = bindRemoteClient.KubeBindV1alpha2().APIServiceExportRequests(ns).Create(ctx, request, metav1.CreateOptions{}) - if err != nil { - return nil, err - } - } - - // wait for the request to be Successful, Failed or deleted - var result *kubebindv1alpha2.APIServiceExportRequest - if err := wait.PollUntilContextTimeout(ctx, 1*time.Second, 10*time.Minute, true, func(ctx context.Context) (bool, error) { - request, err := bindRemoteClient.KubeBindV1alpha2().APIServiceExportRequests(ns).Get(ctx, created.Name, metav1.GetOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return false, err - } else if apierrors.IsNotFound(err) { - return false, fmt.Errorf("APIServiceExportRequest %s was deleted by the service provider", created.Name) - } - if request.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhaseSucceeded { - result = request - return true, nil - } - if request.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhaseFailed { - return false, fmt.Errorf("binding request failed: %s", request.Status.TerminalMessage) - } - return false, nil - }); err != nil { - return nil, err - } - - return result, nil -} - -func (b *BindAPIServiceOptions) printTable(ctx context.Context, config *rest.Config, bindings []*kubebindv1alpha2.APIServiceBinding) error { - printer := printers.NewTablePrinter(printers.PrintOptions{ - WithKind: true, - Kind: kubebindv1alpha2.SchemeGroupVersion.WithKind("APIServiceBinding").GroupKind(), - }) - - tableConfig := rest.CopyConfig(config) - tableConfig.APIPath = "/apis" - tableConfig.ContentConfig.AcceptContentTypes = fmt.Sprintf("application/json;as=Table;v=%s;g=%s", metav1.SchemeGroupVersion.Version, metav1.GroupName) - tableConfig.GroupVersion = &kubebindv1alpha2.SchemeGroupVersion - scheme := runtime.NewScheme() - if err := metav1.AddMetaToScheme(scheme); err != nil { - return err - } - tableConfig.NegotiatedSerializer = serializer.NewCodecFactory(scheme) - tableClient, err := rest.RESTClientFor(tableConfig) - if err != nil { - return err - } - - var bindingsTable metav1.Table - for _, binding := range bindings { - var singularTable metav1.Table - if err := tableClient.Get().Resource("apiservicebindings").Name(binding.Name).Do(ctx).Into(&singularTable); err != nil { - return err - } - if len(bindingsTable.Rows) == 0 { - bindingsTable = singularTable - } else { - bindingsTable.Rows = append(bindingsTable.Rows, singularTable.Rows...) - } - } - return printer.PrintObj(&bindingsTable, b.Options.IOStreams.Out) -} diff --git a/cli/pkg/kubectl/bind-collections/cmd/cmd.go b/cli/pkg/kubectl/bind-collections/cmd/cmd.go deleted file mode 100644 index d104d4a1a..000000000 --- a/cli/pkg/kubectl/bind-collections/cmd/cmd.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-collections/plugin" -) - -var ( - collectionsExampleUses = ` - # List collections from currently authenticated server - %[1]s collections - - # List collections using --server flag to override current server - %[1]s collections --server https://mangodb.com - - # List collections with JSON/YAML output - %[1]s collections -o json - %[1]s collections -o yaml - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewCollectionsOptions(streams) - cmd := &cobra.Command{ - Use: "collections [server-url]", - Short: "List available collections from a kube-bind server", - Long: help.Doc(` - List all available collections from a kube-bind server. - - This command connects to a kube-bind server and displays all the - collections that are available. By default, it uses the current - authenticated server from your configuration. - - If you haven't authenticated to any server yet, you must provide - a server URL argument or use 'kubectl bind-login ' first. - `), - Example: help.Examplesf(collectionsExampleUses, "kubectl"), - SilenceUsage: true, - Args: func(cmd *cobra.Command, args []string) error { - for _, arg := range args { - if !strings.HasPrefix(arg, "http://") && !strings.HasPrefix(arg, "https://") { - return fmt.Errorf("invalid server URL: %s", arg) - } - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context()) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind-collections/plugin/collections.go b/cli/pkg/kubectl/bind-collections/plugin/collections.go deleted file mode 100644 index 66602ab7b..000000000 --- a/cli/pkg/kubectl/bind-collections/plugin/collections.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - "strings" - "text/tabwriter" - "time" - - "github.com/spf13/cobra" - "k8s.io/apimachinery/pkg/util/duration" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/cli-runtime/pkg/printers" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// CollectionsOptions contains the options for listing collections -type CollectionsOptions struct { - *base.Options - Logs *logs.Options - - Print *genericclioptions.PrintFlags - printer printers.ResourcePrinter -} - -// NewCollectionsOptions creates a new CollectionsOptions -func NewCollectionsOptions(streams genericclioptions.IOStreams) *CollectionsOptions { - return &CollectionsOptions{ - Options: base.NewOptions(streams), - Logs: logs.NewOptions(), - Print: genericclioptions.NewPrintFlags("collections").WithDefaultOutput(""), - } -} - -// AddCmdFlags adds command line flags -func (o *CollectionsOptions) AddCmdFlags(cmd *cobra.Command) { - o.Options.BindFlags(cmd) - logsv1.AddFlags(o.Logs, cmd.Flags()) - o.Print.AddFlags(cmd) -} - -// Complete completes the options -func (o *CollectionsOptions) Complete(args []string) error { - // Set this before complete base settings as login accepts server URL as argument without flag. - if len(args) > 0 { - o.Options.ServerName = args[0] - } - - if err := o.Options.Complete(false); err != nil { - return err - } - - printer, err := o.Print.ToPrinter() - if err != nil { - return err - } - o.printer = printer - - return nil -} - -// Validate validates the options -func (o *CollectionsOptions) Validate() error { - return o.Options.Validate() -} - -// Run executes the collections listing command -func (o *CollectionsOptions) Run(ctx context.Context) error { - // Get authenticated client - client, err := o.Options.GetAuthenticatedClient() - if err != nil { - return fmt.Errorf("failed to create authenticated client: %w", err) - } - - // Fetch collections - collections, err := client.GetCollections(ctx) - if err != nil { - return fmt.Errorf("failed to fetch collections: %w", err) - } - - return o.printCollections(collections) -} - -// printCollections handles printing collections using the configured printer -func (o *CollectionsOptions) printCollections(collections *kubebindv1alpha2.CollectionList) error { - // For non-table output formats, print the whole list - if o.Print.OutputFormat != nil && *o.Print.OutputFormat != "" { - collections.SetGroupVersionKind(kubebindv1alpha2.SchemeGroupVersion.WithKind("CollectionList")) - return o.printer.PrintObj(collections, o.Options.IOStreams.Out) - } - - // For table output, create a custom human-readable table - return o.printCollectionsTable(collections) -} - -// printCollectionsTable prints collections in table format using tabwriter -// TODO: Replace with custom TablePrinter when available in cli-runtime -func (o *CollectionsOptions) printCollectionsTable(collections *kubebindv1alpha2.CollectionList) error { - w := tabwriter.NewWriter(o.Options.IOStreams.Out, 0, 0, 3, ' ', 0) - fmt.Fprintf(w, "NAME\tDESCRIPTION\tTEMPLATES\tAGE\n") - - for _, item := range collections.Items { - description := item.Spec.Description - if description == "" { - description = "" - } - - // Create a comma-separated list of template names - templateNames := make([]string, len(item.Spec.Templates)) - for i, template := range item.Spec.Templates { - templateNames[i] = template.Name - } - templates := strings.Join(templateNames, ",") - - age := duration.HumanDuration(time.Since(item.CreationTimestamp.Time)) - - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", item.Name, description, templates, age) - } - - return w.Flush() -} diff --git a/cli/pkg/kubectl/bind-deploy/cmd/cmd.go b/cli/pkg/kubectl/bind-deploy/cmd/cmd.go deleted file mode 100644 index bcacfa9a1..000000000 --- a/cli/pkg/kubectl/bind-deploy/cmd/cmd.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "fmt" - - "github.com/fatih/color" - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-deploy/plugin" - - _ "k8s.io/client-go/plugin/pkg/client/auth/exec" - _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" -) - -var ( - bindDeployExampleUses = ` - # Deploy konnector from a BindingResourceResponse stored in a secret - %[1]s deploy --secret kube-bind/my-binding-response - - # Deploy konnector from a BindingResourceResponse file - %[1]s deploy --file binding-response.yaml - - # Deploy konnector reading from stdin - %[1]s deploy --file - - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewBindDeployOptions(streams) - cmd := &cobra.Command{ - Use: "deploy", - Short: "Deploy konnector from a BindingResourceResponse", - Long: help.Doc(` - Deploy the konnector and create APIServiceBindings from a BindingResourceResponse. - - This command is useful when you have obtained a BindingResourceResponse through - the CRD-based flow (BindableResourcesRequest) and want to deploy the konnector - to establish the connection. - - The BindingResourceResponse can be provided via: - - A Kubernetes secret (--secret namespace/name) - - A file (--file path/to/file.yaml) - - Standard input (--file -) - `), - Example: fmt.Sprintf(bindDeployExampleUses, "kubectl bind"), - SilenceUsage: true, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - if !opts.NoBanner { - yellow := color.New(color.BgRed, color.FgBlack).SprintFunc() - fmt.Fprintf(streams.ErrOut, "%s\n\n", yellow("DISCLAIMER: This is a prototype. It will change in incompatible ways at any time.")) - } - - if err := opts.Run(cmd.Context()); err != nil { - fmt.Fprintf(streams.ErrOut, "Error: %v\n", err) - return nil - } - return nil - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind-deploy/plugin/deploy.go b/cli/pkg/kubectl/bind-deploy/plugin/deploy.go deleted file mode 100644 index 941738500..000000000 --- a/cli/pkg/kubectl/bind-deploy/plugin/deploy.go +++ /dev/null @@ -1,394 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "strings" - - "github.com/spf13/cobra" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/cli-runtime/pkg/printers" - kubeclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - "sigs.k8s.io/yaml" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - bindapiservice "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/plugin" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// BindDeployOptions are the options for the kubectl-bind-deploy command. -type BindDeployOptions struct { - *base.Options - Logs *logs.Options - - JSONYamlPrintFlags *genericclioptions.JSONYamlPrintFlags - OutputFormat string - Print *genericclioptions.PrintFlags - printer printers.ResourcePrinter - - // secretRef is the namespace/name reference to a secret containing the BindingResourceResponse - secretRef string - // secretKey is the key in the secret containing the BindingResourceResponse - secretKey string - // file is the path to a file containing the BindingResourceResponse - file string - // kubeconfigSecretName is the name to use for the kubeconfig secret in kube-bind namespace. - // If empty, a generated name (kubeconfig-) will be used. - kubeconfigSecretName string - - // skipKonnector skips the deployment of the konnector. - SkipKonnector bool - KonnectorImageOverride string - DowngradeKonnector bool - // KonnectorHostAlias is a list of host alias entries to add to the konnector pods. - KonnectorHostAlias []string - // KonnectorHostAliasParsed is the parsed version of KonnectorHostAlias. - KonnectorHostAliasParsed []corev1.HostAlias - - NoBanner bool - DryRun bool -} - -// NewBindDeployOptions returns new BindDeployOptions. -func NewBindDeployOptions(streams genericclioptions.IOStreams) *BindDeployOptions { - return &BindDeployOptions{ - Options: base.NewOptions(streams), - Logs: logs.NewOptions(), - Print: genericclioptions.NewPrintFlags("kubectl-bind-deploy"), - secretKey: "kubeconfig", // default key - } -} - -// AddCmdFlags binds fields to cmd's flagset. -func (b *BindDeployOptions) AddCmdFlags(cmd *cobra.Command) { - b.Options.BindFlags(cmd) - logsv1.AddFlags(b.Logs, cmd.Flags()) - b.Print.AddFlags(cmd) - - // Secret/file source - cmd.Flags().StringVar(&b.secretRef, "secret", b.secretRef, "Reference to a secret containing the BindingResourceResponse (format: namespace/name)") - cmd.Flags().StringVar(&b.secretKey, "secret-key", b.secretKey, "Key in the secret containing the BindingResourceResponse (default: kubeconfig)") - cmd.Flags().StringVarP(&b.file, "file", "f", b.file, "A file with a BindingResourceResponse manifest. Use - to read from stdin") - cmd.Flags().StringVar(&b.kubeconfigSecretName, "provider-kubeconfig-secret-name", b.kubeconfigSecretName, "Name for the kubeconfig secret in kube-bind namespace. If not specified, a generated name will be used") - - // Konnector configuration - cmd.Flags().BoolVar(&b.SkipKonnector, "skip-konnector", b.SkipKonnector, "Skip the deployment of the konnector") - cmd.Flags().BoolVarP(&b.DryRun, "dry-run", "d", b.DryRun, "If true, only print the actions that would be taken without executing them") - cmd.Flags().StringVar(&b.KonnectorImageOverride, "konnector-image", b.KonnectorImageOverride, "The konnector image to use") - cmd.Flags().MarkHidden("konnector-image") //nolint:errcheck - cmd.Flags().StringSliceVarP(&b.KonnectorHostAlias, "konnector-host-alias", "", []string{}, "Add a host alias to the konnector pods in the format IP:hostname1,hostname2") - cmd.Flags().MarkHidden("konnector-host-alias") //nolint:errcheck - cmd.Flags().BoolVar(&b.DowngradeKonnector, "downgrade-konnector", b.DowngradeKonnector, "Downgrade the konnector to the version of the kubectl-bind binary") - cmd.Flags().BoolVar(&b.NoBanner, "no-banner", b.NoBanner, "Do not show the red banner") - cmd.Flags().MarkHidden("no-banner") //nolint:errcheck -} - -// Complete ensures all fields are initialized. -func (b *BindDeployOptions) Complete(args []string) error { - if err := b.Options.Complete(false); err != nil { - return err - } - - printer, err := b.Print.ToPrinter() - if err != nil { - return err - } - b.printer = printer - - // Parse konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - if len(parts) != 2 { - continue - } - hostnames := strings.Split(parts[1], ",") - b.KonnectorHostAliasParsed = append(b.KonnectorHostAliasParsed, corev1.HostAlias{ - IP: parts[0], - Hostnames: hostnames, - }) - } - return nil -} - -// Validate validates the BindDeployOptions are complete and usable. -func (b *BindDeployOptions) Validate() error { - if b.secretRef == "" && b.file == "" { - return errors.New("either --secret or --file is required") - } - - if b.secretRef != "" && b.file != "" { - return errors.New("only one of --secret or --file can be specified") - } - - if b.secretRef != "" { - parts := strings.SplitN(b.secretRef, "/", 2) - if len(parts) != 2 || parts[0] == "" || parts[1] == "" { - return fmt.Errorf("invalid --secret format %q, expected namespace/name", b.secretRef) - } - } - - // Validate konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid konnector-host-alias entry %q, expected format IP:hostname1,hostname2", hostAlias) - } - if parts[0] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, IP address is empty", hostAlias) - } - if parts[1] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, hostnames are empty", hostAlias) - } - } - - return b.Options.Validate() -} - -// Run starts the deployment process. -func (b *BindDeployOptions) Run(ctx context.Context) error { - fmt.Fprintf(b.Options.ErrOut, "Starting deployment process...\n") - - config, err := b.Options.ClientConfig.ClientConfig() - if err != nil { - return err - } - - // Get the BindingResourceResponse - response, err := b.getBindingResponse(ctx, config) - if err != nil { - return fmt.Errorf("failed to get BindingResourceResponse: %w", err) - } - - // Use the shared binder to deploy - binderOpts := &bindapiservice.BinderOptions{ - IOStreams: b.Options.IOStreams, - SkipKonnector: b.SkipKonnector, - KonnectorImageOverride: b.KonnectorImageOverride, - KonnectorHostAliasParsed: b.KonnectorHostAliasParsed, - DowngradeKonnector: b.DowngradeKonnector, - DryRun: b.DryRun, - } - binder := bindapiservice.NewBinder(config, binderOpts) - - bindings, err := b.bindFromKubeconfig(ctx, binder, config, response) - if err != nil { - return fmt.Errorf("failed to create bindings: %w", err) - } - - fmt.Fprintln(b.Options.ErrOut) - return b.printTable(ctx, config, bindings) -} - -// getBindingResponse reads the BindingResourceResponse from the specified source. -func (b *BindDeployOptions) getBindingResponse(ctx context.Context, config *rest.Config) (*kubebindv1alpha2.BindingResourceResponse, error) { - var data []byte - var err error - - if b.secretRef != "" { - parts := strings.SplitN(b.secretRef, "/", 2) - namespace, name := parts[0], parts[1] - - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return nil, fmt.Errorf("failed to create kube client: %w", err) - } - - secret, err := kubeClient.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return nil, fmt.Errorf("failed to get secret %s/%s: %w", namespace, name, err) - } - - data, ok := secret.Data[b.secretKey] - if !ok { - return nil, fmt.Errorf("secret %s/%s does not contain key %q", namespace, name, b.secretKey) - } - - var response kubebindv1alpha2.BindingResourceResponse - if err := json.Unmarshal(data, &response); err != nil { - return nil, fmt.Errorf("failed to unmarshal BindingResourceResponse from secret: %w", err) - } - - fmt.Fprintf(b.Options.ErrOut, "📦 Read BindingResourceResponse from secret %s/%s\n", namespace, name) - return &response, nil - } - - // Read from file - if b.file == "-" { - data, err = io.ReadAll(b.Options.In) - if err != nil { - return nil, fmt.Errorf("failed to read from stdin: %w", err) - } - } else { - data, err = os.ReadFile(b.file) - if err != nil { - return nil, fmt.Errorf("failed to read file %s: %w", b.file, err) - } - } - - var response kubebindv1alpha2.BindingResourceResponse - if err := yaml.Unmarshal(data, &response); err != nil { - // Try JSON if YAML fails - if err := json.Unmarshal(data, &response); err != nil { - return nil, fmt.Errorf("failed to unmarshal BindingResourceResponse: %w", err) - } - } - - if b.file == "-" { - fmt.Fprintf(b.Options.ErrOut, "📦 Read BindingResourceResponse from stdin\n") - } else { - fmt.Fprintf(b.Options.ErrOut, "📦 Read BindingResourceResponse from file %s\n", b.file) - } - - return &response, nil -} - -// bindFromKubeconfig creates bindings from a BindingResourceResponse that contains only kubeconfig. -func (b *BindDeployOptions) bindFromKubeconfig( - ctx context.Context, - binder *bindapiservice.Binder, - config *rest.Config, - response *kubebindv1alpha2.BindingResourceResponse, -) ([]*kubebindv1alpha2.APIServiceBinding, error) { - // Ensure client side namespace exists - err := b.ensureClientSideNamespaceExists(ctx, config) - if err != nil { - return nil, fmt.Errorf("failed to ensure kube-bind namespace exists: %w", err) - } - - // Parse remote kubeconfig to get host and namespace - remoteHost, remoteNamespace, err := base.ParseRemoteKubeconfig(response.Kubeconfig) - if err != nil { - return nil, fmt.Errorf("failed to parse kubeconfig: %w", err) - } - - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return nil, fmt.Errorf("failed to create kube client: %w", err) - } - - // Determine the secret name to use - secretName := b.kubeconfigSecretName - if secretName == "" { - // No name provided, try to find existing secret for this remote - secretName, err = base.FindRemoteKubeconfig(ctx, kubeClient, remoteNamespace, remoteHost) - if err != nil { - return nil, err - } - } - - secret, created, err := base.EnsureKubeconfigSecret(ctx, string(response.Kubeconfig), secretName, kubeClient) - if err != nil { - return nil, err - } - - if created { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "🔒 Created secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } else { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "🔒 Updated secret %s/%s for host %s, namespace %s\n", "kube-bind", secret.Name, remoteHost, remoteNamespace) - } - - if b.DryRun { - return nil, nil - } - - // Load remote config - remoteKubeConfig, err := clientcmd.Load(response.Kubeconfig) - if err != nil { - return nil, fmt.Errorf("failed to load remote kubeconfig: %w", err) - } - - _, err = clientcmd.NewDefaultClientConfig(*remoteKubeConfig, &clientcmd.ConfigOverrides{}).ClientConfig() - if err != nil { - return nil, fmt.Errorf("failed to create remote config: %w", err) - } - - // Deploy konnector - if !b.SkipKonnector { - if err := b.deployKonnector(ctx, config); err != nil { - return nil, fmt.Errorf("failed to deploy konnector: %w", err) - } - } - - // If response has requests, process them (for full BindingResourceResponse flow) - if len(response.Requests) > 0 { - return binder.BindFromResponse(ctx, response) - } - - return []*kubebindv1alpha2.APIServiceBinding{}, nil -} - -func (b *BindDeployOptions) ensureClientSideNamespaceExists(ctx context.Context, config *rest.Config) error { - kubeClient, err := kubeclient.NewForConfig(config) - if err != nil { - return err - } - - _, err = kubeClient.CoreV1().Namespaces().Get(ctx, "kube-bind", metav1.GetOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return err - } else if apierrors.IsNotFound(err) { - ns := &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "kube-bind", - }, - } - if _, err = kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}); err != nil { - return err - } - fmt.Fprintf(b.Options.IOStreams.ErrOut, "📦 Created kube-bind namespace.\n") - } - return nil -} - -func (b *BindDeployOptions) deployKonnector(ctx context.Context, config *rest.Config) error { - tempOpts := &bindapiservice.BindAPIServiceOptions{ - Options: b.Options, - SkipKonnector: b.SkipKonnector, - KonnectorImageOverride: b.KonnectorImageOverride, - DowngradeKonnector: b.DowngradeKonnector, - DryRun: b.DryRun, - KonnectorHostAliasParsed: b.KonnectorHostAliasParsed, - } - return tempOpts.DeployKonnector(ctx, config) -} - -func (b *BindDeployOptions) printTable(ctx context.Context, config *rest.Config, bindings []*kubebindv1alpha2.APIServiceBinding) error { - if len(bindings) == 0 { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "No bindings created.\n") - return nil - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "\nCreated bindings:\n") - for _, binding := range bindings { - fmt.Fprintf(b.Options.IOStreams.Out, " - %s\n", binding.Name) - } - - return nil -} diff --git a/cli/pkg/kubectl/bind-login/cmd/cmd.go b/cli/pkg/kubectl/bind-login/cmd/cmd.go deleted file mode 100644 index 99b9e6f13..000000000 --- a/cli/pkg/kubectl/bind-login/cmd/cmd.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-login/plugin" -) - -var ( - loginExampleUses = ` - # Login to a kube-bind server - %[1]s login https://my-kube-bind-server.example.com - - # Login with a custom callback port - %[1]s login https://my-kube-bind-server.example.com --callback-port 8081 - - # Login and show authentication status - %[1]s login https://my-kube-bind-server.example.com --show-token - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewLoginOptions(streams) - cmd := &cobra.Command{ - Use: "login [SERVER_URL]", - Short: "Login to a kube-bind server and store authentication credentials", - Long: help.Doc(` - Login to a kube-bind server using OAuth2 authentication flow. - - The command will open your browser to complete the OAuth2 flow and - store the resulting JWT token in ~/.kube-bind/config for use by - subsequent commands. - - The SERVER_URL should point to the root of your kube-bind server, - e.g. https://my-server.example.com - `), - Example: help.Examplesf(loginExampleUses, "kubectl bind"), - SilenceUsage: true, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context(), nil) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind-login/plugin/login.go b/cli/pkg/kubectl/bind-login/plugin/login.go deleted file mode 100644 index c9137ad98..000000000 --- a/cli/pkg/kubectl/bind-login/plugin/login.go +++ /dev/null @@ -1,374 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "crypto/rand" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - bindconfig "github.com/kube-bind/kube-bind/cli/pkg/config" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// LoginOptions contains the options for the login command -type LoginOptions struct { - *base.Options - Logs *logs.Options - Streams genericclioptions.IOStreams - - // ShowToken displays the stored token after successful authentication - ShowToken bool - - // SkipBrowser skips opening the browser automatically. - SkipBrowser bool - - // Timeout for the authentication flow - Timeout time.Duration - - loginClient *http.Client -} - -// TokenResponse represents the response from the OAuth callback -// Important: this struct must match one on backend/auth/types.go -type TokenResponse struct { - // OAuth2 token fields - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int64 `json:"expires_in,omitempty"` - ExpiresAt time.Time `json:"expires_at,omitempty"` - Error string `json:"error,omitempty"` - ErrorMessage string `json:"error_description,omitempty"` - - Cluster string `json:"cluster,omitempty"` -} - -// NewLoginOptions creates a new LoginOptions -func NewLoginOptions(streams genericclioptions.IOStreams) *LoginOptions { - opts := base.NewOptions(streams) - return &LoginOptions{ - Options: opts, - Logs: logs.NewOptions(), - Streams: streams, - Timeout: 5 * time.Minute, - } -} - -// AddCmdFlags adds command line flags -func (o *LoginOptions) AddCmdFlags(cmd *cobra.Command) { - o.Options.BindFlags(cmd) - logsv1.AddFlags(o.Logs, cmd.Flags()) - - cmd.Flags().BoolVar(&o.ShowToken, "show-token", false, "Display the stored token after successful authentication") - cmd.Flags().DurationVar(&o.Timeout, "timeout", o.Timeout, "Timeout for the authentication flow") - cmd.Flags().BoolVarP(&o.SkipBrowser, "skip-browser", "", false, "Skip opening the browser automatically") -} - -// Complete completes the options -func (o *LoginOptions) Complete(args []string) error { - if len(args) > 0 { - o.Options.ServerName = strings.TrimSuffix(args[0], "/") - } - err := o.Options.Complete(true) - if err != nil { - return err - } - - o.loginClient = http.DefaultClient - - return nil -} - -// Validate validates the options -func (o *LoginOptions) Validate() error { - return o.Options.Validate() -} - -// Run executes the login command -func (o *LoginOptions) Run(ctx context.Context, authURLCh chan<- string) error { - config := o.Options.GetConfig() - - // Generate a random session ID for cli session to verify callback requests. - sessionID := rand.Text() - - // Setup callback server with random port - tokenCh := make(chan *TokenResponse, 1) - errCh := make(chan error, 1) - - // Get provider information - fmt.Fprintf(o.Streams.ErrOut, "Connecting to kube-bind server %s...\n", o.Options.ServerName) - provider, err := o.getProvider(ctx) - if err != nil { - return fmt.Errorf("failed to get provider information: %w", err) - } - - server, localCallbackURL, err := o.startCallbackServerWithRandomPort(tokenCh, errCh) - if err != nil { - return fmt.Errorf("failed to start callback server: %w", err) - } - defer server.Close() - fmt.Fprintf(o.Streams.ErrOut, "Started local callback server at %s\n", localCallbackURL) - - // Start authentication flow - authURL, err := o.buildAuthURL(provider, localCallbackURL, sessionID) - if err != nil { - return fmt.Errorf("failed to build auth URL: %w", err) - } - if authURLCh != nil { - authURLCh <- authURL - } - - if !o.SkipBrowser { - fmt.Fprintf(o.Streams.ErrOut, "Opening browser for authentication... \n") - err = base.OpenBrowser(authURL) - if err != nil { - fmt.Fprintf(o.Streams.ErrOut, "Failed to open browser automatically: %v\n", err) - fmt.Fprintf(o.Streams.ErrOut, "Please manually open: %s\n\n", authURL) - } - } else { - fmt.Fprintf(o.Streams.ErrOut, "Please open the following URL in your browser to authenticate:\n%s\n\n", authURL) - } - - // Wait for callback with timeout - ctx, cancel := context.WithTimeout(ctx, o.Timeout) - defer cancel() - - var token *TokenResponse - select { - case token = <-tokenCh: - if token.Error != "" { - return fmt.Errorf("authentication failed: %s - %s", token.Error, token.ErrorMessage) - } - case err := <-errCh: - return fmt.Errorf("callback server error: %w", err) - case <-ctx.Done(): - return fmt.Errorf("authentication timed out after %v", o.Timeout) - } - - // Calculate expiration time - if token.ExpiresIn > 0 && token.ExpiresAt.IsZero() { - token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second) - } - - serverHost, err := url.Parse(o.Options.ServerName) - if err != nil { - return fmt.Errorf("failed to parse server URL: %w", err) - } - - // Store token in config - serverConfig := &bindconfig.Server{ - URL: fmt.Sprintf("%s://%s", serverHost.Scheme, serverHost.Host), - Cluster: token.Cluster, - AccessToken: token.AccessToken, - TokenType: token.TokenType, - ExpiresAt: token.ExpiresAt, - } - - // Use cluster-aware server key - serverURL := fmt.Sprintf("%s://%s", serverHost.Scheme, serverHost.Host) - config.AddServerWithCluster(serverURL, token.Cluster, serverConfig) - if err := config.SaveConfig(); err != nil { - return fmt.Errorf("failed to save config: %w", err) - } - - // Set this as the current server using the cluster-aware key - if err := config.SetCurrentServer(serverURL, token.Cluster); err != nil { - return fmt.Errorf("failed to set current server: %w", err) - } - - if err := config.SaveConfig(); err != nil { - return fmt.Errorf("failed to save current server: %w", err) - } - - if token.Cluster != "" { - fmt.Fprintf(o.Streams.ErrOut, "🔑 Successfully authenticated to %s (cluster: %s)\n", serverHost.Host, token.Cluster) - fmt.Fprintf(o.Streams.ErrOut, " Server key: %s\n", fmt.Sprintf("%s@%s", serverURL, token.Cluster)) - } else { - fmt.Fprintf(o.Streams.ErrOut, "🔑 Successfully authenticated to %s\n", serverHost.Host) - } - - if o.ShowToken { - displayToken := token.AccessToken - if len(displayToken) > 20 { - displayToken = displayToken[:20] + "..." - } - fmt.Fprintf(o.Streams.ErrOut, "\nStored token: %s\n", displayToken) - } - - configPath, _ := config.GetConfigPath() - fmt.Fprintf(o.Streams.ErrOut, "Configuration saved to: %s\n", configPath) - - return nil -} - -func (o *LoginOptions) getProvider(ctx context.Context) (*kubebindv1alpha2.BindingProvider, error) { - url, err := url.Parse(o.Options.ServerName) - if err != nil { - return nil, fmt.Errorf("failed to parse server URL: %w", err) - } - - if !strings.Contains(url.Path, "/api/exports") { - url.Path = "/api/exports" - } - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil) - if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) - } - - resp, err := o.loginClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("server returned status %d", resp.StatusCode) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - var provider kubebindv1alpha2.BindingProvider - if err := json.Unmarshal(body, &provider); err != nil { - return nil, err - } - - return &provider, nil -} - -func (o *LoginOptions) buildAuthURL(provider *kubebindv1alpha2.BindingProvider, redirectURL, sessionID string) (string, error) { - var oauth2Method *kubebindv1alpha2.OAuth2CodeGrant - for _, m := range provider.AuthenticationMethods { - if m.Method == "OAuth2CodeGrant" { - oauth2Method = m.OAuth2CodeGrant - break - } - } - - if oauth2Method == nil { - return "", fmt.Errorf("server does not support OAuth2 code grant flow") - } - - u, err := url.Parse(oauth2Method.AuthenticatedURL) - if err != nil { - return "", err - } - - values := u.Query() - values.Set("redirect_url", redirectURL) - values.Set("session_id", sessionID) - values.Set("client_type", "cli") - if o.ClusterName != "" { - values.Set("cluster_id", o.ClusterName) - } - u.RawQuery = values.Encode() - - return u.String(), nil -} - -func (o *LoginOptions) startCallbackServerWithRandomPort(tokenCh chan<- *TokenResponse, errCh chan<- error) (*http.Server, string, error) { - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - return nil, "", fmt.Errorf("failed to find available port: %w", err) - } - - port := listener.Addr().(*net.TCPAddr).Port - - callbackURL := fmt.Sprintf("http://127.0.0.1:%d/callback", port) - - // Setup HTTP handler - mux := http.NewServeMux() - mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { - token := &TokenResponse{ - Error: r.URL.Query().Get("error"), - ErrorMessage: r.URL.Query().Get("error_description"), - AccessToken: r.URL.Query().Get("access_token"), - TokenType: r.URL.Query().Get("token_type"), - Cluster: r.URL.Query().Get("cluster_id"), - } - - if expiresIn := r.URL.Query().Get("expires_in"); expiresIn != "" { - if exp, err := strconv.ParseInt(expiresIn, 10, 64); err == nil { - token.ExpiresIn = exp - } - } - - // Send success page - w.Header().Set("Content-Type", "text/html") - fmt.Fprintf(w, ` - - - - Kube-Bind Authentication - - - -

Kube-Bind Authentication

-
-

%s

-

You can now close this window and return to the CLI.

-
- -`, - map[bool]string{true: "success", false: "error"}[token.Error == ""], - map[bool]string{true: "Authentication Successful!", false: "Authentication Failed"}[token.Error == ""]) - - select { - case tokenCh <- token: - default: - } - }) - - server := &http.Server{ - ReadTimeout: time.Minute * 5, - Addr: fmt.Sprintf(":%d", port), - Handler: mux, - } - - go func() { - if err := server.Serve(listener); err != http.ErrServerClosed { - select { - case errCh <- err: - default: - } - } - }() - - return server, callbackURL, nil -} diff --git a/cli/pkg/kubectl/bind-templates/cmd/cmd.go b/cli/pkg/kubectl/bind-templates/cmd/cmd.go deleted file mode 100644 index 3fab4188b..000000000 --- a/cli/pkg/kubectl/bind-templates/cmd/cmd.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-templates/plugin" -) - -var ( - TemplatesExampleUses = ` - # List templates from currently authenticated server - %[1]s templates - - # List templates from specific server - %[1]s templates - - # List templates using --server flag to override current server - %[1]s templates --server https://mangodb.com - - # List templates with JSON/YAML output - %[1]s templates -o json - %[1]s templates -o yaml - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewTemplatesOptions(streams) - cmd := &cobra.Command{ - Use: "templates [server-url]", - Short: "List available exported templates from a kube-bind server", - Long: `List all available exported templates from a kube-bind server. - -This command connects to a kube-bind server and displays all the templates -that are available for binding. By default, it uses the current authenticated -server from your configuration. - -If you haven't authenticated to any server yet, you must provide a server URL -argument or use 'kubectl bind-login ' first.`, - Example: fmt.Sprintf(TemplatesExampleUses, "kubectl"), - SilenceUsage: true, - Args: func(cmd *cobra.Command, args []string) error { - for _, arg := range args { - if !strings.HasPrefix(arg, "http://") && !strings.HasPrefix(arg, "https://") { - return fmt.Errorf("invalid server URL: %s", arg) - } - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context()) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind-templates/plugin/templates.go b/cli/pkg/kubectl/bind-templates/plugin/templates.go deleted file mode 100644 index 1cb5f1539..000000000 --- a/cli/pkg/kubectl/bind-templates/plugin/templates.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - "strings" - "text/tabwriter" - "time" - - "github.com/spf13/cobra" - "k8s.io/apimachinery/pkg/util/duration" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/cli-runtime/pkg/printers" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// TemplatesOptions contains the options for listing exported templates -type TemplatesOptions struct { - *base.Options - Logs *logs.Options - - Print *genericclioptions.PrintFlags - printer printers.ResourcePrinter -} - -// ExportedResource represents a resource available for binding -type ExportedResource struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - Resources []string `json:"resources,omitempty"` -} - -// NewTemplatesOptions creates a new TemplatesOptions -func NewTemplatesOptions(streams genericclioptions.IOStreams) *TemplatesOptions { - return &TemplatesOptions{ - Options: base.NewOptions(streams), - Logs: logs.NewOptions(), - Print: genericclioptions.NewPrintFlags("templates").WithDefaultOutput(""), - } -} - -// AddCmdFlags adds command line flags -func (o *TemplatesOptions) AddCmdFlags(cmd *cobra.Command) { - o.Options.BindFlags(cmd) - logsv1.AddFlags(o.Logs, cmd.Flags()) - o.Print.AddFlags(cmd) -} - -// Complete completes the options -func (o *TemplatesOptions) Complete(args []string) error { - if err := o.Options.Complete(false); err != nil { - return err - } - printer, err := o.Print.ToPrinter() - if err != nil { - return err - } - o.printer = printer - - return nil -} - -// Validate validates the options -func (o *TemplatesOptions) Validate() error { - return nil -} - -// Run executes the templates listing command -func (o *TemplatesOptions) Run(ctx context.Context) error { - // Get authenticated client - client, err := o.Options.GetAuthenticatedClient() - if err != nil { - return fmt.Errorf("failed to create authenticated client: %w", err) - } - - // Fetch exported templates - templates, err := client.GetTemplates(ctx) - if err != nil { - return fmt.Errorf("failed to fetch exported templates: %w", err) - } - - // Display templates - return o.displayTemplates(templates) -} - -// displayTemplates displays the templates using the configured printer -func (o *TemplatesOptions) displayTemplates(templates *kubebindv1alpha2.APIServiceExportTemplateList) error { - // For non-table output formats, print the whole list - if o.Print.OutputFormat != nil && *o.Print.OutputFormat != "" { - templates.SetGroupVersionKind(kubebindv1alpha2.SchemeGroupVersion.WithKind("APIServiceExportTemplateList")) - return o.printer.PrintObj(templates, o.IOStreams.Out) - } - - // For table output, create a custom human-readable table - return o.displayTemplatesTable(templates) -} - -// displayTemplatesTable prints templates in table format using tabwriter -// TODO: Replace with custom TablePrinter when available in cli-runtime -func (o *TemplatesOptions) displayTemplatesTable(templates *kubebindv1alpha2.APIServiceExportTemplateList) error { - w := tabwriter.NewWriter(o.Options.IOStreams.Out, 0, 0, 3, ' ', 0) - fmt.Fprintf(w, "NAME\tRESOURCES\tPERMISSIONCLAIMS\tAGE\n") - - for _, item := range templates.Items { - // Create a comma-separated list of resource groups - resourceGroups := make([]string, len(item.Spec.Resources)) - for i, resource := range item.Spec.Resources { - resourceGroups[i] = resource.Group - } - resources := strings.Join(resourceGroups, ",") - - // Create a comma-separated list of permission claim resources - permissionResources := make([]string, len(item.Spec.PermissionClaims)) - for i, claim := range item.Spec.PermissionClaims { - permissionResources[i] = claim.Resource - } - permissionClaims := strings.Join(permissionResources, ",") - - age := duration.HumanDuration(time.Since(item.CreationTimestamp.Time)) - - fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", item.Name, resources, permissionClaims, age) - } - - return w.Flush() -} diff --git a/cli/pkg/kubectl/bind/authenticator/authenticator.go b/cli/pkg/kubectl/bind/authenticator/authenticator.go deleted file mode 100644 index 02a65e94c..000000000 --- a/cli/pkg/kubectl/bind/authenticator/authenticator.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 authenticator - -import ( - "context" - "encoding/base64" - "errors" - "fmt" - "net" - "net/http" - "strconv" - "sync" - "time" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -var ( - kubebindSchema = runtime.NewScheme() - kubebindCodecs = serializer.NewCodecFactory(kubebindSchema) -) - -func init() { - utilruntime.Must(kubebindv1alpha2.AddToScheme(kubebindSchema)) -} - -type LocalhostCallbackAuthenticator struct { - port int - server *http.Server - - mu sync.Mutex // synchronizes mutations of fields below - done chan struct{} - response runtime.Object - responseGvk *schema.GroupVersionKind -} - -func NewLocalhostCallbackAuthenticator() *LocalhostCallbackAuthenticator { - return &LocalhostCallbackAuthenticator{ - done: make(chan struct{}), - } -} - -func (d *LocalhostCallbackAuthenticator) Start() error { - if d.server != nil { - return errors.New("already started") - } - - address, err := net.ResolveTCPAddr("tcp", "localhost:0") - if err != nil { - return err - } - - mux := http.NewServeMux() - mux.HandleFunc("/callback", d.callback) - d.server = &http.Server{ - Handler: mux, - ReadTimeout: 30 * time.Second, - } - - listener, err := net.ListenTCP("tcp", address) - if err != nil { - return err - } - d.port = listener.Addr().(*net.TCPAddr).Port - - go func() { - d.server.Serve(listener) //nolint:errcheck - }() - - return nil -} - -// Endpoint returns the URL this server is listening to. -// Start() must be called prior to this. -func (d *LocalhostCallbackAuthenticator) Endpoint() string { - return fmt.Sprintf("http://%s/callback", net.JoinHostPort("localhost", strconv.Itoa(d.port))) -} - -func (d *LocalhostCallbackAuthenticator) WaitForResponse(ctx context.Context) (runtime.Object, *schema.GroupVersionKind, error) { - select { - case <-d.done: - return d.response, d.responseGvk, nil - case <-ctx.Done(): - // 5 seconds shutdown timeout - shutdownCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - if err := d.server.Shutdown(shutdownCtx); err != nil { - return nil, nil, fmt.Errorf("error while waiting for response: %w: error shutting down server: %v", shutdownCtx.Err(), err) - } - return nil, nil, fmt.Errorf("error while waiting for response: %w", shutdownCtx.Err()) - } -} - -func (d *LocalhostCallbackAuthenticator) callback(w http.ResponseWriter, r *http.Request) { - d.mu.Lock() - defer d.mu.Unlock() - - select { - case <-d.done: - w.Write([]byte("Already authenticated")) //nolint:errcheck - return - default: - } - - authData := r.URL.Query().Get("response") - logger := klog.FromContext(r.Context()) - logger.V(7).Info("Received auth data", "data", authData) - - decoded, err := base64.StdEncoding.DecodeString(authData) - if err != nil { - logger.Error(err, "error decoding authData") - http.Error(w, "internal error", http.StatusInternalServerError) - return - } - - response, gvk, err := kubebindCodecs.UniversalDeserializer().Decode(decoded, nil, nil) - if err != nil { - logger.Error(err, "error decoding authResponse") - http.Error(w, "internal error", http.StatusInternalServerError) - return - } - - d.response = response - d.responseGvk = gvk - close(d.done) - - w.Write([]byte("

You have been authenticated successfully! Please head back to the command line

")) //nolint:errcheck -} diff --git a/cli/pkg/kubectl/bind/cmd/cmd.go b/cli/pkg/kubectl/bind/cmd/cmd.go deleted file mode 100644 index 6ad56c45d..000000000 --- a/cli/pkg/kubectl/bind/cmd/cmd.go +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind/plugin" - - _ "k8s.io/client-go/plugin/pkg/client/auth/exec" - _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" -) - -var ( - BindExampleUses = ` - # %[1]s bind login --server https://my-kube-bind-server.com - - # Open kube-bind UI for current server context - %[1]s bind - - # List available templates (CLI mode) - %[1]s bind templates - - # Bind specific template (CLI mode) - %[1]s bind apiservice --name my-api --template-name database-service - - # View template details without binding - %[1]s bind apiservice --name my-api --template-name database-service --dry-run - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewBindOptions(streams) - cmd := &cobra.Command{ - Use: "bind [server-url]", - Short: "Open kube-bind UI or bind templates from a remote server.", - Long: help.Doc(` - kube-bind allows you to bind remote services into your cluster using either - a web UI or command-line interface. - - By default, 'kubectl bind' opens the kube-bind web UI in your browser. - - For more information, see: https://docs.kube-bind.io - `), - Example: help.Examplesf(BindExampleUses, "kubectl"), - SilenceUsage: true, - Args: func(cmd *cobra.Command, args []string) error { - // Allow 0 or 1 arguments - if len(args) > 1 { - return fmt.Errorf("too many arguments, expected at most 1") - } - // If argument is provided, it must be a URL - if len(args) == 1 { - arg := args[0] - if !strings.HasPrefix(arg, "http://") && !strings.HasPrefix(arg, "https://") { - return fmt.Errorf("server URL must start with http:// or https://, got: %s", arg) - } - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context(), nil) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/bind/plugin/authenticate.go b/cli/pkg/kubectl/bind/plugin/authenticate.go deleted file mode 100644 index 9311eded1..000000000 --- a/cli/pkg/kubectl/bind/plugin/authenticate.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "fmt" - "strings" - - "github.com/blang/semver/v4" -) - -func validateProviderVersion(providerVersion string) error { - switch providerVersion { - case "": - return fmt.Errorf("provider version %q is empty, please update the backend to v0.5.0+", providerVersion) - case "v0.0.0", "v0.0.0-master+$Format:%H$": - // unversioned, development version - return nil - } - - providerSemVer, err := semver.Parse(strings.TrimPrefix(providerVersion, "v")) - if err != nil { - return fmt.Errorf("provider version %q cannot be parsed", providerVersion) - } - // Check if provider is higher than 0.4.8, we need to have same version of kube-bind to use this provider. - if min := semver.MustParse("0.6.0"); providerSemVer.LT(min) { - return fmt.Errorf("provider version %s is not supported, must be at least v%s", providerVersion, min) - } - - return nil -} diff --git a/cli/pkg/kubectl/bind/plugin/authenticate_test.go b/cli/pkg/kubectl/bind/plugin/authenticate_test.go deleted file mode 100644 index 8c90cad2e..000000000 --- a/cli/pkg/kubectl/bind/plugin/authenticate_test.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "testing" -) - -func TestValidateVersion(t *testing.T) { - tests := []struct { - name string - version string - wantErr bool - }{ - {"empty", "", true}, - {"v0.0.0", "v0.0.0", false}, - {"development version", "v0.0.0-master+$Format:%H$", false}, - {"old", "v0.2.3", true}, - {"minimum", "v0.6.0", false}, - {"newer minor", "v0.6.1", false}, - {"newer major", "v1.2.5", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if err := validateProviderVersion(tt.version); (err != nil) != tt.wantErr { - t.Errorf("validateVersion() error = %v, wantErr %v", err, tt.wantErr) - } - }) - } -} diff --git a/cli/pkg/kubectl/bind/plugin/bind.go b/cli/pkg/kubectl/bind/plugin/bind.go deleted file mode 100644 index 745a89518..000000000 --- a/cli/pkg/kubectl/bind/plugin/bind.go +++ /dev/null @@ -1,462 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 plugin - -import ( - "context" - "crypto/rand" - "encoding/base64" - "encoding/json" - "fmt" - "net" - "net/http" - "net/url" - "os/exec" - "strconv" - "strings" - "time" - - "github.com/spf13/cobra" - "github.com/spf13/pflag" - corev1 "k8s.io/api/core/v1" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/cli-runtime/pkg/printers" - "k8s.io/client-go/rest" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" - bindapiservice "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/plugin" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// BindResult represents the result from the UI callback -type BindResult struct { - Success bool `json:"success"` - Message string `json:"message,omitempty"` - Error string `json:"error,omitempty"` - ErrorDescription string `json:"error_description,omitempty"` - - Response kubebindv1alpha2.BindingResourceResponse `json:"response,omitempty"` -} - -// BindOptions contains the options for creating an APIBinding. -type BindOptions struct { - *base.Options - Logs *logs.Options - - Print *genericclioptions.PrintFlags - printer printers.ResourcePrinter - DryRun bool - - // skipKonnector skips the deployment of the konnector. - SkipKonnector bool - - // The konnector image to use and override default konnector image - KonnectorImageOverride string - - // KonnectorHostAlias is a list of host alias entries to add to the konnector pods. - KonnectorHostAlias []string - // KonnectorHostAliasParsed is a list of parsed host alias entries to add to the konnector pods. - KonnectorHostAliasParsed []corev1.HostAlias - - // ClusterIdentity is a unique identity for the cluster. - ClusterIdentity string - // clusterIdentityNamespaceName is the namespace name from which the cluster identity will be generated. - clusterIdentityNamespaceName string - - // SkipBrowser skips opening the browser automatically. - SkipBrowser bool - - // Runner is runs the command. It can be replaced in tests. - Runner func(cmd *exec.Cmd) error - - flags *pflag.FlagSet -} - -// NewBindOptions returns new BindOptions. -func NewBindOptions(streams genericclioptions.IOStreams) *BindOptions { - opts := &BindOptions{ - Options: base.NewOptions(streams), - Logs: logs.NewOptions(), - Print: genericclioptions.NewPrintFlags("kubectl-bind").WithDefaultOutput("yaml"), - - clusterIdentityNamespaceName: "kube-system", - - Runner: func(cmd *exec.Cmd) error { - return cmd.Run() - }, - } - - return opts -} - -// AddCmdFlags binds fields to cmd's flagset. -func (b *BindOptions) AddCmdFlags(cmd *cobra.Command) { - b.flags = cmd.Flags() - - b.Options.BindFlags(cmd) - logsv1.AddFlags(b.Logs, cmd.Flags()) - b.Print.AddFlags(cmd) - - // This block of flags are common with bind-apiservice/plugin/bind.go, keep them in sync. - cmd.Flags().BoolVar(&b.SkipKonnector, "skip-konnector", b.SkipKonnector, "Skip the deployment of the konnector") - cmd.Flags().BoolVarP(&b.DryRun, "dry-run", "d", b.DryRun, "If true, only print the requests that would be sent to the service provider after authentication, without actually binding.") - cmd.Flags().StringVar(&b.KonnectorImageOverride, "konnector-image", b.KonnectorImageOverride, "The konnector image to use") - cmd.Flags().MarkHidden("konnector-image") //nolint:errcheck - cmd.Flags().StringSliceVarP(&b.KonnectorHostAlias, "konnector-host-alias", "", []string{}, "Add a host alias to the konnector pods in the format IP:hostname1,hostname2") - cmd.Flags().MarkHidden("konnector-host-alias") //nolint:errcheck - cmd.Flags().StringVarP(&b.ClusterIdentity, "cluster-identity", "", b.ClusterIdentity, "A unique identity for the cluster. If not provided, it will be generated based on the local cluster information. ") - cmd.Flags().StringVarP(&b.clusterIdentityNamespaceName, "cluster-identity-namespace", "", b.clusterIdentityNamespaceName, "The namespace name from which the cluster identity will be generated. Only used if cluster-identity is not provided.") - cmd.Flags().BoolVarP(&b.SkipBrowser, "skip-browser", "", false, "Skip opening the browser automatically") -} - -// Complete ensures all fields are initialized. -func (b *BindOptions) Complete(args []string) error { - // Try base completion, but don't fail if no current server is configured - if err := b.Options.Complete(false); err != nil { - return err - } - - printer, err := b.Print.ToPrinter() - if err != nil { - return err - } - - b.printer = printer - - // parse konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - hostnames := strings.Split(parts[1], ",") - b.KonnectorHostAliasParsed = append(b.KonnectorHostAliasParsed, corev1.HostAlias{ - IP: parts[0], - Hostnames: hostnames, - }) - } - - return nil -} - -// Validate validates the BindOptions are complete and usable. -func (b *BindOptions) Validate() error { - if b.ServerName == "" { - return fmt.Errorf("server is required") - } - - if _, err := url.Parse(b.ServerName); err != nil { - return fmt.Errorf("invalid url %q: %w", b.ServerName, err) - } - - // TODO(mjudeikis): This code is duplicate fromn bind-apiservice/plugin/bind.go. Unify. - // validate konnector host alias entries - for _, hostAlias := range b.KonnectorHostAlias { - parts := strings.SplitN(hostAlias, ":", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid konnector-host-alias entry %q, expected format IP:hostname1,hostname2", hostAlias) - } - if parts[0] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, IP address is empty", hostAlias) - } - if parts[1] == "" { - return fmt.Errorf("invalid konnector-host-alias entry %q, hostnames are empty", hostAlias) - } - } - - return b.Options.Validate() -} - -// Run starts the binding process. -func (b *BindOptions) Run(ctx context.Context, urlCh chan<- string) error { - // Always use UI mode with callback listener - return b.runWithCallback(ctx, urlCh) -} - -// runWithCallback creates a local callback listener and opens the UI -func (b *BindOptions) runWithCallback(ctx context.Context, _ chan<- string) error { - restConfig, err := b.Options.ClientConfig.ClientConfig() - if err != nil { - return fmt.Errorf("failed to get client config: %w", err) - } - - // Generate session ID. It is used to verify callback. - sessionID := rand.Text() - - clusterIdentity, err := b.getClusterIdentity(ctx, restConfig) - if err != nil { - return fmt.Errorf("failed to get cluster identity: %w", err) - } - - // Setup callback server with random port - resultCh := make(chan *BindResult, 1) - errCh := make(chan error, 1) - - callbackServer, callbackPort, err := b.startCallbackServer(resultCh, errCh, sessionID) - if err != nil { - return fmt.Errorf("failed to start callback server: %w", err) - } - defer callbackServer.Close() - - // Build the UI URL with callback parameters - uiURL, err := b.buildUIURL(callbackPort, sessionID, b.ClusterName, clusterIdentity) - if err != nil { - return fmt.Errorf("failed to build UI URL: %w", err) - } - - if !b.SkipBrowser { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "🌐 Opening kube-bind UI in your browser...\n") - fmt.Fprintf(b.Options.IOStreams.ErrOut, " %s\n\n", uiURL) - - // Open browser - if err := base.OpenBrowser(uiURL); err != nil { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Failed to open browser automatically: %v\n", err) - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Please manually open: %s\n\n", uiURL) - } else { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Browser opened successfully\n") - } - } else { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "\n\n🌐 Please manually open: %s\n\n", uiURL) - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Waiting for binding completion from UI...\n") - fmt.Fprintf(b.Options.IOStreams.ErrOut, " (Press Ctrl+C to cancel)\n\n") - - // Wait for callback result with context cancellation - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - select { - case result := <-resultCh: - if result.Error != "" { - return fmt.Errorf("binding failed: %s - %s", result.Error, result.ErrorDescription) - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Binding completed successfully!\n") - if result.Message != "" { - fmt.Fprintf(b.Options.IOStreams.ErrOut, " %s\n", result.Message) - } - - // Handle dry-run mode - if b.DryRun { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Dry-run mode: outputting APIServiceExport requests\n\n") - - // Print each request from the response using the configured printer - for i, request := range result.Response.Requests { - if i > 0 && b.Print.OutputFormat != nil && *b.Print.OutputFormat == "yaml" { - fmt.Fprintf(b.Options.IOStreams.Out, "---\n") - } - - // TODO: support proper k/k style printers. - // Unmarshal the raw JSON into an APIServiceExportRequest - var apiRequest kubebindv1alpha2.APIServiceExportRequest - if err := json.Unmarshal(request.Raw, &apiRequest); err != nil { - return fmt.Errorf("failed to unmarshal request %d: %w", i, err) - } - - // Use the printer to output in the requested format - if b.printer != nil { - if err := b.printer.PrintObj(&apiRequest, b.Options.IOStreams.Out); err != nil { - return fmt.Errorf("failed to print request %d: %w", i, err) - } - } else { - // Fallback to raw JSON output if printer is not available - fmt.Fprintf(b.Options.IOStreams.Out, "%s", request.Raw) - } - } - } - - // Create bindings using the shared binder - config, err := b.Options.ClientConfig.ClientConfig() - if err != nil { - return fmt.Errorf("failed to get client config: %w", err) - } - - bindings, err := b.bindResponseToAPIServiceBindings(ctx, config, &result.Response) - if err != nil { - return fmt.Errorf("failed to create APIServiceBindings: %w", err) - } - - if b.DryRun { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "\nDry-run mode: no APIServiceBindings were created.\n") - return nil - } - - // Print the results - if len(bindings) > 0 { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Created %d APIServiceBinding(s):\n", len(bindings)) - for _, binding := range bindings { - fmt.Fprintf(b.Options.IOStreams.Out, " - %s\n", binding.Name) - } - } - - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Resources bound successfully!\n") - return nil - - case err := <-errCh: - return fmt.Errorf("callback server error: %w", err) - case <-ctx.Done(): - return fmt.Errorf("operation cancelled") - } -} - -// buildUIURL constructs the UI URL with callback parameters -func (b *BindOptions) buildUIURL(callbackPort int, sessionID, backendClusterID, consumerClusterID string) (string, error) { - // Parse the base URL - u, err := url.Parse(b.ServerName) - if err != nil { - return "", fmt.Errorf("invalid server URL: %w", err) - } - - redirectURL := "http://127.0.0.1:" + strconv.Itoa(callbackPort) + "/callback" - - // Add query parameters - values := u.Query() - values.Add("session_id", sessionID) - values.Add("redirect_url", redirectURL) - if backendClusterID != "" { - values.Add("cluster_id", backendClusterID) - } - if consumerClusterID != "" { - values.Add("consumer_id", consumerClusterID) - } - u.RawQuery = values.Encode() - - return u.String(), nil -} - -// startCallbackServer starts a local HTTP server to receive the callback from the UI -func (b *BindOptions) startCallbackServer(resultCh chan<- *BindResult, errCh chan<- error, sessionID string) (*http.Server, int, error) { - // Find an available port - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") - if err != nil { - return nil, 0, fmt.Errorf("failed to find available port: %w", err) - } - - port := listener.Addr().(*net.TCPAddr).Port - - // Setup HTTP handler - mux := http.NewServeMux() - mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { - // Validate session ID - if r.URL.Query().Get("session_id") != sessionID { - http.Error(w, "Invalid session", http.StatusUnauthorized) - return - } - - result := &BindResult{} - payload := kubebindv1alpha2.BindingResourceResponse{} - - // Parse query parameters (for simple callbacks) - query := r.URL.Query() - - response := query.Get("binding_response") - responseData, err := base64.URLEncoding.DecodeString(response) - if err != nil { - http.Error(w, "Invalid binding_response", http.StatusBadRequest) - return - } - if err := json.Unmarshal(responseData, &payload); err != nil { - http.Error(w, "Invalid binding_response JSON", http.StatusBadRequest) - return - } - - result.Response = payload - - result.Success = query.Get("success") == "true" - result.Message = query.Get("message") - result.Error = query.Get("error") - result.ErrorDescription = query.Get("error_description") - - // Send success page - w.Header().Set("Content-Type", "text/html") - fmt.Fprintf(w, ` - - - - Kube-Bind - Binding Complete - - - -

Kube-Bind

-
-

%s

-

You can now close this window and return to the CLI.

-
- -`, - map[bool]string{true: "success", false: "error"}[result.Success || result.Error == ""], - map[bool]string{true: "Binding Completed Successfully!", false: "Binding Failed"}[result.Success || result.Error == ""]) - - // Send result to channel - select { - case resultCh <- result: - default: - } - }) - - server := &http.Server{ - ReadTimeout: time.Minute * 5, - Addr: fmt.Sprintf(":%d", port), - Handler: mux, - } - - go func() { - if err := server.Serve(listener); err != http.ErrServerClosed { - select { - case errCh <- err: - default: - } - } - }() - - return server, port, nil -} - -// bindResponseToAPIServiceBindings uses the shared binder to create API service bindings -func (b *BindOptions) bindResponseToAPIServiceBindings(ctx context.Context, config *rest.Config, response *kubebindv1alpha2.BindingResourceResponse) ([]*kubebindv1alpha2.APIServiceBinding, error) { - binderOpts := &bindapiservice.BinderOptions{ - IOStreams: b.Options.IOStreams, - SkipKonnector: b.SkipKonnector, - KonnectorHostAliasParsed: b.KonnectorHostAliasParsed, - KonnectorImageOverride: b.KonnectorImageOverride, - DryRun: b.DryRun, - } - - binder := bindapiservice.NewBinder(config, binderOpts) - return binder.BindFromResponse(ctx, response) -} - -// getClusterIdentity returns the cluster identity, generating it from the namespace if not provided -func (b *BindOptions) getClusterIdentity(ctx context.Context, restConfig *rest.Config) (string, error) { - if b.ClusterIdentity != "" { - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Manual cluster identity provided: %s. Identity will not be generated from namespace.\n", b.ClusterIdentity) - fmt.Fprintf(b.Options.IOStreams.ErrOut, "If this is not intended, please omit --cluster-identity flag to generate identity from namespace '%s'.\n\n", b.clusterIdentityNamespaceName) - fmt.Fprintf(b.Options.IOStreams.ErrOut, "Re-using same identity on multiple consumer clusters is not supported & might cause un-intended consequeces. Be aware of the dragons!") - return b.ClusterIdentity, nil - } - - identity, err := base.GetClusterIdentityFromNamespace(ctx, restConfig, b.clusterIdentityNamespaceName) - if err != nil { - return "", fmt.Errorf("failed to get cluster identity from namespace '%q': %w. Please provide static identity using --cluster-identity or set current kubectl context to consumer cluster", b.clusterIdentityNamespaceName, err) - } - return identity, nil -} diff --git a/cli/pkg/kubectl/cluster-identity/cmd/cmd.go b/cli/pkg/kubectl/cluster-identity/cmd/cmd.go deleted file mode 100644 index 0e55862f9..000000000 --- a/cli/pkg/kubectl/cluster-identity/cmd/cmd.go +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "fmt" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/cluster-identity/plugin" -) - -var ( - ClusterIdentityExampleUses = ` - # Get the cluster identity for the current kubeconfig context - %[1]s cluster-identity - - # Get the cluster identity using a specific kubeconfig - %[1]s cluster-identity --kubeconfig /path/to/kubeconfig - - # Get the cluster identity using a specific context - %[1]s cluster-identity --context my-context - - # Get the cluster identity from a specific namespace (default: kube-system) - %[1]s cluster-identity --namespace my-namespace - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewClusterIdentityOptions(streams) - cmd := &cobra.Command{ - Use: "cluster-identity", - Short: "Get the cluster identity for the current Kubernetes cluster", - Long: `Get the cluster identity for the current Kubernetes cluster. - -The cluster identity is derived from the UID of a namespace (by default kube-system). -This identity is used by kube-bind to uniquely identify consumer clusters when -binding to service providers. - -This is a helper command for users who are not using the kube-bind web server -and need to manually provide the cluster identity.`, - Example: fmt.Sprintf(ClusterIdentityExampleUses, "kubectl bind"), - SilenceUsage: true, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context()) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/cluster-identity/plugin/cluster_identity.go b/cli/pkg/kubectl/cluster-identity/plugin/cluster_identity.go deleted file mode 100644 index 27e5e3e8c..000000000 --- a/cli/pkg/kubectl/cluster-identity/plugin/cluster_identity.go +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "context" - "fmt" - - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" -) - -const ( - defaultIdentityNamespace = "kube-system" -) - -// ClusterIdentityOptions contains the options for getting the cluster identity -type ClusterIdentityOptions struct { - genericclioptions.IOStreams - Logs *logs.Options - - // Kubeconfig specifies kubeconfig file(s). - Kubeconfig string - // KubectlOverrides stores the extra client connection fields, such as context, user, etc. - KubectlOverrides *clientcmd.ConfigOverrides - // Namespace is the namespace to use for deriving the cluster identity - Namespace string - // ClientConfig is the resolved clientcmd.ClientConfig based on the client connection flags. - ClientConfig clientcmd.ClientConfig -} - -// NewClusterIdentityOptions creates a new ClusterIdentityOptions -func NewClusterIdentityOptions(streams genericclioptions.IOStreams) *ClusterIdentityOptions { - return &ClusterIdentityOptions{ - IOStreams: streams, - Logs: logs.NewOptions(), - KubectlOverrides: &clientcmd.ConfigOverrides{}, - Namespace: defaultIdentityNamespace, - } -} - -// AddCmdFlags adds command line flags -func (o *ClusterIdentityOptions) AddCmdFlags(cmd *cobra.Command) { - cmd.Flags().StringVar(&o.Kubeconfig, "kubeconfig", o.Kubeconfig, "Path to the kubeconfig file") - cmd.Flags().StringVarP(&o.Namespace, "namespace", "n", o.Namespace, "Namespace to use for deriving the cluster identity (default: kube-system)") - - // Add context flag from kubectl overrides - kubectlConfigOverrideFlags := clientcmd.RecommendedConfigOverrideFlags("") - kubectlConfigOverrideFlags.AuthOverrideFlags.ClientCertificate.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.ClientKey.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.Impersonate.LongName = "" - kubectlConfigOverrideFlags.AuthOverrideFlags.ImpersonateGroups.LongName = "" - kubectlConfigOverrideFlags.ContextOverrideFlags.ClusterName.LongName = "" - kubectlConfigOverrideFlags.Timeout.LongName = "" - - clientcmd.BindOverrideFlags(o.KubectlOverrides, cmd.PersistentFlags(), kubectlConfigOverrideFlags) - - logsv1.AddFlags(o.Logs, cmd.Flags()) -} - -// Complete completes the options -func (o *ClusterIdentityOptions) Complete(args []string) error { - loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() - loadingRules.ExplicitPath = o.Kubeconfig - - startingConfig, err := loadingRules.GetStartingConfig() - if err != nil { - return err - } - - o.ClientConfig = clientcmd.NewDefaultClientConfig(*startingConfig, o.KubectlOverrides) - - return nil -} - -// Validate validates the options -func (o *ClusterIdentityOptions) Validate() error { - if o.Namespace == "" { - return fmt.Errorf("namespace cannot be empty") - } - return nil -} - -// Run executes the cluster-identity command -func (o *ClusterIdentityOptions) Run(ctx context.Context) error { - restConfig, err := o.ClientConfig.ClientConfig() - if err != nil { - return fmt.Errorf("failed to get REST config: %w", err) - } - - identity, err := base.GetClusterIdentityFromNamespace(ctx, restConfig, o.Namespace) - if err != nil { - return fmt.Errorf("failed to get cluster identity: %w", err) - } - - fmt.Fprintln(o.Out, identity) - - return nil -} diff --git a/cli/pkg/kubectl/dev/cmd/cmd.go b/cli/pkg/kubectl/dev/cmd/cmd.go deleted file mode 100644 index 19acb2b03..000000000 --- a/cli/pkg/kubectl/dev/cmd/cmd.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 cmd - -import ( - "github.com/spf13/cobra" - "k8s.io/cli-runtime/pkg/genericclioptions" - logsv1 "k8s.io/component-base/logs/api/v1" - - "github.com/kube-bind/kube-bind/cli/pkg/help" - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/dev/plugin" -) - -var ( - devCreateExampleUses = ` - # Create a development environment with kind cluster and default OCI chart - %[1]s create - - # Create a development environment with custom provider cluster name - %[1]s create --provider-cluster-name my-provider - - # Create with custom chart path (local development) - %[1]s create --chart-path ../deploy/charts/backend - - # Create with specific chart version - %[1]s create --chart-version 0.1.0 - - # Create with custom OCI chart - %[1]s create --chart-path oci://registry.example.com/charts/backend --chart-version 1.0.0 - ` -) - -func New(streams genericclioptions.IOStreams) (*cobra.Command, error) { - cmd := &cobra.Command{ - Use: "dev", - Short: "Manage development environment for kube-bind", - Long: help.Doc(` - Manage a development environment for kube-bind using kind clusters. - - This command provides subcommands to initialize and manage kind clusters - configured for kube-bind development. - `), - SilenceUsage: true, - } - - // Add create subcommand - createCmd, err := newCreateCommand(streams) - if err != nil { - return nil, err - } - cmd.AddCommand(createCmd) - - // Add delete subcommand - deleteCmd, err := newDeleteCommand(streams) - if err != nil { - return nil, err - } - cmd.AddCommand(deleteCmd) - - exampleCmd, err := newExampleCommand(streams) - if err != nil { - return nil, err - } - - cmd.AddCommand(exampleCmd) - - return cmd, nil -} - -func newCreateCommand(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewDevOptions(streams) - cmd := &cobra.Command{ - Use: "create", - Short: "Create development environment with kind cluster and kube-bind backend", - Long: help.Doc(` - Create a complete development environment for kube-bind using kind clusters. - - This command will: - - - Create a kind cluster configured for kube-bind development - - Add kube-bind.dev.local to /etc/hosts (with sudo prompts if needed) - - Install kube-bind backend helm chart (default: OCI chart from ghcr.io) - - Configure necessary port mappings (8443, 15021) - - The backend chart can be sourced from: - - - OCI registry (default): oci://ghcr.io/kbind-dev/charts/backend - - Local filesystem: --chart-path ./deploy/charts/backend - - Custom OCI registry: --chart-path oci://custom.registry/charts/backend - `), - Example: help.Examplesf(devCreateExampleUses, "kubectl bind dev"), - SilenceUsage: true, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.Run(cmd.Context()) - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} - -func newDeleteCommand(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewDevOptions(streams) - cmd := &cobra.Command{ - Use: "delete", - Short: "Delete development environment", - Long: help.Doc(` - Delete the development environment for kube-bind. - - This command will delete the kind cluster created for kube-bind development. - `), - SilenceUsage: true, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.RunDelete() - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} - -func newExampleCommand(streams genericclioptions.IOStreams) (*cobra.Command, error) { - opts := plugin.NewDevOptions(streams) - cmd := &cobra.Command{ - Use: "example", - Short: "Get example manifest for MangoDB", - Long: help.Doc(` - This will print example CRD you can use for development environment testing. - `), - SilenceUsage: true, - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - if err := logsv1.ValidateAndApply(opts.Logs, nil); err != nil { - return err - } - - if err := opts.Complete(args); err != nil { - return err - } - - if err := opts.Validate(); err != nil { - return err - } - - return opts.RunPrintExample() - }, - } - opts.AddCmdFlags(cmd) - - return cmd, nil -} diff --git a/cli/pkg/kubectl/dev/plugin/create.go b/cli/pkg/kubectl/dev/plugin/create.go deleted file mode 100644 index 1a412a97a..000000000 --- a/cli/pkg/kubectl/dev/plugin/create.go +++ /dev/null @@ -1,638 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "os/exec" - "runtime" - "slices" - "strconv" - "strings" - "time" - - "github.com/moby/moby/client" - "github.com/spf13/cobra" - "helm.sh/helm/v3/pkg/action" - "helm.sh/helm/v3/pkg/chart" - "helm.sh/helm/v3/pkg/chart/loader" - "helm.sh/helm/v3/pkg/cli" - "helm.sh/helm/v3/pkg/registry" - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/discovery" - "k8s.io/client-go/discovery/cached/memory" - "k8s.io/client-go/rest" - "k8s.io/client-go/restmapper" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - "sigs.k8s.io/kind/pkg/cluster" - - "github.com/kube-bind/kube-bind/cli/pkg/kubectl/base" -) - -// DevOptions contains the options for the dev command -type DevOptions struct { - *base.Options - Logs *logs.Options - Streams genericclioptions.IOStreams - - BackendImage string - BackendTag string - ProviderClusterName string - ConsumerClusterName string - WaitForReadyTimeout time.Duration - ChartPath string - ChartVersion string - KindNetwork string -} - -// fallbackAssetVersion is used when unable to fetch the latest version -const fallbackAssetVersion = "0.8.1" - -// gitHubRelease represents a GitHub release response -type gitHubRelease struct { - TagName string `json:"tag_name"` -} - -// NewDevOptions creates a new DevOptions -func NewDevOptions(streams genericclioptions.IOStreams) *DevOptions { - opts := base.NewOptions(streams) - return &DevOptions{ - Options: opts, - Logs: logs.NewOptions(), - Streams: streams, - ProviderClusterName: "kind-provider", - ConsumerClusterName: "kind-consumer", - ChartPath: "oci://ghcr.io/kbind-dev/charts/backend", - } -} - -// AddCmdFlags adds command line flags -func (o *DevOptions) AddCmdFlags(cmd *cobra.Command) { - o.Options.BindFlags(cmd) - logsv1.AddFlags(o.Logs, cmd.Flags()) - - cmd.Flags().StringVar(&o.ProviderClusterName, "provider-cluster-name", "kind-provider", "Name of the provider cluster in dev mode") - cmd.Flags().StringVar(&o.ConsumerClusterName, "consumer-cluster-name", "kind-consumer", "Name of the consumer cluster in dev mode") - cmd.Flags().DurationVar(&o.WaitForReadyTimeout, "wait-for-ready-timeout", 2*time.Minute, "Timeout for waiting for the cluster to be ready") - cmd.Flags().StringVar(&o.ChartPath, "chart-path", o.ChartPath, "Helm chart path or OCI registry URL") - cmd.Flags().StringVar(&o.ChartVersion, "chart-version", "", "The version of the Helm chart to use") - cmd.Flags().StringVar(&o.BackendImage, "backend-image", "ghcr.io/kbind-dev/backend", "The name of kube-bind backend to use in dev mode") - cmd.Flags().StringVar(&o.BackendTag, "backend-tag", "", "The tag of the kube-bind backend image to use in dev mode") - cmd.Flags().StringVar(&o.KindNetwork, "kind-network", "kube-bind-dev", "The name of the kind network to use in dev mode") -} - -// Complete completes the options -func (o *DevOptions) Complete(args []string) error { - assetVersion := fallbackAssetVersion - version, err := fetchLatestRelease() - if err != nil { - fmt.Fprintf(o.Streams.ErrOut, "Warning: Failed to fetch latest release version: %v. Using fallback version %s\n", err, fallbackAssetVersion) - } else { - assetVersion = version - } - - if o.ChartVersion == "" { - o.ChartVersion = assetVersion - } - - if o.BackendTag == "" { - o.BackendTag = "v" + assetVersion - } - - return nil -} - -// fetchLatestRelease fetches the latest release version from GitHub -func fetchLatestRelease() (string, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/kube-bind/kube-bind/releases/latest", nil) - if err != nil { - return "", fmt.Errorf("failed to create request: %w", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return "", fmt.Errorf("failed to fetch latest release: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("GitHub API returned status %d", resp.StatusCode) - } - - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("failed to read response body: %w", err) - } - - var release gitHubRelease - if err := json.Unmarshal(body, &release); err != nil { - return "", fmt.Errorf("failed to parse release data: %w", err) - } - - if release.TagName == "" { - return "", fmt.Errorf("no tag name in release data") - } - - version := strings.TrimPrefix(release.TagName, "v") - return version, nil -} - -// Validate validates the options -func (o *DevOptions) Validate() error { - return o.Options.Validate() -} - -var providerClusterConfig = `apiVersion: kind.x-k8s.io/v1alpha4 -kind: Cluster -networking: - apiServerAddress: "0.0.0.0" - apiServerPort: 6443 -nodes: -- role: control-plane - extraPortMappings: - - containerPort: 31000 - hostPort: 8080 - protocol: TCP - listenAddress: "127.0.0.1" -` - -var consumerClusterConfig = `apiVersion: kind.x-k8s.io/v1alpha4 -kind: Cluster -nodes: -- role: control-plane -` - -// Color helper functions -func blueCommand(text string) string { - return "\033[38;5;67m" + text + "\033[0m" -} - -func redText(text string) string { - return "\033[31m" + text + "\033[0m" -} - -func (o *DevOptions) runWithColors(ctx context.Context) error { - _ = o.Options.GetConfig() - - // Display experimental warning header with red "EXPERIMENTAL" - fmt.Fprintf(o.Streams.ErrOut, "kube-bind Development Environment Setup\n\n") - fmt.Fprintf(o.Streams.ErrOut, "%s kube-bind dev command is in preview\n", redText("EXPERIMENTAL:")) - fmt.Fprintf(o.Streams.ErrOut, "Requirements: Docker must be installed and running\n\n") - - hostEntryExists := o.setupHostEntries() - - if err := o.checkFileLimits(); err != nil { - fmt.Fprintf(o.Streams.ErrOut, "⚠️ File limit check warning: %v\n", err) - } - - if err := o.createCluster(ctx, o.ProviderClusterName, providerClusterConfig, true); err != nil { - return err - } - - providerIP, err := o.getClusterIPAddress(ctx, o.ProviderClusterName, o.KindNetwork) - if err != nil { - fmt.Fprintf(o.Streams.ErrOut, "⚠️ Failed to get provider cluster IP address: %v\n", err) - providerIP = "" - } - - if err := o.createCluster(ctx, o.ConsumerClusterName, consumerClusterConfig, false); err != nil { - return err - } - - // Success message - fmt.Fprint(o.Streams.ErrOut, "kube-bind dev environment is ready!\n\n") - - // Configuration - fmt.Fprint(o.Streams.ErrOut, "Configuration:\n") - fmt.Fprintf(o.Streams.ErrOut, "• Provider cluster kubeconfig: %s.kubeconfig\n", o.ProviderClusterName) - fmt.Fprintf(o.Streams.ErrOut, "• Consumer cluster kubeconfig: %s.kubeconfig\n", o.ConsumerClusterName) - fmt.Fprint(o.Streams.ErrOut, "• kube-bind server URL: http://kube-bind.dev.local:8080\n\n") - - // Next steps with colored commands - fmt.Fprint(o.Streams.ErrOut, "Next Steps:\n\n") - - stepNum := 1 - - // Only show /etc/hosts step if entry didn't already exist - if !hostEntryExists { - fmt.Fprintf(o.Streams.ErrOut, "%d. Add to /etc/hosts (if not already done):\n", stepNum) - fmt.Fprintf(o.Streams.ErrOut, "%s\n\n", blueCommand("echo '127.0.0.1 kube-bind.dev.local' | sudo tee -a /etc/hosts")) - stepNum++ - } - - fmt.Fprintf(o.Streams.ErrOut, "%d. Login to authenticate to the provider cluster:\n", stepNum) - fmt.Fprintf(o.Streams.ErrOut, "%s\n\n", blueCommand("kubectl bind login http://kube-bind.dev.local:8080")) - stepNum++ - - fmt.Fprintf(o.Streams.ErrOut, "%d. Bind an API service from provider to consumer:\n", stepNum) - if providerIP != "" { - fmt.Fprintf(o.Streams.ErrOut, "%s\n", blueCommand(fmt.Sprintf("KUBECONFIG=%s.kubeconfig kubectl bind --konnector-host-alias %s:kube-bind.dev.local", o.ConsumerClusterName, providerIP))) - } else { - fmt.Fprintf(o.Streams.ErrOut, "%s\n", blueCommand(fmt.Sprintf("PROVIDER_IP=$(docker inspect %s-control-plane | jq -r '.[0].NetworkSettings.Networks[\"%s\"].IPAddress') && KUBECONFIG=%s.kubeconfig kubectl bind --konnector-host-alias ${PROVIDER_IP}:kube-bind.dev.local", o.ProviderClusterName, o.KindNetwork, o.ConsumerClusterName))) - } - - return nil -} - -// Run runs the dev command -func (o *DevOptions) Run(ctx context.Context) error { - return o.runWithColors(ctx) -} - -func (o *DevOptions) setupHostEntries() bool { - if err := addHostEntry("kube-bind.dev.local"); err != nil { - fmt.Fprintf(o.Streams.ErrOut, "Warning: Could not automatically add host entry. Please run:\n") - if runtime.GOOS == "windows" { - fmt.Fprintf(o.Streams.ErrOut, " echo 127.0.0.1 kube-bind.dev.local >> C:\\Windows\\System32\\drivers\\etc\\hosts\n") - } else { - fmt.Fprintf(o.Streams.ErrOut, " echo '127.0.0.1 kube-bind.dev.local' | sudo tee -a /etc/hosts\n") - } - - return false - } - - fmt.Fprint(o.Streams.ErrOut, "Host entry exists for kube-bind.dev.local\n") - return true -} - -func (o *DevOptions) createCluster(ctx context.Context, clusterName, clusterConfig string, installKubeBind bool) error { - // Set experimental Docker network for kind clusters to communicate - os.Setenv("KIND_EXPERIMENTAL_DOCKER_NETWORK", o.KindNetwork) - - provider := cluster.NewProvider() - - clusters, err := provider.List() - if err != nil { - return err - } - - kubeconfigPath := fmt.Sprintf("%s.kubeconfig", clusterName) - - if slices.Contains(clusters, clusterName) { - fmt.Fprint(o.Streams.ErrOut, "Kind cluster "+clusterName+" already exists, skipping creation\n") - - // Export kubeconfig for existing cluster - err := provider.ExportKubeConfig(clusterName, kubeconfigPath, false) - if err != nil { - return fmt.Errorf("failed to export kubeconfig for existing cluster %s: %w", clusterName, err) - } - } else { - fmt.Fprintf(o.Streams.ErrOut, "Creating kind cluster %s with network %s\n", clusterName, o.KindNetwork) - err := provider.Create(clusterName, - cluster.CreateWithRawConfig([]byte(clusterConfig)), - cluster.CreateWithWaitForReady(o.WaitForReadyTimeout), - cluster.CreateWithDisplaySalutation(true), - cluster.CreateWithKubeconfigPath(kubeconfigPath), - ) - if err != nil { - return err - } - fmt.Fprint(o.Streams.ErrOut, "Kind cluster "+clusterName+" created\n") - } - - if installKubeBind { - restConfig, err := base.LoadRestConfigFromFile(kubeconfigPath) - if err != nil { - return err - } - if err := o.installHelmChart(ctx, restConfig); err != nil { - fmt.Fprint(o.Streams.ErrOut, "Failed to install Helm chart\n") - return err - } - fmt.Fprint(o.Streams.ErrOut, "Helm chart installed successfully\n") - } - - return nil -} - -func (o *DevOptions) getClusterIPAddress(ctx context.Context, clusterName, networkName string) (string, error) { - dockerClient, err := client.New(client.FromEnv) - if err != nil { - return "", fmt.Errorf("failed to create docker client: %w", err) - } - defer dockerClient.Close() - - // Get the container name for the kind cluster control plane - containerName := fmt.Sprintf("%s-control-plane", clusterName) - - containers, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{}) - if err != nil { - return "", fmt.Errorf("failed to list containers: %w", err) - } - - for _, c := range containers.Items { - for _, name := range c.Names { - if strings.Contains(name, containerName) { - containerDetails, err := dockerClient.ContainerInspect(ctx, c.ID, client.ContainerInspectOptions{}) - if err != nil { - return "", fmt.Errorf("failed to inspect container %s: %w", c.ID, err) - } - - if networks := containerDetails.Container.NetworkSettings.Networks; networks != nil { - if network, exists := networks[networkName]; exists { - if network.IPAddress.IsValid() { - return network.IPAddress.String(), nil - } - } - } - } - } - } - - return "", fmt.Errorf("could not find IP address for cluster %s in network %s", clusterName, networkName) -} - -func (o *DevOptions) installHelmChart(_ context.Context, restConfig *rest.Config) error { - actionConfig := new(action.Configuration) - - if err := actionConfig.Init(&restConfigGetter{config: restConfig}, "kube-bind", "secret", func(format string, v ...any) {}); err != nil { - return fmt.Errorf("failed to initialize helm action config: %w", err) - } - - // Initialize registry client for OCI support - registryClient, regErr := registry.NewClient() - if regErr != nil { - return fmt.Errorf("failed to create registry client: %w", regErr) - } - actionConfig.RegistryClient = registryClient - - values := map[string]any{ - "image": map[string]any{ - "repository": o.BackendImage, - "tag": o.BackendTag, - }, - - "examples": map[string]any{ - "enabled": true, - }, - "backend": map[string]any{ - "image": map[string]any{ - "repository": o.BackendImage, - "tag": o.BackendTag, - }, - "listenAddress": "0.0.0.0:8080", - "namespacePrefix": "kube-bind-", - "externalAddress": "https://kube-bind.dev.local:6443", - "externalServerName": "kind-provider-control-plane", - "consumerScope": "cluster", - "oidc": map[string]any{ - "callbackUrl": "http://kube-bind.dev.local:8080/api/callback", - "issuerUrl": "http://kube-bind.dev.local:8080/oidc", - "type": "embedded", - }, - }, - "service": map[string]any{ - "type": "NodePort", - "port": 8080, - "nodePort": 31000, - }, - "hostAliases": []map[string]any{ - { - "ip": "0.0.0.0", - "hostnames": []string{"kube-bind.dev.local"}, - }, - }, - } - - var chart *chart.Chart - var err error - - if strings.HasPrefix(o.ChartPath, "oci://") { - tempInstallAction := action.NewInstall(actionConfig) - tempInstallAction.ChartPathOptions.Version = o.ChartVersion - chartPath, err := tempInstallAction.ChartPathOptions.LocateChart(o.ChartPath, cli.New()) - if err != nil { - return fmt.Errorf("failed to locate OCI chart: %w", err) - } - chart, err = loader.Load(chartPath) - if err != nil { - return fmt.Errorf("failed to load OCI chart: %w", err) - } - } else { - chart, err = loader.Load(o.ChartPath) - if err != nil { - return fmt.Errorf("failed to load local chart: %w", err) - } - } - - histClient := action.NewHistory(actionConfig) - histClient.Max = 1 - if _, err := histClient.Run("kube-bind"); err == nil { - upgradeAction := action.NewUpgrade(actionConfig) - upgradeAction.Namespace = "kube-bind" - _, err = upgradeAction.Run("kube-bind", chart, values) - if err != nil { - return fmt.Errorf("failed to upgrade chart: %w", err) - } - } else { - installAction := action.NewInstall(actionConfig) - installAction.ReleaseName = "kube-bind" - installAction.Namespace = "kube-bind" - installAction.CreateNamespace = true - _, err = installAction.Run(chart, values) - if err != nil { - return fmt.Errorf("failed to install chart: %w", err) - } - } - - return nil -} - -type restConfigGetter struct { - config *rest.Config -} - -func (r *restConfigGetter) ToRESTConfig() (*rest.Config, error) { - return r.config, nil -} - -func (r *restConfigGetter) ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error) { - discoveryClient, err := discovery.NewDiscoveryClientForConfig(r.config) - if err != nil { - return nil, err - } - return memory.NewMemCacheClient(discoveryClient), nil -} - -func (r *restConfigGetter) ToRESTMapper() (meta.RESTMapper, error) { - discoveryClient, err := r.ToDiscoveryClient() - if err != nil { - return nil, err - } - mapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient) - return mapper, nil -} - -func (r *restConfigGetter) ToRawKubeConfigLoader() clientcmd.ClientConfig { - return clientcmd.NewNonInteractiveClientConfig(clientcmdapi.Config{}, "", &clientcmd.ConfigOverrides{ - Context: clientcmdapi.Context{ - Namespace: "kube-bind", - }, - }, nil) -} - -func getHostsPath() string { - if runtime.GOOS == "windows" { - return `C:\Windows\System32\drivers\etc\hosts` - } - return "/etc/hosts" -} - -func addHostEntry(hostname string) error { - hostsPath := getHostsPath() - entry := fmt.Sprintf("127.0.0.1 %s", hostname) - - exists, err := hostEntryExists(hostsPath, hostname) - if err != nil { - return err - } - if exists { - return nil - } - - file, err := os.OpenFile(hostsPath, os.O_APPEND|os.O_WRONLY, 0644) - if err != nil { - return fmt.Errorf("failed to open hosts file: %w", err) - } - defer file.Close() - - if _, err := fmt.Fprintf(file, "\n%s\n", entry); err != nil { - return fmt.Errorf("failed to write to hosts file: %w", err) - } - - return nil -} - -func removeHostEntry(hostname string) error { - hostsPath := getHostsPath() - - file, err := os.Open(hostsPath) - if err != nil { - return fmt.Errorf("failed to open hosts file: %w", err) - } - defer file.Close() - - var lines []string - scanner := bufio.NewScanner(file) - for scanner.Scan() { - line := scanner.Text() - if !strings.Contains(line, hostname) || !strings.Contains(line, "127.0.0.1") { - lines = append(lines, line) - } - } - - if err := scanner.Err(); err != nil { - return fmt.Errorf("failed to read hosts file: %w", err) - } - - content := strings.Join(lines, "\n") - if err := os.WriteFile(hostsPath, []byte(content), 0600); err != nil { - return fmt.Errorf("failed to write hosts file: %w", err) - } - - return nil -} - -func hostEntryExists(hostsPath, hostname string) (bool, error) { - file, err := os.Open(hostsPath) - if err != nil { - return false, fmt.Errorf("failed to open hosts file: %w", err) - } - defer file.Close() - - scanner := bufio.NewScanner(file) - for scanner.Scan() { - line := scanner.Text() - if strings.Contains(line, hostname) && strings.Contains(line, "127.0.0.1") { - return true, nil - } - } - - return false, scanner.Err() -} - -// CheckFileLimits checks system file limits for the dev environment -func (o *DevOptions) CheckFileLimits() error { - return o.checkFileLimits() -} - -// GetClusterIPAddress gets the IP address of a cluster in the specified network -func (o *DevOptions) GetClusterIPAddress(ctx context.Context, clusterName, networkName string) (string, error) { - return o.getClusterIPAddress(ctx, clusterName, networkName) -} - -// CreateProviderCluster creates the provider cluster -func (o *DevOptions) CreateProviderCluster(ctx context.Context) error { - return o.createCluster(ctx, o.ProviderClusterName, providerClusterConfig, true) -} - -// CreateConsumerCluster creates the consumer cluster -func (o *DevOptions) CreateConsumerCluster(ctx context.Context) error { - return o.createCluster(ctx, o.ConsumerClusterName, consumerClusterConfig, false) -} - -// GetProviderClusterName returns the provider cluster name -func (o *DevOptions) GetProviderClusterName() string { - return o.ProviderClusterName -} - -// GetConsumerClusterName returns the consumer cluster name -func (o *DevOptions) GetConsumerClusterName() string { - return o.ConsumerClusterName -} - -func (o *DevOptions) checkFileLimits() error { - // Only check on Linux systems - if runtime.GOOS != "linux" { - return nil - } - - // Check fs.inotify.max_user_watches - watchesCmd := exec.CommandContext(context.Background(), "sysctl", "-n", "fs.inotify.max_user_watches") - watchesOutput, err := watchesCmd.Output() - if err == nil { - if watches, err := strconv.Atoi(strings.TrimSpace(string(watchesOutput))); err == nil && watches < 524288 { - fmt.Fprintf(o.Streams.ErrOut, "⚠️ fs.inotify.max_user_watches is %d (recommended: 524288)\n", watches) - fmt.Fprintf(o.Streams.ErrOut, "💡 To increase: sudo sysctl fs.inotify.max_user_watches=524288\n") - } - } - - // Check fs.inotify.max_user_instances - instancesCmd := exec.CommandContext(context.Background(), "sysctl", "-n", "fs.inotify.max_user_instances") - instancesOutput, err := instancesCmd.Output() - if err == nil { - if instances, err := strconv.Atoi(strings.TrimSpace(string(instancesOutput))); err == nil && instances < 512 { - fmt.Fprintf(o.Streams.ErrOut, "⚠️ fs.inotify.max_user_instances is %d (recommended: 512)\n", instances) - fmt.Fprintf(o.Streams.ErrOut, "💡 To increase: sudo sysctl fs.inotify.max_user_instances=512\n") - } - } - - return nil -} diff --git a/cli/pkg/kubectl/dev/plugin/delete.go b/cli/pkg/kubectl/dev/plugin/delete.go deleted file mode 100644 index 651a2f125..000000000 --- a/cli/pkg/kubectl/dev/plugin/delete.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "fmt" - "os" - "runtime" - - "sigs.k8s.io/kind/pkg/cluster" -) - -func (o *DevOptions) RunDelete() error { - if err := o.deleteCluster(o.ProviderClusterName); err != nil { - return err - } - - if err := o.deleteCluster(o.ConsumerClusterName); err != nil { - return err - } - - return o.cleanupHostEntries() -} - -func (o *DevOptions) deleteCluster(clusterName string) error { - fmt.Fprintf(o.Streams.ErrOut, "Deleting kind cluster %s\n", clusterName) - provider := cluster.NewProvider() - - err := provider.Delete(clusterName, "") - if err != nil { - return err - } - - kubeconfigPath := fmt.Sprintf("%s.kubeconfig", clusterName) - if err := os.Remove(kubeconfigPath); err != nil && !os.IsNotExist(err) { - fmt.Fprintf(o.Streams.ErrOut, "Failed to remove kubeconfig file %s: %v\n", kubeconfigPath, err) - } else { - fmt.Fprintf(o.Streams.ErrOut, "Removed kubeconfig file %s\n", kubeconfigPath) - } - - return nil -} - -func (o *DevOptions) cleanupHostEntries() error { - if err := removeHostEntry("kube-bind.dev.local"); err != nil { - fmt.Fprintf(o.Streams.ErrOut, "Failed to remove host entry: %v\n", err) - fmt.Fprintf(o.Streams.ErrOut, "Warning: Could not automatically remove host entry. Please run:\n") - if runtime.GOOS == "windows" { - fmt.Fprintf(o.Streams.ErrOut, " Remove '127.0.0.1 kube-bind.dev.local' line from C:\\Windows\\System32\\drivers\\etc\\hosts\n") - } else { - fmt.Fprintf(o.Streams.ErrOut, " sudo sed -i '/127.0.0.1 kube-bind.dev.local/d' /etc/hosts\n") - } - } else { - fmt.Fprintf(o.Streams.ErrOut, "Removed host entry kube-bind.dev.local\n") - } - return nil -} diff --git a/cli/pkg/kubectl/dev/plugin/example.go b/cli/pkg/kubectl/dev/plugin/example.go deleted file mode 100644 index 3f1583c05..000000000 --- a/cli/pkg/kubectl/dev/plugin/example.go +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 plugin - -import ( - "fmt" -) - -var example = `apiVersion: mangodb.com/v1alpha1 -kind: MangoDB -metadata: - name: my-first-mangodb-instance - namespace: default -spec: - tier: Dedicated` - -func (o *DevOptions) RunPrintExample() error { - fmt.Fprintf(o.Streams.Out, "%s", example) - return nil -} diff --git a/cmd/backend/main.go b/cmd/backend/main.go index b110f9b41..5651dc23d 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,97 +14,384 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Command backend is the kbind provider-side service layer: one binary with +// module flags. Gateway (HTTP API + UI), issuer (Grant provisioning), reaper +// (Lease-keyed GC) and browser-apply are each independently switchable; the +// GitOps-only core path needs none of them. package main import ( "context" + "encoding/base64" + "errors" + "flag" "fmt" + "net/http" "os" "strings" + "time" - "github.com/spf13/pflag" - genericapiserver "k8s.io/apiserver/pkg/server" - logsv1 "k8s.io/component-base/logs/api/v1" - "k8s.io/component-base/version" - "k8s.io/klog/v2" + "golang.org/x/sync/errgroup" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log/zap" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" - backend "github.com/kube-bind/kube-bind/backend" - "github.com/kube-bind/kube-bind/backend/options" + "github.com/kbind/kbind/backend/auth" + "github.com/kbind/kbind/backend/gateway" + "github.com/kbind/kbind/backend/issuer" + "github.com/kbind/kbind/backend/reaper" + "github.com/kbind/kbind/pkg/konnectorinstall" + "github.com/kbind/kbind/pkg/servicecrds" + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" + "github.com/kbind/kbind/web" ) +// version is stamped via -ldflags at release time. +var version = "dev" + +var scheme = runtime.NewScheme() + +func init() { + for _, add := range []func(*runtime.Scheme) error{ + clientgoscheme.AddToScheme, + apiextensionsv1.AddToScheme, + corev1alpha1.AddToScheme, + catalogv1alpha1.AddToScheme, + iamv1alpha1.AddToScheme, + } { + if err := add(scheme); err != nil { + panic(err) + } + } +} + +type options struct { + // Modules. + enableGateway bool + enableIssuer bool + enableReaper bool + enableApply bool + + // CRD self-install. + installCRDs bool + + // Gateway. + listenAddr string + providerName string + externalURL string + pickupTTL time.Duration + konnectorImage string + + // Issuer. + externalAddress string + externalCAFile string + issuerScope string + + // Sessions. + cookieSigningKey string + cookieEncryptionKey string + sessionTTL time.Duration + + // OIDC (kube-apiserver/kcp style). + oidcIssuerURL string + oidcClientID string + oidcClientSecret string + oidcCAFile string + oidcUsernameClaim string + oidcGroupsClaim string + oidcScopes string + oidcRedirectURL string + oidcMock bool + oidcMockListen string + + // kubernetes auth. + kubernetesAuth bool + + // Reaper. + reaperTTL time.Duration + reaperRevoke bool + reaperDelete bool + reaperInterval time.Duration + + // Manager (issuer/reaper controllers). + metricsAddr string + probeAddr string + leaderElect bool + leaderElectionID string +} + func main() { - err := run(genericapiserver.SetupSignalContext()) - klog.Flush() + var o options + flag.BoolVar(&o.enableGateway, "enable-gateway", true, "serve the HTTP API (catalog, bind, bundle pickup) and UI") + flag.BoolVar(&o.enableIssuer, "enable-issuer", true, "run the provider-side controllers (Grant provisioning, catalog validation)") + flag.BoolVar(&o.enableReaper, "enable-reaper", false, "run the Lease-keyed GC of stale Grants") + flag.BoolVar(&o.enableApply, "enable-apply", false, + "enable POST /api/apply (browser-apply): consumer kubeconfigs transit the gateway when on") + flag.BoolVar(&o.installCRDs, "install-crds", true, + "install/refresh the service-layer CRDs (catalog.kbind.io, iam.kbind.io) at startup") - if err != nil { - fmt.Printf("Error running example backend: %v\n", err) + flag.StringVar(&o.listenAddr, "listen-address", ":8080", "address the gateway listens on") + flag.StringVar(&o.providerName, "provider-name", "kbind", "human-facing provider name") + flag.StringVar(&o.externalURL, "external-url", "", "externally reachable base URL of this gateway (defaults callback URLs; e.g. https://kbind.example.com)") + flag.DurationVar(&o.pickupTTL, "pickup-ttl", 5*time.Minute, "lifetime of one-time bundle pickup URLs") + flag.StringVar(&o.konnectorImage, "konnector-image", konnectorinstall.DefaultImage, "konnector image installed by browser-apply") + + flag.StringVar(&o.externalAddress, "external-address", "", "provider API server URL written into issued kubeconfigs (default: this process's API server host)") + flag.StringVar(&o.externalCAFile, "external-ca-file", "", "CA bundle for issued kubeconfigs (default: the SA token's ca.crt)") + flag.StringVar(&o.issuerScope, "issuer-scope", string(issuer.ScopeCluster), + "RBAC reach of issued credentials: Cluster (exported resources in all namespaces) or Namespace (boundary namespace only)") + + flag.StringVar(&o.cookieSigningKey, "cookie-signing-key", "", "base64 HMAC key for session tokens (32/64 bytes; shared across replicas; empty = ephemeral random, dev only)") + flag.StringVar(&o.cookieEncryptionKey, "cookie-encryption-key", "", "base64 AES key for session tokens (16/24/32 bytes; shared across replicas; empty = ephemeral random, dev only)") + flag.DurationVar(&o.sessionTTL, "session-ttl", 12*time.Hour, "session token lifetime") + + flag.StringVar(&o.oidcIssuerURL, "oidc-issuer-url", "", "OIDC issuer URL") + flag.StringVar(&o.oidcClientID, "oidc-client-id", "", "OIDC client ID") + flag.StringVar(&o.oidcClientSecret, "oidc-client-secret", "", "OIDC client secret") + flag.StringVar(&o.oidcCAFile, "oidc-ca-file", "", "CA bundle for the OIDC issuer's TLS") + flag.StringVar(&o.oidcUsernameClaim, "oidc-username-claim", "sub", "ID-token claim used as the stable username") + flag.StringVar(&o.oidcGroupsClaim, "oidc-groups-claim", "", "ID-token claim holding group membership") + flag.StringVar(&o.oidcScopes, "oidc-scopes", "openid,profile,email", "comma-separated OAuth2 scopes") + flag.StringVar(&o.oidcRedirectURL, "oidc-redirect-url", "", "externally reachable OIDC callback URL (default: /api/auth/oidc/callback)") + flag.BoolVar(&o.oidcMock, "oidc-mock", false, "run an embedded mock OIDC issuer that auto-approves every login (dev only)") + flag.StringVar(&o.oidcMockListen, "oidc-mock-listen", "", + "fixed listen address for the mock issuer (e.g. 127.0.0.1:5556 — port-forwardable when running in-cluster; empty = random port)") + flag.BoolVar(&o.kubernetesAuth, "kubernetes-auth", false, + "also accept provider-cluster bearer tokens, verified via TokenReview (for in-platform callers that already hold a cluster identity)") + + flag.DurationVar(&o.reaperTTL, "reaper-ttl", 30*time.Minute, "heartbeat silence after which a Grant is considered stale") + flag.BoolVar(&o.reaperRevoke, "reaper-revoke", false, "delete stale Grants (revokes their credentials)") + flag.BoolVar(&o.reaperDelete, "reaper-delete-boundary", false, + "when revoking, also delete the boundary namespace and the synced objects inside it (destructive; requires --reaper-revoke)") + flag.DurationVar(&o.reaperInterval, "reaper-interval", time.Minute, "reaper sweep cadence") + + flag.StringVar(&o.metricsAddr, "metrics-bind-address", ":8086", "address the metric endpoint binds to") + flag.StringVar(&o.probeAddr, "health-probe-bind-address", ":8082", "address the health/readiness probe endpoint binds to") + flag.BoolVar(&o.leaderElect, "leader-elect", false, "enable leader election for the provider-side controllers") + flag.StringVar(&o.leaderElectionID, "leader-election-id", "backend.kbind.io", "name of the Lease used for leader election") + + zapOpts := zap.Options{Development: true} + zapOpts.BindFlags(flag.CommandLine) + flag.Parse() + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zapOpts))) + + if err := run(o); err != nil { + ctrl.Log.Error(err, "backend exited with error") os.Exit(1) } } -func run(ctx context.Context) error { - options := options.NewOptions() - options.AddFlags(pflag.CommandLine) - pflag.Parse() +func run(o options) error { + ctx := ctrl.SetupSignalHandler() + log := ctrl.Log.WithName("backend") - // setup logging first - if err := logsv1.ValidateAndApply(options.Logs, nil); err != nil { + cfg, err := ctrl.GetConfig() + if err != nil { return err } - // Set up controller-runtime logger early to avoid warnings - ctrl.SetLogger(zap.New(zap.UseDevMode(true))) - log.SetLogger(klog.NewKlogr()) + // Self-install the service-layer CRDs so a fresh provider (and the plain + // `go run ./cmd/backend` dev loop) works without a chart install first. + if o.installCRDs { + if err := servicecrds.Install(ctx, cfg); err != nil { + return fmt.Errorf("installing service-layer CRDs (disable with --install-crds=false): %w", err) + } + log.Info("service-layer CRDs installed") + } + + g, ctx := errgroup.WithContext(ctx) + + kubeIssuer := &issuer.KubeIssuer{Scope: issuer.Scope(o.issuerScope)} - ver := version.Get().GitVersion - if i := strings.Index(ver, "bind-"); i != -1 { - ver = ver[i+5:] // example: v1.25.2+kubectl-bind-v0.0.7-52-g8fee0baeaff3aa + // Provider-side controllers (issuer, catalog validation, reaper) run on a + // manager; the gateway is a plain HTTP server with a direct client. + if o.enableIssuer || o.enableReaper { + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: o.metricsAddr}, + HealthProbeBindAddress: o.probeAddr, + LeaderElection: o.leaderElect, + LeaderElectionID: o.leaderElectionID, + LeaderElectionReleaseOnCancel: true, + }) + if err != nil { + return err + } + if o.enableIssuer { + kubeIssuer.Client = mgr.GetClient() + if err := (&issuer.GrantReconciler{Issuer: kubeIssuer}).SetupWithManager(mgr); err != nil { + return err + } + if err := (&issuer.ExportReconciler{}).SetupWithManager(mgr); err != nil { + return err + } + } + if o.enableReaper { + reapIssuer := kubeIssuer + if reapIssuer.Client == nil { + reapIssuer.Client = mgr.GetClient() + } + if err := mgr.Add(&reaper.Reaper{ + Client: mgr.GetClient(), + Issuer: reapIssuer, + TTL: o.reaperTTL, + Revoke: o.reaperRevoke, + DeleteBoundary: o.reaperDelete, + Interval: o.reaperInterval, + }); err != nil { + return err + } + } + g.Go(func() error { return ignoreCanceled(mgr.Start(ctx)) }) } - logger := klog.FromContext(ctx) - logger.Info("Starting backend", "version", ver) - // create server - completed, err := options.Complete() + if o.enableGateway { + server, err := buildGateway(ctx, o, cfg) + if err != nil { + return err + } + httpServer := &http.Server{ + Addr: o.listenAddr, + Handler: server.Handler(), + ReadHeaderTimeout: 10 * time.Second, + } + g.Go(func() error { + log.Info("gateway listening", "address", o.listenAddr) + if err := httpServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + return err + } + return nil + }) + g.Go(func() error { + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return httpServer.Shutdown(shutdownCtx) + }) + } + + log.Info("starting kbind backend", "version", version, + "gateway", o.enableGateway, "issuer", o.enableIssuer, "reaper", o.enableReaper, "apply", o.enableApply) + return g.Wait() +} + +// buildGateway wires sessions, authenticators, the bundle builder and the +// HTTP server. +func buildGateway(ctx context.Context, o options, cfg *rest.Config) (*gateway.Server, error) { + signingKey, err := decodeKeyFlag(o.cookieSigningKey, "--cookie-signing-key") if err != nil { - return err + return nil, err } - if err := completed.Validate(); err != nil { - return err + encryptionKey, err := decodeKeyFlag(o.cookieEncryptionKey, "--cookie-encryption-key") + if err != nil { + return nil, err } + if len(signingKey) == 0 { + ctrl.Log.Info("WARNING: no --cookie-signing-key set; sessions are ephemeral and will not survive restarts or work across replicas") + } + sessions := auth.NewSessions(signingKey, encryptionKey, o.sessionTTL) - // Show development mode warning for embedded OIDC - if completed.OIDC.Type == "embedded" { - fmt.Println("┌────────────────────────────────────────────────────────────────────────────────┐") - fmt.Println("│ DEVELOPMENT MODE │") - fmt.Println("│ running with embedded oidc │") - fmt.Println("│ do not use in production │") - fmt.Println("└────────────────────────────────────────────────────────────────────────────────┘") - fmt.Println() + externalURL := strings.TrimSuffix(o.externalURL, "/") + if externalURL == "" { + externalURL = "http://localhost" + o.listenAddr // dev fallback for :8080-style addrs } - // start server - config, err := backend.NewConfig(completed) + oidcCfg := auth.OIDCConfig{ + IssuerURL: o.oidcIssuerURL, + ClientID: o.oidcClientID, + ClientSecret: o.oidcClientSecret, + CAFile: o.oidcCAFile, + UsernameClaim: o.oidcUsernameClaim, + GroupsClaim: o.oidcGroupsClaim, + Scopes: splitNonEmpty(o.oidcScopes), + RedirectURL: o.oidcRedirectURL, + } + if oidcCfg.RedirectURL == "" { + oidcCfg.RedirectURL = externalURL + "/api/auth/oidc/callback" + } + if o.oidcMock { + mockCfg, err := auth.StartMockOIDC(ctx, oidcCfg.RedirectURL, o.oidcMockListen) + if err != nil { + return nil, err + } + ctrl.Log.Info("WARNING: --oidc-mock is on; every login auto-approves as the mock user (dev only)", "issuer", mockCfg.IssuerURL) + mockCfg.RedirectURL = oidcCfg.RedirectURL + oidcCfg = mockCfg + } + oidcAuth, err := auth.NewOIDC(ctx, oidcCfg, sessions) if err != nil { - return err + return nil, err + } + authenticators := []auth.Authenticator{oidcAuth} + if o.kubernetesAuth { + k8sAuth, err := auth.NewKubernetes(cfg) + if err != nil { + return nil, err + } + authenticators = append(authenticators, k8sAuth) } - server, err := backend.NewServer(ctx, config) + + providerClient, err := client.New(cfg, client.Options{Scheme: scheme}) if err != nil { - return err + return nil, err } - if err := server.Run(ctx); err != nil { - return err + externalAddress := o.externalAddress + if externalAddress == "" { + externalAddress = cfg.Host } - if addr := server.Addr(); addr != nil { - logger.Info("Listening", "address", addr) - } else { - logger.Info("Running in backend-only mode (no HTTP frontend)") + var externalCA []byte + if o.externalCAFile != "" { + externalCA, err = os.ReadFile(o.externalCAFile) + if err != nil { + return nil, fmt.Errorf("reading --external-ca-file: %w", err) + } } - <-ctx.Done() + return gateway.New(gateway.Config{ + ProviderName: o.providerName, + Version: version, + ApplyEnabled: o.enableApply, + PickupTTL: o.pickupTTL, + KonnectorImage: o.konnectorImage, + }, providerClient, &issuer.BundleBuilder{ + Client: providerClient, + ExternalAddress: externalAddress, + ExternalCA: externalCA, + }, authenticators, web.Static()), nil +} - return nil +func decodeKeyFlag(value, flagName string) ([]byte, error) { + if value == "" { + return nil, nil + } + key, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return nil, fmt.Errorf("%s must be base64: %w", flagName, err) + } + return key, nil +} + +func splitNonEmpty(s string) []string { + var out []string + for _, part := range strings.Split(s, ",") { + if part = strings.TrimSpace(part); part != "" { + out = append(out, part) + } + } + return out +} + +func ignoreCanceled(err error) error { + if errors.Is(err, context.Canceled) { + return nil + } + return err } diff --git a/cli/cmd/kubectl-bind/main.go b/cmd/bind/main.go similarity index 51% rename from cli/cmd/kubectl-bind/main.go rename to cmd/bind/main.go index ef9fefcb5..9bc86759a 100644 --- a/cli/cmd/kubectl-bind/main.go +++ b/cmd/bind/main.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,24 +14,30 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Command bind is the CLI over a kbind gateway: login, connect, catalog, +// and binding an export (the root command). Shipped to krew as the "bind" +// plugin (binary kubectl-bind), so `kubectl bind ` just works. package main import ( + "context" "fmt" "os" + "os/signal" + "syscall" - "github.com/spf13/pflag" - - cmd "github.com/kube-bind/kube-bind/cli/cmd/kubectl-bind/cmd" + "github.com/kbind/kbind/cli/cmd" ) func main() { - flags := pflag.NewFlagSet("kubectl-bind", pflag.ExitOnError) - pflag.CommandLine = flags - - command := cmd.KubectlBindCommand() - if err := command.Execute(); err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } } + +func run() error { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + return cmd.New().ExecuteContext(ctx) +} diff --git a/cmd/konnector/cmd/konnector.go b/cmd/konnector/cmd/konnector.go deleted file mode 100644 index c18e3882b..000000000 --- a/cmd/konnector/cmd/konnector.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 cmd - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/spf13/cobra" - "k8s.io/client-go/tools/leaderelection" - logsv1 "k8s.io/component-base/logs/api/v1" - componentbaseversion "k8s.io/component-base/version" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector" - konnectoroptions "github.com/kube-bind/kube-bind/pkg/konnector/options" - bindversion "github.com/kube-bind/kube-bind/pkg/version" - - _ "k8s.io/component-base/logs/json/register" -) - -const LeaderElectionTimeout = 20 * time.Second - -func New(ctx context.Context) *cobra.Command { - ver, err := bindversion.BinaryVersion(componentbaseversion.Get().GitVersion) - if err != nil { - fmt.Fprintf(os.Stderr, "failed to get version: %v\n", err) - ver = "" - } - - options := konnectoroptions.NewOptions() - cmd := &cobra.Command{ - Use: "konnector", - Short: "Connect remote API services to local APIs", - Version: ver, - RunE: func(cmd *cobra.Command, args []string) error { - // setup logging first - if err := logsv1.ValidateAndApply(options.Logs, nil); err != nil { - return err - } - - logger := klog.FromContext(ctx) - logger.Info("Starting konnector", "version", ver) - - // setup server - completed, err := options.Complete() - if err != nil { - return err - } - if err := completed.Validate(); err != nil { - return err - } - config, err := konnector.NewConfig(completed) - if err != nil { - return err - } - server, err := konnector.NewServer(config) - if err != nil { - return err - } - prepared, err := server.PrepareRun(ctx) - if err != nil { - return err - } - prepared.OptionallyStartInformers(ctx) - - logger.Info("trying to acquire the lock") - lock := NewLock(config.KubeClient, options.LeaseLockNamespace, options.LeaseLockName, options.LeaseLockIdentity) - - le := makeLeaderElectorOrDie(ctx, lock, options.LeaseLockIdentity, func(ctx context.Context) { - logger.Info("starting konnector controller") - err = prepared.Run(ctx) - }) - - hz := leaderelection.NewLeaderHealthzAdaptor(LeaderElectionTimeout) - hz.SetLeaderElection(le) - - server.AddCheck(hz) - server.StartHealthCheck(ctx) - - le.Run(ctx) - <-ctx.Done() - - return err - }, - } - options.AddFlags(cmd.Flags()) - - return cmd -} diff --git a/cmd/konnector/cmd/leaderelection.go b/cmd/konnector/cmd/leaderelection.go deleted file mode 100644 index 6a7387aae..000000000 --- a/cmd/konnector/cmd/leaderelection.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 cmd - -import ( - "context" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubeclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/leaderelection" - "k8s.io/client-go/tools/leaderelection/resourcelock" - "k8s.io/klog/v2" -) - -func NewLock(client kubeclient.Interface, namespace, lockName, podName string) *resourcelock.LeaseLock { - return &resourcelock.LeaseLock{ - LeaseMeta: metav1.ObjectMeta{ - Name: lockName, - Namespace: namespace, - }, - Client: client.CoordinationV1(), - LockConfig: resourcelock.ResourceLockConfig{ - Identity: podName, - }, - } -} - -func makeLeaderElectorOrDie(ctx context.Context, lock *resourcelock.LeaseLock, id string, run func(ctx context.Context)) *leaderelection.LeaderElector { - logger := klog.FromContext(ctx) - - le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{ - Lock: lock, - ReleaseOnCancel: true, - LeaseDuration: 15 * time.Second, - RenewDeadline: 10 * time.Second, - RetryPeriod: 2 * time.Second, - Callbacks: leaderelection.LeaderCallbacks{ - OnStartedLeading: func(c context.Context) { - logger.Info("started leading", "id", id) - run(ctx) - }, - OnStoppedLeading: func() { - logger.Info("no longer the leader, staying inactive.") - }, - OnNewLeader: func(currentID string) { - if currentID == id { - logger.Info("still the leader!") - return - } - logger.Info("new leader", "id", currentID) - }, - }, - }) - if err != nil { - panic(err) - } - return le -} diff --git a/cmd/konnector/main.go b/cmd/konnector/main.go index c0693cc0a..92fd9e1b0 100644 --- a/cmd/konnector/main.go +++ b/cmd/konnector/main.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,20 +14,145 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Command konnector is the v2 slim-core sync engine. It runs in (or against) a +// consumer cluster, watches Connection/ClusterBinding/Binding objects, and +// bridges to provider clusters discovered from Connections. package main import ( + "context" + "errors" + "flag" "os" - genericapiserver "k8s.io/apiserver/pkg/server" - "k8s.io/component-base/cli" + "golang.org/x/sync/errgroup" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/healthz" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" - "github.com/kube-bind/kube-bind/cmd/konnector/cmd" + "github.com/kbind/kbind/engine/binding" + "github.com/kbind/kbind/engine/connection" + "github.com/kbind/kbind/engine/provider" + syncengine "github.com/kbind/kbind/engine/sync" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" ) +var scheme = runtime.NewScheme() + +func init() { + utilRuntimeMust(clientgoscheme.AddToScheme(scheme)) + utilRuntimeMust(apiextensionsv1.AddToScheme(scheme)) + utilRuntimeMust(corev1alpha1.AddToScheme(scheme)) +} + +// options holds the konnector's runtime flags. +type options struct { + metricsAddr string + probeAddr string + leaderElect bool + leaderElectionID string +} + func main() { - ctx := genericapiserver.SetupSignalContext() - syncerCommand := cmd.New(ctx) - code := cli.Run(syncerCommand) - os.Exit(code) + var o options + flag.StringVar(&o.metricsAddr, "metrics-bind-address", ":8085", "address the metric endpoint binds to") + flag.StringVar(&o.probeAddr, "health-probe-bind-address", ":8081", "address the health/readiness probe endpoint binds to") + flag.BoolVar(&o.leaderElect, "leader-elect", false, + "enable leader election, ensuring only one active konnector replica (required for HA / multiple replicas)") + flag.StringVar(&o.leaderElectionID, "leader-election-id", "konnector.kbind.io", + "name of the Lease used for leader election") + opts := zap.Options{Development: true} + opts.BindFlags(flag.CommandLine) + flag.Parse() + ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + + if err := run(o); err != nil { + ctrl.Log.Error(err, "konnector exited with error") + os.Exit(1) + } +} + +func run(o options) error { + ctx := ctrl.SetupSignalHandler() + log := ctrl.Log.WithName("konnector") + + cfg, err := ctrl.GetConfig() + if err != nil { + return err + } + + // Local (consumer) manager: owns the core CRDs and the consumer-side caches. + // Leader election gates all consumer-side controllers, so standby replicas + // engage no provider clusters and run no syncers until they win the lease. + localMgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: o.metricsAddr}, + HealthProbeBindAddress: o.probeAddr, + LeaderElection: o.leaderElect, + LeaderElectionID: o.leaderElectionID, + LeaderElectionReleaseOnCancel: true, + }) + if err != nil { + return err + } + if err := localMgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { + return err + } + if err := localMgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { + return err + } + + // Connection provider: each ready Connection becomes an engaged provider cluster. + connProvider, err := provider.New(localMgr, provider.Options{}) + if err != nil { + return err + } + + // Multicluster manager bridging consumer <-> provider clusters. + mcMgr, err := mcmanager.New(cfg, connProvider, mcmanager.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + }) + if err != nil { + return err + } + + // Consumer-side reconcilers (run on the local manager). + if err := (&connection.Reconciler{}).SetupWithManager(localMgr); err != nil { + return err + } + if err := (&binding.ClusterReconciler{}).SetupWithManager(localMgr); err != nil { + return err + } + if err := (&binding.NamespacedReconciler{}).SetupWithManager(localMgr); err != nil { + return err + } + if err := syncengine.SetupWithManager(localMgr, connProvider); err != nil { + return err + } + + log.Info("starting konnector") + g, ctx := errgroup.WithContext(ctx) + g.Go(func() error { return ignoreCanceled(localMgr.Start(ctx)) }) + g.Go(func() error { return ignoreCanceled(connProvider.Run(ctx, mcMgr)) }) + g.Go(func() error { return ignoreCanceled(mcMgr.Start(ctx)) }) + return g.Wait() +} + +func ignoreCanceled(err error) error { + if errors.Is(err, context.Canceled) { + return nil + } + return err +} + +func utilRuntimeMust(err error) { + if err != nil { + panic(err) + } } diff --git a/cmd/release/main.go b/cmd/release/main.go new file mode 100644 index 000000000..384caaa2a --- /dev/null +++ b/cmd/release/main.go @@ -0,0 +1,183 @@ +/* +Copyright 2026 The kbind 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. +*/ + +// Command release computes and creates the next v2 release-candidate tag. +// +// It inspects the tags already present on an upstream remote, finds the highest +// release candidate for the target version (default v2.0.0), and creates the +// next one (e.g. v2.0.0-rc3 if rc2 is the highest upstream). Pushing the tag to +// the remote triggers the Image workflow, so pushing is gated behind -push. +// +// Usage: +// +// go run ./cmd/release # compute + create the next rc tag locally +// go run ./cmd/release -dry-run # only print what would be created +// go run ./cmd/release -push # create and push the tag to the remote +package main + +import ( + "context" + "flag" + "fmt" + "os" + "os/exec" + "os/signal" + "regexp" + "sort" + "strconv" + "strings" +) + +// options holds the release tool's flags. +type options struct { + remote string + version string + push bool + dryRun bool +} + +func newFlagSet(o *options) *flag.FlagSet { + fs := flag.NewFlagSet("release", flag.ContinueOnError) + fs.StringVar(&o.remote, "remote", "origin", "git remote to read existing tags from and push to") + fs.StringVar(&o.version, "version", "v2.0.0", "target GA version the release candidates lead up to") + fs.BoolVar(&o.push, "push", false, "push the created tag to the remote (triggers the Image workflow)") + fs.BoolVar(&o.dryRun, "dry-run", false, "only print the tag that would be created") + return fs +} + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + err := run(ctx) + stop() + if err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +func run(ctx context.Context) error { + var o options + fs := newFlagSet(&o) + if err := fs.Parse(os.Args[1:]); err != nil { + return err + } + + if !strings.HasPrefix(o.version, "v2.") { + return fmt.Errorf("target version %q is not a v2 version", o.version) + } + + tags, err := remoteTags(ctx, o.remote) + if err != nil { + return err + } + + next := nextRC(o.version, tags) + fmt.Printf("remote %q: highest rc for %s -> next tag %s\n", o.remote, o.version, next) + + if o.dryRun { + return nil + } + + if localTagExists(ctx, next) { + return fmt.Errorf("tag %s already exists locally; delete it first or bump the version", next) + } + + if err := gitRun(ctx, "tag", "-a", next, "-m", next); err != nil { + return fmt.Errorf("creating tag %s: %w", next, err) + } + fmt.Printf("created annotated tag %s on HEAD\n", next) + + if !o.push { + fmt.Printf("not pushed. To publish (triggers the Image workflow):\n\n git push %s %s\n", o.remote, next) + return nil + } + + if err := gitRun(ctx, "push", o.remote, next); err != nil { + return fmt.Errorf("pushing tag %s to %s: %w", next, o.remote, err) + } + fmt.Printf("pushed %s to %s — the Image workflow will build ghcr.io//konnector:%s\n", next, o.remote, next) + return nil +} + +// rcTagRE matches a release-candidate tag and captures the rc number, e.g. +// "v2.0.0-rc3" -> "3". +var rcTagRE = regexp.MustCompile(`^(v\d+\.\d+\.\d+)-rc(\d+)$`) + +// nextRC returns the next release-candidate tag for version, given the set of +// existing tags. If no rc exists for version yet it returns "-rc1". +func nextRC(version string, tags []string) string { + highest := 0 + for _, t := range tags { + m := rcTagRE.FindStringSubmatch(t) + if m == nil || m[1] != version { + continue + } + n, err := strconv.Atoi(m[2]) + if err != nil { + continue + } + if n > highest { + highest = n + } + } + return fmt.Sprintf("%s-rc%d", version, highest+1) +} + +// remoteTags lists the tag names present on the given remote via +// `git ls-remote --tags`, so no local fetch is required. Dereferenced tag refs +// (the "^{}" suffix) are collapsed to their base tag name. +func remoteTags(ctx context.Context, remote string) ([]string, error) { + out, err := gitOutput(ctx, "ls-remote", "--tags", remote) + if err != nil { + return nil, fmt.Errorf("listing tags on remote %q: %w", remote, err) + } + seen := map[string]struct{}{} + var tags []string + for line := range strings.SplitSeq(strings.TrimSpace(out), "\n") { + fields := strings.Fields(line) + if len(fields) != 2 { + continue + } + ref := strings.TrimPrefix(fields[1], "refs/tags/") + ref = strings.TrimSuffix(ref, "^{}") + if _, ok := seen[ref]; ok { + continue + } + seen[ref] = struct{}{} + tags = append(tags, ref) + } + sort.Strings(tags) + return tags, nil +} + +// localTagExists reports whether tag already exists in the local repository. +func localTagExists(ctx context.Context, tag string) bool { + return gitRun(ctx, "rev-parse", "--verify", "--quiet", "refs/tags/"+tag) == nil +} + +func gitRun(ctx context.Context, args ...string) error { + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} + +func gitOutput(ctx context.Context, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Stderr = os.Stderr + out, err := cmd.Output() + return string(out), err +} diff --git a/code-of-conduct.md b/code-of-conduct.md deleted file mode 100644 index cfff0529a..000000000 --- a/code-of-conduct.md +++ /dev/null @@ -1,89 +0,0 @@ -This project is following the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md). - -# Community Code of Conduct - -As contributors, maintainers, and participants in the CNCF community, and in the interest of fostering -an open and welcoming community, we pledge to respect all people who participate or contribute -through reporting issues, posting feature requests, updating documentation, -submitting pull requests or patches, attending conferences or events, or engaging in other community or project activities. - -We are committed to making participation in the CNCF community a harassment-free experience for everyone, regardless of age, body size, caste, disability, ethnicity, level of experience, family status, gender, gender identity and expression, marital status, military or veteran status, nationality, personal appearance, race, religion, sexual orientation, socioeconomic status, tribe, or any other dimension of diversity. - -## Scope - -This code of conduct applies: -* within project and community spaces, -* in other spaces when an individual CNCF community participant's words or actions are directed at or are about a CNCF project, the CNCF community, or another CNCF community participant in the context of a CNCF activity. - -### CNCF Events - -CNCF events that are produced by the Linux Foundation with professional events staff are governed by the Linux Foundation [Events Code of Conduct](https://events.linuxfoundation.org/code-of-conduct/) available on the event page. This is designed to be used in conjunction with the CNCF Code of Conduct. - -## Our Standards - -The CNCF Community is open, inclusive and respectful. Every member of our community has the right to have their identity respected. - -Examples of behavior that contributes to a positive environment include but are not limited to: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community -* Using welcoming and inclusive language - - -Examples of unacceptable behavior include but are not limited to: - -* The use of sexualized language or imagery -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment in any form -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Violence, threatening violence, or encouraging others to engage in violent behavior -* Stalking or following someone without their consent -* Unwelcome physical contact -* Unwelcome sexual or romantic attention or advances -* Using CNCF projects or community spaces for political campaigning or promotion of political causes - that are unrelated to the advancement of cloud native technology. To clarify, this policy does not restrict individuals' personal attire, including attire that expresses personal beliefs or aspects of identity. -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -The following behaviors are also prohibited: -* Providing knowingly false or misleading information in connection with a Code of Conduct investigation or otherwise intentionally tampering with an investigation. -* Retaliating against a person because they reported an incident or provided information about an incident as a witness. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. -By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect -of managing a CNCF project. -Project maintainers who do not follow or enforce the Code of Conduct may be temporarily or permanently removed from the project team. - -## Reporting - -For incidents occurring in the Kubernetes community, contact the [Kubernetes Code of Conduct Committee](https://git.k8s.io/community/committee-code-of-conduct) via . You can expect a response within three business days. - -For other projects, or for incidents that are project-agnostic or impact multiple CNCF projects, please contact the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) via . Alternatively, you can contact any of the individual members of the [CNCF Code of Conduct Committee](https://www.cncf.io/conduct/committee/) to submit your report. For more detailed instructions on how to submit a report, including how to submit a report anonymously, please see our [Incident Resolution Procedures](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-incident-resolution-procedures.md). You can expect a response within three business days. - -For incidents occurring at CNCF event that is produced by the Linux Foundation, please contact . - -## Frequently asked questions - -For more information about this Code of Conduct, please see the [CNCF Code of Conduct Frequently Asked Questions](https://www.cncf.io/conduct/faq/). - -## Enforcement - -Upon review and investigation of a reported incident, the CoC response team that has jurisdiction will determine what action is appropriate based on this Code of Conduct and its related documentation. - -For information about which Code of Conduct incidents are handled by project leadership, which incidents are handled by the CNCF Code of Conduct Committee, and which incidents are handled by the Linux Foundation (including its events team), see our [Jurisdiction Policy](https://github.com/cncf/foundation/blob/main/code-of-conduct/coc-committee-jurisdiction-policy.md). - -## Amendments - -Consistent with the CNCF Charter, any substantive changes to this Code of Conduct must be approved by the Technical Oversight Committee. - -## Acknowledgements - -This Code of Conduct is adapted from the Contributor Covenant -(http://contributor-covenant.org), version 2.0 available at -http://contributor-covenant.org/version/2/0/code_of_conduct/ diff --git a/config/samples/binding.yaml b/config/samples/binding.yaml new file mode 100644 index 000000000..8f22b158e --- /dev/null +++ b/config/samples/binding.yaml @@ -0,0 +1,42 @@ +# The "one apply" bundle. Apply this on the CONSUMER cluster. +# (The kubeconfig Secret is created separately by the demo script; a kbind +# backend generates this whole file for you — see docs/proposals/v2-extended.md.) +apiVersion: core.kbind.io/v1alpha1 +kind: Connection +metadata: + name: demo-provider +spec: + kubeconfigSecretRef: + namespace: kbind + name: demo-provider-kubeconfig + key: kubeconfig + schema: + source: CRD +--- +apiVersion: core.kbind.io/v1alpha1 +kind: ClusterBinding +metadata: + name: widgets +spec: + connectionRef: + name: demo-provider + apis: + - name: widgets.example.org + # Related resources: the provider's labeled Secret/ConfigMap sync into this + # cluster alongside the widgets (same namespace/name, garbage-collected when + # they stop matching or on unbind). + relatedResources: + - group: "" + resource: secrets + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/related: "true" + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/related: "true" diff --git a/config/samples/provider-widget-crd.yaml b/config/samples/provider-widget-crd.yaml new file mode 100644 index 000000000..a0d65d07d --- /dev/null +++ b/config/samples/provider-widget-crd.yaml @@ -0,0 +1,68 @@ +# The provider side of the demo. Apply this on the PROVIDER cluster: +# - the Widget CRD, labeled as exported (the core's entire provider opt-in), +# - a Secret + ConfigMap the service ships alongside its API ("related +# resources"), selected by label and synced provider -> consumer. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: widgets.example.org + labels: + core.kbind.io/exported: "true" +spec: + group: example.org + names: + plural: widgets + singular: widget + kind: Widget + listKind: WidgetList + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + size: + type: string + status: + type: object + properties: + phase: + type: string + additionalPrinterColumns: + - name: Size + type: string + jsonPath: .spec.size + - name: Phase + type: string + jsonPath: .status.phase +--- +# Related resources: connection details and tuning the service hands to every +# consumer. Anything matching the binding's selector syncs to the consumer. +apiVersion: v1 +kind: Secret +metadata: + name: widgets-connection + namespace: default + labels: + widgets.example.org/related: "true" +stringData: + endpoint: https://widgets.internal.example.org + api-key: demo-not-a-real-key +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: widgets-tuning + namespace: default + labels: + widgets.example.org/related: "true" +data: + pointiness: "11" diff --git a/config/samples/widget.yaml b/config/samples/widget.yaml new file mode 100644 index 000000000..c4c05b74f --- /dev/null +++ b/config/samples/widget.yaml @@ -0,0 +1,19 @@ +# A consumer-side instance. Apply on the CONSUMER cluster after the binding is +# Ready (the Widget CRD will have been pulled from the provider). +# +# The konnector syncs this object's spec up to the provider; provider status +# flows back here. Alongside it, the binding's related resources (the +# provider's widgets-connection Secret and widgets-tuning ConfigMap) land in +# this cluster's default namespace: +# +# kubectl get widget my-widget -o jsonpath='{.status.phase}' +# kubectl -n default get secret widgets-connection +# kubectl -n default get configmap widgets-tuning +--- +apiVersion: example.org/v1 +kind: Widget +metadata: + name: my-widget + namespace: default +spec: + size: large diff --git a/contrib/kcp/Makefile b/contrib/kcp/Makefile deleted file mode 100644 index a3eb6dec6..000000000 --- a/contrib/kcp/Makefile +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2025 The Kube Bind 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. - -ROOT_DIR = $(abspath ../..) - -export UGET_DIRECTORY := $(ROOT_DIR)/hack/tools -export UGET_CHECKSUMS := $(ROOT_DIR)/hack/tools.checksums -export UGET_VERSIONED_BINARIES = true - -# pre-release kcp version -KCP_APIGEN_VERSION := 11364df3071c021e96b4ed8c48aa9cd63e8f0115 - -.PHONY: all -all: build - -.PHONY: install-apigen -install-apigen: - @GO_MODULE=true $(ROOT_DIR)/hack/uget.sh github.com/kcp-dev/sdk/cmd/apigen apigen $(KCP_APIGEN_VERSION) - -codegen: ## Generate kcp API resources from CRDs - ./hack/update-kcp-codegen.sh diff --git a/contrib/kcp/README.md b/contrib/kcp/README.md deleted file mode 100644 index 828e7aa21..000000000 --- a/contrib/kcp/README.md +++ /dev/null @@ -1,448 +0,0 @@ -# kcp - -kcp folder contains isolated set of tooling to bootstrap kube-bind to work with a kcp instance. -It is split into a separate package to avoid vendoring pollution. - -kcp requires initial setup before it can be used. -This includes setting up workspaces, `APIResourceSchema`s, and `APIExport`s. - -It was its own Go module to avoid kcp dependencies in the main kube-bind module. - -This is not required if you are doing deeper integration and controlling the setup with your own scripts. - -## Architecture - -This example demonstrates a **three-tier** kube-bind setup with kcp: - -``` -:root:provider — owns the Cowboys APIResourceSchema + APIExport (source of truth) - | - | (APIBinding: :root:backend binds cowboys from :root:provider) - v -:root:backend — binds cowboys from provider, re-exposes them to consumers via kube-bind - | - | (kube-bind runs in :root:kube-bind, serves the binding API for consumers) - v - consumer — any kcp workspace or external cluster that wants cowboys -``` - -Three kubeconfigs are used throughout this guide: - -| File | Points to | Used for | -|------|-----------|----------| -| `provider.kubeconfig` | `:root:provider` | creating cowboys `APIResourceSchema` + `APIExport` | -| `backend.kubeconfig` | `:root:backend` | binding cowboys from provider, creating templates | -| `kube-bind.kubeconfig` | `:root:kube-bind` | running the kube-bind backend process | - -- **Provider** (`:root:provider`): defines the `cowboys` API (`APIResourceSchema` + `APIExport`). The upstream API owner. -- **Backend** (`:root:backend`): binds provider's `cowboys` APIExport, creates `APIServiceExport` templates. The broker layer. -- **kube-bind** (`:root:kube-bind`): where the kube-bind backend process runs, serving the binding HTTP API to consumers. -- **Consumer**: binds cowboys via kube-bind, with no direct dependency on the provider. - -## How to run - -### Preparation - -1. Start kcp: - -```bash -make run-kcp -``` - ---- - -### Provider - -The provider workspace owns the `cowboys` `APIResourceSchema` and `APIExport`. - -2. Set up the provider workspace: - - -```bash -cp .kcp/admin.kubeconfig .kcp/provider.kubeconfig -export KUBECONFIG=.kcp/provider.kubeconfig -kubectl ws use :root -kubectl ws create provider --enter -``` - -3. Create the `APIResourceSchema` and `APIExport` for cowboys: - -```bash -kubectl apply -f contrib/kcp/deploy/examples/apiresourceschema-cowboys.yaml -kubectl apply -f contrib/kcp/deploy/examples/apiexport-cowboys.yaml -``` - -The `APIExport` named `cowboys` makes the cowboys API available for other workspaces to bind. - ---- - -### kube-bind - -The `:root:kube-bind` workspace is where the kube-bind backend process runs. `kcp-init` creates this workspace and installs the kube-bind `APIExport` into it. - -4. Bootstrap the kube-bind workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/kube-bind.kubeconfig -export KUBECONFIG=.kcp/kube-bind.kubeconfig -./bin/kcp-init --kcp-kubeconfig $KUBECONFIG -``` - -5. Run the kube-bind backend: - -```bash -kubectl ws use :root:kube-bind - -go run ./cmd/backend \ - --multicluster-runtime-provider kcp \ - --apiexport-endpoint-slice-name=kube-bind.io \ - --pretty-name="BigCorp.com" \ - --oidc-type=embedded \ - --oidc-issuer-url=http://127.0.0.1:8080/oidc \ - --oidc-callback-url=http://127.0.0.1:8080/api/callback \ - --namespace-prefix="kube-bind-" \ - --schema-source apiresourceschemas \ - --consumer-scope=cluster -``` - -This process keeps running — open a new terminal. - ---- - -### Backend - -The backend workspace (`:root:backend`) binds the provider's cowboys `APIExport` and sets up `APIServiceExport` templates so kube-bind knows what to offer consumers. - -6. Set up the backend workspace and bind the kube-bind `APIExport`: - -```bash -cp .kcp/admin.kubeconfig .kcp/backend.kubeconfig -export KUBECONFIG=.kcp/backend.kubeconfig -kubectl ws use :root -kubectl ws create backend --enter - -kubectl kcp bind apiexport root:kube-bind:kube-bind.io \ - --accept-permission-claim clusterrolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim clusterroles.rbac.authorization.k8s.io \ - --accept-permission-claim customresourcedefinitions.apiextensions.k8s.io \ - --accept-permission-claim serviceaccounts.core \ - --accept-permission-claim configmaps.core \ - --accept-permission-claim secrets.core \ - --accept-permission-claim namespaces.core \ - --accept-permission-claim roles.rbac.authorization.k8s.io \ - --accept-permission-claim subjectaccessreviews.authorization.k8s.io \ - --accept-permission-claim rolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim apiresourceschemas.apis.kcp.io \ - --accept-permission-claim apibindings.apis.kcp.io -``` - -7. Bind the provider's cowboys `APIExport` into `:root:backend`: - -```bash -kubectl kcp bind apiexport root:provider:cowboys -``` - -8. Get the LogicalCluster identity (needed for consumer binding): - -```bash -kubectl get logicalcluster -# NAME PHASE URL AGE -# cluster Ready https://192.168.2.166:6443/clusters/2ocmmccjkme8bof4 -``` - ---- - -### Consumer - -The consumer binds cowboys from kube-bind (backed by `:root:backend`), with no direct dependency on the provider. - -9. Set up the consumer workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/consumer.kubeconfig -export KUBECONFIG=.kcp/consumer.kubeconfig -kubectl ws use :root -kubectl ws create consumer --enter -``` - -// TODO: Backend in kcp should dynamically lifecycle schemas. - -10. Log in and bind cowboys: - -```bash -./bin/kubectl-bind login http://127.0.0.1:8080 --cluster 216gnjm1cqct4x1j - -./bin/kubectl-bind --dry-run -o yaml > apiserviceexport.yaml - -# Extract the secret for the binding process. -# Note: the secret name may differ — check with `kubectl get secret -n kube-bind` -kubectl get secrets -n kube-bind -o jsonpath='{.items[0].data.kubeconfig}' | base64 -d > remote.kubeconfig - -namespace=$(yq '.contexts[0].context.namespace' remote.kubeconfig) - -./bin/kubectl-bind apiservice -v 6 \ - --remote-kubeconfig remote.kubeconfig \ - -f apiserviceexport.yaml \ - --skip-konnector \ - --remote-namespace "$namespace" -``` - -This process keeps running — switch to a new terminal. - -11. Start the konnector: - -```bash -./bin/konnector --lease-namespace default --kubeconfig .kcp/consumer.kubeconfig -``` - ---- - -### Create an instance - -Once binding is complete, create a cowboy on the consumer: - -```bash -kubectl apply -f deploy/examples/cr-cowboy.yaml -``` - -The cowboy is synced to `:root:backend`, which in turn stores it via the provider's APIExport in `:root:provider`. - ---- - -## Backend-only mode - -Sometimes you want to run kube-bind without any frontend, HTTP API, or OIDC — useful in multi-tenant environments, GitOps pipelines, or when each tenant has their own identity provider. - -The same three kubeconfigs apply: - -| File | Points to | Used for | -|------|-----------|----------| -| `provider.kubeconfig` | `:root:provider` | creating cowboys `APIResourceSchema` + `APIExport` | -| `backend.kubeconfig` | `:root:backend` | binding cowboys from provider, creating templates | -| `kube-bind.kubeconfig` | `:root:kube-bind` | running the kube-bind backend process | - -### Preparation - -1. Start kcp: - -```bash -make run-kcp -``` - -### Provider - -2. Set up the provider workspace and cowboys API: - -```bash -cp .kcp/admin.kubeconfig .kcp/provider.kubeconfig -export KUBECONFIG=.kcp/provider.kubeconfig -kubectl ws use :root -kubectl ws create provider --enter -kubectl apply -f contrib/kcp/deploy/examples/apiresourceschema-cowboys.yaml -kubectl apply -f contrib/kcp/deploy/examples/apiexport-cowboys.yaml -``` - -### kube-bind - -3. Bootstrap the kube-bind workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/kube-bind.kubeconfig -export KUBECONFIG=.kcp/kube-bind.kubeconfig -./bin/kcp-init --kcp-kubeconfig $KUBECONFIG -``` - -4. Run the backend in backend-only mode (no OIDC, no HTTP frontend): - -```bash -kubectl ws use :root:kube-bind - -go run ./cmd/backend \ - --multicluster-runtime-provider kcp \ - --apiexport-endpoint-slice-name=kube-bind.io \ - --pretty-name="BigCorp.com" \ - --frontend-disabled=true \ - --namespace-prefix="kube-bind-" \ - --schema-source apiresourceschemas \ - --consumer-scope=cluster \ - --isolation=None -``` - -This process keeps running — open a new terminal. - -### Backend - -5. Set up the backend workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/backend.kubeconfig -export KUBECONFIG=.kcp/backend.kubeconfig -kubectl ws use :root -kubectl ws create backend --enter - -kubectl kcp bind apiexport root:kube-bind:kube-bind.io \ - --accept-permission-claim clusterrolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim clusterroles.rbac.authorization.k8s.io \ - --accept-permission-claim customresourcedefinitions.apiextensions.k8s.io \ - --accept-permission-claim serviceaccounts.core \ - --accept-permission-claim configmaps.core \ - --accept-permission-claim secrets.core \ - --accept-permission-claim namespaces.core \ - --accept-permission-claim roles.rbac.authorization.k8s.io \ - --accept-permission-claim subjectaccessreviews.authorization.k8s.io \ - --accept-permission-claim rolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim apiresourceschemas.apis.kcp.io \ - --accept-permission-claim apibindings.apis.kcp.io -``` - -6. Bind the provider's cowboys `APIExport` into `:root:backend`: - -```bash -kubectl kcp bind apiexport root:provider:cowboys -``` - -7. Create the `APIResourceSchema` and `APIServiceExport` template for cowboys: - -```bash -kubectl apply -f contrib/kcp/deploy/examples/apiresourceschema-cowboys.yaml -kubectl apply -f deploy/examples/template-cowboys.yaml -``` - -8. Get the LogicalCluster identity: - -```bash -kubectl get logicalcluster -# NAME PHASE URL AGE -# cluster Ready https://192.168.2.166:6443/clusters/20nuv280snhqd5j4 -``` - -### Consumer (backend-only) - -9. Set up the consumer workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/consumer.kubeconfig -export KUBECONFIG=.kcp/consumer.kubeconfig -kubectl ws use :root -kubectl ws create consumer --enter -``` - -In backend-only mode there is no HTTP API or OIDC, so the CLI login flow does not apply. -Instead, binding is initiated via a `BindableResourcesRequest` CRD. - -**How backend-only binding works:** - -In traditional mode, `BindableResourcesRequest` is sent as a REST API payload to the backend HTTP server, which: -1. Creates a dedicated namespace for the consumer -2. Generates a kubeconfig for that namespace -3. Returns it as an HTTP response - -In backend-only mode, `BindableResourcesRequest` is a **CRD** watched by a controller, which: -1. Creates the namespace and kubeconfig automatically -2. Stores the result in a Secret specified by `kubeconfigSecretRef` - -This enables GitOps and automation without requiring HTTP API access. - -10. Get the cluster identity: - -```bash -./bin/kubectl-bind cluster-identity -``` - -11. Create the `BindableResourcesRequest` (applied against `:root:kube-bind` where the backend is running): - -```bash -export KUBECONFIG=.kcp/kube-bind.kubeconfig -kubectl ws use :root:kube-bind - -kubectl apply -f - < remote.data -``` - -13. Deploy the binding on the consumer: - -```bash -export KUBECONFIG=.kcp/consumer.kubeconfig -./bin/kubectl-bind deploy --file remote.data --skip-konnector -``` - -14. Start the konnector: - -```bash -./bin/konnector --lease-namespace default --kubeconfig .kcp/consumer.kubeconfig -``` - -15. Create an `APIServiceBindingBundle` to pull all available contracts: - -```bash -kubectl apply -f - </...` or `/api` for the core group." - type: string - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It must - be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIServiceExportVersion describes one API version of - a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - properties: - openAPIV3Schema: - description: openAPIV3Schema is the OpenAPI v3 schema to use - for validation and pruning. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - required: - - openAPIV3Schema - type: object - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should serve - a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - x-kubernetes-validations: - - message: informerScope must be Cluster for cluster-scoped resources - rule: self.scope == "Namespaced" || self.informerScope == "Cluster" - - message: clusterScopedIsolation must be defined for cluster-scoped resources - rule: self.scope == "Namespaced" || has(self.clusterScopedIsolation) - - message: clusterScopedIsolation is not relevant for namespaced resources - rule: self.scope == "Cluster" || !has(self.clusterScopedIsolation) - status: - description: status contains reconciliation information for the resource. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It must - be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: informerScope is immutable - rule: self.metadata.name == self.spec.names.plural+"."+self.spec.group - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Established")].status - name: Established - priority: 5 - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - APIServiceExport specifies the resource to be exported. It is mostly a CRD: - - the spec is a CRD spec, but without webhooks - - the status reflects that on the consumer cluster - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the resource. - properties: - clusterScopedIsolation: - description: |- - ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - It can be "Prefixed", "Namespaced", or "None". - - Deprecated: ClusterScopedIsolation is deprecated, use Isolation instead. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: clusterScopedIsolation is immutable - rule: self == oldSelf - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - isolation: - description: Isolation specifies how service objects are isolated between - multiple consumers on the provider side. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: isolation is immutable - rule: self == oldSelf - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting a - single resource by name and namespace. - items: - description: NamedResource selects a specific resource by - name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that contains - jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - x-kubernetes-validations: - - message: permissionClaims are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - required: - - informerScope - - isolation - - resources - type: object - status: - description: status contains reconciliation information for the resource. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-apiserviceexporttemplates.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-apiserviceexporttemplates.kube-bind.io.yaml deleted file mode 100644 index bf94d3258..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-apiserviceexporttemplates.kube-bind.io.yaml +++ /dev/null @@ -1,332 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v260224-1c64e9a.apiserviceexporttemplates.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: APIServiceExportTemplate - listKind: APIServiceExportTemplateList - plural: apiserviceexporttemplates - singular: apiserviceexporttemplate - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.resources[*].group - name: Resources - type: string - - jsonPath: .spec.permissionClaims[*].resource - name: PermissionClaims - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - APIServiceExportTemplate groups multiple CRDs with related resources (permissionClaims) as a Service definition. - It is used by a web UI or CLI to allow users to select a set of resources to export from provider cluster to consumer cluster. - This object is considered a static asset on the provider side and is not expected to change frequently. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the template. - properties: - description: - description: description is an optional description of the template. - type: string - namespaces: - description: |- - Namespaces specifies the namespaces that should be bootstrapped as part of this template. - When objects originate from provider side, consumer does not always know the necessary details - This field allows provider to pre-heat the necessary namespaces on provider side by creating - APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - items: - properties: - name: - description: name is the name of the namespace to create on provider - side. - type: string - required: - - name - type: object - type: array - permissionClaims: - description: permissionClaims defines the permission claims required - by this template. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting a - single resource by name and namespace. - items: - description: NamedResource selects a specific resource by - name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that contains - jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - resources: - description: resources defines the CRDs that are part of this template. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - schemaUpdatePolicy: - default: Never - description: |- - SchemaUpdatePolicy defines how BoundSchemas should be updated. - Never means schemas are immutable after creation. - Always means schemas are updated when the source content changes. - Default: Never - - NOTE: This field is intentionally mutable on the template so that providers - can change the default for future binding requests. Already-created - APIServiceExportRequests use CEL validation (self == oldSelf) to lock in - the policy chosen at binding time. - enum: - - Never - - Always - type: string - scope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Namespaced - - Cluster - description: scope defines the scope of the resources in this template. - type: string - required: - - resources - - scope - type: object - status: - description: status contains reconciliation information for the template. - properties: - conditions: - description: conditions is a list of conditions that apply to the APIServiceExportTemplate. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-apiservicenamespaces.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-apiservicenamespaces.kube-bind.io.yaml deleted file mode 100644 index 4056e25a3..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-apiservicenamespaces.kube-bind.io.yaml +++ /dev/null @@ -1,119 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v250809-5ed76a1.apiservicenamespaces.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceNamespace - listKind: APIServiceNamespaceList - plural: apiservicenamespaces - singular: apiservicenamespace - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-bindableresourcesrequests.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-bindableresourcesrequests.kube-bind.io.yaml deleted file mode 100644 index dbd24b501..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-bindableresourcesrequests.kube-bind.io.yaml +++ /dev/null @@ -1,220 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v260507-3080410e.bindableresourcesrequests.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BindableResourcesRequest - listKind: BindableResourcesRequestList - plural: bindableresourcesrequests - singular: bindableresourcesrequest - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .spec.templateRef.name - name: Template - type: string - - jsonPath: .status.phase - name: Phase - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - BindableResourcesRequest is sent by the consumer to the service provider - to indicate which resources the user wants to bind to. It can be sent via - the HTTP API after authentication, or created directly as a CRD when the - backend is running without the HTTP API/OIDC flow (frontend disabled mode). - - When created as a CRD, a controller will process the request and create the - necessary APIServiceExport and related resources. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the binding request details. - properties: - author: - description: |- - Author is the identifier of the entity that created this binding request. - This is used for audit purposes and to track who initiated the binding. - type: string - clusterIdentity: - description: |- - ClusterIdentity contains information that uniquely identifies the cluster. - This is used when the request is made via the HTTP API after authentication. - properties: - identity: - description: Identity is the unique identifier of the cluster. - type: string - prettyName: - description: |- - PrettyName is a human-readable name for the cluster, used for display - purposes. If not provided, the controller defaults it to the request name. - type: string - type: object - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to an existing secret where the binding response - will be stored. If specified, the controller will update this secret with the - binding response data. If not specified, a new secret will be created with - the name "-binding-response". - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - templateRef: - description: TemplateRef specifies the APIServiceExportTemplate to bind - to. - properties: - name: - description: name is the name of the APIServiceExportTemplate to - bind to. - type: string - required: - - name - type: object - ttlAfterFinished: - description: |- - ttlAfterFinished is the TTL after the request has succeeded or failed - before it is automatically deleted. If not set, the request will not be - automatically deleted. Example values: "1h", "30m", "300s". - type: string - required: - - author - - clusterIdentity - type: object - status: - default: {} - description: status contains reconciliation information for the binding - request. - properties: - completionTime: - description: |- - completionTime is the time when the request finished processing (succeeded or failed). - Used for TTL-based cleanup. - format: date-time - type: string - conditions: - description: conditions contains the current conditions of the binding - request. - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to a secret containing the kubeconfig, used - to be used by the konnector agent. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - namespace: - description: |- - namespace is the namespace assigned to this binding request on the service provider cluster. - This is where the resources for this binding are created and managed. - type: string - phase: - default: Pending - description: phase is the current phase of the binding request. - enum: - - Pending - - Failed - - Succeeded - type: string - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-boundschemas.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-boundschemas.kube-bind.io.yaml deleted file mode 100644 index ea39d01f1..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-boundschemas.kube-bind.io.yaml +++ /dev/null @@ -1,466 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v251106-640871f.boundschemas.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BoundSchema - listKind: BoundSchemaList - plural: boundschemas - shortNames: - - bs - singular: boundschema - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - BoundSchema defines the schema of a bound API resource. It is created on the provider side to track - CRD status on the consumer side by reflecting the CRD spec and status conditions. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: BoundSchemaSpec defines the desired state of the BoundSchema. - properties: - conversion: - description: conversion defines conversion settings for the defined - custom resource. - properties: - strategy: - description: |- - strategy specifies how custom resources are converted between versions. Allowed values are: - - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information - is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. - enum: - - None - - Webhook - type: string - webhook: - description: webhook describes how to call the conversion webhook. - Required when `strategy` is set to `"Webhook"`. - properties: - clientConfig: - description: clientConfig is the instructions for how to call - the webhook if strategy is `Webhook`. - properties: - caBundle: - description: |- - caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. - If unspecified, system trust roots on the apiserver are used. - format: byte - type: string - url: - description: |- - url gives the location of the webhook, in standard URL form - (`scheme://host:port/path`). - - Please note that using `localhost` or `127.0.0.1` as a `host` is - risky unless you take great care to run this webhook on all hosts - which run an apiserver which might need to make calls to this - webhook. Such installs are likely to be non-portable, i.e., not easy - to turn up in a new cluster. - - The scheme must be "https"; the URL must begin with "https://". - - A path is optional, and if present may be any string permissible in - a URL. You may use the path to pass an arbitrary string to the - webhook, for example, a cluster identifier. - - Attempting to use a user or basic auth e.g. "user:password@" is not - allowed. Fragments ("#...") and query parameters ("?...") are not - allowed, either. - format: uri - type: string - type: object - conversionReviewVersions: - description: |- - conversionReviewVersions is an ordered list of preferred `ConversionReview` - versions the Webhook expects. The API server will use the first version in - the list which it supports. If none of the versions specified in this list - are supported by API server, conversion will fail for the custom resource. - If a persisted Webhook configuration specifies allowed versions and does not - include any versions known to the API Server, calls to the webhook will fail. - items: - type: string - type: array - x-kubernetes-list-type: atomic - type: object - type: object - x-kubernetes-validations: - - message: Webhook must be specified if strategy=Webhook - rule: (self.strategy == 'None' && !has(self.webhook)) || (self.strategy - == 'Webhook' && has(self.webhook)) - group: - description: "group is the API group of the defined custom resource. - Empty string means the\ncore API group. \tThe resources are served - under `/apis//...` or `/api` for the core group." - type: string - informerScope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Cluster - - Namespaced - description: |- - InformerScope indicates whether the informer for defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - type: string - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It must - be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIResourceVersion describes one API version of a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should serve - a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - status: - description: BoundSchemaStatus defines the observed state of the BoundSchema. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It must - be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: Conditions represent the latest available observations - of the object's state. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - instantiations: - description: Instantiations tracks the number of instances of the resource - on the consumer side. - type: integer - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-clusterbindings.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-clusterbindings.kube-bind.io.yaml deleted file mode 100644 index 715a48b58..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-clusterbindings.kube-bind.io.yaml +++ /dev/null @@ -1,342 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v260226-fc494c6a.clusterbindings.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: ClusterBinding - listKind: ClusterBindingList - plural: clusterbindings - singular: clusterbinding - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service provider cluster - and is a singleton named "cluster". - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains the - kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. Must be "kubeconfig". - enum: - - kubeconfig - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service - provider cluster and is a singleton named "cluster" per namespace. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains the - kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - consumerSecretRef: - description: |- - consumerSecretRef is the reference to the secret in the consumer cluster - that contains the kubeconfig for connecting to the service provider. - properties: - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - name - - namespace - type: object - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-clusters.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-clusters.kube-bind.io.yaml deleted file mode 100644 index a48f14fd8..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-clusters.kube-bind.io.yaml +++ /dev/null @@ -1,102 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v251215-7d342944.clusters.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Cluster - listKind: ClusterList - plural: clusters - singular: cluster - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - name: v1alpha2 - schema: - description: Cluster represents a cluster, managed by kube-bind. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/apiresourceschema-collections.kube-bind.io.yaml b/contrib/kcp/deploy/resources/apiresourceschema-collections.kube-bind.io.yaml deleted file mode 100644 index 870463fba..000000000 --- a/contrib/kcp/deploy/resources/apiresourceschema-collections.kube-bind.io.yaml +++ /dev/null @@ -1,128 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v251106-640871f.collections.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Collection - listKind: CollectionList - plural: collections - singular: collection - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.description - name: Description - type: string - - jsonPath: .spec.templates[*].name - name: Templates - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - description: |- - Collection groups multiple APIServiceExportTemplates into a logical group. This functions as a grouping mechanism - in UIs or CLIs to allow users to select a set of resources to export from provider cluster to consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the collection. - properties: - description: - description: description is a human readable description of this collection. - type: string - templates: - description: templates is a list of template references that are part - of this collection. - items: - description: APIServiceExportTemplateReference references an APIServiceExportTemplate - by name. - properties: - name: - description: name is the name of the template. - type: string - required: - - name - type: object - minItems: 1 - type: array - required: - - templates - type: object - status: - description: status contains reconciliation information for the collection. - properties: - conditions: - description: conditions is a list of conditions that apply to the Collection. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/contrib/kcp/deploy/resources/bootstrap.go b/contrib/kcp/deploy/resources/bootstrap.go deleted file mode 100644 index a19da2555..000000000 --- a/contrib/kcp/deploy/resources/bootstrap.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 resources - -import ( - "context" - "embed" - - confighelpers "github.com/kcp-dev/kcp/config/helpers" - kcpclientcluster "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" -) - -//go:embed *.yaml -var kubeFS embed.FS - -// Bootstrap creates resources in this package by continuously retrying the list. -// This is blocking, i.e. it only returns (with error) when the context is closed or with nil when -// the bootstrapping is successfully completed. -func Bootstrap( - ctx context.Context, - kcpClient kcpclientcluster.ClusterInterface, - discoveryClient discovery.DiscoveryInterface, - dynamicClient dynamic.Interface, - crdClient apiextensionsv1.CustomResourceDefinitionInterface, - batteriesIncluded sets.Set[string], -) error { - // create resources in core cluster - return confighelpers.Bootstrap(ctx, discoveryClient, dynamicClient, batteriesIncluded, kubeFS, confighelpers.ReplaceOption()) -} diff --git a/contrib/kcp/go.mod b/contrib/kcp/go.mod deleted file mode 100644 index 094034e92..000000000 --- a/contrib/kcp/go.mod +++ /dev/null @@ -1,200 +0,0 @@ -module github.com/kube-bind/kube-bind/contrib/kcp - -go 1.26.9 - -replace ( - github.com/kube-bind/kube-bind => ../../ - github.com/kube-bind/kube-bind/cli => ../../cli - github.com/kube-bind/kube-bind/sdk => ../../sdk - github.com/kube-bind/kube-bind/web => ../../web -) - -require ( - github.com/google/uuid v1.6.0 - github.com/kcp-dev/client-go v0.31.0 - github.com/kcp-dev/kcp v0.31.4 - github.com/kcp-dev/logicalcluster/v3 v3.0.5 - github.com/kcp-dev/sdk v0.31.0 - github.com/kube-bind/kube-bind v0.7.1 - github.com/kube-bind/kube-bind/cli v0.7.1 - github.com/kube-bind/kube-bind/sdk v0.7.1 - github.com/spf13/pflag v1.0.10 - github.com/stretchr/testify v1.11.1 - k8s.io/apiextensions-apiserver v0.36.0 - k8s.io/apimachinery v0.36.0 - k8s.io/apiserver v0.36.0 - k8s.io/cli-runtime v0.36.0 - k8s.io/client-go v1.5.2 - k8s.io/component-base v0.36.0 - k8s.io/klog/v2 v2.140.0 -) - -require ( - cel.dev/expr v0.25.2 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/NYTimes/gziphandler v1.1.1 // indirect - github.com/PuerkitoBio/goquery v1.12.0 // indirect - github.com/andybalholm/cascadia v1.3.3 // indirect - github.com/antlr4-go/antlr/v4 v4.13.1 // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/blang/semver/v4 v4.0.0 // indirect - github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/coreos/go-oidc/v3 v3.18.0 // indirect - github.com/coreos/go-semver v0.3.1 // indirect - github.com/coreos/go-systemd/v22 v22.7.0 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/dexidp/dex/api/v2 v2.4.0 // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-errors/errors v1.5.1 // indirect - github.com/go-jose/go-jose/v3 v3.0.5 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect - github.com/go-logr/logr v1.4.4 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-logr/zapr v1.3.0 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.5 // indirect - github.com/go-openapi/swag v0.26.0 // indirect - github.com/go-openapi/swag/cmdutils v0.26.0 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.26.0 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang-jwt/jwt/v5 v5.3.1 // indirect - github.com/golang/protobuf v1.5.4 // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/cel-go v0.29.0 // indirect - github.com/google/gnostic-models v0.7.1 // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/gorilla/mux v1.8.1 // indirect - github.com/gorilla/securecookie v1.1.2 // indirect - github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect - github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect - github.com/headzoo/surf v1.0.1 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/kcp-dev/apimachinery/v2 v2.31.0 // indirect - github.com/kcp-dev/multicluster-provider v0.6.0 // indirect - github.com/kube-bind/kube-bind/web v0.0.0-20260424090035-f3f89e73d6ee // indirect - github.com/kylelemons/godebug v1.1.0 // indirect - github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/martinlindhe/base36 v1.1.1 // indirect - github.com/moby/term v0.5.2 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect - github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/onsi/gomega v1.39.1 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.20.1 // indirect - github.com/redis/go-redis/v9 v9.18.0 // indirect - github.com/spf13/cobra v1.10.2 // indirect - github.com/tidwall/gjson v1.18.0 // indirect - github.com/tidwall/match v1.2.0 // indirect - github.com/tidwall/pretty v1.2.1 // indirect - github.com/vmihailenco/msgpack/v4 v4.3.13 // indirect - github.com/vmihailenco/tagparser v0.1.2 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xlab/treeprint v1.2.0 // indirect - github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a // indirect - go.etcd.io/etcd/api/v3 v3.6.10 // indirect - go.etcd.io/etcd/client/pkg/v3 v3.6.10 // indirect - go.etcd.io/etcd/client/v3 v3.6.10 // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect - go.opentelemetry.io/proto/otlp v1.11.0 // indirect - go.uber.org/atomic v1.11.0 // indirect - go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.1 // indirect - go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.23.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/time v0.15.0 // indirect - gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect - google.golang.org/appengine v1.6.8 // 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 - google.golang.org/grpc v1.83.2 // indirect - google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect - gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect - gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - k8s.io/api v0.36.0 // indirect - k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f // indirect - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 // indirect - sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 // indirect - sigs.k8s.io/controller-runtime v0.23.3 // indirect - sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect - sigs.k8s.io/kustomize/api v0.21.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect - sigs.k8s.io/multicluster-runtime v0.23.3 // indirect - sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.0 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect -) - -replace ( - k8s.io/api => github.com/kcp-dev/kubernetes/staging/src/k8s.io/api v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/apiextensions-apiserver => github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/apimachinery => github.com/kcp-dev/kubernetes/staging/src/k8s.io/apimachinery v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/apiserver => github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiserver v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/cli-runtime => github.com/kcp-dev/kubernetes/staging/src/k8s.io/cli-runtime v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/client-go => github.com/kcp-dev/kubernetes/staging/src/k8s.io/client-go v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/cloud-provider => github.com/kcp-dev/kubernetes/staging/src/k8s.io/cloud-provider v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/cluster-bootstrap => github.com/kcp-dev/kubernetes/staging/src/k8s.io/cluster-bootstrap v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/code-generator => github.com/kcp-dev/kubernetes/staging/src/k8s.io/code-generator v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/component-base => github.com/kcp-dev/kubernetes/staging/src/k8s.io/component-base v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/component-helpers => github.com/kcp-dev/kubernetes/staging/src/k8s.io/component-helpers v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/controller-manager => github.com/kcp-dev/kubernetes/staging/src/k8s.io/controller-manager v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/cri-api => github.com/kcp-dev/kubernetes/staging/src/k8s.io/cri-api v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/cri-client => github.com/kcp-dev/kubernetes/staging/src/k8s.io/cri-client v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/csi-translation-lib => github.com/kcp-dev/kubernetes/staging/src/k8s.io/csi-translation-lib v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/dynamic-resource-allocation => github.com/kcp-dev/kubernetes/staging/src/k8s.io/dynamic-resource-allocation v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/endpointslice => github.com/kcp-dev/kubernetes/staging/src/k8s.io/endpointslice v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/externaljwt => github.com/kcp-dev/kubernetes/staging/src/k8s.io/externaljwt v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kms => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kms v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kube-aggregator => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kube-aggregator v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kube-controller-manager => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kube-controller-manager v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kube-proxy => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kube-proxy v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kube-scheduler => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kube-scheduler v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kubectl => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kubectl v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kubelet => github.com/kcp-dev/kubernetes/staging/src/k8s.io/kubelet v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/kubernetes => github.com/kcp-dev/kubernetes v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/metrics => github.com/kcp-dev/kubernetes/staging/src/k8s.io/metrics v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/mount-utils => github.com/kcp-dev/kubernetes/staging/src/k8s.io/mount-utils v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/pod-security-admission => github.com/kcp-dev/kubernetes/staging/src/k8s.io/pod-security-admission v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/sample-apiserver => github.com/kcp-dev/kubernetes/staging/src/k8s.io/sample-apiserver v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/sample-cli-plugin => github.com/kcp-dev/kubernetes/staging/src/k8s.io/sample-cli-plugin v0.0.0-20260401063412-ba4f7d493d5b - k8s.io/sample-controller => github.com/kcp-dev/kubernetes/staging/src/k8s.io/sample-controller v0.0.0-20260401063412-ba4f7d493d5b -) diff --git a/contrib/kcp/go.sum b/contrib/kcp/go.sum deleted file mode 100644 index 3c3469fb4..000000000 --- a/contrib/kcp/go.sum +++ /dev/null @@ -1,499 +0,0 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= -github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= -github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= -github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo= -github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ= -github.com/alicebob/miniredis/v2 v2.37.0 h1:RheObYW32G1aiJIj81XVt78ZHJpHonHLHW7OLIshq68= -github.com/alicebob/miniredis/v2 v2.37.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= -github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= -github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= -github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= -github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= -github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= -github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= -github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= -github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= -github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= -github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= -github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dexidp/dex/api/v2 v2.4.0 h1:gNba7n6BKVp8X4Jp24cxYn5rIIGhM6kDOXcZoL6tr9A= -github.com/dexidp/dex/api/v2 v2.4.0/go.mod h1:/p550ADvFFh7K95VmhUD+jgm15VdaNnab9td8DHOpyI= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= -github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= -github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= -github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= -github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ= -github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= -github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= -github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= -github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= -github.com/go-openapi/swag v0.26.0 h1:GVDXCmfvhfu1BxiHo8/FA+BbKmhecHnG3varjON5/RI= -github.com/go-openapi/swag v0.26.0/go.mod h1:82g3193sZJRbocs7bNCqGfIgq8pkuwVwCfhKIRlEQF0= -github.com/go-openapi/swag/cmdutils v0.26.0 h1:iowihOcvq7y4egO8cOq0dmfohz6wfeQ63U1EnuhO2TU= -github.com/go-openapi/swag/cmdutils v0.26.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.26.0 h1:CmZp+ZT7HrmFwrC3GdGsXBq2+42T1bjKBapcqVpIs3c= -github.com/go-openapi/swag/netutils v0.26.0/go.mod h1:5iK+Ok3ZohWWex1C50BFTPexi03UaPwjW4Oj8kgrpwo= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= -github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= -github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= -github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= -github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/cel-go v0.29.0 h1:fEG+Ja3YRwNOqnQxTyJwoByAUAvTuxUGiro/jhrm4F4= -github.com/google/cel-go v0.29.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= -github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= -github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= -github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= -github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= -github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= -github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 h1:QGLs/O40yoNK9vmy4rhUGBVyMf1lISBGtXRpsu/Qu/o= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.mod h1:hM2alZsMUni80N33RBe6J0e423LB+odMj7d3EMP9l20= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/headzoo/surf v1.0.1 h1:wk3+LT8gjnCxEwfBJl6MhaNg154En5KjgmgzAG9uMS0= -github.com/headzoo/surf v1.0.1/go.mod h1:/bct0m/iMNEqpn520y01yoaWxsAEigGFPnvyR1ewR5M= -github.com/headzoo/ut v0.0.0-20181013193318-a13b5a7a02ca h1:utFgFwgxaqx5OthzE3DSGrtOq7rox5r2sxZ2wbfTuK0= -github.com/headzoo/ut v0.0.0-20181013193318-a13b5a7a02ca/go.mod h1:8926sG02TCOX4RFRzIMFIzRw4xuc/TwO2gtN7teMJZ4= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= -github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kcp-dev/apimachinery/v2 v2.31.0 h1:N/ALc/v8ZXMxC9a8ovXeQaiFwx8COrqG+FOqD1zl2fY= -github.com/kcp-dev/apimachinery/v2 v2.31.0/go.mod h1:ta+d3xQkLYWBEEg8ICed+PekW3MckEYqXG4amq6Uk9Y= -github.com/kcp-dev/client-go v0.31.0 h1:11G7kDeNsEYANNLsE5X7OTalDtGhXdTro5gEbxMmXXE= -github.com/kcp-dev/client-go v0.31.0/go.mod h1:easrOk06OcW/rKAM+dX3wUYgy71lugySvOm7QSvlf5E= -github.com/kcp-dev/kcp v0.31.4 h1:OIy9ULzc7VBnieoAWfPcXpH/jRQwSdaYGQXQA6atyUQ= -github.com/kcp-dev/kcp v0.31.4/go.mod h1:V/JPoevUr3ihiXEAmJ6JG1MdyeNzfHRthffxywMWYfU= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/api v0.0.0-20260401063412-ba4f7d493d5b h1:a9iJZxtR6d7o0/FYeoi1J61fkMu7SIKz/BDLQCIuX1s= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/api v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:ORtWYHjWzOroksSDirox8pog9u4/vB7vV2cwgsvrAMc= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20260401063412-ba4f7d493d5b h1:4wKmD8PVLfpvEPgvxHr6ZYf3WUcmht5z4fOWBq/BYJ8= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:TyU0Xqm9I1qNqKZPUz8o19VVjP/Fv2svhjIG5rdqiPw= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apimachinery v0.0.0-20260401063412-ba4f7d493d5b h1:8gujlbiNrVTvqsmZNF4qBvCBg4JdBxVk3keh6bN6ZI0= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apimachinery v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiserver v0.0.0-20260401063412-ba4f7d493d5b h1:WgrHh89kb55JvZ+14d9sb8b7rS+9tKnknSgK85JBEAw= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiserver v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:WOHgQh0eI+6DMRwQB2M4CYsmwMHgd04v7hhxi5YAw58= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/cli-runtime v0.0.0-20260401063412-ba4f7d493d5b h1:6rnOUrMSC7NiAF9G7AouzGnfucNxQunPv6kFpYERDU4= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/cli-runtime v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:ZJK2sHi3CbLMQnFvFZVIwz9njxOq89xtC5hTRaInXbk= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/client-go v0.0.0-20260401063412-ba4f7d493d5b h1:Lk1vyIrA5d276OzDiRZ6hkLPH6k3JrXkGAunB/06Vks= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/client-go v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:nC64c6nHuBAQMICDgY3OfK4PpcpQCparuBsJcEB7tWc= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/component-base v0.0.0-20260401063412-ba4f7d493d5b h1:WRodjaagbeY3Tjba7gaPngMb4kuTLh53ukmvJozbLHI= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/component-base v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:HOrpwrIREPdoQppvSAywMPdNrMvjw9kd0ZBYLUMGI+0= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/kms v0.0.0-20260401063412-ba4f7d493d5b h1:auSPURX6hZV849ddSANTdWed59ECWCmQ3O6+Afx37vY= -github.com/kcp-dev/kubernetes/staging/src/k8s.io/kms v0.0.0-20260401063412-ba4f7d493d5b/go.mod h1:VT+4ekZAdrZDMgShK37vvlyHUVhwI9t/9tvh0AyCWmQ= -github.com/kcp-dev/logicalcluster/v3 v3.0.5 h1:JbYakokb+5Uinz09oTXomSUJVQsqfxEvU4RyHUYxHOU= -github.com/kcp-dev/logicalcluster/v3 v3.0.5/go.mod h1:EWBUBxdr49fUB1cLMO4nOdBWmYifLbP1LfoL20KkXYY= -github.com/kcp-dev/multicluster-provider v0.6.0 h1:t7Wac92T4dde9DMMVqA/VPhNhrqkgZ4/Cyij0yh0M5s= -github.com/kcp-dev/multicluster-provider v0.6.0/go.mod h1:pJvWD+5dP+aMsntlu7sBG7oOmYrWfuWKqDQ8WBHur34= -github.com/kcp-dev/sdk v0.31.0 h1:fLqgY6MHVmmBcttqR/V3h2Dnv7xmab84FTKTwV08+Bo= -github.com/kcp-dev/sdk v0.31.0/go.mod h1:GpNW9wPULY9+UuLVAaB5z/sJ8r0Jo/l0Jgy4BKnIJTE= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= -github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= -github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/martinlindhe/base36 v1.1.1 h1:1F1MZ5MGghBXDZ2KJ3QfxmiydlWOGB8HCEtkap5NkVg= -github.com/martinlindhe/base36 v1.1.1/go.mod h1:vMS8PaZ5e/jV9LwFKlm0YLnXl/hpOihiBxKkIoc3g08= -github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= -github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/onsi/ginkgo/v2 v2.28.0 h1:Rrf+lVLmtlBIKv6KrIGJCjyY8N36vDVcutbGJkyqjJc= -github.com/onsi/ginkgo/v2 v2.28.0/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= -github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= -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.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= -github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= -github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= -github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= -github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= -github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= -github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= -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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= -github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM= -github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= -github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7otjonDflCTK0BCfls4SPy3NcCVb5dqqmbRknE= -github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= -github.com/vmihailenco/msgpack/v4 v4.3.13 h1:A2wsiTbvp63ilDaWmsk2wjx6xZdxQOvpiNlKBGKKXKI= -github.com/vmihailenco/msgpack/v4 v4.3.13/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= -github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbd1qPqc= -github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= -github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= -github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= -github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a h1:rPK2vAgG4T5k6ay5v+DVU7j2xjW/S3LWbzKpOGukdeE= -github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a/go.mod h1:1S3+yz/sau3wSTpmFOwg+JmOudpq6KA6vTuvmP5VReM= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= -github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= -github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= -go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= -go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= -go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY= -go.etcd.io/etcd/api/v3 v3.6.10/go.mod h1:pdV4VeFmvhdNjB4LWRkC8ReLyRBAxUOze3GarMhE2sk= -go.etcd.io/etcd/client/pkg/v3 v3.6.10 h1:tBT7podcPhuVbCVkAEzx8bC5I+aqxfLwBN8/As1arrA= -go.etcd.io/etcd/client/pkg/v3 v3.6.10/go.mod h1:WEy3PpwbbEBVRdh1NVJYsuUe/8eyI21PNJRazeD8z/Y= -go.etcd.io/etcd/client/v3 v3.6.10 h1:J598zJ+C/ZPvImypmq5waj84+bovePrlZERHklf34y0= -go.etcd.io/etcd/client/v3 v3.6.10/go.mod h1:iHhUDUcEwaKs1YFq3MgmI9U4zhTVasp/vgdVbFf1RS8= -go.etcd.io/etcd/pkg/v3 v3.6.5 h1:byxWB4AqIKI4SBmquZUG1WGtvMfMaorXFoCcFbVeoxM= -go.etcd.io/etcd/pkg/v3 v3.6.5/go.mod h1:uqrXrzmMIJDEy5j00bCqhVLzR5jEJIwDp5wTlLwPGOU= -go.etcd.io/etcd/server/v3 v3.6.5 h1:4RbUb1Bd4y1WkBHmuF+cZII83JNQMuNXzyjwigQ06y0= -go.etcd.io/etcd/server/v3 v3.6.5/go.mod h1:PLuhyVXz8WWRhzXDsl3A3zv/+aK9e4A9lpQkqawIaH0= -go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ= -go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo= -go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= -go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.3.1-0.20251210191316-2b7fd8a0d244 h1:OdZ8e4E9yDUGiis9x2ta/Ec5yhMAKT6ZivRvakyxC7E= -go.uber.org/goleak v1.3.1-0.20251210191316-2b7fd8a0d244/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= -go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= -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/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= -golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -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.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= -golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= -golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= -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/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/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.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/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.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.28.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/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= -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.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= -golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= -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/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -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.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -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.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= -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/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/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= -gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= -gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= -gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= -gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= -gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= -k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f h1:4Qiq0YAoQATdgmHALJWz9rJ4fj20pB3xebpB4CFNhYM= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 h1:hSfpvjjTQXQY2Fol2CS0QHMNs/WI1MOSGzCm1KhM5ec= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= -sigs.k8s.io/controller-runtime v0.23.3 h1:VjB/vhoPoA9l1kEKZHBMnQF33tdCLQKJtydy4iqwZ80= -sigs.k8s.io/controller-runtime v0.23.3/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= -sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= -sigs.k8s.io/kustomize/kyaml v0.21.1 h1:IVlbmhC076nf6foyL6Taw4BkrLuEsXUXNpsE+ScX7fI= -sigs.k8s.io/kustomize/kyaml v0.21.1/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= -sigs.k8s.io/multicluster-runtime v0.23.3 h1:vrzlXRzHTDsjspUAfoW2rCtr0agoI4q20p9x4Fz4png= -sigs.k8s.io/multicluster-runtime v0.23.3/go.mod h1:r/UA4GHgFoXCcR4tcvlZz7SiLx3l1kJKDuBAhILNIHs= -sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= -sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0 h1:qmp2e3ZfFi1/jJbDGpD4mt3wyp6PE1NfKHCYLqgNQJo= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= -sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= -sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/contrib/kcp/hack/update-kcp-codegen.sh b/contrib/kcp/hack/update-kcp-codegen.sh deleted file mode 100755 index 964e19111..000000000 --- a/contrib/kcp/hack/update-kcp-codegen.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -cd "$(dirname "$0")/../../.." - -APIGEN="$(UGET_PRINT_PATH=absolute make -C contrib/kcp --no-print-directory install-apigen)" - -# Generate kcp API resources from CRDs -"$APIGEN" --input-dir deploy/crd --output-dir contrib/kcp/deploy/resources diff --git a/contrib/kcp/test/e2e/backend.go b/contrib/kcp/test/e2e/backend.go deleted file mode 100644 index 8306651ef..000000000 --- a/contrib/kcp/test/e2e/backend.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 e2e - -import ( - "fmt" - "net/http" - "strings" - "testing" - "time" - - "github.com/kcp-dev/logicalcluster/v3" - kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" - kcptestinghelpers "github.com/kcp-dev/sdk/testing/helpers" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -func bootstrapBackend(t *testing.T, rest *rest.Config, scope kubebindv1alpha2.InformerScope, kbindPath logicalcluster.Path) string { - t.Helper() - t.Log("Bootstrapping backend") - - rest.Host = strings.Split(rest.Host, "/clusters/")[0] - - client, err := kcpclientset.NewForConfig(rest) - require.NoError(t, err) - - exportUrl := "" - kcptestinghelpers.Eventually(t, func() (bool, string) { - exportES, err := client.Cluster(kbindPath). - ApisV1alpha1(). - APIExportEndpointSlices(). - Get(t.Context(), "kube-bind.io", metav1.GetOptions{}) - if err != nil { - return false, fmt.Sprintf("Error getting APIExportEndpointSlice: %v", err) - } - if len(exportES.Status.APIExportEndpoints) == 0 { - return false, "APIExportEndpoints is empty" - } - exportUrl = exportES.Status.APIExportEndpoints[0].URL - return true, "" - }, wait.ForeverTestTimeout, time.Millisecond*100) - require.NotEmpty(t, exportUrl, "APIExportEndpointSlice URL is empty") - - _, backendKubeconfig := wsConfig(t, rest, kbindPath) - - t.Log("Starting kube-bind backend for kcp") - addr, _ := framework.StartBackend(t, - "--kubeconfig="+backendKubeconfig, - "--multicluster-runtime-provider=kcp", - "--apiexport-endpoint-slice-name=kube-bind.io", - "--pretty-name=BigCorp.com", - "--namespace-prefix=kube-bind-", - "--schema-source=apiresourceschemas", - "--consumer-scope="+string(scope), - ) - - t.Log("Wait for backend to be ready") - req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+addr.String()+"/healthz", nil) - require.NoError(t, err) - kcptestinghelpers.Eventually(t, func() (bool, string) { - resp, err := http.DefaultClient.Do(req) - if err != nil { - return false, "" - } - defer resp.Body.Close() - return resp.StatusCode == http.StatusOK, "" - }, wait.ForeverTestTimeout, time.Millisecond*100) - t.Log("Backend is ready") - - return addr.String() -} diff --git a/contrib/kcp/test/e2e/binding.go b/contrib/kcp/test/e2e/binding.go deleted file mode 100644 index 8034081c8..000000000 --- a/contrib/kcp/test/e2e/binding.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 e2e - -import ( - "strings" - "testing" - "time" - - "github.com/google/uuid" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/rest" - - bindapiservice "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/plugin" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -func performBinding( - t *testing.T, - consumerCfg *rest.Config, - templateRef string, - crdName string, - kubeBindConfig string, -) { - // Implementation of the binding process using the provided parameters - // This is a placeholder for the actual binding logic - t.Logf("Performing binding with templateRef: %s", templateRef) - - // 1. Get APIServiceExportRequest from provider - c := framework.GetKubeBindRestClient(t, kubeBindConfig) - - identity, err := uuid.NewUUID() - require.NoError(t, err) - - bindResponse, err := c.Bind(t.Context(), &kubebindv1alpha2.BindableResourcesRequest{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-binding", - }, - Spec: kubebindv1alpha2.BindableResourcesRequestSpec{ - TemplateRef: kubebindv1alpha2.APIServiceExportTemplateRef{ - Name: templateRef, - }, - ClusterIdentity: kubebindv1alpha2.ClusterIdentity{ - Identity: identity.String(), - }, - }, - }) - require.NoError(t, err) - require.NotNil(t, bindResponse) - - iostreams, _, _, _ := genericclioptions.NewTestIOStreams() - binderOpts := &bindapiservice.BinderOptions{ - IOStreams: iostreams, - SkipKonnector: true, - } - - binder := bindapiservice.NewBinder(consumerCfg, binderOpts) - result, err := binder.BindFromResponse(t.Context(), bindResponse) - require.NoError(t, err) - require.Len(t, result, 1) - - t.Logf("Waiting for %s CRD to be created on consumer side", templateRef) - crdClient := framework.ApiextensionsClient(t, consumerCfg).ApiextensionsV1().CustomResourceDefinitions() - require.Eventually(t, func() bool { - crds, err := crdClient.List(t.Context(), metav1.ListOptions{}) - if err != nil { - return false - } - for _, crd := range crds.Items { - if strings.Contains(crd.Name, crdName) { - return true - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for %s CRD to be created on consumer side", crdName) -} diff --git a/contrib/kcp/test/e2e/kcp.go b/contrib/kcp/test/e2e/kcp.go deleted file mode 100644 index 3fa1dc2d5..000000000 --- a/contrib/kcp/test/e2e/kcp.go +++ /dev/null @@ -1,214 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 e2e - -import ( - "fmt" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/kcp-dev/logicalcluster/v3" - kcpapisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" - kcptenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1" - kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" - kcptestinghelpers "github.com/kcp-dev/sdk/testing/helpers" - "github.com/spf13/pflag" - "github.com/stretchr/testify/require" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - - "github.com/kube-bind/kube-bind/contrib/kcp/bootstrap" - "github.com/kube-bind/kube-bind/contrib/kcp/bootstrap/options" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -// waitForClusterEngaged blocks until the kcp multicluster provider has engaged -// the workspace described by cfg. The provider creates a kube-bind.io Cluster -// named "default" in every workspace it engages, so we poll for that object. -func waitForClusterEngaged(t testing.TB, cfg *rest.Config) { - t.Helper() - - gvr := schema.GroupVersionResource{ - Group: kubebindv1alpha2.SchemeGroupVersion.Group, - Version: kubebindv1alpha2.SchemeGroupVersion.Version, - Resource: "clusters", - } - - client := framework.DynamicClient(t, cfg).Resource(gvr) - - kcptestinghelpers.Eventually(t, func() (bool, string) { - _, err := client.Get(t.Context(), kubebindv1alpha2.DefaultClusterName, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - return false, "kube-bind.io Cluster \"default\" not created yet" - } - return false, fmt.Sprintf("error getting kube-bind.io Cluster: %v", err) - } - return true, "" - }, wait.ForeverTestTimeout, time.Millisecond*100) -} - -func wsConfig(t testing.TB, rest *rest.Config, workspace logicalcluster.Path) (*rest.Config, string) { - cfg := rest - cfg.Host += "/clusters/" + workspace.String() - - kubeconfig := framework.WriteKubeconfig(t, - framework.RestToKubeconfig(cfg, "default"), - workspace.Base()+".kubeconfig", - ) - - return cfg, kubeconfig -} - -func generateApiBinding(t testing.TB, path logicalcluster.Path, name, exportName string, acceptPermissionClaims ...string) *kcpapisv1alpha2.APIBinding { - t.Helper() - - apiBinding := &kcpapisv1alpha2.APIBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Spec: kcpapisv1alpha2.APIBindingSpec{ - Reference: kcpapisv1alpha2.BindingReference{ - Export: &kcpapisv1alpha2.ExportBindingReference{ - Path: path.String(), - Name: exportName, - }, - }, - }, - } - - for _, claim := range acceptPermissionClaims { - split := strings.SplitN(claim, ".", 2) - require.Len(t, split, 2, "invalid permission claim: %s, must be in the form .", claim) - - resource, group := split[0], split[1] - require.NotEmpty(t, group, "invalid permission claim: %s, group cannot be empty", claim) - require.NotEmpty(t, resource, "invalid permission claim: %s, resource cannot be empty", claim) - - if group == "core" { - group = "" - } - - apiBinding.Spec.PermissionClaims = append( - apiBinding.Spec.PermissionClaims, - kcpapisv1alpha2.AcceptablePermissionClaim{ - State: kcpapisv1alpha2.ClaimAccepted, - ScopedPermissionClaim: kcpapisv1alpha2.ScopedPermissionClaim{ - Selector: kcpapisv1alpha2.PermissionClaimSelector{ - MatchAll: true, - }, - PermissionClaim: kcpapisv1alpha2.PermissionClaim{ - GroupResource: kcpapisv1alpha2.GroupResource{ - Group: group, - Resource: resource, - }, - Verbs: []string{"*"}, - }, - }, - }, - ) - } - - return apiBinding -} - -func createApiBinding(t testing.TB, client *kcpclientset.ClusterClientset, path logicalcluster.Path, apiBinding *kcpapisv1alpha2.APIBinding) *kcpapisv1alpha2.APIBinding { - t.Helper() - - _, err := client.Cluster(path). - ApisV1alpha2(). - APIBindings(). - Create(t.Context(), apiBinding, metav1.CreateOptions{}) - require.NoError(t, err, "Error creating APIBinding") - - var inCluster *kcpapisv1alpha2.APIBinding - kcptestinghelpers.Eventually(t, func() (bool, string) { - var err error - inCluster, err = client. - Cluster(path). - ApisV1alpha2(). - APIBindings(). - Get(t.Context(), apiBinding.Name, metav1.GetOptions{}) - if err != nil { - return false, fmt.Sprintf("Error getting APIBinding: %v", err) - } - return inCluster.Status.Phase == kcpapisv1alpha2.APIBindingPhaseBound, fmt.Sprintf("APIBinding not ready: %#v", inCluster.Status) - }, wait.ForeverTestTimeout, time.Millisecond*100) - return inCluster -} - -// bootstrapKCP bootstraps kcp for a test. It creates a per-test root workspace -// (root:) with a kbind workspace beneath it (root::kbind) and installs -// the kube-bind APIs there. It returns a rest.Config pointing at the per-test root -// workspace (so consumer/provider workspaces can be created as siblings of kbind) -// and the path of the kbind workspace. -func bootstrapKCP(t testing.TB, rest *rest.Config) (*rest.Config, logicalcluster.Path) { - t.Helper() - t.Log("Bootstrapping kcp") - - wsName := strings.ToLower(t.Name()) - kbindLeafName := "kbind" - rootWorkspace := fmt.Sprintf("root:%s", wsName) - kbindWorkspace := fmt.Sprintf("%s:%s", rootWorkspace, kbindLeafName) - - // The provided rest.Config should already point to a running kcp server. - // It should already have /clusters/root in the path if read from kubeconfig. - // Just ensure we have the right base URL for bootstrap. - cfg := *rest - adminApiCfg := framework.RestToKubeconfig(&cfg, "default") - - // create the two workspaces we want our tests to run in - testRootCfg, _ := framework.NewWorkspace(t, rest, func(ws *kcptenancyv1alpha1.Workspace) { - ws.Name = wsName - ws.GenerateName = "" - }) - - framework.NewWorkspace(t, testRootCfg, func(ws *kcptenancyv1alpha1.Workspace) { - ws.Name = kbindLeafName - ws.GenerateName = "" - }) - - adminKubeconfig := framework.WriteKubeconfigToPath(t, adminApiCfg, filepath.Join(framework.WorkDir(t), "admin.kubeconfig")) - - fs := pflag.NewFlagSet("kcp-bootstrap", pflag.ContinueOnError) - options := options.NewOptions() - options.AddFlags(fs) - - options.KCPKubeConfig = adminKubeconfig - options.RootWorkspace = rootWorkspace - options.KBindWorkspace = kbindWorkspace - - completed, err := options.Complete() - require.NoError(t, err) - - config, err := bootstrap.NewConfig(completed) - require.NoError(t, err) - - bootstrapper, err := bootstrap.NewServer(t.Context(), config) - require.NoError(t, err) - - err = bootstrapper.Start(t.Context()) - require.NoError(t, err) - - return testRootCfg, logicalcluster.NewPath(kbindWorkspace) -} diff --git a/contrib/kcp/test/e2e/kcp_3tier_test.go b/contrib/kcp/test/e2e/kcp_3tier_test.go deleted file mode 100644 index fbead67a5..000000000 --- a/contrib/kcp/test/e2e/kcp_3tier_test.go +++ /dev/null @@ -1,354 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 e2e - -import ( - "fmt" - "path" - "strings" - "testing" - "time" - - kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" - kcptestinghelpers "github.com/kcp-dev/sdk/testing/helpers" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/rest" - - kcpboostrapdeploy "github.com/kube-bind/kube-bind/contrib/kcp/deploy" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -// TestKCP3TierClusterScope tests the 3-tier kcp flow with cluster-scoped resources. -func TestKCP3TierClusterScope(t *testing.T) { - t.Parallel() - testKcp3TierIntegration(t, "3cc", kubebindv1alpha2.ClusterScope) -} - -// TestKCP3TierNamespacedScope tests the 3-tier kcp flow with namespaced resources. -func TestKCP3TierNamespacedScope(t *testing.T) { - t.Parallel() - testKcp3TierIntegration(t, "3nc", kubebindv1alpha2.NamespacedScope) -} - -// testKcp3TierIntegration tests the 3-tier kcp flow: -// -// :root:provider — owns the APIResourceSchema + APIExport (source of truth) -// | -// | (APIBinding: :root:backend binds from :root:provider) -// v -// :root:backend — binds resources from provider; apibindingtemplate controller -// auto-creates APIServiceExportTemplates; apiresourceschema -// controller copies schemas with kube-bind.io/exported=true label -// | -// | (kube-bind serves the binding API) -// v -// consumer — binds resources via kube-bind -func testKcp3TierIntegration(t *testing.T, name string, scope kubebindv1alpha2.InformerScope) { - t.Helper() - t.Logf("Testing 3-tier kcp integration with informer scope %s", scope) - - // kcp bootstrap (creates :root:kube-bind workspace with APIExport etc.) - // Note: no StartDex needed — the backend uses embedded OIDC (mockoidc) which auto-approves. - testRootCfg, kbindWsPath := bootstrapKCP(t, framework.ClientConfig(t)) - testRootPath, _ := kbindWsPath.Parent() - - suffix := framework.RandomString(4) - - cfg := framework.ClientConfig(t) - cfg.Host = strings.Split(cfg.Host, "/clusters/")[0] - kcpClusterClient, err := kcpclientset.NewForConfig(cfg) - require.NoError(t, err, "failed to create kcp client") - - // --- Provider workspace --- - t.Log("Create provider workspace") - providerWsName := fmt.Sprintf("%s-provider-%s", name, suffix) - providerWsPath := testRootPath.Join(providerWsName) - providerCfg, _ := framework.NewWorkspace(t, testRootCfg, framework.WithStaticName(providerWsName)) - - t.Log("Applying APIResourceSchema and APIExport to provider workspace") - // Apply the cowboys APIResourceSchema and a cowboys-only APIExport. - providerFiles := []string{ - "examples/apiresourceschema-cowboys.yaml", - "examples/apiresourceschema-sheriffs.yaml", - } - for _, f := range providerFiles { - data, err := kcpboostrapdeploy.Examples.ReadFile(f) - require.NoError(t, err, "failed to read provider file %s", f) - framework.ApplyManifest(t, providerCfg, data) - } - // Apply the combined APIExport (cowboys + sheriffs). - data, err := kcpboostrapdeploy.Examples.ReadFile("examples/apiexport.yaml") - require.NoError(t, err) - framework.ApplyManifest(t, providerCfg, data) - - // --- Consumer workspace --- - t.Log("Create consumer workspace") - consumerWsName := fmt.Sprintf("%s-consumer-%s", name, suffix) - consumerCfg, consumerKubeconfigPath := framework.NewWorkspace(t, testRootCfg, framework.WithStaticName(consumerWsName)) - - t.Log("Start konnector for consumer workspace") - framework.StartKonnector(t, consumerCfg, "--kubeconfig="+consumerKubeconfigPath) - - // --- Backend (kube-bind process + backend workspace) --- - backendAddr := bootstrapBackend(t, framework.ClientConfig(t), scope, kbindWsPath) - - // --- Backend workspace --- - // The backend workspace binds both kube-bind.io and the provider's cowboys APIExport. - // The apibindingtemplate and apiresourceschema controllers will automatically: - // 1. Create APIServiceExportTemplates from the cowboys APIBinding - // 2. Copy APIResourceSchemas with kube-bind.io/exported=true label - t.Log("Create backend workspace") - backendWsName := fmt.Sprintf("%s-backend-%s", name, suffix) - backendWsPath := testRootPath.Join(backendWsName) - backendCfg, _ := framework.NewWorkspace(t, testRootCfg, framework.WithStaticName(backendWsName)) - - // Grant the embedded OIDC user permission to bind kube-bind.io resources in - // the backend workspace. This is required for the backend's bind - // SubjectAccessReview during the login flow. - rbacData, err := kcpboostrapdeploy.Examples.ReadFile("examples/rbac-embedded-user.yaml") - require.NoError(t, err, "failed to read embedded user RBAC") - framework.ApplyManifest(t, backendCfg, rbacData) - - t.Log("Bind kube-bind.io APIExport to backend workspace") - createApiBinding(t, - kcpClusterClient, - backendWsPath, - generateApiBinding(t, kbindWsPath, "kube-bind.io", "kube-bind.io", - "clusterrolebindings.rbac.authorization.k8s.io", - "clusterroles.rbac.authorization.k8s.io", - "customresourcedefinitions.apiextensions.k8s.io", - "serviceaccounts.core", - "configmaps.core", - "secrets.core", - "namespaces.core", - "roles.rbac.authorization.k8s.io", - "rolebindings.rbac.authorization.k8s.io", - "subjectaccessreviews.authorization.k8s.io", - "apiresourceschemas.apis.kcp.io", - "apibindings.apis.kcp.io", - ), - ) - - t.Log("Bind provider's cowboys-stable APIExport to backend workspace") - createApiBinding(t, - kcpClusterClient, - backendWsPath, - generateApiBinding(t, providerWsPath, "cowboys-stable", "cowboys-stable"), - ) - - // --- Wait for dynamic template creation --- - // The apibindingtemplate controller creates separate templates per scope: - // cowboys-stable-namespaced (for cowboys) and cowboys-stable-cluster (for sheriffs). - t.Log("Waiting for APIServiceExportTemplates to be auto-created by apibindingtemplate controller") - templateGVR := schema.GroupVersionResource{Group: "kube-bind.io", Version: "v1alpha2", Resource: "apiserviceexporttemplates"} - templateDynClient := framework.DynamicClient(t, backendCfg).Resource(templateGVR) - expectedTemplates := []string{"cowboys-stable-namespaced", "cowboys-stable-cluster"} - kcptestinghelpers.Eventually(t, func() (bool, string) { - templates, err := templateDynClient.List(t.Context(), metav1.ListOptions{}) - if err != nil { - return false, fmt.Sprintf("Error listing templates: %v", err) - } - found := map[string]bool{} - for _, tmpl := range templates.Items { - found[tmpl.GetName()] = true - } - for _, expected := range expectedTemplates { - if !found[expected] { - return false, fmt.Sprintf("Template %q not found, got %v", expected, found) - } - } - return true, "" - }, wait.ForeverTestTimeout, time.Second) - - // --- Wait for APIResourceSchema copy --- - // The apiresourceschema controller should copy the bound schemas with the - // kube-bind.io/exported=true label. - t.Log("Waiting for APIResourceSchema copies with exported label") - waitForExportedSchemas(t, backendCfg) - - // --- Get logical cluster ID for login --- - t.Log("Get logical cluster of backend workspace") - backendCluster, err := kcpClusterClient.Cluster(backendWsPath).CoreV1alpha1().LogicalClusters().Get(t.Context(), "cluster", metav1.GetOptions{}) - require.NoError(t, err) - require.NotEmpty(t, backendCluster.Status.URL, "backend cluster URL is empty") - - backendClusterSplit := strings.Split(backendCluster.Status.URL, "/") - require.GreaterOrEqual(t, len(backendClusterSplit), 2, "Unexpected URL format: %s", backendCluster.Status.URL) - require.Equal(t, "clusters", backendClusterSplit[len(backendClusterSplit)-2], "Unexpected URL format: %s", backendCluster.Status.URL) - backendClusterID := backendClusterSplit[len(backendClusterSplit)-1] - require.NotEmpty(t, backendClusterID, "Retrieved cluster id is empty") - - // Wait for the backend to engage the backend workspace before logging in, - // as the bind SubjectAccessReview during login depends on it. - t.Log("Wait for backend to engage backend workspace") - waitForClusterEngaged(t, backendCfg) - - // --- Binding --- - var templateRef, kind, resource string - switch scope { - case kubebindv1alpha2.ClusterScope: - kind = "Sheriff" - resource = "sheriffs" - templateRef = "cowboys-stable-cluster" - case kubebindv1alpha2.NamespacedScope: - kind = "Cowboy" - resource = "cowboys" - templateRef = "cowboys-stable-namespaced" - default: - require.Fail(t, "unhandled scope %q", scope) - } - - kubeBindConfig := path.Join(framework.WorkDir(t), "kube-bind-config-kcp-3tier.yaml") - - iostreams, _, _, _ := genericclioptions.NewTestIOStreams() - authURLDryRunCh := make(chan string, 1) - go framework.SimulateBrowser(t, authURLDryRunCh) - framework.Login(t, iostreams, authURLDryRunCh, kubeBindConfig, fmt.Sprintf("http://%s/api/exports", backendAddr), backendClusterID) - - t.Logf("Performing binding using template %s", templateRef) - performBinding(t, consumerCfg, templateRef, resource, kubeBindConfig) - - // --- Resource sync --- - t.Log("Testing resource creation and synchronization...") - testKCP3TierResourceSync(t, consumerCfg, backendCfg, scope, kind, resource) -} - -// waitForExportedSchemas waits for APIResourceSchemas with the kube-bind.io/exported=true -// label to appear in the backend workspace. These are created by the apiresourceschema controller. -func waitForExportedSchemas(t *testing.T, backendCfg *rest.Config) { - t.Helper() - - schemaGVR := schema.GroupVersionResource{Group: "apis.kcp.io", Version: "v1alpha1", Resource: "apiresourceschemas"} - dynClient := framework.DynamicClient(t, backendCfg).Resource(schemaGVR) - - kcptestinghelpers.Eventually(t, func() (bool, string) { - schemas, err := dynClient.List(t.Context(), metav1.ListOptions{ - LabelSelector: "kube-bind.io/exported=true", - }) - if err != nil { - return false, fmt.Sprintf("Error listing schemas: %v", err) - } - if len(schemas.Items) == 0 { - return false, "No exported APIResourceSchemas found yet" - } - // Verify at least one schema has the expected structure. - for _, s := range schemas.Items { - group, _, _ := unstructured.NestedString(s.Object, "spec", "group") - if group == "wildwest.dev" { - return true, "" - } - } - return false, fmt.Sprintf("Found %d schemas but none for wildwest.dev group", len(schemas.Items)) - }, wait.ForeverTestTimeout, time.Second) -} - -func testKCP3TierResourceSync(t *testing.T, consumerCfg, backendCfg *rest.Config, scope kubebindv1alpha2.InformerScope, kind, resource string) { - serviceGVR := schema.GroupVersionResource{Group: "wildwest.dev", Version: "v1alpha1", Resource: resource} - - consumerClient := testKcpClient(t, consumerCfg, scope, serviceGVR, "default") - backendClient := testKcpClient(t, backendCfg, scope, serviceGVR, "") - - t.Run("instance created downstream syncs upstream", func(t *testing.T) { - t.Logf("Creating %s instance on consumer side", kind) - - resourceInstance := &unstructured.Unstructured{ - Object: map[string]any{ - "apiVersion": "wildwest.dev/v1alpha1", - "kind": kind, - "metadata": map[string]any{ - "name": "test-3tier-" + resource, - }, - "spec": map[string]any{ - "intent": "draw", - }, - }, - } - - kcptestinghelpers.Eventually(t, func() (bool, string) { - _, err := consumerClient.Create(t.Context(), resourceInstance, metav1.CreateOptions{}) - return err == nil, fmt.Sprintf("Error creating %s instance: %v", resource, err) - }, wait.ForeverTestTimeout, time.Millisecond*100) - - t.Logf("Waiting for %s instance to be synced to backend side", resource) - var instances *unstructured.UnstructuredList - kcptestinghelpers.Eventually(t, func() (bool, string) { - var err error - instances, err = backendClient.List(t.Context(), metav1.ListOptions{}) - return err == nil && len(instances.Items) >= 1, fmt.Sprintf("Error listing %s instances: %v", resource, err) - }, wait.ForeverTestTimeout, time.Millisecond*100) - - require.GreaterOrEqual(t, len(instances.Items), 1, "Expected at least one %s instance on backend side", resource) - }) - - t.Run("instance spec updated downstream syncs upstream", func(t *testing.T) { - t.Logf("Updating %s spec on consumer side", resource) - - require.Eventually(t, func() bool { - obj, err := consumerClient.Get(t.Context(), "test-3tier-"+resource, metav1.GetOptions{}) - if err != nil { - return false - } - - unstructured.SetNestedField(obj.Object, "holster", "spec", "intent") //nolint:errcheck - _, err = consumerClient.Update(t.Context(), obj, metav1.UpdateOptions{}) - return err == nil - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s spec to be updated on consumer side", resource) - - t.Logf("Waiting for %s spec update to sync to backend side", resource) - require.Eventually(t, func() bool { - instances, err := backendClient.List(t.Context(), metav1.ListOptions{}) - if err != nil || len(instances.Items) == 0 { - return false - } - - for _, item := range instances.Items { - intent, found, err := unstructured.NestedString(item.Object, "spec", "intent") - if err == nil && found && intent == "holster" { - return true - } - } - return false - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s spec update to sync to backend side", resource) - }) - - t.Run("instance deleted downstream is deleted upstream", func(t *testing.T) { - t.Logf("Deleting %s instance on consumer side", resource) - - err := consumerClient.Delete(t.Context(), "test-3tier-"+resource, metav1.DeleteOptions{}) - require.NoError(t, err, "Failed to delete %s on consumer side", resource) - - t.Logf("Waiting for %s instance to be deleted on backend side", resource) - require.Eventually(t, func() bool { - instances, err := backendClient.List(t.Context(), metav1.ListOptions{}) - if err != nil { - return false - } - for _, item := range instances.Items { - if item.GetName() == "test-3tier-"+resource { - return false - } - } - return true - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s instance to be deleted on backend side", resource) - }) -} diff --git a/contrib/kcp/test/e2e/kcp_test.go b/contrib/kcp/test/e2e/kcp_test.go deleted file mode 100644 index c9b9aa0d9..000000000 --- a/contrib/kcp/test/e2e/kcp_test.go +++ /dev/null @@ -1,289 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 e2e - -import ( - "fmt" - "path" - "strings" - "testing" - "time" - - kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" - kcptestinghelpers "github.com/kcp-dev/sdk/testing/helpers" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/rest" - - kcpboostrapdeploy "github.com/kube-bind/kube-bind/contrib/kcp/deploy" - bootstrapdeploy "github.com/kube-bind/kube-bind/deploy/examples" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -func TestKCPClusterScope(t *testing.T) { - t.Parallel() - testKcpIntegration(t, "cc", kubebindv1alpha2.ClusterScope) -} - -func TestKCPNamespacedScope(t *testing.T) { - t.Parallel() - testKcpIntegration(t, "nc", kubebindv1alpha2.NamespacedScope) -} - -func testKcpIntegration(t *testing.T, name string, scope kubebindv1alpha2.InformerScope) { - t.Helper() - t.Logf("Testing kcp integration with informer scope %s, tempdir: %s", scope, t.TempDir()) - - // kcp bootstrap - testRootCfg, kbindWsPath := bootstrapKCP(t, framework.ClientConfig(t)) - - // The per-test root workspace is the parent of the kbind workspace, i.e. - // kbindWsPath is root::kbind, so its parent is root:. - testRootPath, _ := kbindWsPath.Parent() - - suffix := framework.RandomString(4) - - // consumer - t.Log("Create consumer workspace") - consumerWsName := fmt.Sprintf("%s-consumer-%s", name, suffix) - consumerCfg, consumerKubeconfigPath := framework.NewWorkspace(t, testRootCfg, framework.WithStaticName(consumerWsName)) - - t.Log("Start konnector for consumer workspace") - framework.StartKonnector(t, consumerCfg, "--kubeconfig="+consumerKubeconfigPath) - - // backend - backendAddr := bootstrapBackend(t, framework.ClientConfig(t), scope, kbindWsPath) - - // provider - t.Log("Create provider workspace") - providerWsName := fmt.Sprintf("%s-provider-%s", name, suffix) - providerWsPath := testRootPath.Join(providerWsName) - providerCfg, _ := framework.NewWorkspace(t, testRootCfg, framework.WithStaticName(providerWsName)) - - cfg := framework.ClientConfig(t) - cfg.Host = strings.Split(cfg.Host, "/clusters/")[0] - kcpClusterClient, err := kcpclientset.NewForConfig(cfg) - require.NoError(t, err, "failed to create kcp client") - - t.Log("Bind kube-bind.io APIExport to provider workspace") - createApiBinding(t, - kcpClusterClient, - providerWsPath, - generateApiBinding(t, kbindWsPath, "kube-bind.io", "kube-bind.io", - "clusterrolebindings.rbac.authorization.k8s.io", - "clusterroles.rbac.authorization.k8s.io", - "customresourcedefinitions.apiextensions.k8s.io", - "serviceaccounts.core", - "configmaps.core", - "secrets.core", - "namespaces.core", - "roles.rbac.authorization.k8s.io", - "rolebindings.rbac.authorization.k8s.io", - "subjectaccessreviews.authorization.k8s.io", - "apiresourceschemas.apis.kcp.io", - ), - ) - - t.Log("Applying example APIExport, APIResourceSchemas and templates to provider workspace") - - // Grant the embedded OIDC user permission to bind kube-bind.io resources in - // the provider workspace. This is required for the backend's bind - // SubjectAccessReview during the login flow. - rbacData, err := kcpboostrapdeploy.Examples.ReadFile("examples/rbac-embedded-user.yaml") - require.NoError(t, err, "failed to read embedded user RBAC") - framework.ApplyManifest(t, providerCfg, rbacData) - - files := []string{"examples/apiexport.yaml", - "examples/apiresourceschema-cowboys.yaml", // namespaced - "examples/apiresourceschema-sheriffs.yaml", // cluster scoped - } - for _, f := range files { - data, err := kcpboostrapdeploy.Examples.ReadFile(f) - require.NoError(t, err, "failed to read example file %s", f) - framework.ApplyManifest(t, providerCfg, data) - } - - files = []string{ - "template-cowboys.yaml", // template for cowboys - "template-sheriffs.yaml", // template for sheriffs - "collection.yaml", - } - for _, f := range files { - data, err := bootstrapdeploy.Examples.ReadFile(f) - require.NoError(t, err, "failed to read example file %s", f) - framework.ApplyManifest(t, providerCfg, data) - } - - t.Log("Bind the APIExport locally") - createApiBinding(t, - kcpClusterClient, - providerWsPath, - generateApiBinding(t, providerWsPath, "cowboys-stable", "cowboys-stable"), - ) - - t.Log("Get logical cluster of provider workspace") - providerCluster, err := kcpClusterClient.Cluster(providerWsPath).CoreV1alpha1().LogicalClusters().Get(t.Context(), "cluster", metav1.GetOptions{}) - require.NoError(t, err) - require.NotEmpty(t, providerCluster.Status.URL, "provider cluster URL is empty") - - // .Status.URL should have the form: ://(....)/clusters/, the is what is needed for kube-bind - // The URL overall is irrelevant, so split on `/` and validate that - // at least the tail end is /cluster/"] - require.GreaterOrEqual(t, len(providerClusterSplit), 2, "Unexpected URL format: %s", providerCluster.Status.URL) - // Validate the second last segment is "clusters" as a sanity check - require.Equal(t, "clusters", providerClusterSplit[len(providerClusterSplit)-2], "Unexpected URL format: %s", providerCluster.Status.URL) - // Can assume that the last entry is now the cluster-id, grab it and - // sanity check that it's not empty - providerClusterID := providerClusterSplit[len(providerClusterSplit)-1] - require.NotEmpty(t, providerClusterID, "Retrieved cluster id is empty, source URL: %s", providerCluster.Status.URL) - - // Wait for the backend to engage the provider workspace. The kcp provider - // creates a kube-bind.io Cluster named "default" in every workspace it - // engages, so its presence signals that the backend can serve requests for - // this cluster (which the bind SubjectAccessReview during login depends on). - t.Log("Wait for backend to engage provider workspace") - waitForClusterEngaged(t, providerCfg) - - // kube-bind process - t.Log("Perform binding process with browser") - var templateRef, kind, resource string - switch scope { - case kubebindv1alpha2.ClusterScope: - kind = "Sheriff" - resource = "sheriffs" - templateRef = "sheriffs" - case kubebindv1alpha2.NamespacedScope: - kind = "Cowboy" - resource = "cowboys" - templateRef = "cowboys" - default: - require.Fail(t, "unhandled scope %q", scope) - } - - kubeBindConfig := path.Join(framework.WorkDir(t), "kube-bind-config-kcp.yaml") - - iostreams, _, _, _ := genericclioptions.NewTestIOStreams() - authURLDryRunCh := make(chan string, 1) - go framework.SimulateBrowser(t, authURLDryRunCh) - framework.Login(t, iostreams, authURLDryRunCh, kubeBindConfig, fmt.Sprintf("http://%s/api/exports", backendAddr), providerClusterID) - - t.Logf("Performing binding using template %s", templateRef) - performBinding(t, consumerCfg, templateRef, resource, kubeBindConfig) - - t.Log("Testing resource creation and synchronization...") - testKCPResourceSync(t, consumerCfg, providerCfg, scope, kind, resource) -} - -func testKcpClient(t testing.TB, cfg *rest.Config, scope kubebindv1alpha2.InformerScope, gvr schema.GroupVersionResource, namespace string) dynamic.ResourceInterface { - t.Helper() - - client := framework.DynamicClient(t, cfg).Resource(gvr) - if scope == kubebindv1alpha2.NamespacedScope && namespace != "" { - return client.Namespace(namespace) - } - return client -} - -func testKCPResourceSync(t *testing.T, consumerCfg, providerCfg *rest.Config, scope kubebindv1alpha2.InformerScope, kind, resource string) { - serviceGVR := schema.GroupVersionResource{Group: "wildwest.dev", Version: "v1alpha1", Resource: resource} - - consumerClient := testKcpClient(t, consumerCfg, scope, serviceGVR, "default") - // provider side has a namespace with a random name for the consumer - // so it needs to be a non namespaced client - providerClient := testKcpClient(t, providerCfg, scope, serviceGVR, "") - - t.Run("instance created downstream syncs upstream", func(t *testing.T) { - t.Logf("Creating %s instance on consumer side", kind) - - resourceInstance := &unstructured.Unstructured{ - Object: map[string]any{ - "apiVersion": "wildwest.dev/v1alpha1", - "kind": kind, - "metadata": map[string]any{ - "name": "test-" + resource, - }, - "spec": map[string]any{ - "intent": "draw", - }, - }, - } - - kcptestinghelpers.Eventually(t, func() (bool, string) { - _, err := consumerClient.Create(t.Context(), resourceInstance, metav1.CreateOptions{}) - return err == nil, fmt.Sprintf("Error creating %s instance: %v", resource, err) - }, wait.ForeverTestTimeout, time.Millisecond*100) - - t.Logf("Waiting for %s instance to be synced to provider side", resource) - var instances *unstructured.UnstructuredList - kcptestinghelpers.Eventually(t, func() (bool, string) { - var err error - instances, err = providerClient.List(t.Context(), metav1.ListOptions{}) - return err == nil && len(instances.Items) >= 1, fmt.Sprintf("Error listing %s instances: %v", resource, err) - }, wait.ForeverTestTimeout, time.Millisecond*100) - - require.Equal(t, 1, len(instances.Items), "Expected exactly one %s instance on provider side", resource) - }) - - t.Run("instance spec updated downstream syncs upstream", func(t *testing.T) { - t.Logf("Updating %s spec on consumer side", resource) - - require.Eventually(t, func() bool { - obj, err := consumerClient.Get(t.Context(), "test-"+resource, metav1.GetOptions{}) - if err != nil { - return false - } - - unstructured.SetNestedField(obj.Object, "holster", "spec", "intent") //nolint:errcheck - _, err = consumerClient.Update(t.Context(), obj, metav1.UpdateOptions{}) - return err == nil - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s spec to be updated on consumer side", resource) - - t.Logf("Waiting for %s spec update to sync to provider side", resource) - require.Eventually(t, func() bool { - instances, err := providerClient.List(t.Context(), metav1.ListOptions{}) - if err != nil || len(instances.Items) == 0 { - return false - } - - intent, found, err := unstructured.NestedString(instances.Items[0].Object, "spec", "intent") - return err == nil && found && intent == "holster" - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s spec update to sync to provider side", resource) - }) - - t.Run("instance deleted downstream is deleted upstream", func(t *testing.T) { - t.Logf("Deleting %s instance on consumer side", resource) - - err := consumerClient.Delete(t.Context(), "test-"+resource, metav1.DeleteOptions{}) - require.NoError(t, err, "Failed to delete %s on consumer side", resource) - - t.Logf("Waiting for %s instance to be deleted on provider side", resource) - require.Eventually(t, func() bool { - instances, err := providerClient.List(t.Context(), metav1.ListOptions{}) - return err == nil && len(instances.Items) == 0 - }, wait.ForeverTestTimeout, 5*time.Second, "waiting for %s instance to be deleted on provider side", resource) - }) -} diff --git a/deploy/charts/backend-v2/.helmignore b/deploy/charts/backend-v2/.helmignore new file mode 100644 index 000000000..cb365c23b --- /dev/null +++ b/deploy/charts/backend-v2/.helmignore @@ -0,0 +1,8 @@ +# Patterns to ignore when building Helm packages. +.DS_Store +.git/ +.gitignore +*.tmpl +*.gotmpl +.idea/ +*.tgz diff --git a/deploy/charts/backend-v2/Chart.yaml b/deploy/charts/backend-v2/Chart.yaml new file mode 100644 index 000000000..02ac9d56d --- /dev/null +++ b/deploy/charts/backend-v2/Chart.yaml @@ -0,0 +1,16 @@ +apiVersion: v2 +name: backend-v2 +description: kbind v2 backend — the optional provider-side service layer (gateway, issuer, reaper). +type: application + +# version / appVersion are placeholders bumped by the release tooling. +version: 0.0.0 +appVersion: "0.0.0" + +home: https://kbind.io +sources: + - https://github.com/kbind/kbind +keywords: + - kbind + - multicluster + - api-binding diff --git a/deploy/charts/backend-v2/files/crds/catalog.kbind.io_collections.yaml b/deploy/charts/backend-v2/files/crds/catalog.kbind.io_collections.yaml new file mode 100644 index 000000000..9bc289b91 --- /dev/null +++ b/deploy/charts/backend-v2/files/crds/catalog.kbind.io_collections.yaml @@ -0,0 +1,86 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: collections.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Collection + listKind: CollectionList + plural: collections + singular: collection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Collection groups Exports for UI/CLI browsing. Pure presentation, nothing + binds to a Collection. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: CollectionSpec is a titled grouping of Exports. + properties: + description: + description: description explains the grouping. + type: string + exports: + description: exports lists the member Exports by name. + items: + description: ExportRef references an Export by name. + properties: + name: + description: name of the Export. + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + title: + description: title is the human-facing name of the group. + minLength: 1 + type: string + required: + - exports + - title + type: object + required: + - spec + type: object + served: true + storage: true + subresources: {} diff --git a/deploy/charts/backend-v2/files/crds/catalog.kbind.io_exports.yaml b/deploy/charts/backend-v2/files/crds/catalog.kbind.io_exports.yaml new file mode 100644 index 000000000..ae36c4f1d --- /dev/null +++ b/deploy/charts/backend-v2/files/crds/catalog.kbind.io_exports.yaml @@ -0,0 +1,287 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: exports.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Export + listKind: ExportList + plural: exports + singular: export + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Export is one curated offering in the provider's catalog: human-facing + metadata plus defaults on top of one or more exported APIs. The catalog is + derived-from-core-truth: an Export listing an API that is not actually + exported (label/boundary) gets a condition and is hidden by the gateway, + the export label remains the source of truth, the catalog is presentation + and defaults. Lives on the provider, the konnector never sees it. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ExportSpec describes one offering. + properties: + apis: + description: |- + apis lists the exported APIs a binding to this offering syncs, by CRD + name on the provider ("."). + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name, it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + defaults: + description: |- + defaults are copied into the generated ClusterBinding of the one-apply + bundle. + properties: + conflictPolicy: + description: |- + conflictPolicy is the default conflict behavior for the generated + ClusterBinding. + enum: + - Fail + - Adopt + type: string + relatedResources: + description: |- + relatedResources are the related-resource selectors for the generated + ClusterBinding. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string + for the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by + label. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact + name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + type: object + description: + description: description explains the offering to a human choosing + it. + type: string + docs: + description: docs optionally links to the offering's documentation. + type: string + icon: + description: icon optionally points at an icon for UIs. + properties: + url: + description: url of the icon image. + minLength: 1 + type: string + required: + - url + type: object + title: + description: title is the human-facing name of the offering. + minLength: 1 + type: string + required: + - apis + - title + type: object + status: + description: ExportStatus is the observed state of an Export. + properties: + conditions: + description: 'conditions: Ready (all listed APIs are actually exported).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/charts/backend-v2/files/crds/iam.kbind.io_grants.yaml b/deploy/charts/backend-v2/files/crds/iam.kbind.io_grants.yaml new file mode 100644 index 000000000..10e0a4729 --- /dev/null +++ b/deploy/charts/backend-v2/files/crds/iam.kbind.io_grants.yaml @@ -0,0 +1,308 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: grants.iam.kbind.io +spec: + group: iam.kbind.io + names: + categories: + - kbind + kind: Grant + listKind: GrantList + plural: grants + singular: grant + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.identity.subject + name: Subject + type: string + - jsonPath: .spec.exportName + name: Export + type: string + - jsonPath: .status.namespace + name: Namespace + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Grant records that an identity was issued credentials for an export. The + gateway creates it with the export's API list and defaults resolved in + (issuance is a stable record even if the catalog entry changes later), the + issuer controller provisions the tenancy boundary, ServiceAccount, RBAC and + token from the spec and reports the artifacts in status. Deleting the Grant + revokes: the issuer's cleanup finalizer unwinds everything it provisioned. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: GrantSpec is the issuance request/record. + properties: + apis: + description: |- + apis is the export's API list resolved at issuance time, by CRD name on + the provider ("."). The issuer scopes RBAC to exactly + these. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name, it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + conflictPolicy: + description: |- + conflictPolicy is the export's default conflict policy resolved at + issuance time, copied into the generated bundle's ClusterBinding. + enum: + - Fail + - Adopt + type: string + exportName: + description: exportName records which catalog Export this Grant was + issued for. + minLength: 1 + type: string + identity: + description: identity is who the credentials were issued to. + properties: + displayName: + description: displayName is a human-facing name (e.g. email), + informational only. + type: string + groups: + description: groups the identity carried at issuance, informational + only. + items: + type: string + type: array + x-kubernetes-list-type: atomic + subject: + description: subject is the stable identity key, "#" + for OIDC. + minLength: 1 + type: string + required: + - subject + type: object + relatedResources: + description: |- + relatedResources are the export's related-resource selectors resolved at + issuance time. They flow into the bundle's ClusterBinding and widen the + issued RBAC (secrets/configmaps in the declared direction). + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - exportName + - identity + type: object + status: + description: GrantStatus reports what the issuer provisioned. + properties: + conditions: + description: 'conditions: Ready (credentials provisioned and token + populated).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + namespace: + description: namespace is the per-consumer tenancy boundary on the + provider. + type: string + serviceAccount: + description: serviceAccount is the name of the issued ServiceAccount + (in namespace). + type: string + tokenSecret: + description: |- + tokenSecret is the name of the long-lived SA token Secret (in + namespace). The gateway reads it to assemble the bundle's kubeconfig. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/charts/backend-v2/templates/NOTES.txt b/deploy/charts/backend-v2/templates/NOTES.txt new file mode 100644 index 000000000..f259fb0ac --- /dev/null +++ b/deploy/charts/backend-v2/templates/NOTES.txt @@ -0,0 +1,35 @@ +kbind backend installed: {{ include "backend.fullname" . }} (namespace {{ .Release.Namespace }}) + +Modules: gateway={{ .Values.modules.gateway }} issuer={{ .Values.modules.issuer }} reaper={{ .Values.modules.reaper }} apply={{ .Values.modules.apply }} + +{{- if .Values.modules.gateway }} + +Reach the gateway (port-forward for a quick look): + + kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "backend.fullname" . }} 8080:{{ .Values.service.port }} + open http://localhost:8080 # the catalog UI + kubectl bind login http://localhost:8080 # CLI login + +{{- if not .Values.externalURL }} +NOTE: externalURL is not set, OIDC callbacks and pickup URLs default to +localhost. Set it (and expose the Service) for real consumers. +{{- end }} +{{- if not .Values.cookieKeys.existingSecret }} +NOTE: cookieKeys.existingSecret is not set, sessions are ephemeral and will +not survive restarts or work across replicas. +{{- end }} +{{- end }} + +Curate the catalog by labeling exported CRDs and creating Exports: + + kubectl label crd mangodbs.mangodb.io "core.kbind.io/exported=true" + kubectl apply -f - <<'EOF' + apiVersion: catalog.kbind.io/v1alpha1 + kind: Export + metadata: + name: mangodb + spec: + title: MangoDB + apis: + - name: mangodbs.mangodb.io + EOF diff --git a/deploy/charts/backend-v2/templates/_helpers.tpl b/deploy/charts/backend-v2/templates/_helpers.tpl new file mode 100644 index 000000000..3722599bc --- /dev/null +++ b/deploy/charts/backend-v2/templates/_helpers.tpl @@ -0,0 +1,53 @@ +{{/* Chart name (overridable). */}} +{{- define "backend.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* Fully qualified app name. */}} +{{- define "backend.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* Chart label. */}} +{{- define "backend.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* Common labels. */}} +{{- define "backend.labels" -}} +helm.sh/chart: {{ include "backend.chart" . }} +{{ include "backend.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* Selector labels. */}} +{{- define "backend.selectorLabels" -}} +app.kubernetes.io/name: {{ include "backend.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* ServiceAccount name. */}} +{{- define "backend.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "backend.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} + +{{/* Whether leader election is effectively on (forced when replicaCount > 1). */}} +{{- define "backend.leaderElect" -}} +{{- if or .Values.leaderElect (gt (int .Values.replicaCount) 1) }}true{{ else }}false{{ end }} +{{- end }} diff --git a/deploy/charts/backend-v2/templates/clusterrole.yaml b/deploy/charts/backend-v2/templates/clusterrole.yaml new file mode 100644 index 000000000..fe41a1a22 --- /dev/null +++ b/deploy/charts/backend-v2/templates/clusterrole.yaml @@ -0,0 +1,75 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "backend.fullname" . }} + labels: + {{- include "backend.labels" . | nindent 4 }} +rules: + # Catalog: the gateway reads it, the Export controller validates it. + - apiGroups: ["catalog.kbind.io"] + resources: ["exports", "collections"] + verbs: ["get", "list", "watch"] + - apiGroups: ["catalog.kbind.io"] + resources: ["exports/status"] + verbs: ["get", "update", "patch"] + # Issuance records: the gateway writes Grants, the issuer reconciles them. + - apiGroups: ["iam.kbind.io"] + resources: ["grants"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["iam.kbind.io"] + resources: ["grants/status"] + verbs: ["get", "update", "patch"] + - apiGroups: ["iam.kbind.io"] + resources: ["grants/finalizers"] + verbs: ["update"] + # Exported-CRD discovery (catalog validation is derived-from-core-truth), + # plus create/update for the backend's CRD self-install (--install-crds; + # set it false and drop these verbs if CRDs are managed out-of-band). + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + # Issuer artifacts: boundary namespaces, ServiceAccounts, token Secrets. + # Namespace delete is the reaper's destructive opt-in. + - apiGroups: [""] + resources: ["namespaces"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["serviceaccounts"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + # Issued RBAC. The issuer creates Roles enumerating the granted APIs, which + # the backend does not hold itself — "escalate" allows exactly that, and + # "bind" (also a verb on the role resources, not the binding resources) + # allows binding those roles to the tenant ServiceAccounts. + - apiGroups: ["rbac.authorization.k8s.io"] + resources: ["roles", "clusterroles"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete", "escalate", "bind"] + - apiGroups: ["rbac.authorization.k8s.io"] + resources: ["rolebindings", "clusterrolebindings"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + # Consumer heartbeats (reaper and the clusters view read them across + # boundary namespaces). + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch"] + # The clusters view counts synced objects of the exported APIs. Those are + # open-ended (whatever this provider exports), so read access defaults to + # all groups — narrow to your exported groups to tighten the blast radius. + {{- with .Values.rbac.syncedResourceGroups }} + - apiGroups: + {{- toYaml . | nindent 6 }} + resources: ["*"] + verbs: ["get", "list"] + {{- end }} + # kubernetes-auth: verify caller tokens. + - apiGroups: ["authentication.k8s.io"] + resources: ["tokenreviews"] + verbs: ["create"] + # Events emitted by the controllers. + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +{{- end }} diff --git a/deploy/charts/backend-v2/templates/clusterrolebinding.yaml b/deploy/charts/backend-v2/templates/clusterrolebinding.yaml new file mode 100644 index 000000000..a1f4120aa --- /dev/null +++ b/deploy/charts/backend-v2/templates/clusterrolebinding.yaml @@ -0,0 +1,16 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "backend.fullname" . }} + labels: + {{- include "backend.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "backend.fullname" . }} +subjects: + - kind: ServiceAccount + name: {{ include "backend.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/charts/backend-v2/templates/crds.yaml b/deploy/charts/backend-v2/templates/crds.yaml new file mode 100644 index 000000000..693db13a2 --- /dev/null +++ b/deploy/charts/backend-v2/templates/crds.yaml @@ -0,0 +1,6 @@ +{{- if .Values.installCRDs }} +{{- range $path, $_ := .Files.Glob "files/crds/*.yaml" }} +--- +{{ $.Files.Get $path }} +{{- end }} +{{- end }} diff --git a/deploy/charts/backend-v2/templates/deployment.yaml b/deploy/charts/backend-v2/templates/deployment.yaml new file mode 100644 index 000000000..44fd7e56d --- /dev/null +++ b/deploy/charts/backend-v2/templates/deployment.yaml @@ -0,0 +1,166 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "backend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "backend.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "backend.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "backend.selectorLabels" . | nindent 8 }} + {{- with .Values.podLabels }} + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + spec: + serviceAccountName: {{ include "backend.serviceAccountName" . }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: backend + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + {{- if or .Values.oidc.existingSecret .Values.cookieKeys.existingSecret }} + env: + {{- if .Values.oidc.existingSecret }} + - name: OIDC_CLIENT_SECRET + valueFrom: + secretKeyRef: + name: {{ .Values.oidc.existingSecret }} + key: clientSecret + {{- end }} + {{- if .Values.cookieKeys.existingSecret }} + - name: COOKIE_SIGNING_KEY + valueFrom: + secretKeyRef: + name: {{ .Values.cookieKeys.existingSecret }} + key: signingKey + - name: COOKIE_ENCRYPTION_KEY + valueFrom: + secretKeyRef: + name: {{ .Values.cookieKeys.existingSecret }} + key: encryptionKey + {{- end }} + {{- end }} + args: + - --enable-gateway={{ .Values.modules.gateway }} + - --enable-issuer={{ .Values.modules.issuer }} + - --enable-reaper={{ .Values.modules.reaper }} + - --enable-apply={{ .Values.modules.apply }} + - --listen-address=:{{ .Values.listenPort }} + - --provider-name={{ .Values.providerName }} + {{- with .Values.externalURL }} + - --external-url={{ . }} + {{- end }} + {{- with .Values.externalAddress }} + - --external-address={{ . }} + {{- end }} + - --issuer-scope={{ .Values.issuerScope }} + {{- with .Values.konnectorImage }} + - --konnector-image={{ . }} + {{- end }} + {{- if .Values.oidc.mock }} + - --oidc-mock=true + - --oidc-mock-listen=127.0.0.1:{{ .Values.oidc.mockPort }} + {{- else }} + - --oidc-issuer-url={{ required "oidc.issuerURL is required unless oidc.mock is on" .Values.oidc.issuerURL }} + - --oidc-client-id={{ required "oidc.clientID is required unless oidc.mock is on" .Values.oidc.clientID }} + {{- if .Values.oidc.existingSecret }} + - --oidc-client-secret=$(OIDC_CLIENT_SECRET) + {{- end }} + - --oidc-username-claim={{ .Values.oidc.usernameClaim }} + {{- with .Values.oidc.groupsClaim }} + - --oidc-groups-claim={{ . }} + {{- end }} + - --oidc-scopes={{ .Values.oidc.scopes }} + {{- with .Values.oidc.redirectURL }} + - --oidc-redirect-url={{ . }} + {{- end }} + {{- end }} + {{- if .Values.kubernetesAuth }} + - --kubernetes-auth=true + {{- end }} + {{- if .Values.cookieKeys.existingSecret }} + - --cookie-signing-key=$(COOKIE_SIGNING_KEY) + - --cookie-encryption-key=$(COOKIE_ENCRYPTION_KEY) + {{- end }} + - --session-ttl={{ .Values.sessionTTL }} + - --pickup-ttl={{ .Values.pickupTTL }} + {{- if .Values.modules.reaper }} + - --reaper-ttl={{ .Values.reaper.ttl }} + - --reaper-revoke={{ .Values.reaper.revoke }} + - --reaper-delete-boundary={{ .Values.reaper.deleteBoundary }} + - --reaper-interval={{ .Values.reaper.interval }} + {{- end }} + - --metrics-bind-address=:{{ .Values.metrics.port }} + - --health-probe-bind-address=:{{ .Values.healthProbe.port }} + - --leader-elect={{ include "backend.leaderElect" . }} + - --leader-election-id={{ .Values.leaderElectionID }} + {{- with .Values.extraArgs }} + {{- toYaml . | nindent 12 }} + {{- end }} + ports: + {{- if .Values.modules.gateway }} + - name: http + containerPort: {{ .Values.listenPort }} + {{- end }} + - name: metrics + containerPort: {{ .Values.metrics.port }} + - name: probe + containerPort: {{ .Values.healthProbe.port }} + {{- if .Values.modules.gateway }} + livenessProbe: + httpGet: + path: /api/healthz + port: http + initialDelaySeconds: 15 + periodSeconds: 20 + readinessProbe: + httpGet: + path: /api/healthz + port: http + initialDelaySeconds: 5 + periodSeconds: 10 + {{- else }} + livenessProbe: + httpGet: + path: /healthz + port: probe + initialDelaySeconds: 15 + periodSeconds: 20 + readinessProbe: + httpGet: + path: /readyz + port: probe + initialDelaySeconds: 5 + periodSeconds: 10 + {{- end }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/deploy/charts/backend-v2/templates/role.yaml b/deploy/charts/backend-v2/templates/role.yaml new file mode 100644 index 000000000..5833759f0 --- /dev/null +++ b/deploy/charts/backend-v2/templates/role.yaml @@ -0,0 +1,17 @@ +{{- if .Values.rbac.create }} +# Leader-election lease, scoped to the release namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "backend.fullname" . }}-leaderelection + namespace: {{ .Release.Namespace }} + labels: + {{- include "backend.labels" . | nindent 4 }} +rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +{{- end }} diff --git a/deploy/charts/backend-v2/templates/rolebinding.yaml b/deploy/charts/backend-v2/templates/rolebinding.yaml new file mode 100644 index 000000000..4d4e1ace5 --- /dev/null +++ b/deploy/charts/backend-v2/templates/rolebinding.yaml @@ -0,0 +1,17 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "backend.fullname" . }}-leaderelection + namespace: {{ .Release.Namespace }} + labels: + {{- include "backend.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "backend.fullname" . }}-leaderelection +subjects: + - kind: ServiceAccount + name: {{ include "backend.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/charts/backend-v2/templates/service.yaml b/deploy/charts/backend-v2/templates/service.yaml new file mode 100644 index 000000000..8eabbccad --- /dev/null +++ b/deploy/charts/backend-v2/templates/service.yaml @@ -0,0 +1,18 @@ +{{- if .Values.modules.gateway }} +apiVersion: v1 +kind: Service +metadata: + name: {{ include "backend.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "backend.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - name: http + port: {{ .Values.service.port }} + targetPort: http + protocol: TCP + selector: + {{- include "backend.selectorLabels" . | nindent 4 }} +{{- end }} diff --git a/deploy/charts/backend-v2/templates/serviceaccount.yaml b/deploy/charts/backend-v2/templates/serviceaccount.yaml new file mode 100644 index 000000000..811d2ba51 --- /dev/null +++ b/deploy/charts/backend-v2/templates/serviceaccount.yaml @@ -0,0 +1,13 @@ +{{- if .Values.serviceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "backend.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "backend.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/deploy/charts/backend-v2/values.yaml b/deploy/charts/backend-v2/values.yaml new file mode 100644 index 000000000..8976d02f6 --- /dev/null +++ b/deploy/charts/backend-v2/values.yaml @@ -0,0 +1,155 @@ +# Default values for the backend chart. The backend runs on (or against) the +# **provider** cluster. + +image: + repository: ghcr.io/kbind-dev/backend + # Defaults to the chart appVersion when empty. + tag: "" + pullPolicy: IfNotPresent + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +# The gateway is stateless — every replica serves traffic. Sessions and pickup +# tokens work across replicas as long as cookieKeys.existingSecret is set (so +# all replicas share the same keys). The issuer/reaper controllers are gated by +# leader election, forced on automatically when replicaCount > 1. +replicaCount: 1 + +leaderElect: false +leaderElectionID: backend.kbind.io + +# Module flags: any subset works; the GitOps-only core path needs none of them. +modules: + gateway: true + issuer: true + reaper: false + # Browser-apply (POST /api/apply). Consumer kubeconfigs transit the gateway + # when enabled — turn on consciously. + apply: false + +# Human-facing provider name in /api/provider and the UI. +providerName: kbind + +# Externally reachable base URL of the gateway (e.g. https://kbind.example.com). +# Defaults the OIDC callback URL. Required for real deployments. +externalURL: "" + +# Provider API server URL written into issued kubeconfigs. Empty = the API +# server host the backend itself talks to (fine when consumers can reach it). +externalAddress: "" + +# RBAC reach of issued credentials: Cluster (exported resources in all +# namespaces) or Namespace (boundary namespace only — strict tenancy). +issuerScope: Cluster + +# Konnector image installed by browser-apply. Empty = the baked-in default. +konnectorImage: "" + +oidc: + # Kube-apiserver-style OIDC configuration for the gateway's login flow. + issuerURL: "" + clientID: "" + # Name of an existing Secret with key "clientSecret". + existingSecret: "" + usernameClaim: sub + groupsClaim: "" + scopes: "openid,profile,email" + # Defaults to /api/auth/oidc/callback. + redirectURL: "" + # Dev only: embedded mock issuer that auto-approves every login. + mock: false + # Fixed in-pod port for the mock issuer (127.0.0.1-bound). Port-forward it + # alongside the gateway so a host browser can reach the issuer: + # kubectl port-forward ... 5556:5556 + mockPort: 5556 + +# Also accept provider-cluster bearer tokens (TokenReview) — for in-platform +# callers that already hold a cluster identity. +kubernetesAuth: false + +# Name of an existing Secret holding the session cookie keys, with keys +# "signingKey" (base64 text of 32/64 random bytes) and "encryptionKey" (base64 +# text of 16/24/32 random bytes). REQUIRED for replicaCount > 1 and for +# sessions to survive restarts; empty = ephemeral random keys (dev only). +# Generate: kubectl create secret generic kbind-cookie-keys \ +# --from-literal=signingKey=$(openssl rand -base64 64) \ +# --from-literal=encryptionKey=$(openssl rand -base64 32) +cookieKeys: + existingSecret: "" + +sessionTTL: 12h +pickupTTL: 5m + +reaper: + # Heartbeat silence after which a Grant is considered stale. + ttl: 30m + # Delete stale Grants (revokes their credentials). Conservative default: off. + revoke: false + # When revoking, also delete the boundary namespace and the synced objects + # inside it. Destructive; requires revoke. + deleteBoundary: false + interval: 1m + +service: + type: ClusterIP + port: 80 + +# Port the gateway listens on inside the pod (--listen-address). +listenPort: 8080 + +serviceAccount: + create: true + name: "" + annotations: {} + +rbac: + create: true + # API groups the clusters view may read to count synced objects (the + # exported APIs are open-ended). Narrow to the groups you actually export + # (e.g. ["example.org"]) to tighten the backend's read reach. + syncedResourceGroups: + - "*" + +# Extra args appended to the backend command. +extraArgs: [] + +metrics: + # Controller-manager metrics endpoint (issuer/reaper modules). + port: 8086 + +healthProbe: + # Controller-manager probe endpoint (used when the gateway module is off). + port: 8082 + +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 500m + memory: 256Mi + +podAnnotations: {} +podLabels: {} + +podSecurityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + +securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + +nodeSelector: {} +tolerations: [] +affinity: {} + +# Install the service-layer CRDs (Export, Collection, Grant) with the release. +# Set false if they are managed out-of-band. +installCRDs: true diff --git a/deploy/charts/backend/.helmignore b/deploy/charts/backend/.helmignore deleted file mode 100644 index 0e8a0eb36..000000000 --- a/deploy/charts/backend/.helmignore +++ /dev/null @@ -1,23 +0,0 @@ -# Patterns to ignore when building packages. -# This supports shell glob matching, relative path matching, and -# negation (prefixed with !). Only one pattern per line. -.DS_Store -# Common VCS dirs -.git/ -.gitignore -.bzr/ -.bzrignore -.hg/ -.hgignore -.svn/ -# Common backup files -*.swp -*.bak -*.tmp -*.orig -*~ -# Various IDEs -.project -.idea/ -*.tmproj -.vscode/ diff --git a/deploy/charts/backend/Chart.yaml b/deploy/charts/backend/Chart.yaml deleted file mode 100644 index 131b99318..000000000 --- a/deploy/charts/backend/Chart.yaml +++ /dev/null @@ -1,26 +0,0 @@ -apiVersion: v2 -name: backend -description: A Helm chart for kube-bind backend deployment - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -# Versions are expected to follow Semantic Versioning (https://semver.org/) -# NOTE: updated by helm-build.sh during the build — do not edit manually. -version: 0.0.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. Versions are not expected to -# follow Semantic Versioning. They should reflect the version the application is using. -# It is recommended to use it with quotes. -# NOTE: updated by helm-build.sh during the build — do not edit manually. -appVersion: "0.0.0" diff --git a/deploy/charts/backend/README.md b/deploy/charts/backend/README.md deleted file mode 100644 index 83fd81a6d..000000000 --- a/deploy/charts/backend/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# backend - -A Helm chart for kube-bind backend deployment - -![Version: 0.0.0](https://img.shields.io/badge/Version-0.0.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 0.0.0](https://img.shields.io/badge/AppVersion-0.0.0-informational?style=flat-square) - -## Installation - -```bash -helm install kube-bind-backend oci://ghcr.io/kbind-dev/charts/backend --version -``` - -## Configuration - -See [values.yaml](values.yaml) for the full list of configurable parameters. - -## Values - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| affinity | object | `{}` | Affinity rules for pod scheduling | -| autoscaling.enabled | bool | `false` | Enable horizontal pod autoscaling | -| autoscaling.maxReplicas | int | `100` | Maximum number of replicas | -| autoscaling.minReplicas | int | `1` | Minimum number of replicas | -| autoscaling.targetCPUUtilizationPercentage | int | `80` | Target CPU utilization percentage | -| backend.apibindingIgnorePrefixes | list | `[]` | Name prefixes of APIBindings to ignore when generating APIServiceExportTemplates | -| backend.apiexportEndpointSliceName | string | `""` | APIExport EndpointSlice name to watch | -| backend.clusterScopeIsolation | string | `"prefix"` | Cluster-scope isolation mode. Options: none, prefix, namespaced | -| backend.consumerScope | string | `"namespaced"` | Consumer scope. Options: "namespaced" | -| backend.context | string | `""` | The name of the kubeconfig context to use | -| backend.cookieEncryptionKey | string | `""` | Cookie encryption key (base64 encoded). Empty generates random key on each start (not for production!) | -| backend.cookieSigningKey | string | `""` | Cookie signing key (base64 encoded). Empty generates random key on each start (not for production!) | -| backend.externalAddress | string | `""` | External address clients use to reach the backend | -| backend.externalServerName | string | `""` | External server name for TLS SNI | -| backend.extraArgs | list | `[]` | Extra command-line arguments to pass to the backend | -| backend.frontendDisabled | bool | `false` | Disable the frontend UI | -| backend.image.pullPolicy | string | `"IfNotPresent"` | Image pull policy | -| backend.image.repository | string | `"ghcr.io/kbind-dev/backend"` | Image repository | -| backend.image.tag | string | `""` | Overrides the image tag whose default is the chart appVersion | -| backend.kubeconfig | string | `""` | Path to a kubeconfig file. Only required if out-of-cluster. | -| backend.listenAddress | string | `"0.0.0.0:8080"` | Address the backend listens on | -| backend.loggingLevel | int | `2` | Logging verbosity level | -| backend.multiclusterRuntimeProvider | string | `""` | Multicluster runtime provider (e.g., "kcp") | -| backend.namespacePrefix | string | `"kube-bind-"` | Prefix for namespaces created by kube-bind | -| backend.oidc.allowedGroups | list | `[]` | List of groups allowed to access bindings. With embedded OIDC, system:authenticated is added automatically | -| backend.oidc.allowedUsers | list | `[]` | List of users allowed to access bindings | -| backend.oidc.callbackUrl | string | `""` | OIDC callback URL | -| backend.oidc.clientId | string | `""` | OIDC client ID | -| backend.oidc.clientSecret | string | `""` | Not required for providers using PKCE or public clients | -| backend.oidc.clientSecretKey | string | `""` | Key within the secret (e.g., "client-secret") | -| backend.oidc.clientSecretName | string | `""` | If set, the secret will be mounted as OIDC_CLIENT_SECRET env var | -| backend.oidc.issuerUrl | string | `""` | OIDC issuer URL (leave empty for embedded OIDC server) | -| backend.oidc.type | string | `"embedded"` | OIDC provider type. Options: "embedded" or "external" | -| backend.prettyName | string | `""` | Human-readable name for this backend instance | -| backend.schemaSource | string | `""` | Schema source (e.g., "apiresourceschemas") | -| backend.sessionStorage.redisAddress | string | `""` | | -| backend.sessionStorage.redisPassword | string | `""` | | -| backend.tls.certSecretName | string | `""` | Name of the Kubernetes secret containing TLS certificate | -| backend.tls.enabled | bool | `false` | Enable TLS for the backend | -| backend.tls.tlsCertFile | string | `"/etc/kube-bind/tls/tls.crt"` | Path to TLS certificate file inside the container | -| backend.tls.tlsKeyFile | string | `"/etc/kube-bind/tls/tls.key"` | Path to TLS key file inside the container | -| certManager.clusterIssuer | string | `""` | Name of the ClusterIssuer to use | -| certManager.enabled | bool | `false` | Enable cert-manager integration for automatic TLS certificates | -| examples.enabled | bool | `false` | Enable example resources to seed on first start | -| fullnameOverride | string | `""` | Override the full release name | -| gatewayApi.enabled | bool | `false` | Enable Gateway API resources | -| gatewayApi.gateway.annotations | object | `{}` | Annotations to add to the Gateway resource | -| gatewayApi.gateway.className | string | `""` | Gateway class name | -| gatewayApi.gateway.httpPort | int | `80` | HTTP listener port | -| gatewayApi.gateway.httpsPort | int | `443` | HTTPS listener port | -| gatewayApi.gateway.tls.certificateRefs | list | `[]` | TLS certificate references for the Gateway | -| gatewayApi.route.annotations | object | `{}` | Annotations to add to the HTTPRoute resource | -| gatewayApi.route.hostnames | list | `[]` | Hostnames for the HTTPRoute | -| gatewayApi.route.path | string | `"/"` | Path match for the HTTPRoute | -| gatewayApi.route.pathType | string | `"PathPrefix"` | Path match type for the HTTPRoute | -| hostAliases | list | `[]` | Host aliases for /etc/hosts injection into pods | -| imagePullSecrets | list | `[]` | Secrets for pulling images from a private repository | -| initContainers | list | `[]` | Additional init containers | -| livenessProbe | object | `{"httpGet":{"path":"/healthz","port":"http"}}` | Liveness probe configuration | -| nameOverride | string | `""` | Override the chart name | -| nodeSelector | object | `{}` | Node selector for pod scheduling | -| podAnnotations | object | `{}` | Annotations to add to the pod | -| podLabels | object | `{}` | Labels to add to the pod | -| podSecurityContext | object | `{}` | Pod security context | -| rbac.create | bool | `true` | Specifies whether RBAC resources should be created | -| readinessProbe | object | `{"httpGet":{"path":"/healthz","port":"http"}}` | Readiness probe configuration | -| replicaCount | int | `1` | Number of replicas for the backend deployment | -| resources | object | `{}` | Resource requests and limits | -| securityContext | object | `{}` | Container security context | -| service.httpsNodePort | string | `""` | NodePort for HTTPS (only used when type is NodePort) | -| service.httpsPort | int | `8443` | HTTPS service port | -| service.nodePort | string | `""` | NodePort for HTTP (only used when type is NodePort) | -| service.port | int | `8080` | HTTP service port | -| service.type | string | `"ClusterIP"` | Service type | -| serviceAccount.annotations | object | `{}` | Annotations to add to the service account | -| serviceAccount.automount | bool | `true` | Automatically mount the ServiceAccount's API credentials | -| serviceAccount.create | bool | `true` | Specifies whether a service account should be created | -| serviceAccount.name | string | `""` | The name of the service account to use. If not set and create is true, a name is generated using the fullname template | -| tolerations | list | `[]` | Tolerations for pod scheduling | -| volumeMounts | list | `[]` | Additional volumeMounts on the output Deployment definition | -| volumes | list | `[]` | Additional volumes on the output Deployment definition | - ---- - -*This README is generated by [helm-docs](https://github.com/norwoodj/helm-docs). Do not edit manually.* diff --git a/deploy/charts/backend/README.md.gotmpl b/deploy/charts/backend/README.md.gotmpl deleted file mode 100644 index abf817895..000000000 --- a/deploy/charts/backend/README.md.gotmpl +++ /dev/null @@ -1,25 +0,0 @@ -{{ template "chart.header" . }} - -{{ template "chart.description" . }} - -{{ template "chart.versionBadge" . }}{{ template "chart.typeBadge" . }}{{ template "chart.appVersionBadge" . }} - -## Installation - -```bash -helm install kube-bind-backend oci://ghcr.io/kbind-dev/charts/backend --version -``` - -## Configuration - -See [values.yaml](values.yaml) for the full list of configurable parameters. - -{{ template "chart.requirementsSection" . }} - -{{ template "chart.valuesSection" . }} - -{{ template "chart.maintainersSection" . }} - ---- - -*This README is generated by [helm-docs](https://github.com/norwoodj/helm-docs). Do not edit manually.* diff --git a/deploy/charts/backend/crds/kube-bind.io_apiservicebindingbundles.yaml b/deploy/charts/backend/crds/kube-bind.io_apiservicebindingbundles.yaml deleted file mode 100644 index 849902618..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiservicebindingbundles.yaml +++ /dev/null @@ -1,149 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicebindingbundles.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceBindingBundle - listKind: APIServiceBindingBundleList - plural: apiservicebindingbundles - shortNames: - - sbb - singular: apiservicebindingbundle - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceBindingBundle automatically binds multiple API services represented by - APIServiceExports in a service provider cluster into a consumer cluster. This object lives in consumer clusters, - and pulls in all API services defined in the provider clusters, based on the kubeconfig secret provided. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBindingBundle. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_apiservicebindings.yaml b/deploy/charts/backend/crds/kube-bind.io_apiservicebindings.yaml deleted file mode 100644 index c443447f3..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiservicebindings.yaml +++ /dev/null @@ -1,463 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicebindings.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceBinding - listKind: APIServiceBindingList - plural: apiservicebindings - shortNames: - - sb - singular: apiservicebinding - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceBinding binds an API service represented by a APIServiceExport - in a service provider cluster into a consumer cluster. This object lives in - the consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. Must be "kubeconfig". - enum: - - kubeconfig - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBinding. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different APIServiceBindings. - type: string - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceBinding binds an API service represented by a APIServiceExport - in a service provider cluster into a consumer cluster. This object lives in - the consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - boundSchemas: - description: |- - BoundSchemas contains references to all BoundAPIResourceSchema objects - associated with this APIServiceBinding, tracking consumer usage status. - items: - description: BoundSchemaReference contains a reference to a BoundAPIResourceSchema - with status information. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - required: - - resource - type: object - minItems: 1 - type: array - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBinding. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different APIServiceBindings. - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_apiserviceexportrequests.yaml b/deploy/charts/backend/crds/kube-bind.io_apiserviceexportrequests.yaml deleted file mode 100644 index d5d06e244..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiserviceexportrequests.yaml +++ /dev/null @@ -1,516 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexportrequests.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceExportRequest - listKind: APIServiceExportRequestList - plural: apiserviceexportrequests - singular: apiserviceexportrequest - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. - - The service provider can prune these objects after some time. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - parameters: - description: |- - parameters holds service provider specific parameters for this binding - request. - type: object - x-kubernetes-preserve-unknown-fields: true - x-kubernetes-validations: - - message: parameters are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - required: - - resources - type: object - status: - default: {} - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - phase: - default: Pending - description: |- - phase is the current phase of the binding request. It starts in Pending - and transitions to Succeeded or Failed. See the condition for detailed - information. - enum: - - Pending - - Failed - - Succeeded - type: string - terminalMessage: - description: |- - terminalMessage is a human readable message that describes the reason - for the current phase. - type: string - type: object - required: - - spec - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. - - The service provider can prune these objects after some time. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - namespaces: - description: |- - namespaces specifies the namespaces to bootstrap as part of this request. - When objects originate from provider side, the consumer does not always know the necessary details. - This field allows provider to pre-heat the necessary namespaces on provider side by creating - APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - items: - properties: - name: - description: name is the name of the namespace to create on - provider side. - type: string - required: - - name - type: object - type: array - x-kubernetes-validations: - - message: namespaces are immutable - rule: self == oldSelf - parameters: - description: |- - parameters holds service provider specific parameters for this binding - request. - type: object - x-kubernetes-preserve-unknown-fields: true - x-kubernetes-validations: - - message: parameters are immutable - rule: self == oldSelf - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - x-kubernetes-validations: - - message: permissionClaims are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - schemaUpdatePolicy: - default: Never - description: |- - schemaUpdatePolicy defines how BoundSchemas should be updated when the source schema changes. - This is propagated from the APIServiceExportTemplate. - Never means schemas are immutable after creation. - Always means schemas are updated when the source content changes. - enum: - - Never - - Always - type: string - x-kubernetes-validations: - - message: schemaUpdatePolicy is immutable - rule: self == oldSelf - required: - - resources - type: object - status: - default: {} - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - phase: - default: Pending - description: |- - phase is the current phase of the binding request. It starts in Pending - and transitions to Succeeded or Failed. See the condition for detailed - information. - enum: - - Pending - - Failed - - Succeeded - type: string - terminalMessage: - description: |- - terminalMessage is a human readable message that describes the reason - for the current phase. - type: string - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_apiserviceexports.yaml b/deploy/charts/backend/crds/kube-bind.io_apiserviceexports.yaml deleted file mode 100644 index 10f802367..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiserviceexports.yaml +++ /dev/null @@ -1,752 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexports.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceExport - listKind: APIServiceExportList - plural: apiserviceexports - singular: apiserviceexport - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Established")].status - name: Established - priority: 5 - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceExport specifies the resource to be exported. It is mostly a CRD: - - the spec is a CRD spec, but without webhooks - - the status reflects that on the consumer cluster - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the resource. - properties: - clusterScopedIsolation: - description: |- - ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - It can be "Prefixed", "Namespaced", or "None". - enum: - - Prefixed - - Namespaced - - None - type: string - group: - description: "group is the API group of the defined custom resource. - Empty string means the\ncore API group. \tThe resources are served - under `/apis//...` or `/api` for the core group." - type: string - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIServiceExportVersion describes one API version of - a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - properties: - openAPIV3Schema: - description: openAPIV3Schema is the OpenAPI v3 schema to - use for validation and pruning. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - required: - - openAPIV3Schema - type: object - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should - serve a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - x-kubernetes-validations: - - message: informerScope must be Cluster for cluster-scoped resources - rule: self.scope == "Namespaced" || self.informerScope == "Cluster" - - message: clusterScopedIsolation must be defined for cluster-scoped resources - rule: self.scope == "Namespaced" || has(self.clusterScopedIsolation) - - message: clusterScopedIsolation is not relevant for namespaced resources - rule: self.scope == "Cluster" || !has(self.clusterScopedIsolation) - status: - description: status contains reconciliation information for the resource. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: informerScope is immutable - rule: self.metadata.name == self.spec.names.plural+"."+self.spec.group - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Established")].status - name: Established - priority: 5 - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExport specifies the resource to be exported. It is mostly a CRD: - - the spec is a CRD spec, but without webhooks - - the status reflects that on the consumer cluster - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the resource. - properties: - clusterScopedIsolation: - description: |- - ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - It can be "Prefixed", "Namespaced", or "None". - - Deprecated: ClusterScopedIsolation is deprecated, use Isolation instead. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: clusterScopedIsolation is immutable - rule: self == oldSelf - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - isolation: - description: Isolation specifies how service objects are isolated - between multiple consumers on the provider side. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: isolation is immutable - rule: self == oldSelf - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - x-kubernetes-validations: - - message: permissionClaims are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - required: - - informerScope - - isolation - - resources - type: object - status: - description: status contains reconciliation information for the resource. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_apiserviceexporttemplates.yaml b/deploy/charts/backend/crds/kube-bind.io_apiserviceexporttemplates.yaml deleted file mode 100644 index 2d254f037..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiserviceexporttemplates.yaml +++ /dev/null @@ -1,337 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexporttemplates.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: APIServiceExportTemplate - listKind: APIServiceExportTemplateList - plural: apiserviceexporttemplates - singular: apiserviceexporttemplate - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.resources[*].group - name: Resources - type: string - - jsonPath: .spec.permissionClaims[*].resource - name: PermissionClaims - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExportTemplate groups multiple CRDs with related resources (permissionClaims) as a Service definition. - It is used by a web UI or CLI to allow users to select a set of resources to export from provider cluster to consumer cluster. - This object is considered a static asset on the provider side and is not expected to change frequently. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the template. - properties: - description: - description: description is an optional description of the template. - type: string - namespaces: - description: |- - Namespaces specifies the namespaces that should be bootstrapped as part of this template. - When objects originate from provider side, consumer does not always know the necessary details - This field allows provider to pre-heat the necessary namespaces on provider side by creating - APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - items: - properties: - name: - description: name is the name of the namespace to create on - provider side. - type: string - required: - - name - type: object - type: array - permissionClaims: - description: permissionClaims defines the permission claims required - by this template. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - resources: - description: resources defines the CRDs that are part of this template. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - schemaUpdatePolicy: - default: Never - description: |- - SchemaUpdatePolicy defines how BoundSchemas should be updated. - Never means schemas are immutable after creation. - Always means schemas are updated when the source content changes. - Default: Never - - NOTE: This field is intentionally mutable on the template so that providers - can change the default for future binding requests. Already-created - APIServiceExportRequests use CEL validation (self == oldSelf) to lock in - the policy chosen at binding time. - enum: - - Never - - Always - type: string - scope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Namespaced - - Cluster - description: scope defines the scope of the resources in this template. - type: string - required: - - resources - - scope - type: object - status: - description: status contains reconciliation information for the template. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceExportTemplate. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_apiservicenamespaces.yaml b/deploy/charts/backend/crds/kube-bind.io_apiservicenamespaces.yaml deleted file mode 100644 index 1f84ff597..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_apiservicenamespaces.yaml +++ /dev/null @@ -1,124 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicenamespaces.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceNamespace - listKind: APIServiceNamespaceList - plural: apiservicenamespaces - singular: apiservicenamespace - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service - namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service - namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_bindableresourcesrequests.yaml b/deploy/charts/backend/crds/kube-bind.io_bindableresourcesrequests.yaml deleted file mode 100644 index b628ca26e..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_bindableresourcesrequests.yaml +++ /dev/null @@ -1,224 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: bindableresourcesrequests.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BindableResourcesRequest - listKind: BindableResourcesRequestList - plural: bindableresourcesrequests - singular: bindableresourcesrequest - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .spec.templateRef.name - name: Template - type: string - - jsonPath: .status.phase - name: Phase - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - BindableResourcesRequest is sent by the consumer to the service provider - to indicate which resources the user wants to bind to. It can be sent via - the HTTP API after authentication, or created directly as a CRD when the - backend is running without the HTTP API/OIDC flow (frontend disabled mode). - - When created as a CRD, a controller will process the request and create the - necessary APIServiceExport and related resources. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the binding request details. - properties: - author: - description: |- - Author is the identifier of the entity that created this binding request. - This is used for audit purposes and to track who initiated the binding. - type: string - clusterIdentity: - description: |- - ClusterIdentity contains information that uniquely identifies the cluster. - This is used when the request is made via the HTTP API after authentication. - properties: - identity: - description: Identity is the unique identifier of the cluster. - type: string - prettyName: - description: |- - PrettyName is a human-readable name for the cluster, used for display - purposes. If not provided, the controller defaults it to the request name. - type: string - type: object - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to an existing secret where the binding response - will be stored. If specified, the controller will update this secret with the - binding response data. If not specified, a new secret will be created with - the name "-binding-response". - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - templateRef: - description: TemplateRef specifies the APIServiceExportTemplate to - bind to. - properties: - name: - description: name is the name of the APIServiceExportTemplate - to bind to. - type: string - required: - - name - type: object - ttlAfterFinished: - description: |- - ttlAfterFinished is the TTL after the request has succeeded or failed - before it is automatically deleted. If not set, the request will not be - automatically deleted. Example values: "1h", "30m", "300s". - type: string - required: - - author - - clusterIdentity - type: object - status: - default: {} - description: status contains reconciliation information for the binding - request. - properties: - completionTime: - description: |- - completionTime is the time when the request finished processing (succeeded or failed). - Used for TTL-based cleanup. - format: date-time - type: string - conditions: - description: conditions contains the current conditions of the binding - request. - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to a secret containing the kubeconfig, used - to be used by the konnector agent. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - namespace: - description: |- - namespace is the namespace assigned to this binding request on the service provider cluster. - This is where the resources for this binding are created and managed. - type: string - phase: - default: Pending - description: phase is the current phase of the binding request. - enum: - - Pending - - Failed - - Succeeded - type: string - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_boundschemas.yaml b/deploy/charts/backend/crds/kube-bind.io_boundschemas.yaml deleted file mode 100644 index 80e87a042..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_boundschemas.yaml +++ /dev/null @@ -1,468 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: boundschemas.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BoundSchema - listKind: BoundSchemaList - plural: boundschemas - shortNames: - - bs - singular: boundschema - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - BoundSchema defines the schema of a bound API resource. It is created on the provider side to track - CRD status on the consumer side by reflecting the CRD spec and status conditions. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: BoundSchemaSpec defines the desired state of the BoundSchema. - properties: - conversion: - description: conversion defines conversion settings for the defined - custom resource. - properties: - strategy: - description: |- - strategy specifies how custom resources are converted between versions. Allowed values are: - - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information - is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. - enum: - - None - - Webhook - type: string - webhook: - description: webhook describes how to call the conversion webhook. - Required when `strategy` is set to `"Webhook"`. - properties: - clientConfig: - description: clientConfig is the instructions for how to call - the webhook if strategy is `Webhook`. - properties: - caBundle: - description: |- - caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. - If unspecified, system trust roots on the apiserver are used. - format: byte - type: string - url: - description: |- - url gives the location of the webhook, in standard URL form - (`scheme://host:port/path`). - - Please note that using `localhost` or `127.0.0.1` as a `host` is - risky unless you take great care to run this webhook on all hosts - which run an apiserver which might need to make calls to this - webhook. Such installs are likely to be non-portable, i.e., not easy - to turn up in a new cluster. - - The scheme must be "https"; the URL must begin with "https://". - - A path is optional, and if present may be any string permissible in - a URL. You may use the path to pass an arbitrary string to the - webhook, for example, a cluster identifier. - - Attempting to use a user or basic auth e.g. "user:password@" is not - allowed. Fragments ("#...") and query parameters ("?...") are not - allowed, either. - format: uri - type: string - type: object - conversionReviewVersions: - description: |- - conversionReviewVersions is an ordered list of preferred `ConversionReview` - versions the Webhook expects. The API server will use the first version in - the list which it supports. If none of the versions specified in this list - are supported by API server, conversion will fail for the custom resource. - If a persisted Webhook configuration specifies allowed versions and does not - include any versions known to the API Server, calls to the webhook will fail. - items: - type: string - type: array - x-kubernetes-list-type: atomic - type: object - type: object - x-kubernetes-validations: - - message: Webhook must be specified if strategy=Webhook - rule: (self.strategy == 'None' && !has(self.webhook)) || (self.strategy - == 'Webhook' && has(self.webhook)) - group: - description: "group is the API group of the defined custom resource. - Empty string means the\ncore API group. \tThe resources are served - under `/apis//...` or `/api` for the core group." - type: string - informerScope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Cluster - - Namespaced - description: |- - InformerScope indicates whether the informer for defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - type: string - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIResourceVersion describes one API version of a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should - serve a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - status: - description: BoundSchemaStatus defines the observed state of the BoundSchema. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: Conditions represent the latest available observations - of the object's state. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - instantiations: - description: Instantiations tracks the number of instances of the - resource on the consumer side. - type: integer - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_clusterbindings.yaml b/deploy/charts/backend/crds/kube-bind.io_clusterbindings.yaml deleted file mode 100644 index 6c12f18ab..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_clusterbindings.yaml +++ /dev/null @@ -1,345 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: clusterbindings.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: ClusterBinding - listKind: ClusterBindingList - plural: clusterbindings - singular: clusterbinding - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service provider cluster - and is a singleton named "cluster". - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. Must be "kubeconfig". - enum: - - kubeconfig - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service - provider cluster and is a singleton named "cluster" per namespace. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - consumerSecretRef: - description: |- - consumerSecretRef is the reference to the secret in the consumer cluster - that contains the kubeconfig for connecting to the service provider. - properties: - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - name - - namespace - type: object - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_clusters.yaml b/deploy/charts/backend/crds/kube-bind.io_clusters.yaml deleted file mode 100644 index 7dba0d0e9..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_clusters.yaml +++ /dev/null @@ -1,106 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: clusters.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Cluster - listKind: ClusterList - plural: clusters - singular: cluster - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - name: v1alpha2 - schema: - openAPIV3Schema: - description: Cluster represents a cluster, managed by kube-bind. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/crds/kube-bind.io_collections.yaml b/deploy/charts/backend/crds/kube-bind.io_collections.yaml deleted file mode 100644 index 1b262685d..000000000 --- a/deploy/charts/backend/crds/kube-bind.io_collections.yaml +++ /dev/null @@ -1,133 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: collections.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Collection - listKind: CollectionList - plural: collections - singular: collection - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.description - name: Description - type: string - - jsonPath: .spec.templates[*].name - name: Templates - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - Collection groups multiple APIServiceExportTemplates into a logical group. This functions as a grouping mechanism - in UIs or CLIs to allow users to select a set of resources to export from provider cluster to consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the collection. - properties: - description: - description: description is a human readable description of this collection. - type: string - templates: - description: templates is a list of template references that are part - of this collection. - items: - description: APIServiceExportTemplateReference references an APIServiceExportTemplate - by name. - properties: - name: - description: name is the name of the template. - type: string - required: - - name - type: object - minItems: 1 - type: array - required: - - templates - type: object - status: - description: status contains reconciliation information for the collection. - properties: - conditions: - description: conditions is a list of conditions that apply to the - Collection. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/charts/backend/examples/values-local-development.yaml b/deploy/charts/backend/examples/values-local-development.yaml deleted file mode 100644 index e657ad1c0..000000000 --- a/deploy/charts/backend/examples/values-local-development.yaml +++ /dev/null @@ -1,64 +0,0 @@ -# Local development values for kube-bind backend -# This is a YAML-formatted file with common configuration for local development - -# Image configuration -image: - pullPolicy: IfNotPresent - -# Backend configuration -backend: - listenAddress: "0.0.0.0:8443" - # OIDC configuration - oidc: - type: "external" - issuerUrl: "https://auth.genericcontrolplane.io" - clientId: "kube-bind" - clientSecret: "### REPLACE_ME ###" - callbackUrl: "https://kube-bind.genericcontrolplane.io/callback" - # Example allowed groups and users for external OIDC - allowedGroups: - - "kube-bind-users" - - "admins" - allowedUsers: - - "user@example.com" - - # Cookie encryption keys (generate your own for production!) - # example: openssl rand -base64 32 - cookieSigningKey: "### REPLACE_ME ###" - cookieEncryptionKey: "### REPLACE_ME ###" - - tls: - enabled: true - certSecretName: backend-tls-cert - tlsCertFile: /etc/kube-bind/tls/tls.crt - tlsKeyFile: /etc/kube-bind/tls/tls.key - -# Cert-manager configuration -certManager: - enabled: true - clusterIssuer: letsencrypt-prod - -# RBAC configuration -rbac: - create: true - -# Service account configuration -serviceAccount: - create: true - automount: true - -service: - type: LoadBalancer - port: 8080 - httpsPort: 443 - -livenessProbe: - httpGet: - path: /healthz - port: https - scheme: HTTPS -readinessProbe: - httpGet: - path: /healthz - port: https - scheme: HTTPS \ No newline at end of file diff --git a/deploy/charts/backend/templates/clusterrolebinding.yaml b/deploy/charts/backend/templates/clusterrolebinding.yaml deleted file mode 100644 index 11d3e5b26..000000000 --- a/deploy/charts/backend/templates/clusterrolebinding.yaml +++ /dev/null @@ -1,16 +0,0 @@ -{{- if .Values.rbac.create -}} -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: {{ include "kube-bind.fullname" . }}-manager - labels: - {{- include "kube-bind.labels" . | nindent 4 }} -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: kube-bind-role -subjects: -- kind: ServiceAccount - name: {{ include "kube-bind.serviceAccountName" . }} - namespace: {{ .Release.Namespace }} -{{- end }} \ No newline at end of file diff --git a/deploy/charts/backend/templates/deployment.yaml b/deploy/charts/backend/templates/deployment.yaml deleted file mode 100644 index 084403146..000000000 --- a/deploy/charts/backend/templates/deployment.yaml +++ /dev/null @@ -1,204 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: {{ include "kube-bind.fullname" . }} - labels: - {{- include "kube-bind.labels" . | nindent 4 }} -spec: - {{- if not .Values.autoscaling.enabled }} - replicas: {{ .Values.replicaCount }} - {{- end }} - selector: - matchLabels: - {{- include "kube-bind.selectorLabels" . | nindent 6 }} - template: - metadata: - {{- with .Values.podAnnotations }} - annotations: - {{- toYaml . | nindent 8 }} - {{- end }} - labels: - {{- include "kube-bind.labels" . | nindent 8 }} - {{- with .Values.podLabels }} - {{- toYaml . | nindent 8 }} - {{- end }} - spec: - {{- with .Values.imagePullSecrets }} - imagePullSecrets: - {{- toYaml . | nindent 8 }} - {{- end }} - serviceAccountName: {{ include "kube-bind.serviceAccountName" . }} - {{- with .Values.podSecurityContext }} - securityContext: - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .Values.hostAliases }} - hostAliases: - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .Values.initContainers }} - initContainers: - {{- toYaml . | nindent 8 }} - {{- end }} - containers: - - name: {{ .Chart.Name }} - {{- with .Values.securityContext }} - securityContext: - {{- toYaml . | nindent 12 }} - {{- end }} - image: "{{ .Values.backend.image.repository }}:{{ .Values.backend.image.tag | default .Chart.AppVersion }}" - imagePullPolicy: {{ .Values.backend.image.pullPolicy }} - env: - {{- if .Values.backend.oidc.clientSecretName }} - - name: OIDC_CLIENT_SECRET - valueFrom: - secretKeyRef: - name: {{ .Values.backend.oidc.clientSecretName }} - key: {{ .Values.backend.oidc.clientSecretKey }} - {{- end }} - {{- if .Values.backend.sessionStorage.redisPassword }} - - name: REDIS_PASSWORD - value: {{ .Values.backend.sessionStorage.redisPassword }} - {{- end }} - args: - - --listen-address={{ .Values.backend.listenAddress }} - {{- if .Values.backend.kubeconfig }} - - --kubeconfig={{ .Values.backend.kubeconfig }} - {{- end }} - {{- if .Values.backend.context }} - - --context={{ .Values.backend.context }} - {{- end }} - {{- if .Values.backend.logLevel }} - - --log-level={{ .Values.backend.logLevel }} - {{- end }} - {{- if .Values.backend.externalAddress }} - - --external-address={{ .Values.backend.externalAddress }} - {{- end }} - {{- if .Values.backend.externalServerName }} - - --external-server-name={{ .Values.backend.externalServerName }} - {{- end }} - {{- if .Values.backend.oidc.issuerUrl }} - - --oidc-issuer-url={{ .Values.backend.oidc.issuerUrl }} - {{- end }} - {{- if .Values.backend.oidc.clientId }} - - --oidc-issuer-client-id={{ .Values.backend.oidc.clientId }} - {{- end }} - {{- if .Values.backend.oidc.clientSecret }} - - --oidc-issuer-client-secret={{ .Values.backend.oidc.clientSecret }} - {{- end }} - {{- if .Values.backend.oidc.callbackUrl }} - - --oidc-callback-url={{ .Values.backend.oidc.callbackUrl }} - {{- end }} - {{- if .Values.backend.prettyName }} - - --pretty-name={{ .Values.backend.prettyName }} - {{- end }} - {{- if .Values.backend.namespacePrefix }} - - --namespace-prefix={{ .Values.backend.namespacePrefix }} - {{- end }} - {{- if .Values.backend.consumerScope }} - - --consumer-scope={{ .Values.backend.consumerScope }} - {{- end }} - {{- if .Values.backend.isolation }} - - --isolation={{ .Values.backend.isolation }} - {{- end }} - {{- if .Values.backend.cookieSigningKey }} - - --cookie-signing-key={{ .Values.backend.cookieSigningKey }} - {{- end }} - {{- if .Values.backend.cookieEncryptionKey }} - - --cookie-encryption-key={{ .Values.backend.cookieEncryptionKey }} - {{- end }} - {{- if .Values.backend.sessionStorage.redisAddress }} - - --redis-addr={{ .Values.backend.sessionStorage.redisAddress }} - {{- end }} - {{- if .Values.backend.tls.enabled }} - - --tls-cert-file={{ .Values.backend.tls.tlsCertFile }} - - --tls-key-file={{ .Values.backend.tls.tlsKeyFile }} - {{- end }} - {{- if eq .Values.backend.oidc.type "embedded" }} - - --oidc-type=embedded - {{- else if eq .Values.backend.oidc.type "external" }} - - --oidc-type=external - {{- end }} - {{- if .Values.backend.oidc.allowedGroups }} - {{- range .Values.backend.oidc.allowedGroups }} - - --oidc-allowed-groups={{ . }} - {{- end }} - {{- end }} - {{- if .Values.backend.oidc.allowedUsers }} - {{- range .Values.backend.oidc.allowedUsers }} - - --oidc-allowed-users={{ . }} - {{- end }} - {{- end }} - {{- if .Values.backend.multiclusterRuntimeProvider }} - - --multicluster-runtime-provider={{ .Values.backend.multiclusterRuntimeProvider }} - {{- end }} - {{- if .Values.backend.schemaSource }} - - --schema-source={{ .Values.backend.schemaSource }} - {{- end }} - {{- if .Values.backend.apiexportEndpointSliceName }} - - --apiexport-endpoint-slice-name={{ .Values.backend.apiexportEndpointSliceName }} - {{- end }} - {{- if .Values.backend.frontendDisabled }} - - --frontend-disabled=true - {{- end }} - {{- range .Values.backend.apibindingIgnorePrefixes }} - - --apibinding-ignore-prefixes={{ . }} - {{- end }} - {{- range .Values.backend.extraArgs }} - - {{ . }} - {{- end }} - {{- if .Values.backend.loggingLevel }} - - -v={{ .Values.backend.loggingLevel }} - {{- end }} - ports: - {{- if .Values.backend.tls.enabled }} - - name: https - containerPort: 8443 - protocol: TCP - {{- else }} - - name: http - containerPort: 8080 - protocol: TCP - {{- end }} - {{- with .Values.livenessProbe }} - livenessProbe: - {{- toYaml . | nindent 12 }} - {{- end }} - {{- with .Values.readinessProbe }} - readinessProbe: - {{- toYaml . | nindent 12 }} - {{- end }} - {{- with .Values.resources }} - resources: - {{- toYaml . | nindent 12 }} - {{- end }} - volumeMounts: - {{- if .Values.backend.tls.enabled }} - - name: tls-certs - mountPath: /etc/kube-bind/tls - readOnly: true - {{- end }} - {{- with .Values.volumeMounts }} - {{- toYaml . | nindent 12 }} - {{- end }} - volumes: - {{- if .Values.backend.tls.enabled }} - - name: tls-certs - secret: - secretName: {{ .Values.backend.tls.certSecretName }} - {{- end }} - {{- with .Values.volumes }} - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .Values.nodeSelector }} - nodeSelector: - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .Values.affinity }} - affinity: - {{- toYaml . | nindent 8 }} - {{- end }} - {{- with .Values.tolerations }} - tolerations: - {{- toYaml . | nindent 8 }} - {{- end }} diff --git a/deploy/charts/backend/templates/example.yaml b/deploy/charts/backend/templates/example.yaml deleted file mode 100644 index db627d6e4..000000000 --- a/deploy/charts/backend/templates/example.yaml +++ /dev/null @@ -1,67 +0,0 @@ -{{- if .Values.examples.enabled }} ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - name: mangodbs.mangodb.com - labels: - kube-bind.io/exported: "true" -spec: - group: mangodb.com - names: - kind: MangoDB - listKind: MangoDBList - plural: mangodbs - singular: mangodb - scope: Namespaced - versions: - - name: v1alpha1 - served: true - storage: true - schema: - openAPIV3Schema: - type: object - properties: - spec: - type: object - properties: - tier: - type: string - enum: - - Dedicated - - Shared - default: Shared - status: - type: object - properties: - phase: - type: string - required: - - spec - subresources: - status: {} ---- -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExportTemplate -metadata: - name: mangodb -spec: - scope: Namespaced - resources: - - group: mangodb.com - versions: - - v1alpha1 - resource: mangodbs - permissionClaims: - - group: "" - resource: "secrets" - selector: - labelSelector: - matchLabels: - app: "mangodb" - namedResources: - - name: "mangodb-credentials" - namespace: "mangodb-namespace" - namespaces: - - name: mangodb-namespace -{{- end }} \ No newline at end of file diff --git a/deploy/charts/backend/templates/gateway-api.yaml b/deploy/charts/backend/templates/gateway-api.yaml deleted file mode 100644 index 187ddb888..000000000 --- a/deploy/charts/backend/templates/gateway-api.yaml +++ /dev/null @@ -1,88 +0,0 @@ -{{- if .Values.gatewayApi.enabled }} -{{- if .Values.certManager.enabled }} -apiVersion: cert-manager.io/v1 -kind: Certificate -metadata: - name: {{ include "kube-bind.fullname" . }}-tls - labels: - {{- include "kube-bind.labels" . | nindent 4 }} -spec: - secretName: {{ include "kube-bind.fullname" . }}-tls - issuerRef: - name: {{ .Values.certManager.clusterIssuer }} - kind: ClusterIssuer - {{- if .Values.gatewayApi.route.hostnames }} - dnsNames: - {{- range .Values.gatewayApi.route.hostnames }} - - {{ . }} - {{- end }} - {{- end }} ---- -{{- end }} -apiVersion: gateway.networking.k8s.io/v1 -kind: Gateway -metadata: - name: {{ include "kube-bind.fullname" . }}-gateway - labels: - {{- include "kube-bind.labels" . | nindent 4 }} - {{- with .Values.gatewayApi.gateway.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - gatewayClassName: {{ .Values.gatewayApi.gateway.className }} - listeners: - - name: https - protocol: HTTPS - port: {{ .Values.gatewayApi.gateway.httpsPort | default 443 }} - tls: - mode: Terminate - certificateRefs: - {{- if .Values.certManager.enabled }} - - name: {{ include "kube-bind.fullname" . }}-tls - {{- else if .Values.gatewayApi.gateway.tls.certificateRefs }} - {{- range .Values.gatewayApi.gateway.tls.certificateRefs }} - - name: {{ .name }} - {{- if .namespace }} - namespace: {{ .namespace }} - {{- end }} - {{- if .group }} - group: {{ .group }} - {{- end }} - {{- if .kind }} - kind: {{ .kind }} - {{- end }} - {{- end }} - {{- end }} - - name: http - protocol: HTTP - port: {{ .Values.gatewayApi.gateway.httpPort | default 80 }} ---- -apiVersion: gateway.networking.k8s.io/v1 -kind: HTTPRoute -metadata: - name: {{ include "kube-bind.fullname" . }}-route - labels: - {{- include "kube-bind.labels" . | nindent 4 }} - {{- with .Values.gatewayApi.route.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - parentRefs: - - name: {{ include "kube-bind.fullname" . }}-gateway - {{- if .Values.gatewayApi.route.hostnames }} - hostnames: - {{- range .Values.gatewayApi.route.hostnames }} - - {{ . | quote }} - {{- end }} - {{- end }} - rules: - - matches: - - path: - type: {{ .Values.gatewayApi.route.pathType | default "PathPrefix" }} - value: {{ .Values.gatewayApi.route.path | default "/" }} - backendRefs: - - name: {{ include "kube-bind.fullname" . }} - port: {{ .Values.service.port }} -{{- end }} \ No newline at end of file diff --git a/deploy/charts/backend/templates/hpa.yaml b/deploy/charts/backend/templates/hpa.yaml deleted file mode 100644 index 9eb020211..000000000 --- a/deploy/charts/backend/templates/hpa.yaml +++ /dev/null @@ -1,32 +0,0 @@ -{{- if .Values.autoscaling.enabled }} -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: {{ include "kube-bind.fullname" . }} - labels: - {{- include "kube-bind.labels" . | nindent 4 }} -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: {{ include "kube-bind.fullname" . }} - minReplicas: {{ .Values.autoscaling.minReplicas }} - maxReplicas: {{ .Values.autoscaling.maxReplicas }} - metrics: - {{- if .Values.autoscaling.targetCPUUtilizationPercentage }} - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} - {{- end }} - {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }} - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }} - {{- end }} -{{- end }} diff --git a/deploy/charts/backend/templates/role.yaml b/deploy/charts/backend/templates/role.yaml deleted file mode 100644 index 635ebfcec..000000000 --- a/deploy/charts/backend/templates/role.yaml +++ /dev/null @@ -1,116 +0,0 @@ ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRole -metadata: - name: kube-bind-role -rules: -- apiGroups: - - "" - resources: - - configmaps - - secrets - verbs: - - '*' -- apiGroups: - - "" - resources: - - namespaces - - serviceaccounts - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - '*' - resources: - - '*' - verbs: - - '*' -- apiGroups: - - apiextensions.k8s.io - resources: - - customresourcedefinitions - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - kube-bind.io - resources: - - apiresourceschemas - - apiserviceexportrequests - - apiserviceexports - - apiservicenamespaces - - bindableresourcesrequests - - boundschemas - - clusterbindings - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - kube-bind.io - resources: - - apiserviceexportrequests/finalizers - - apiserviceexports/finalizers - - apiservicenamespaces/finalizers - - bindableresourcesrequests/finalizers - - clusterbindings/finalizers - verbs: - - update -- apiGroups: - - kube-bind.io - resources: - - apiserviceexportrequests/status - - apiserviceexports/status - - apiservicenamespaces/status - - bindableresourcesrequests/status - - clusterbindings/status - verbs: - - get - - patch - - update -- apiGroups: - - kube-bind.io - resources: - - apiserviceexporttemplates - - collections - verbs: - - get - - list - - watch -- apiGroups: - - kube-bind.io - resources: - - boundschemas/status - verbs: - - get - - list - - patch - - update -- apiGroups: - - rbac.authorization.k8s.io - resources: - - clusterrolebindings - - clusterroles - - rolebindings - verbs: - - create - - delete - - get - - list - - patch - - update - - watch diff --git a/deploy/charts/backend/templates/service.yaml b/deploy/charts/backend/templates/service.yaml deleted file mode 100644 index b30d7355b..000000000 --- a/deploy/charts/backend/templates/service.yaml +++ /dev/null @@ -1,28 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: {{ include "kube-bind.fullname" . }} - labels: - {{- include "kube-bind.labels" . | nindent 4 }} -spec: - type: {{ .Values.service.type }} - ports: - {{- if .Values.backend.tls.enabled }} - - port: {{ .Values.service.httpsPort | default 8443 }} - targetPort: https - protocol: TCP - name: https - {{- if and (eq .Values.service.type "NodePort") .Values.service.httpsNodePort }} - nodePort: {{ .Values.service.httpsNodePort }} - {{- end }} - {{- else }} - - port: {{ .Values.service.port }} - targetPort: http - protocol: TCP - name: http - {{- if and (eq .Values.service.type "NodePort") .Values.service.nodePort }} - nodePort: {{ .Values.service.nodePort }} - {{- end }} - {{- end }} - selector: - {{- include "kube-bind.selectorLabels" . | nindent 4 }} diff --git a/deploy/charts/backend/templates/serviceaccount.yaml b/deploy/charts/backend/templates/serviceaccount.yaml deleted file mode 100644 index 86e6fb813..000000000 --- a/deploy/charts/backend/templates/serviceaccount.yaml +++ /dev/null @@ -1,13 +0,0 @@ -{{- if .Values.serviceAccount.create -}} -apiVersion: v1 -kind: ServiceAccount -metadata: - name: {{ include "kube-bind.serviceAccountName" . }} - labels: - {{- include "kube-bind.labels" . | nindent 4 }} - {{- with .Values.serviceAccount.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -automountServiceAccountToken: {{ .Values.serviceAccount.automount }} -{{- end }} diff --git a/deploy/charts/backend/templates/tests/test-connection.yaml b/deploy/charts/backend/templates/tests/test-connection.yaml deleted file mode 100644 index ea7ec43de..000000000 --- a/deploy/charts/backend/templates/tests/test-connection.yaml +++ /dev/null @@ -1,15 +0,0 @@ -apiVersion: v1 -kind: Pod -metadata: - name: "{{ include "kube-bind.fullname" . }}-test-connection" - labels: - {{- include "kube-bind.labels" . | nindent 4 }} - annotations: - "helm.sh/hook": test -spec: - containers: - - name: wget - image: busybox - command: ['wget'] - args: ['{{ include "kube-bind.fullname" . }}:{{ .Values.service.port }}'] - restartPolicy: Never diff --git a/deploy/charts/backend/values.yaml b/deploy/charts/backend/values.yaml deleted file mode 100644 index 0dba4ebe0..000000000 --- a/deploy/charts/backend/values.yaml +++ /dev/null @@ -1,264 +0,0 @@ -# Default values for kube-bind. -# This is a YAML-formatted file. -# Declare variables to be passed into your templates. - -# -- Number of replicas for the backend deployment -replicaCount: 1 - -# Backend configuration -backend: - # Container image configuration - image: - # -- Image repository - repository: ghcr.io/kbind-dev/backend - # -- Image pull policy - pullPolicy: IfNotPresent - # -- Overrides the image tag whose default is the chart appVersion - tag: "" - # -- Address the backend listens on - listenAddress: "0.0.0.0:8080" - # -- Path to a kubeconfig file. Only required if out-of-cluster. - kubeconfig: "" - # -- The name of the kubeconfig context to use - context: "" - # -- External address clients use to reach the backend - externalAddress: "" - # -- External server name for TLS SNI - externalServerName: "" - # -- Logging verbosity level - loggingLevel: 2 - # TLS configuration - tls: - # -- Enable TLS for the backend - enabled: false - # -- Name of the Kubernetes secret containing TLS certificate - certSecretName: "" - # -- Path to TLS certificate file inside the container - tlsCertFile: "/etc/kube-bind/tls/tls.crt" - # -- Path to TLS key file inside the container - tlsKeyFile: "/etc/kube-bind/tls/tls.key" - # OIDC configuration. Empty values will run the embedded OIDC server. - oidc: - # -- OIDC provider type. Options: "embedded" or "external" - type: "embedded" - # -- OIDC issuer URL (leave empty for embedded OIDC server) - issuerUrl: "" - # -- OIDC client ID - clientId: "" - # -- OIDC client secret (plaintext, prefer clientSecretName for production) - # -- Not required for providers using PKCE or public clients - clientSecret: "" - # -- Name of the Kubernetes secret containing the OIDC client secret - # -- If set, the secret will be mounted as OIDC_CLIENT_SECRET env var - clientSecretName: "" - # -- Key within the secret (e.g., "client-secret") - clientSecretKey: "" - # -- OIDC callback URL - callbackUrl: "" - # -- List of groups allowed to access bindings. With embedded OIDC, system:authenticated is added automatically - allowedGroups: [] - # -- List of users allowed to access bindings - allowedUsers: [] - - # -- Human-readable name for this backend instance - prettyName: "" - # -- Prefix for namespaces created by kube-bind - namespacePrefix: "kube-bind-" - # -- Consumer scope. Options: "namespaced" - consumerScope: "namespaced" - # -- Cluster-scope isolation mode. Options: none, prefix, namespaced - clusterScopeIsolation: "prefix" - - # -- Multicluster runtime provider (e.g., "kcp") - multiclusterRuntimeProvider: "" - # -- Schema source (e.g., "apiresourceschemas") - schemaSource: "" - # -- APIExport EndpointSlice name to watch - apiexportEndpointSliceName: "" - # -- Disable the frontend UI - frontendDisabled: false - # -- Name prefixes of APIBindings to ignore when generating APIServiceExportTemplates - apibindingIgnorePrefixes: [] - # -- Extra command-line arguments to pass to the backend - extraArgs: [] - - # Session storage configuration - sessionStorage: - redisAddress: "" - redisPassword: "" - - # Cookie configuration - these should be base64 encoded keys - # -- Cookie signing key (base64 encoded). Empty generates random key on each start (not for production!) - cookieSigningKey: "" - # -- Cookie encryption key (base64 encoded). Empty generates random key on each start (not for production!) - cookieEncryptionKey: "" - -# Cert-manager configuration -certManager: - # -- Enable cert-manager integration for automatic TLS certificates - enabled: false - # -- Name of the ClusterIssuer to use - clusterIssuer: "" - -# Gateway API configuration -gatewayApi: - # -- Enable Gateway API resources - enabled: false - gateway: - # -- Gateway class name - className: "" - # -- HTTP listener port - httpPort: 80 - # -- HTTPS listener port - httpsPort: 443 - # -- Annotations to add to the Gateway resource - annotations: {} - tls: - # -- TLS certificate references for the Gateway - # @default -- `[]` - certificateRefs: [] - # Example: - # - name: tls-cert - # namespace: default - route: - # -- Hostnames for the HTTPRoute - # @default -- `[]` - hostnames: [] - # Example: - # - "example.com" - # - "api.example.com" - # -- Path match for the HTTPRoute - path: "/" - # -- Path match type for the HTTPRoute - pathType: "PathPrefix" - # -- Annotations to add to the HTTPRoute resource - annotations: {} - -examples: - # -- Enable example resources to seed on first start - enabled: false - -# -- Secrets for pulling images from a private repository -imagePullSecrets: [] -# -- Override the chart name -nameOverride: "" -# -- Override the full release name -fullnameOverride: "" - -# Service account configuration -serviceAccount: - # -- Specifies whether a service account should be created - create: true - # -- Automatically mount the ServiceAccount's API credentials - automount: true - # -- Annotations to add to the service account - annotations: {} - # -- The name of the service account to use. If not set and create is true, a name is generated using the fullname template - name: "" - -# RBAC configuration -rbac: - # -- Specifies whether RBAC resources should be created - create: true - -# -- Annotations to add to the pod -podAnnotations: {} -# -- Labels to add to the pod -podLabels: {} - -# -- Pod security context -podSecurityContext: {} - # fsGroup: 2000 - -# -- Host aliases for /etc/hosts injection into pods -# @default -- `[]` -hostAliases: [] -# Example: -# - ip: "127.0.0.1" -# hostnames: -# - "example.local" - -# -- Container security context -securityContext: {} - # capabilities: - # drop: - # - ALL - # readOnlyRootFilesystem: true - # runAsNonRoot: true - # runAsUser: 1000 - -# Service configuration -service: - # -- Service type - type: ClusterIP - # -- HTTP service port - port: 8080 - # -- HTTPS service port - httpsPort: 8443 - # -- NodePort for HTTP (only used when type is NodePort) - nodePort: "" - # -- NodePort for HTTPS (only used when type is NodePort) - httpsNodePort: "" - -# -- Resource requests and limits -resources: {} - # limits: - # cpu: 100m - # memory: 128Mi - # requests: - # cpu: 100m - # memory: 128Mi - -# -- Liveness probe configuration -livenessProbe: - httpGet: - path: /healthz - port: http -# -- Readiness probe configuration -readinessProbe: - httpGet: - path: /healthz - port: http - -# Autoscaling configuration -autoscaling: - # -- Enable horizontal pod autoscaling - enabled: false - # -- Minimum number of replicas - minReplicas: 1 - # -- Maximum number of replicas - maxReplicas: 100 - # -- Target CPU utilization percentage - targetCPUUtilizationPercentage: 80 - # targetMemoryUtilizationPercentage: 80 - -# -- Additional init containers -# @default -- `[]` -initContainers: [] -# - name: init -# image: ghcr.io/platform-mesh/kube-bind-provider-init:latest -# args: ["--kcp-kubeconfig", "/etc/kube-bind/kubeconfig"] - -# -- Additional volumes on the output Deployment definition -# @default -- `[]` -volumes: [] -# - name: foo -# secret: -# secretName: mysecret -# optional: false - -# -- Additional volumeMounts on the output Deployment definition -# @default -- `[]` -volumeMounts: [] -# - name: foo -# mountPath: "/etc/foo" -# readOnly: true - -# -- Node selector for pod scheduling -nodeSelector: {} - -# -- Tolerations for pod scheduling -tolerations: [] - -# -- Affinity rules for pod scheduling -affinity: {} diff --git a/deploy/charts/konnector-v2/.helmignore b/deploy/charts/konnector-v2/.helmignore new file mode 100644 index 000000000..cb365c23b --- /dev/null +++ b/deploy/charts/konnector-v2/.helmignore @@ -0,0 +1,8 @@ +# Patterns to ignore when building Helm packages. +.DS_Store +.git/ +.gitignore +*.tmpl +*.gotmpl +.idea/ +*.tgz diff --git a/deploy/charts/konnector-v2/Chart.yaml b/deploy/charts/konnector-v2/Chart.yaml new file mode 100644 index 000000000..15cf9bf7a --- /dev/null +++ b/deploy/charts/konnector-v2/Chart.yaml @@ -0,0 +1,16 @@ +apiVersion: v2 +name: konnector-v2 +description: kbind v2 slim-core konnector — the consumer-side sync engine. +type: application + +# version / appVersion are placeholders bumped by the release tooling. +version: 0.0.0 +appVersion: "0.0.0" + +home: https://kbind.io +sources: + - https://github.com/kbind/kbind +keywords: + - kbind + - multicluster + - api-binding diff --git a/deploy/charts/konnector-v2/files/crds/core.kbind.io_bindings.yaml b/deploy/charts/konnector-v2/files/crds/core.kbind.io_bindings.yaml new file mode 100644 index 000000000..d935588ab --- /dev/null +++ b/deploy/charts/konnector-v2/files/crds/core.kbind.io_bindings.yaml @@ -0,0 +1,297 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: bindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Binding + listKind: BindingList + plural: bindings + singular: binding + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Binding activates instance sync for one or more exported APIs within its own + namespace. Namespaced, following the Role convention. It is the v2 answer to + v1's informerScope: Namespaced. Where a ClusterBinding and a Binding cover the + same API on the same connection, the ClusterBinding wins. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name, it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict, + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object details are recorded in consumer-object annotations and Events. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/charts/konnector-v2/files/crds/core.kbind.io_clusterbindings.yaml b/deploy/charts/konnector-v2/files/crds/core.kbind.io_clusterbindings.yaml new file mode 100644 index 000000000..bb9561f11 --- /dev/null +++ b/deploy/charts/konnector-v2/files/crds/core.kbind.io_clusterbindings.yaml @@ -0,0 +1,295 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: clusterbindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: ClusterBinding + listKind: ClusterBindingList + plural: clusterbindings + singular: clusterbinding + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClusterBinding activates instance sync for one or more exported APIs + cluster-wide. Cluster-scoped, following the ClusterRole convention. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name, it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict, + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object details are recorded in consumer-object annotations and Events. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/charts/konnector-v2/files/crds/core.kbind.io_connections.yaml b/deploy/charts/konnector-v2/files/crds/core.kbind.io_connections.yaml new file mode 100644 index 000000000..0fe509b8b --- /dev/null +++ b/deploy/charts/konnector-v2/files/crds/core.kbind.io_connections.yaml @@ -0,0 +1,258 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: connections.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Connection + listKind: ConnectionList + plural: connections + singular: connection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .spec.kubeconfigSecretRef.name + name: Secret + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Connection is the link to one provider cluster. It owns the credentials and + schema delivery, and surfaces what the provider exports. Cluster-scoped. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ConnectionSpec defines the desired provider link. + properties: + autoBind: + default: false + description: |- + autoBind, when true, makes the konnector maintain a managed ClusterBinding + (named after this Connection) covering all exported APIs. + type: boolean + kubeconfigSecretRef: + description: |- + kubeconfigSecretRef points at the Secret holding the provider kubeconfig. + Immutable. The only credential reference in the core. + properties: + key: + default: kubeconfig + description: key within the Secret holding the kubeconfig. + type: string + name: + description: name of the Secret. + minLength: 1 + type: string + namespace: + description: namespace of the Secret. + minLength: 1 + type: string + required: + - name + - namespace + type: object + x-kubernetes-validations: + - message: kubeconfigSecretRef is immutable + rule: self == oldSelf + schema: + default: {} + description: schema controls how exported APIs reach the consumer. + properties: + pullPolicy: + default: Bound + description: |- + pullPolicy selects which exported APIs are installed: + Bound - only APIs referenced by a Binding/ClusterBinding (default). + All - every exported API readable by the credentials. + None - never install CRDs (user/extension manages them). + enum: + - Bound + - All + - None + type: string + source: + default: Auto + description: |- + source selects how schemas are obtained: + Auto - CRD if readable on the provider, else OpenAPI (default). + CRD - read apiextensions CRDs verbatim. + OpenAPI - synthesize CRDs from discovery + /openapi/v3. + enum: + - Auto + - CRD + - OpenAPI + type: string + updatePolicy: + default: Always + description: |- + updatePolicy selects whether installed schemas follow provider changes: + Always - follow provider schema changes (default). + Once - pin at first pull. + enum: + - Always + - Once + type: string + type: object + required: + - kubeconfigSecretRef + type: object + status: + description: ConnectionStatus is the observed state of a Connection. + properties: + activeSchemaSource: + description: |- + activeSchemaSource is the schema source actually in effect after resolving + "Auto" (CRD or OpenAPI). The binding uses it to decide whether the + Connection already installed the CRDs (OpenAPI) or it should pull them (CRD). + type: string + conditions: + description: 'conditions: SecretValid, Connected, SchemaInSync, Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + exportedAPIs: + description: 'exportedAPIs is the discovery result: APIs exported + to these credentials.' + items: + description: ExportedAPI describes one API the provider exports + to these credentials. + properties: + group: + description: group of the exported API. + type: string + name: + description: name is the CRD name of the exported API, ".". + type: string + resource: + description: resource is the plural resource name of the exported + API. + type: string + scope: + description: scope is whether the API is Namespaced or Cluster + scoped. + type: string + versions: + description: versions are the served versions of the exported + API. + items: + type: string + type: array + x-kubernetes-list-type: set + required: + - group + - name + - resource + - scope + - versions + type: object + type: array + x-kubernetes-list-type: atomic + localClusterUID: + description: |- + localClusterUID is the identity of the consumer cluster, pinned on first + connect and immutable thereafter. + type: string + x-kubernetes-validations: + - message: localClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + remoteClusterUID: + description: |- + remoteClusterUID is the identity of the provider cluster, pinned on first + connect and immutable thereafter. A Secret later pointing at a different + cluster is rejected rather than silently re-homing synced objects. + type: string + x-kubernetes-validations: + - message: remoteClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/deploy/charts/konnector-v2/templates/NOTES.txt b/deploy/charts/konnector-v2/templates/NOTES.txt new file mode 100644 index 000000000..7244a56f0 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/NOTES.txt @@ -0,0 +1,21 @@ +The kbind konnector is installed as "{{ include "konnector.fullname" . }}" in namespace "{{ .Release.Namespace }}". + +Replicas: {{ .Values.replicaCount }} +Leader election: {{ include "konnector.leaderElect" . }} + +Check it is running: + + kubectl -n {{ .Release.Namespace }} rollout status deploy/{{ include "konnector.fullname" . }} + +Bind a provider API (one apply): create the kubeconfig Secret, a Connection +referencing it, and a ClusterBinding/Binding selecting the exported APIs. See +the konnector/config/samples/ directory for examples. + +{{- if eq (include "konnector.leaderElect" .) "false" }} +{{- if gt (int .Values.replicaCount) 1 }} + +WARNING: replicaCount > 1 with leader election disabled runs multiple active +konnectors against the same cluster, which will fight over the same objects. +Set leaderElect: true (or it is forced on automatically for replicaCount > 1). +{{- end }} +{{- end }} diff --git a/deploy/charts/backend/templates/_helpers.tpl b/deploy/charts/konnector-v2/templates/_helpers.tpl similarity index 51% rename from deploy/charts/backend/templates/_helpers.tpl rename to deploy/charts/konnector-v2/templates/_helpers.tpl index dcd9bc945..f0392e9c6 100644 --- a/deploy/charts/backend/templates/_helpers.tpl +++ b/deploy/charts/konnector-v2/templates/_helpers.tpl @@ -1,16 +1,10 @@ -{{/* -Expand the name of the chart. -*/}} -{{- define "kube-bind.name" -}} +{{/* Chart name (overridable). */}} +{{- define "konnector.name" -}} {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} {{- end }} -{{/* -Create a default fully qualified app name. -We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). -If release name contains chart name it will be used as a full name. -*/}} -{{- define "kube-bind.fullname" -}} +{{/* Fully qualified app name. */}} +{{- define "konnector.fullname" -}} {{- if .Values.fullnameOverride }} {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} {{- else }} @@ -23,40 +17,37 @@ If release name contains chart name it will be used as a full name. {{- end }} {{- end }} -{{/* -Create chart name and version as used by the chart label. -*/}} -{{- define "kube-bind.chart" -}} +{{/* Chart label. */}} +{{- define "konnector.chart" -}} {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} {{- end }} -{{/* -Common labels -*/}} -{{- define "kube-bind.labels" -}} -helm.sh/chart: {{ include "kube-bind.chart" . }} -{{ include "kube-bind.selectorLabels" . }} +{{/* Common labels. */}} +{{- define "konnector.labels" -}} +helm.sh/chart: {{ include "konnector.chart" . }} +{{ include "konnector.selectorLabels" . }} {{- if .Chart.AppVersion }} app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} {{- end }} app.kubernetes.io/managed-by: {{ .Release.Service }} {{- end }} -{{/* -Selector labels -*/}} -{{- define "kube-bind.selectorLabels" -}} -app.kubernetes.io/name: {{ include "kube-bind.name" . }} +{{/* Selector labels. */}} +{{- define "konnector.selectorLabels" -}} +app.kubernetes.io/name: {{ include "konnector.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} {{- end }} -{{/* -Create the name of the service account to use -*/}} -{{- define "kube-bind.serviceAccountName" -}} +{{/* ServiceAccount name. */}} +{{- define "konnector.serviceAccountName" -}} {{- if .Values.serviceAccount.create }} -{{- default (include "kube-bind.fullname" .) .Values.serviceAccount.name }} +{{- default (include "konnector.fullname" .) .Values.serviceAccount.name }} {{- else }} {{- default "default" .Values.serviceAccount.name }} {{- end }} {{- end }} + +{{/* Whether leader election is effectively on (forced when replicaCount > 1). */}} +{{- define "konnector.leaderElect" -}} +{{- if or .Values.leaderElect (gt (int .Values.replicaCount) 1) }}true{{ else }}false{{ end }} +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/clusterrole.yaml b/deploy/charts/konnector-v2/templates/clusterrole.yaml new file mode 100644 index 000000000..0a8709f87 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/clusterrole.yaml @@ -0,0 +1,54 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ include "konnector.fullname" . }} + labels: + {{- include "konnector.labels" . | nindent 4 }} +rules: + # Core kbind objects the konnector reconciles (+ status, + finalizers). + - apiGroups: ["core.kbind.io"] + resources: ["connections", "clusterbindings", "bindings"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["core.kbind.io"] + resources: ["connections/status", "clusterbindings/status", "bindings/status"] + verbs: ["get", "update", "patch"] + - apiGroups: ["core.kbind.io"] + resources: ["connections/finalizers", "clusterbindings/finalizers", "bindings/finalizers"] + verbs: ["update"] + # CRDs: the konnector pulls/synthesizes and installs the bound APIs, stamps + # markers, and adds/removes finalizers. + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + # Provider kubeconfig Secrets: read + finalizer (never deleted by the konnector). + - apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "list", "watch", "update", "patch"] + # Namespaces: read for cluster identity; create when materializing + # related-resource copies into consumer namespaces. + - apiGroups: [""] + resources: ["namespaces"] + verbs: ["get", "list", "watch", "create"] + # Cluster identity on kcp-shaped consumers (best-effort; harmless if absent). + - apiGroups: ["core.kcp.io"] + resources: ["logicalclusters"] + verbs: ["get", "list", "watch"] + # Events emitted by the reconcilers (conflicts, permission denials). + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] + - apiGroups: ["events.k8s.io"] + resources: ["events"] + verbs: ["create", "patch"] + # Instances of the bound APIs synced between consumer and provider. These are + # open-ended (whatever providers export), so access is granted per + # .Values.rbac.boundResourceGroups — default "*". Narrow it to the specific + # provider API groups to reduce the blast radius. + {{- with .Values.rbac.boundResourceGroups }} + - apiGroups: + {{- toYaml . | nindent 6 }} + resources: ["*"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + {{- end }} +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/clusterrolebinding.yaml b/deploy/charts/konnector-v2/templates/clusterrolebinding.yaml new file mode 100644 index 000000000..b1011da50 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/clusterrolebinding.yaml @@ -0,0 +1,16 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "konnector.fullname" . }} + labels: + {{- include "konnector.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "konnector.fullname" . }} +subjects: + - kind: ServiceAccount + name: {{ include "konnector.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/crds.yaml b/deploy/charts/konnector-v2/templates/crds.yaml new file mode 100644 index 000000000..693db13a2 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/crds.yaml @@ -0,0 +1,6 @@ +{{- if .Values.installCRDs }} +{{- range $path, $_ := .Files.Glob "files/crds/*.yaml" }} +--- +{{ $.Files.Get $path }} +{{- end }} +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/deployment.yaml b/deploy/charts/konnector-v2/templates/deployment.yaml new file mode 100644 index 000000000..49547a7a9 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/deployment.yaml @@ -0,0 +1,80 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "konnector.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "konnector.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + {{- include "konnector.selectorLabels" . | nindent 6 }} + template: + metadata: + labels: + {{- include "konnector.selectorLabels" . | nindent 8 }} + {{- with .Values.podLabels }} + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + spec: + serviceAccountName: {{ include "konnector.serviceAccountName" . }} + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.hostAliases }} + hostAliases: + {{- toYaml . | nindent 8 }} + {{- end }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: konnector + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - --metrics-bind-address=:{{ .Values.metrics.port }} + - --health-probe-bind-address=:{{ .Values.healthProbe.port }} + - --leader-elect={{ include "konnector.leaderElect" . }} + - --leader-election-id={{ .Values.leaderElectionID }} + {{- with .Values.extraArgs }} + {{- toYaml . | nindent 12 }} + {{- end }} + ports: + - name: metrics + containerPort: {{ .Values.metrics.port }} + - name: probe + containerPort: {{ .Values.healthProbe.port }} + livenessProbe: + httpGet: + path: /healthz + port: probe + initialDelaySeconds: 15 + periodSeconds: 20 + readinessProbe: + httpGet: + path: /readyz + port: probe + initialDelaySeconds: 5 + periodSeconds: 10 + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/deploy/charts/konnector-v2/templates/role.yaml b/deploy/charts/konnector-v2/templates/role.yaml new file mode 100644 index 000000000..209a59d68 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/role.yaml @@ -0,0 +1,17 @@ +{{- if .Values.rbac.create }} +# Leader-election lease + bootstrap, scoped to the release namespace. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "konnector.fullname" . }}-leaderelection + namespace: {{ .Release.Namespace }} + labels: + {{- include "konnector.labels" . | nindent 4 }} +rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/rolebinding.yaml b/deploy/charts/konnector-v2/templates/rolebinding.yaml new file mode 100644 index 000000000..251a12a27 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/rolebinding.yaml @@ -0,0 +1,17 @@ +{{- if .Values.rbac.create }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "konnector.fullname" . }}-leaderelection + namespace: {{ .Release.Namespace }} + labels: + {{- include "konnector.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "konnector.fullname" . }}-leaderelection +subjects: + - kind: ServiceAccount + name: {{ include "konnector.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/charts/konnector-v2/templates/serviceaccount.yaml b/deploy/charts/konnector-v2/templates/serviceaccount.yaml new file mode 100644 index 000000000..73a4c86a0 --- /dev/null +++ b/deploy/charts/konnector-v2/templates/serviceaccount.yaml @@ -0,0 +1,13 @@ +{{- if .Values.serviceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "konnector.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "konnector.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/deploy/charts/konnector-v2/values.yaml b/deploy/charts/konnector-v2/values.yaml new file mode 100644 index 000000000..1f51cd900 --- /dev/null +++ b/deploy/charts/konnector-v2/values.yaml @@ -0,0 +1,85 @@ +# Default values for the konnector chart. + +image: + repository: ghcr.io/kbind-dev/konnector + # Defaults to the chart appVersion when empty. + tag: "" + pullPolicy: IfNotPresent + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +# Number of konnector replicas. >1 requires leaderElect (only one is active at a +# time; the rest are warm standbys). +replicaCount: 1 + +# Leader election ensures a single active replica. Enable for HA / replicaCount>1. +# It is forced on automatically whenever replicaCount > 1. +leaderElect: false +leaderElectionID: konnector.kbind.io + +serviceAccount: + create: true + name: "" + annotations: {} + +rbac: + create: true + # The konnector syncs instances of the bound (provider-exported) APIs on this + # consumer cluster. Those APIs are open-ended, so by default it is granted the + # standard verbs on all API groups. Narrow this to the specific groups your + # providers export (e.g. ["mounts.example.org", "example.org"]) to tighten the + # blast radius — but bindings for groups not listed here will fail to sync. + boundResourceGroups: + - "*" + +# Extra args appended to the konnector command. +extraArgs: [] + +metrics: + # Port the controller-runtime metrics endpoint binds to (matches --metrics-bind-address). + port: 8085 + +healthProbe: + # Port the health/readiness probe endpoint binds to (matches --health-probe-bind-address). + port: 8081 + +resources: + requests: + cpu: 100m + memory: 128Mi + limits: + cpu: 500m + memory: 256Mi + +# Host aliases injected into /etc/hosts. +# Needed when circumventing local DNS (e.g. local setup). +hostAliases: [] +# Example: +# - ip: "1.2.3.4" +# hostnames: +# - kcp.api.portal.localhost + +podAnnotations: {} +podLabels: {} + +podSecurityContext: + runAsNonRoot: true + seccompProfile: + type: RuntimeDefault + +securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + +nodeSelector: {} +tolerations: [] +affinity: {} + +# Install the core CRDs (Connection, ClusterBinding, Binding) with the release. +# Set false if they are managed out-of-band. +installCRDs: true diff --git a/deploy/config/cluster.yaml b/deploy/config/cluster.yaml deleted file mode 100644 index 37b20939e..000000000 --- a/deploy/config/cluster.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: kube-bind.io/v1alpha2 -kind: Cluster -metadata: - name: default -spec: {} \ No newline at end of file diff --git a/deploy/crd/bootstrap.go b/deploy/crd/bootstrap.go deleted file mode 100644 index 2972d337b..000000000 --- a/deploy/crd/bootstrap.go +++ /dev/null @@ -1,181 +0,0 @@ -/* -Copyright 2021 The Kube Bind 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 crd - -import ( - "context" - "embed" - "fmt" - "sync" - "time" - - crdhelpers "k8s.io/apiextensions-apiserver/pkg/apihelpers" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - extensionsapiserver "k8s.io/apiextensions-apiserver/pkg/apiserver" - apiextensionsv1client "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - kerrors "k8s.io/apimachinery/pkg/util/errors" - utilnet "k8s.io/apimachinery/pkg/util/net" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/util/retry" - "k8s.io/klog/v2" -) - -//go:embed *.yaml -var raw embed.FS - -// CreateFromFS creates the given CRDs using the target client from the -// provided filesystem and waits for it to become established. This call is blocking. -func CreateFromFS(ctx context.Context, client apiextensionsv1client.CustomResourceDefinitionInterface, fs embed.FS, grs ...metav1.GroupResource) error { - wg := sync.WaitGroup{} - bootstrapErrChan := make(chan error, len(grs)) - for _, gk := range grs { - wg.Add(1) - go func(gr metav1.GroupResource) { - defer wg.Done() - err := retryRetryableErrors(func() error { - return createSingleFromFS(ctx, client, gr, fs) - }) - // wait.Poll functions return ErrWaitTimeout instead the context cancellation error, for backward compatibility reasons, see: - // https://github.com/kubernetes/kubernetes/blob/b5f8cca701575678819b5e9e6372df989ab6799f/staging/src/k8s.io/apimachinery/pkg/util/wait/wait.go - // however, retryOnError swallows that error and replaces it for the last one, that is nil if it is still retrying, see: - // https://github.com/kubernetes/kubernetes/blob/ee81e5ebfad1b3f3c1112e7b83b0a5113286a3d3/pkg/client/unversioned/util.go - // if the context is cancelled, we have to inform the upper layers about that, so context error takes precedence. - if ctx.Err() != nil { - err = ctx.Err() - } - bootstrapErrChan <- err - }(gk) - } - wg.Wait() - close(bootstrapErrChan) - bootstrapErrors := []error{} - for err := range bootstrapErrChan { - bootstrapErrors = append(bootstrapErrors, err) - } - if err := kerrors.NewAggregate(bootstrapErrors); err != nil { - return fmt.Errorf("could not bootstrap CRDs: %w", err) - } - return nil -} - -// Create creates the given CRDs using the target client and waits -// for all of them to become established in parallel. This call is blocking. -func Create(ctx context.Context, client apiextensionsv1client.CustomResourceDefinitionInterface, grs ...metav1.GroupResource) error { - return CreateFromFS(ctx, client, raw, grs...) -} - -// CreateFromFS creates the given CRD using the target client from the -// provided filesystem and waits for it to become established. This call is blocking. -func createSingleFromFS(ctx context.Context, client apiextensionsv1client.CustomResourceDefinitionInterface, gr metav1.GroupResource, fs embed.FS) error { - crd, err := CRD(fs, gr) - if err != nil { - return err - } - - return CreateSingle(ctx, client, crd) -} - -// CRD returns an *apiextensionsv1.CustomResourceDefinition for the GroupResource specified by gr from fs. The embedded -// file's name must have the format _.yaml. -func CRD(fs embed.FS, gr metav1.GroupResource) (*apiextensionsv1.CustomResourceDefinition, error) { - raw, err := fs.ReadFile(fmt.Sprintf("%s_%s.yaml", gr.Group, gr.Resource)) - if err != nil { - return nil, fmt.Errorf("could not read CRD %s: %w", gr.String(), err) - } - - expectedGvk := &schema.GroupVersionKind{Group: apiextensionsv1.GroupName, Version: "v1", Kind: "CustomResourceDefinition"} - - obj, gvk, err := extensionsapiserver.Codecs.UniversalDeserializer().Decode(raw, expectedGvk, &apiextensionsv1.CustomResourceDefinition{}) - if err != nil { - return nil, fmt.Errorf("could not decode raw CRD %s: %w", gr.String(), err) - } - - if !equality.Semantic.DeepEqual(gvk, expectedGvk) { - return nil, fmt.Errorf("decoded CRD %s into incorrect GroupVersionKind, got %#v, wanted %#v", gr.String(), gvk, expectedGvk) - } - - crd, ok := obj.(*apiextensionsv1.CustomResourceDefinition) - if !ok { - return nil, fmt.Errorf("decoded CRD %s into incorrect type, got %T, wanted %T", gr.String(), obj, &apiextensionsv1.CustomResourceDefinition{}) - } - - return crd, nil -} - -func CreateSingle(ctx context.Context, client apiextensionsv1client.CustomResourceDefinitionInterface, rawCRD *apiextensionsv1.CustomResourceDefinition) error { - start := time.Now() - klog.V(4).Infof("Bootstrapping %v", rawCRD.Name) - - updateNeeded := false - crd, err := client.Get(ctx, rawCRD.Name, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - crd, err = client.Create(ctx, rawCRD, metav1.CreateOptions{}) - if err != nil { - // If multiple post-start hooks specify the same CRD, they could race with each other, so we need to - // handle the scenario where another hook created this CRD after our Get() call returned not found. - if apierrors.IsAlreadyExists(err) { - // Re-get so we have the correct resourceVersion - crd, err = client.Get(ctx, rawCRD.Name, metav1.GetOptions{}) - if err != nil { - return fmt.Errorf("error getting CRD %s: %w", rawCRD.Name, err) - } - updateNeeded = true - } else { - return fmt.Errorf("error creating CRD %s: %w", rawCRD.Name, err) - } - } else { - klog.Infof("Bootstrapped CRD %v after %s", crd.Name, time.Since(start).String()) - } - } else { - return fmt.Errorf("error fetching CRD %s: %w", rawCRD.Name, err) - } - } else { - updateNeeded = true - } - - if updateNeeded { - rawCRD.ResourceVersion = crd.ResourceVersion - _, err := client.Update(ctx, rawCRD, metav1.UpdateOptions{}) - if err != nil { - return err - } - klog.Infof("Updated CRD %v after %s", rawCRD.Name, time.Since(start).String()) - } - - return wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (bool, error) { - crd, err := client.Get(ctx, rawCRD.Name, metav1.GetOptions{}) - if err != nil { - if apierrors.IsNotFound(err) { - return false, fmt.Errorf("CRD %s was deleted before being established", rawCRD.Name) - } - return false, fmt.Errorf("error fetching CRD %s: %w", rawCRD.Name, err) - } - - return crdhelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established), nil - }) -} - -func retryRetryableErrors(f func() error) error { - return retry.OnError(retry.DefaultBackoff, func(err error) bool { - return utilnet.IsConnectionRefused(err) || apierrors.IsTooManyRequests(err) || apierrors.IsConflict(err) - }, f) -} diff --git a/deploy/crd/kube-bind.io_apiconversions.yaml b/deploy/crd/kube-bind.io_apiconversions.yaml deleted file mode 100644 index 0fd755b3d..000000000 --- a/deploy/crd/kube-bind.io_apiconversions.yaml +++ /dev/null @@ -1,125 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.16.5 - name: apiconversions.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kcp - kind: APIConversion - listKind: APIConversionList - plural: apiconversions - singular: apiconversion - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIConversion contains rules to convert between different API versions in an APIResourceSchema. The name must match - the name of the APIResourceSchema for the conversions to take effect. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: Spec holds the desired state. - properties: - conversions: - description: conversions specify rules to convert between different - API versions in an APIResourceSchema. - items: - description: |- - APIVersionConversion contains rules to convert between two specific API versions in an - APIResourceSchema. Additionally, to avoid data loss when round-tripping from a version that - contains a new field to one that doesn't and back again, you can specify a list of fields to - preserve (these are stored in annotations). - properties: - from: - description: from is the source version. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - preserve: - description: |- - preserve contains a list of JSONPath expressions to fields to preserve in the originating version - of the object, relative to its root, such as '.spec.name.first'. - items: - type: string - type: array - rules: - description: rules contains field-specific conversion expressions. - items: - description: APIConversionRule specifies how to convert a - single field. - properties: - destination: - description: |- - destination is a JSONPath expression to the field in the target version of the object, relative to - its root, such as '.spec.name.first'. - minLength: 1 - type: string - field: - description: |- - field is a JSONPath expression to the field in the originating version of the object, relative to its root, such - as '.spec.name.first'. - minLength: 1 - type: string - transformation: - description: |- - transformation is an optional CEL expression used to execute user-specified rules to transform the - originating field -- identified by 'self' -- to the destination field. - type: string - required: - - destination - - field - type: object - type: array - x-kubernetes-list-map-keys: - - destination - x-kubernetes-list-type: map - to: - description: to is the target version. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - required: - - from - - rules - - to - type: object - type: array - x-kubernetes-list-map-keys: - - from - - to - x-kubernetes-list-type: map - required: - - conversions - type: object - type: object - served: true - storage: true - subresources: {} diff --git a/deploy/crd/kube-bind.io_apiservicebindingbundles.yaml b/deploy/crd/kube-bind.io_apiservicebindingbundles.yaml deleted file mode 100644 index 849902618..000000000 --- a/deploy/crd/kube-bind.io_apiservicebindingbundles.yaml +++ /dev/null @@ -1,149 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicebindingbundles.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceBindingBundle - listKind: APIServiceBindingBundleList - plural: apiservicebindingbundles - shortNames: - - sbb - singular: apiservicebindingbundle - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceBindingBundle automatically binds multiple API services represented by - APIServiceExports in a service provider cluster into a consumer cluster. This object lives in consumer clusters, - and pulls in all API services defined in the provider clusters, based on the kubeconfig secret provided. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBindingBundle. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_apiservicebindings.yaml b/deploy/crd/kube-bind.io_apiservicebindings.yaml deleted file mode 100644 index 3a15f95d3..000000000 --- a/deploy/crd/kube-bind.io_apiservicebindings.yaml +++ /dev/null @@ -1,464 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicebindings.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceBinding - listKind: APIServiceBindingList - plural: apiservicebindings - shortNames: - - sb - singular: apiservicebinding - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceBinding binds an API service represented by a APIServiceExport - in a service provider cluster into a consumer cluster. This object lives in - the consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. Must be "kubeconfig". - enum: - - kubeconfig - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBinding. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different APIServiceBindings. - type: string - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.providerPrettyName - name: Provider - type: string - - jsonPath: .metadata.annotations.kube-bind\.io/resources - name: Resources - priority: 1 - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .status.conditions[?(@.type=="Ready")].message - name: Message - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceBinding binds an API service represented by a APIServiceExport - in a service provider cluster into a consumer cluster. This object lives in - the consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - key - - name - - namespace - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - required: - - kubeconfigSecretRef - type: object - status: - description: status contains reconciliation information for a service - binding. - properties: - boundSchemas: - description: |- - BoundSchemas contains references to all BoundAPIResourceSchema objects - associated with this APIServiceBinding, tracking consumer usage status. - items: - description: BoundSchemaReference contains a reference to a BoundAPIResourceSchema - with status information. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - required: - - resource - type: object - minItems: 1 - type: array - conditions: - description: conditions is a list of conditions that apply to the - APIServiceBinding. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different APIServiceBindings. - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_apiserviceexportrequests.yaml b/deploy/crd/kube-bind.io_apiserviceexportrequests.yaml deleted file mode 100644 index 22ecb0a05..000000000 --- a/deploy/crd/kube-bind.io_apiserviceexportrequests.yaml +++ /dev/null @@ -1,517 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexportrequests.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceExportRequest - listKind: APIServiceExportRequestList - plural: apiserviceexportrequests - singular: apiserviceexportrequest - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. - - The service provider can prune these objects after some time. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - parameters: - description: |- - parameters holds service provider specific parameters for this binding - request. - type: object - x-kubernetes-preserve-unknown-fields: true - x-kubernetes-validations: - - message: parameters are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - required: - - resources - type: object - status: - default: {} - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - phase: - default: Pending - description: |- - phase is the current phase of the binding request. It starts in Pending - and transitions to Succeeded or Failed. See the condition for detailed - information. - enum: - - Pending - - Failed - - Succeeded - type: string - terminalMessage: - description: |- - terminalMessage is a human readable message that describes the reason - for the current phase. - type: string - type: object - required: - - spec - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. - - The service provider can prune these objects after some time. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: |- - spec specifies how an API service from a service provider should be bound in the - local consumer cluster. - properties: - namespaces: - description: |- - namespaces specifies the namespaces to bootstrap as part of this request. - When objects originate from provider side, the consumer does not always know the necessary details. - This field allows provider to pre-heat the necessary namespaces on provider side by creating - APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - items: - properties: - name: - description: name is the name of the namespace to create on - provider side. - type: string - required: - - name - type: object - type: array - x-kubernetes-validations: - - message: namespaces are immutable - rule: self == oldSelf - parameters: - description: |- - parameters holds service provider specific parameters for this binding - request. - type: object - x-kubernetes-preserve-unknown-fields: true - x-kubernetes-validations: - - message: parameters are immutable - rule: self == oldSelf - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - x-kubernetes-validations: - - message: permissionClaims are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - schemaUpdatePolicy: - default: Never - description: |- - schemaUpdatePolicy defines how BoundSchemas should be updated when the source schema changes. - This is propagated from the APIServiceExportTemplate. - Never means schemas are immutable after creation. - Always means schemas are updated when the source content changes. - enum: - - Never - - Always - type: string - x-kubernetes-validations: - - message: schemaUpdatePolicy is immutable - rule: self == oldSelf - required: - - resources - type: object - status: - default: {} - description: status contains reconciliation information for a service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - phase: - default: Pending - description: |- - phase is the current phase of the binding request. It starts in Pending - and transitions to Succeeded or Failed. See the condition for detailed - information. - enum: - - Pending - - Failed - - Succeeded - type: string - terminalMessage: - description: |- - terminalMessage is a human readable message that describes the reason - for the current phase. - type: string - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_apiserviceexports.yaml b/deploy/crd/kube-bind.io_apiserviceexports.yaml deleted file mode 100644 index 34f3a3681..000000000 --- a/deploy/crd/kube-bind.io_apiserviceexports.yaml +++ /dev/null @@ -1,753 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexports.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceExport - listKind: APIServiceExportList - plural: apiserviceexports - singular: apiserviceexport - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Established")].status - name: Established - priority: 5 - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceExport specifies the resource to be exported. It is mostly a CRD: - - the spec is a CRD spec, but without webhooks - - the status reflects that on the consumer cluster - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the resource. - properties: - clusterScopedIsolation: - description: |- - ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - It can be "Prefixed", "Namespaced", or "None". - enum: - - Prefixed - - Namespaced - - None - type: string - group: - description: "group is the API group of the defined custom resource. - Empty string means the\ncore API group. \tThe resources are served - under `/apis//...` or `/api` for the core group." - type: string - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIServiceExportVersion describes one API version of - a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - properties: - openAPIV3Schema: - description: openAPIV3Schema is the OpenAPI v3 schema to - use for validation and pruning. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - required: - - openAPIV3Schema - type: object - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should - serve a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - x-kubernetes-validations: - - message: informerScope must be Cluster for cluster-scoped resources - rule: self.scope == "Namespaced" || self.informerScope == "Cluster" - - message: clusterScopedIsolation must be defined for cluster-scoped resources - rule: self.scope == "Namespaced" || has(self.clusterScopedIsolation) - - message: clusterScopedIsolation is not relevant for namespaced resources - rule: self.scope == "Cluster" || !has(self.clusterScopedIsolation) - status: - description: status contains reconciliation information for the resource. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: informerScope is immutable - rule: self.metadata.name == self.spec.names.plural+"."+self.spec.group - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Established")].status - name: Established - priority: 5 - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExport specifies the resource to be exported. It is mostly a CRD: - - the spec is a CRD spec, but without webhooks - - the status reflects that on the consumer cluster - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the resource. - properties: - clusterScopedIsolation: - description: |- - ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - It can be "Prefixed", "Namespaced", or "None". - - Deprecated: ClusterScopedIsolation is deprecated, use Isolation instead. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: clusterScopedIsolation is immutable - rule: self == oldSelf - informerScope: - description: |- - informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - - Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - This is more efficient than watching each namespace individually. - Namespaced: The konnector has permission to watch only single namespaces. - This is more resource intensive. And it means cluster-scoped resources cannot be exported. - enum: - - Cluster - - Namespaced - type: string - x-kubernetes-validations: - - message: informerScope is immutable - rule: self == oldSelf - isolation: - description: Isolation specifies how service objects are isolated - between multiple consumers on the provider side. - enum: - - Prefixed - - Namespaced - - None - type: string - x-kubernetes-validations: - - message: isolation is immutable - rule: self == oldSelf - permissionClaims: - description: |- - PermissionClaims records decisions about permission claims requested by the service provider. - Access is granted per GroupResource. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - x-kubernetes-validations: - - message: permissionClaims are immutable - rule: self == oldSelf - resources: - description: resources is a list of resources that should be exported. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - x-kubernetes-validations: - - message: resources are immutable - rule: self == oldSelf - required: - - informerScope - - isolation - - resources - type: object - status: - description: status contains reconciliation information for the resource. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the APIServiceExport. It is - updated by the konnector on the consumer cluster. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_apiserviceexporttemplates.yaml b/deploy/crd/kube-bind.io_apiserviceexporttemplates.yaml deleted file mode 100644 index 2d254f037..000000000 --- a/deploy/crd/kube-bind.io_apiserviceexporttemplates.yaml +++ /dev/null @@ -1,337 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiserviceexporttemplates.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: APIServiceExportTemplate - listKind: APIServiceExportTemplateList - plural: apiserviceexporttemplates - singular: apiserviceexporttemplate - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.resources[*].group - name: Resources - type: string - - jsonPath: .spec.permissionClaims[*].resource - name: PermissionClaims - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceExportTemplate groups multiple CRDs with related resources (permissionClaims) as a Service definition. - It is used by a web UI or CLI to allow users to select a set of resources to export from provider cluster to consumer cluster. - This object is considered a static asset on the provider side and is not expected to change frequently. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the template. - properties: - description: - description: description is an optional description of the template. - type: string - namespaces: - description: |- - Namespaces specifies the namespaces that should be bootstrapped as part of this template. - When objects originate from provider side, consumer does not always know the necessary details - This field allows provider to pre-heat the necessary namespaces on provider side by creating - APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - items: - properties: - name: - description: name is the name of the namespace to create on - provider side. - type: string - required: - - name - type: object - type: array - permissionClaims: - description: permissionClaims defines the permission claims required - by this template. - items: - description: |- - PermissionClaim selects objects of a GVR that a service provider may - request and that a consumer may accept and allow the service provider access to. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - selector: - description: Selector is a resource selector that selects objects - of a GVR. - properties: - labelSelector: - description: LabelSelector is a label selector that selects - objects of a GVR. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: |- - A label selector requirement is a selector that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: |- - operator represents a key's relationship to a set of values. - Valid operators are In, NotIn, Exists and DoesNotExist. - type: string - values: - description: |- - values is an array of string values. If the operator is In or NotIn, - the values array must be non-empty. If the operator is Exists or DoesNotExist, - the values array must be empty. This array is replaced during a strategic - merge patch. - items: - type: string - type: array - x-kubernetes-list-type: atomic - required: - - key - - operator - type: object - type: array - x-kubernetes-list-type: atomic - matchLabels: - additionalProperties: - type: string - description: |- - matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, whose key field is "key", the - operator is "In", and the values array contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - namedResources: - description: NamedResource is a shorthand for selecting - a single resource by name and namespace. - items: - description: NamedResource selects a specific resource - by name and namespace. - properties: - name: - description: |- - Name is the name of the resource. - Name matches the metadata.name field of the underlying object. - type: string - namespace: - description: |- - Namespace represents namespace where an object of the given group/resource may be managed. - Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - Namespaces field is ignored for namespaced isolation mode. - type: string - required: - - name - type: object - type: array - references: - description: Reference is a reference to the object that - contains jsonPath to select objects of a GVR. - items: - description: SelectorReference selects objects of a GVR - via a reference to another object. - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - jsonPath: - description: JSONPath is a JSONPath expression that - selects the name and namespace of the resource from - the referenced object. - properties: - name: - type: string - namespace: - type: string - type: object - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be used to fetch the referenced object. - If not specified and apiserviceexport contains versions for the same group/resource, - those versions are used. Otherwise, references is considered invalid. - items: - type: string - type: array - required: - - jsonPath - - resource - type: object - type: array - type: object - required: - - resource - - selector - type: object - type: array - resources: - description: resources defines the CRDs that are part of this template. - items: - properties: - group: - default: "" - description: |- - group is the name of an API group. - For core groups this is the empty string '""'. - pattern: ^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$ - type: string - resource: - description: |- - resource is the name of the resource. - Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - not provided by an service binding export. - pattern: ^[a-z][-a-z0-9]*[a-z0-9]$ - type: string - versions: - description: |- - versions is a list of versions that should be exported. If this is empty - a sensible default is chosen by the service provider. - items: - type: string - type: array - required: - - resource - type: object - minItems: 1 - type: array - schemaUpdatePolicy: - default: Never - description: |- - SchemaUpdatePolicy defines how BoundSchemas should be updated. - Never means schemas are immutable after creation. - Always means schemas are updated when the source content changes. - Default: Never - - NOTE: This field is intentionally mutable on the template so that providers - can change the default for future binding requests. Already-created - APIServiceExportRequests use CEL validation (self == oldSelf) to lock in - the policy chosen at binding time. - enum: - - Never - - Always - type: string - scope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Namespaced - - Cluster - description: scope defines the scope of the resources in this template. - type: string - required: - - resources - - scope - type: object - status: - description: status contains reconciliation information for the template. - properties: - conditions: - description: conditions is a list of conditions that apply to the - APIServiceExportTemplate. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_apiservicenamespaces.yaml b/deploy/crd/kube-bind.io_apiservicenamespaces.yaml deleted file mode 100644 index 5ff91b0d4..000000000 --- a/deploy/crd/kube-bind.io_apiservicenamespaces.yaml +++ /dev/null @@ -1,125 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: apiservicenamespaces.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: APIServiceNamespace - listKind: APIServiceNamespaceList - plural: apiservicenamespaces - singular: apiservicenamespace - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service - namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.namespace - name: Namespace - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - APIServiceNamespace defines how consumer namespaces map to service namespaces. - These objects are created by the konnector, and a service namespace is then - created by the service provider. - - The name of the APIServiceNamespace equals the namespace name in the consumer - cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies a service namespace. - type: object - status: - description: status contains reconciliation information for a service - namespace - properties: - namespace: - description: |- - namespace is the service provider namespace name that will be bound to the - consumer namespace named like this object. - type: string - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_bindableresourcesrequests.yaml b/deploy/crd/kube-bind.io_bindableresourcesrequests.yaml deleted file mode 100644 index b628ca26e..000000000 --- a/deploy/crd/kube-bind.io_bindableresourcesrequests.yaml +++ /dev/null @@ -1,224 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: bindableresourcesrequests.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BindableResourcesRequest - listKind: BindableResourcesRequestList - plural: bindableresourcesrequests - singular: bindableresourcesrequest - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .spec.templateRef.name - name: Template - type: string - - jsonPath: .status.phase - name: Phase - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - BindableResourcesRequest is sent by the consumer to the service provider - to indicate which resources the user wants to bind to. It can be sent via - the HTTP API after authentication, or created directly as a CRD when the - backend is running without the HTTP API/OIDC flow (frontend disabled mode). - - When created as a CRD, a controller will process the request and create the - necessary APIServiceExport and related resources. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the binding request details. - properties: - author: - description: |- - Author is the identifier of the entity that created this binding request. - This is used for audit purposes and to track who initiated the binding. - type: string - clusterIdentity: - description: |- - ClusterIdentity contains information that uniquely identifies the cluster. - This is used when the request is made via the HTTP API after authentication. - properties: - identity: - description: Identity is the unique identifier of the cluster. - type: string - prettyName: - description: |- - PrettyName is a human-readable name for the cluster, used for display - purposes. If not provided, the controller defaults it to the request name. - type: string - type: object - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to an existing secret where the binding response - will be stored. If specified, the controller will update this secret with the - binding response data. If not specified, a new secret will be created with - the name "-binding-response". - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - templateRef: - description: TemplateRef specifies the APIServiceExportTemplate to - bind to. - properties: - name: - description: name is the name of the APIServiceExportTemplate - to bind to. - type: string - required: - - name - type: object - ttlAfterFinished: - description: |- - ttlAfterFinished is the TTL after the request has succeeded or failed - before it is automatically deleted. If not set, the request will not be - automatically deleted. Example values: "1h", "30m", "300s". - type: string - required: - - author - - clusterIdentity - type: object - status: - default: {} - description: status contains reconciliation information for the binding - request. - properties: - completionTime: - description: |- - completionTime is the time when the request finished processing (succeeded or failed). - Used for TTL-based cleanup. - format: date-time - type: string - conditions: - description: conditions contains the current conditions of the binding - request. - items: - description: Condition contains details for one aspect of the current - state of this API Resource. - properties: - lastTransitionTime: - description: |- - lastTransitionTime is the last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - message is a human readable message indicating details about the transition. - This may be an empty string. - maxLength: 32768 - type: string - observedGeneration: - description: |- - observedGeneration represents the .metadata.generation that the condition was set based upon. - For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date - with respect to the current state of the instance. - format: int64 - minimum: 0 - type: integer - reason: - description: |- - reason contains a programmatic identifier indicating the reason for the condition's last transition. - Producers of specific condition types may define expected values and meanings for this field, - and whether the values are considered a guaranteed API. - The value should be a CamelCase string. - This field may not be empty. - maxLength: 1024 - minLength: 1 - pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ - type: string - status: - description: status of the condition, one of True, False, Unknown. - enum: - - "True" - - "False" - - Unknown - type: string - type: - description: type of condition in CamelCase or in foo.example.com/CamelCase. - maxLength: 316 - pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ - type: string - required: - - lastTransitionTime - - message - - reason - - status - - type - type: object - type: array - kubeconfigSecretRef: - description: |- - kubeconfigSecretRef is a reference to a secret containing the kubeconfig, used - to be used by the konnector agent. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - namespace: - description: |- - namespace is the namespace assigned to this binding request on the service provider cluster. - This is where the resources for this binding are created and managed. - type: string - phase: - default: Pending - description: phase is the current phase of the binding request. - enum: - - Pending - - Failed - - Succeeded - type: string - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_boundschemas.yaml b/deploy/crd/kube-bind.io_boundschemas.yaml deleted file mode 100644 index 42399192d..000000000 --- a/deploy/crd/kube-bind.io_boundschemas.yaml +++ /dev/null @@ -1,469 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: boundschemas.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: BoundSchema - listKind: BoundSchemaList - plural: boundschemas - shortNames: - - bs - singular: boundschema - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - BoundSchema defines the schema of a bound API resource. It is created on the provider side to track - CRD status on the consumer side by reflecting the CRD spec and status conditions. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: BoundSchemaSpec defines the desired state of the BoundSchema. - properties: - conversion: - description: conversion defines conversion settings for the defined - custom resource. - properties: - strategy: - description: |- - strategy specifies how custom resources are converted between versions. Allowed values are: - - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information - is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. - enum: - - None - - Webhook - type: string - webhook: - description: webhook describes how to call the conversion webhook. - Required when `strategy` is set to `"Webhook"`. - properties: - clientConfig: - description: clientConfig is the instructions for how to call - the webhook if strategy is `Webhook`. - properties: - caBundle: - description: |- - caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. - If unspecified, system trust roots on the apiserver are used. - format: byte - type: string - url: - description: |- - url gives the location of the webhook, in standard URL form - (`scheme://host:port/path`). - - Please note that using `localhost` or `127.0.0.1` as a `host` is - risky unless you take great care to run this webhook on all hosts - which run an apiserver which might need to make calls to this - webhook. Such installs are likely to be non-portable, i.e., not easy - to turn up in a new cluster. - - The scheme must be "https"; the URL must begin with "https://". - - A path is optional, and if present may be any string permissible in - a URL. You may use the path to pass an arbitrary string to the - webhook, for example, a cluster identifier. - - Attempting to use a user or basic auth e.g. "user:password@" is not - allowed. Fragments ("#...") and query parameters ("?...") are not - allowed, either. - format: uri - type: string - type: object - conversionReviewVersions: - description: |- - conversionReviewVersions is an ordered list of preferred `ConversionReview` - versions the Webhook expects. The API server will use the first version in - the list which it supports. If none of the versions specified in this list - are supported by API server, conversion will fail for the custom resource. - If a persisted Webhook configuration specifies allowed versions and does not - include any versions known to the API Server, calls to the webhook will fail. - items: - type: string - type: array - x-kubernetes-list-type: atomic - type: object - type: object - x-kubernetes-validations: - - message: Webhook must be specified if strategy=Webhook - rule: (self.strategy == 'None' && !has(self.webhook)) || (self.strategy - == 'Webhook' && has(self.webhook)) - group: - description: "group is the API group of the defined custom resource. - Empty string means the\ncore API group. \tThe resources are served - under `/apis//...` or `/api` for the core group." - type: string - informerScope: - allOf: - - enum: - - Cluster - - Namespaced - - enum: - - Cluster - - Namespaced - description: |- - InformerScope indicates whether the informer for defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - type: string - names: - description: names specify the resource and kind names for the custom - resource. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - scope: - description: |- - scope indicates whether the defined custom resource is cluster- or namespace-scoped. - Allowed values are `Cluster` and `Namespaced`. - enum: - - Cluster - - Namespaced - type: string - versions: - description: |- - versions is the API version of the defined custom resource. - - Note: the OpenAPI v3 schemas must be equal for all versions until CEL - version migration is supported. - items: - description: APIResourceVersion describes one API version of a resource. - properties: - additionalPrinterColumns: - description: |- - additionalPrinterColumns specifies additional columns returned in Table output. - See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - If no columns are specified, a single column displaying the age of the custom resource is used. - items: - description: CustomResourceColumnDefinition specifies a column - for server side printing. - properties: - description: - description: description is a human readable description - of this column. - type: string - format: - description: |- - format is an optional OpenAPI type definition for this column. The 'name' format is applied - to the primary identifier column to assist in clients identifying column is the resource name. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - jsonPath: - description: |- - jsonPath is a simple JSON path (i.e. with array notation) which is evaluated against - each custom resource to produce the value for this column. - type: string - name: - description: name is a human readable name for the column. - type: string - priority: - description: |- - priority is an integer defining the relative importance of this column compared to others. Lower - numbers are considered higher priority. Columns that may be omitted in limited space scenarios - should be given a priority greater than 0. - format: int32 - type: integer - type: - description: |- - type is an OpenAPI type definition for this column. - See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for details. - type: string - required: - - jsonPath - - name - - type - type: object - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - deprecated: - description: |- - deprecated indicates this version of the custom resource API is deprecated. - When set to true, API requests to this version receive a warning header in the server response. - Defaults to false. - type: boolean - deprecationWarning: - description: |- - deprecationWarning overrides the default warning returned to API clients. - May only be set when `deprecated` is true. - The default warning indicates this version is deprecated and recommends use - of the newest served version of equal or greater stability, if one exists. - type: string - name: - description: |- - name is the version name, e.g. “v1”, “v2beta1”, etc. - The custom resources are served under this version at `/apis///...` if `served` is true. - minLength: 1 - pattern: ^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - type: string - schema: - description: |- - schema describes the structural schema used for validation, pruning, and defaulting - of this version of the custom resource. - type: object - x-kubernetes-map-type: atomic - x-kubernetes-preserve-unknown-fields: true - served: - default: true - description: served is a flag enabling/disabling this version - from being served via REST APIs - type: boolean - storage: - description: |- - storage indicates this version should be used when persisting custom resources to storage. - There must be exactly one version with storage=true. - type: boolean - subresources: - description: subresources specify what subresources this version - of the defined custom resource have. - properties: - scale: - description: scale indicates the custom resource should - serve a `/scale` subresource that returns an `autoscaling/v1` - Scale object. - properties: - labelSelectorPath: - description: |- - labelSelectorPath defines the JSON path inside of a custom resource that corresponds to Scale `status.selector`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status` or `.spec`. - Must be set to work with HorizontalPodAutoscaler. - The field pointed by this JSON path must be a string field (not a complex selector struct) - which contains a serialized label selector in string form. - More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource - If there is no value under the given path in the custom resource, the `status.selector` value in the `/scale` - subresource will default to the empty string. - type: string - specReplicasPath: - description: |- - specReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `spec.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.spec`. - If there is no value under the given path in the custom resource, the `/scale` subresource will return an error on GET. - type: string - statusReplicasPath: - description: |- - statusReplicasPath defines the JSON path inside of a custom resource that corresponds to Scale `status.replicas`. - Only JSON paths without the array notation are allowed. - Must be a JSON Path under `.status`. - If there is no value under the given path in the custom resource, the `status.replicas` value in the `/scale` subresource - will default to 0. - type: string - required: - - specReplicasPath - - statusReplicasPath - type: object - status: - description: |- - status indicates the custom resource should serve a `/status` subresource. - When enabled: - 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. - 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. - type: object - type: object - required: - - name - - schema - - served - - storage - type: object - minItems: 1 - type: array - x-kubernetes-list-map-keys: - - name - x-kubernetes-list-type: map - required: - - group - - informerScope - - names - - scope - - versions - type: object - status: - description: BoundSchemaStatus defines the observed state of the BoundSchema. - properties: - acceptedNames: - description: |- - acceptedNames are the names that are actually being used to serve discovery. - They may be different than the names in spec. - properties: - categories: - description: |- - categories is a list of grouped resources this custom resource belongs to (e.g. 'all'). - This is published in API discovery documents, and used by clients to support invocations like - `kubectl get all`. - items: - type: string - type: array - x-kubernetes-list-type: atomic - kind: - description: |- - kind is the serialized kind of the resource. It is normally CamelCase and singular. - Custom resource instances will use this value as the `kind` attribute in API calls. - type: string - listKind: - description: listKind is the serialized kind of the list for this - resource. Defaults to "`kind`List". - type: string - plural: - description: |- - plural is the plural name of the resource to serve. - The custom resources are served under `/apis///.../`. - Must match the name of the CustomResourceDefinition (in the form `.`). - Must be all lowercase. - type: string - shortNames: - description: |- - shortNames are short names for the resource, exposed in API discovery documents, - and used by clients to support invocations like `kubectl get `. - It must be all lowercase. - items: - type: string - type: array - x-kubernetes-list-type: atomic - singular: - description: singular is the singular name of the resource. It - must be all lowercase. Defaults to lowercased `kind`. - type: string - required: - - kind - - plural - type: object - conditions: - description: Conditions represent the latest available observations - of the object's state. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - instantiations: - description: Instantiations tracks the number of instances of the - resource on the consumer side. - type: integer - storedVersions: - description: |- - storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - versions allows a migration path for stored versions in etcd. The field is mutable - so a migration controller can finish a migration to another version (ensuring - no old objects are left in storage), and then remove the rest of the - versions from this list. - Versions may not be removed from `spec.versions` while they exist in this list. - items: - type: string - type: array - type: object - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_clusterbindings.yaml b/deploy/crd/kube-bind.io_clusterbindings.yaml deleted file mode 100644 index 328689321..000000000 --- a/deploy/crd/kube-bind.io_clusterbindings.yaml +++ /dev/null @@ -1,346 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: clusterbindings.kube-bind.io -spec: - conversion: - strategy: None - group: kube-bind.io - names: - categories: - - kube-bindings - kind: ClusterBinding - listKind: ClusterBindingList - plural: clusterbindings - singular: clusterbinding - scope: Namespaced - versions: - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha1 - schema: - openAPIV3Schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service provider cluster - and is a singleton named "cluster". - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. Must be "kubeconfig". - enum: - - kubeconfig - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - jsonPath: .status.konnectorVersion - name: Konnector Version - type: string - - jsonPath: .status.lastHeartbeatTime - name: Last Heartbeat - type: date - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - ClusterBinding represents a bound consumer cluster. It lives in a service - provider cluster and is a singleton named "cluster" per namespace. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - properties: - kubeconfigSecretRef: - description: kubeconfigSecretName is the secret ref that contains - the kubeconfig of the service cluster. - properties: - key: - description: The key of the secret to select from. - type: string - name: - description: Name of the referent. - minLength: 1 - type: string - required: - - key - - name - type: object - x-kubernetes-validations: - - message: kubeconfigSecretRef is immutable - rule: self == oldSelf - providerPrettyName: - description: |- - providerPrettyName is the pretty name of the service provider cluster. This - can be shared among different ServiceBindings. - minLength: 1 - type: string - serviceProviderSpec: - description: |- - serviceProviderSpec contains all the data and information about the service which has been bound to the service - binding request. The service providers decide what they need and what to configure based on what then include in - this field, such as service region, type, tiers, etc... - type: object - x-kubernetes-preserve-unknown-fields: true - required: - - kubeconfigSecretRef - - providerPrettyName - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - consumerSecretRef: - description: |- - consumerSecretRef is the reference to the secret in the consumer cluster - that contains the kubeconfig for connecting to the service provider. - properties: - name: - description: Name of the referent. - minLength: 1 - type: string - namespace: - description: Namespace of the referent. - minLength: 1 - type: string - required: - - name - - namespace - type: object - heartbeatInterval: - description: |- - heartbeatInterval is the maximal interval between heartbeats that the - konnector promises to send. The service provider can assume that the - konnector is not unhealthy if it does not receive a heartbeat within - this time. - type: string - konnectorVersion: - description: |- - konnectorVersion is the version of the konnector that is running on the - consumer cluster. - type: string - lastHeartbeatTime: - description: lastHeartbeatTime is the last time the konnector updated - the status. - format: date-time - type: string - type: object - required: - - spec - type: object - x-kubernetes-validations: - - message: cluster binding name should be cluster - rule: self.metadata.name == "cluster" - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_clusters.yaml b/deploy/crd/kube-bind.io_clusters.yaml deleted file mode 100644 index 7dba0d0e9..000000000 --- a/deploy/crd/kube-bind.io_clusters.yaml +++ /dev/null @@ -1,106 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: clusters.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Cluster - listKind: ClusterList - plural: clusters - singular: cluster - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .status.conditions[?(@.type=="Ready")].status - name: Ready - type: string - name: v1alpha2 - schema: - openAPIV3Schema: - description: Cluster represents a cluster, managed by kube-bind. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec represents the data in the newly created ClusterBinding. - type: object - status: - description: status contains reconciliation information for the service - binding. - properties: - conditions: - description: |- - conditions is a list of conditions that apply to the ClusterBinding. It is - updated by the konnector and the service provider. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/crd/kube-bind.io_collections.yaml b/deploy/crd/kube-bind.io_collections.yaml deleted file mode 100644 index 1b262685d..000000000 --- a/deploy/crd/kube-bind.io_collections.yaml +++ /dev/null @@ -1,133 +0,0 @@ ---- -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - annotations: - controller-gen.kubebuilder.io/version: v0.17.3 - name: collections.kube-bind.io -spec: - group: kube-bind.io - names: - categories: - - kube-bind - kind: Collection - listKind: CollectionList - plural: collections - singular: collection - scope: Cluster - versions: - - additionalPrinterColumns: - - jsonPath: .spec.description - name: Description - type: string - - jsonPath: .spec.templates[*].name - name: Templates - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1alpha2 - schema: - openAPIV3Schema: - description: |- - Collection groups multiple APIServiceExportTemplates into a logical group. This functions as a grouping mechanism - in UIs or CLIs to allow users to select a set of resources to export from provider cluster to consumer cluster. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: spec specifies the collection. - properties: - description: - description: description is a human readable description of this collection. - type: string - templates: - description: templates is a list of template references that are part - of this collection. - items: - description: APIServiceExportTemplateReference references an APIServiceExportTemplate - by name. - properties: - name: - description: name is the name of the template. - type: string - required: - - name - type: object - minItems: 1 - type: array - required: - - templates - type: object - status: - description: status contains reconciliation information for the collection. - properties: - conditions: - description: conditions is a list of conditions that apply to the - Collection. - items: - description: Condition defines an observation of a object operational - state. - properties: - lastTransitionTime: - description: |- - Last time the condition transitioned from one status to another. - This should be when the underlying condition changed. If that is not known, then using the time when - the API field changed is acceptable. - format: date-time - type: string - message: - description: |- - A human readable message indicating details about the transition. - This field may be empty. - type: string - reason: - description: |- - The reason for the condition's last transition in CamelCase. - The specific API may choose whether or not this field is considered a guaranteed API. - This field may not be empty. - type: string - severity: - description: |- - Severity provides an explicit classification of Reason code, so the users or machines can immediately - understand the current situation and act accordingly. - The Severity field MUST be set only when Status=False. - type: string - status: - description: Status of the condition, one of True, False, Unknown. - type: string - type: - description: |- - Type of condition in CamelCase or in foo.example.com/CamelCase. - Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - can be useful (see .node.status.conditions), the ability to deconflict is important. - type: string - required: - - lastTransitionTime - - status - - type - type: object - type: array - type: object - required: - - spec - type: object - served: true - storage: true - subresources: - status: {} diff --git a/deploy/examples/collection.yaml b/deploy/examples/collection.yaml deleted file mode 100644 index 21c0fc74e..000000000 --- a/deploy/examples/collection.yaml +++ /dev/null @@ -1,8 +0,0 @@ -apiVersion: kube-bind.io/v1alpha2 -kind: Collection -metadata: - name: all -spec: - templates: - - name: cowboys - - name: sheriffs diff --git a/deploy/examples/cr-cowboy.yaml b/deploy/examples/cr-cowboy.yaml deleted file mode 100644 index 21844ffa1..000000000 --- a/deploy/examples/cr-cowboy.yaml +++ /dev/null @@ -1,40 +0,0 @@ ---- -apiVersion: v1 -kind: Namespace -metadata: - name: wild-west ---- -apiVersion: wildwest.dev/v1alpha1 -kind: Cowboy -metadata: - name: billy-the-kid - namespace: wild-west -spec: - intent: "Ride the range and protect the cattle" - secretRefs: - - name: colt-45-permit -status: - result: "Ready to ride" ---- -apiVersion: v1 -kind: Secret -metadata: - name: colt-45-permit - namespace: wild-west - labels: - app: cowboy - type: weapon -data: - serial_number: QzQ1LTEyMzQ1Ng== # "C45-123456" base64 encoded - permit_date: MTg4MS0wNC0xNQ== # "1881-04-15" base64 encoded - issued_by: VG9tYnN0b25lIE1hcnNoYWw= # "Tombstone Marshal" base64 encoded ---- -apiVersion: v1 -kind: Secret -metadata: - name: cowboy-gang-affiliation - namespace: wild-west - labels: - app: cowboy -data: - gang_name: IEJ1ZmZhbG8gQ2h1Y2tlcnMg # " Buffalo Chuckers " base64 encoded \ No newline at end of file diff --git a/deploy/examples/cr-sheriff.yaml b/deploy/examples/cr-sheriff.yaml deleted file mode 100644 index d62c5b88a..000000000 --- a/deploy/examples/cr-sheriff.yaml +++ /dev/null @@ -1,37 +0,0 @@ ---- -apiVersion: v1 -kind: Namespace -metadata: - name: wild-west ---- -apiVersion: wildwest.dev/v1alpha1 -kind: Sheriff -metadata: - name: wyatt-earp -spec: - intent: "Keep the peace in Tombstone" - secretRefs: - - name: sheriff-badge-credentials - namespace: wild-west -status: - result: "Ready for duty" ---- -apiVersion: v1 -kind: Secret -metadata: - name: sheriff-badge-credentials - namespace: wild-west -data: - badge_number: IzEyMzQ1 # "#12345" base64 encoded - authority_level: aGlnaA== # "high" base64 encoded - jurisdiction: dG9tYnN0b25l # "tombstone" base64 encoded ---- -apiVersion: v1 -kind: Secret -metadata: - name: sheriff-jurisdiction-config - namespace: wild-west - labels: - app: sheriff -data: - patrol_area: IFNvdXRoIE1haW4gU3QgYW5kIE1haW4gU3Qg # " South Main St and Main St " base64 encoded \ No newline at end of file diff --git a/deploy/examples/crd-cowboys.yaml b/deploy/examples/crd-cowboys.yaml deleted file mode 100644 index 0f5971ffd..000000000 --- a/deploy/examples/crd-cowboys.yaml +++ /dev/null @@ -1,60 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - name: cowboys.wildwest.dev - labels: - kube-bind.io/exported: "true" -spec: - group: wildwest.dev - names: - kind: Cowboy - listKind: CowboyList - plural: cowboys - singular: cowboy - scope: Namespaced - versions: - - name: v1alpha1 - served: true - storage: true - schema: - openAPIV3Schema: - description: Cowboy is part of the wild west - type: object - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: CowboySpec holds the desired state of the Cowboy. - type: object - properties: - intent: - type: string - secretRefs: - type: array - description: "Array of references to Secrets containing cowboy credentials" - items: - type: object - properties: - name: - type: string - description: "Name of the referenced Secret" - required: - - name - status: - description: CowboyStatus communicates the observed state of the Cowboy. - type: object - properties: - result: - type: string - subresources: - status: {} \ No newline at end of file diff --git a/deploy/examples/crd-sheriffs.yaml b/deploy/examples/crd-sheriffs.yaml deleted file mode 100644 index ba6670506..000000000 --- a/deploy/examples/crd-sheriffs.yaml +++ /dev/null @@ -1,63 +0,0 @@ -apiVersion: apiextensions.k8s.io/v1 -kind: CustomResourceDefinition -metadata: - name: sheriffs.wildwest.dev - labels: - kube-bind.io/exported: "true" -spec: - group: wildwest.dev - names: - kind: Sheriff - listKind: SheriffList - plural: sheriffs - singular: sheriff - scope: Cluster - versions: - - name: v1alpha1 - served: true - storage: true - schema: - openAPIV3Schema: - description: Sheriff is part of the wild west - type: object - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: SheriffSpec holds the desired state of the Sheriff. - type: object - properties: - intent: - type: string - secretRefs: - type: array - description: "Array of references to Secrets containing sheriff credentials" - items: - type: object - properties: - name: - type: string - description: "Name of the referenced Secret" - namespace: - type: string - description: "Namespace of the referenced Secret" - required: - - name - status: - description: SheriffStatus communicates the observed state of the Sheriff. - type: object - properties: - result: - type: string - subresources: - status: {} \ No newline at end of file diff --git a/deploy/examples/examples.go b/deploy/examples/examples.go deleted file mode 100644 index 0bce263e8..000000000 --- a/deploy/examples/examples.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 examples - -import ( - "context" - "embed" - "testing" - - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" - - "github.com/kube-bind/kube-bind/pkg/bootstrap" -) - -//go:embed crd-*.yaml template-*.yaml collection.yaml -var Examples embed.FS - -//go:embed cr-*.yaml -var CRExamples embed.FS - -func Bootstrap(t *testing.T, discoveryClient discovery.DiscoveryInterface, dynamicClient dynamic.Interface, batteriesIncluded sets.Set[string]) { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - err := bootstrap.Bootstrap(ctx, discoveryClient, dynamicClient, batteriesIncluded, Examples) - require.NoError(t, err) -} diff --git a/deploy/examples/template-cowboys.yaml b/deploy/examples/template-cowboys.yaml deleted file mode 100644 index 5e9c7c805..000000000 --- a/deploy/examples/template-cowboys.yaml +++ /dev/null @@ -1,18 +0,0 @@ -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExportTemplate -metadata: - name: cowboys -spec: - scope: Namespaced - resources: - - group: wildwest.dev - versions: - - v1alpha1 - resource: cowboys - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - app: cowboy diff --git a/deploy/examples/template-sheriffs.yaml b/deploy/examples/template-sheriffs.yaml deleted file mode 100644 index b70a46577..000000000 --- a/deploy/examples/template-sheriffs.yaml +++ /dev/null @@ -1,24 +0,0 @@ -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExportTemplate -metadata: - name: sheriffs -spec: - scope: Cluster - resources: - - group: wildwest.dev - versions: - - v1alpha1 - resource: sheriffs - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - app: sheriff - references: - - resource: sheriffs - group: wildwest.dev - jsonPath: - name: spec.secretRefs.#.name - namespace: spec.secretRefs.#.namespace \ No newline at end of file diff --git a/deploy/patches/kube-bind.io_apiconversions.yaml-patch b/deploy/patches/kube-bind.io_apiconversions.yaml-patch deleted file mode 100644 index aed790a21..000000000 --- a/deploy/patches/kube-bind.io_apiconversions.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None diff --git a/deploy/patches/kube-bind.io_apiservicebindings.yaml-patch b/deploy/patches/kube-bind.io_apiservicebindings.yaml-patch deleted file mode 100644 index 15feab278..000000000 --- a/deploy/patches/kube-bind.io_apiservicebindings.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None \ No newline at end of file diff --git a/deploy/patches/kube-bind.io_apiserviceexportrequests.yaml-patch b/deploy/patches/kube-bind.io_apiserviceexportrequests.yaml-patch deleted file mode 100644 index 5aac78147..000000000 --- a/deploy/patches/kube-bind.io_apiserviceexportrequests.yaml-patch +++ /dev/null @@ -1,9 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None - -- op: add - path: /spec/versions/name=v1alpha1/schema/openAPIV3Schema/properties/status/default - value: {} diff --git a/deploy/patches/kube-bind.io_apiserviceexports.yaml-patch b/deploy/patches/kube-bind.io_apiserviceexports.yaml-patch deleted file mode 100644 index 15feab278..000000000 --- a/deploy/patches/kube-bind.io_apiserviceexports.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None \ No newline at end of file diff --git a/deploy/patches/kube-bind.io_apiservicenamespaces.yaml-patch b/deploy/patches/kube-bind.io_apiservicenamespaces.yaml-patch deleted file mode 100644 index 15feab278..000000000 --- a/deploy/patches/kube-bind.io_apiservicenamespaces.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None \ No newline at end of file diff --git a/deploy/patches/kube-bind.io_boundschemas.yaml-patch b/deploy/patches/kube-bind.io_boundschemas.yaml-patch deleted file mode 100644 index aed790a21..000000000 --- a/deploy/patches/kube-bind.io_boundschemas.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None diff --git a/deploy/patches/kube-bind.io_clusterbindings.yaml-patch b/deploy/patches/kube-bind.io_clusterbindings.yaml-patch deleted file mode 100644 index 15feab278..000000000 --- a/deploy/patches/kube-bind.io_clusterbindings.yaml-patch +++ /dev/null @@ -1,5 +0,0 @@ -# schema's Convert functions directly, but the CRD still needs to define a conversion. -- op: add - path: /spec/conversion - value: - strategy: None \ No newline at end of file diff --git a/docs/.gitignore b/docs/.gitignore index 856657629..5d506eddd 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -1,5 +1,3 @@ -venv -generated -__pycache__ -.cache/ -site/ +/.venv/ +/generated/ +/.cache/ diff --git a/docs/README.md b/docs/README.md index 9b9f68aa7..e48b4c3d0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,48 +1,76 @@ -# kbind.dev Documentation Setup +# Documentation and publishing -## Overview +The v2 site keeps the original MkDocs Material theme, **mike** versioning, +and directory-based navigation using the **awesome-pages** plugin. +Content lives under `docs/content`, each section's `.pages` file controls +its navigation. Only this directory is published, design proposals and +release-maintenance notes remain repository documents. -Our documentation is powered by [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) with some -additional plugins and tools: +## Build and preview -- [awesome-pages plugin](https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin) -- [macros plugin](https://mkdocs-macros-plugin.readthedocs.io/en/latest/) -- [mike](https://github.com/jimporter/mike) for multiple version support +Use Python with `venv` and the Go version from `go.mod`. CI uses Python +3.12. From the repository root: -We have support in place for multiple languages (i18n), although we currently only have documentation in English. If -you're interested in contributing translations, please let us know! +```bash +make docs-venv +make build-docs +make serve-docs +``` -## File structure +The first command installs dependencies into the ignored `docs/.venv`. +`build-docs` generates references and runs a strict MkDocs build. +`serve-docs` serves a local preview at `http://127.0.0.1:8000`, it does not +modify any published version or redirect. -All documentation-related items live in `docs` (with the small exception of various `make` targets and some helper -scripts in `hack`). +The API generator scans this checkout's `sdk/apis` using a pinned +`crd-ref-docs` version. The CLI generator uses this checkout's Cobra +command tree. Generated references and the built site are ignored by git. +After changing API types or CLI definitions, restart the preview or run +`make generate-docs` again. -The structure of `docs` is as follows: +## Non-default v2 publication -| Path | Description | -|-----------------------------|-----------------------------------------------------------------------------------| -| config/$language/mkdocs.yml | Language-specific `mkdocs` configuration. | -| content/$language | Language-specific website content. | -| generated/branch | All generated content for all languages for the current version. | -| generated/branch/$language | Generated content for a single language. Never added to git. | -| generated/branch/index.html | Minimal index for the current version that redirects to the default language (en) | -| overrides | Global (not language-specific) content. | -| Dockerfile | Builds the kcp-docs image containing mkdocs + associated tooling. | -| mkdocs.yml | Minimal `mkdocs` configuration for `mike` for multi-version support. | -| requirements.txt | List of Python modules used to build the site. | +The preview is always published as **`v2`**, displayed in the +version selector as **v2 (preview)**: -## Publishing Workflow + -All documentation building and publishing is done using GitHub Actions in -[docs-gen-and-push.yaml](../.github/workflows/docs-gen-and-push.yaml). The overall sequence is: +Publication deliberately does **not** derive the version from the newest +tag, assign the `latest` alias, call `mike set-default`, or replace the +root redirect. The existing 0.x versions, `latest`, and custom domain +stay in the `gh-pages` branch. -1. Generate CLI docs -2. Generate API docs -3. Run `mkdocs build` for all languages -4. Run `mike deploy --push` +The **Docs** workflow (`.github/workflows/docs-gen-and-push.yaml`) +builds relevant pull requests without deployment. Pushes to `v2-next` +or the temporary `docs-v2` preparation branch, and manual dispatches on +those branches, can publish only in `kbind-dev/kbind` once the workflow +is committed there. Forks build but +cannot publish to the canonical site. Publication shares the `Docs` +concurrency group with the stable docs workflow and never force-pushes. -## Theme Overrides +## Publish a checkout manually -The goal is to have no full overrides of any theme partials. We currently override `header.html` to customize the -way the language selection dropdown is rendered. We are working with the theme developers to see if we can help make -some changes upstream that don't require an override. +Use a clean checkout containing the intended documentation, review its +build, and confirm the selected remote is the canonical repository. For +example, if it is named `upstream`: + +```bash +git remote get-url upstream +make docs-venv +REMOTE=upstream make deploy-docs +git diff --stat upstream/gh-pages..gh-pages +git diff upstream/gh-pages..gh-pages -- versions.json index.html CNAME latest +git push upstream gh-pages:gh-pages +``` + +`deploy-docs` fetches the existing publishing branch and makes a local mike +commit. **It does not push by default.** Review that only `v2/` and the +new `versions.json` entry changed before pushing. If someone publishes in +the meantime, fetch and rebuild on the updated branch rather than +force-pushing. + +CI passes `PUSH=1` to publish immediately after the strict build. +`REMOTE` defaults to `origin` and `BRANCH` to `gh-pages`, override them +only deliberately. There is intentionally no `VERSION` or default-version +switch in the preview publisher. Making v2 the stable default is a +separate release decision. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 000000000..4dbb5ab0b --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,167 @@ +# Releasing + +This document describes how to cut a v2 release and how to create release +branches for future maintenance. + +## How releases work + +Releases are driven entirely by git tags. Pushing a tag that matches `v*` +triggers the [Image workflow](../.github/workflows/image.yaml), which builds the +multi-arch `konnector` and `backend` images and pushes them to the GitHub +Container Registry: + +``` +ghcr.io//konnector: +ghcr.io//backend: +``` + +The same workflow publishes `konnector-v2` and `backend-v2` OCI Helm charts +under `oci://ghcr.io//charts`. Their chart version drops the leading +`v`, while `appVersion` retains it to select the matching image tag. + +There is no `:latest` or `:` tag, the image registry is shared with the +0.x/`main` images, so only the exact version tag is published. + +The [CLI workflow](../.github/workflows/cli.yaml) publishes CLI archives and +updates krew only for final tags. Prerelease users must build the CLI from +the intended checkout. + +Version tags follow [semantic versioning](https://semver.org): + +- `v2.0.0-rc1`, `v2.0.0-rc2`, …, release candidates (pre-releases). +- `v2.0.0`, the final GA release. +- `v2.0.1`, `v2.1.0`, …, patch / minor releases. + +## Cutting a release candidate + +Release candidates are cut directly from `v2-next` (the v2 development branch) +until GA, then from the release branch (see below). + +### The `release` helper + +Rather than working out the next rc number by hand, use the +[`cmd/release`](../cmd/release) tool. It reads the tags already on the upstream +remote, finds the highest rc for the target version, and creates the next one: + +```bash +# see what the next tag would be, without creating anything +go run ./cmd/release -dry-run + +# create the next rc tag locally (e.g. v2.0.0-rc3) +go run ./cmd/release + +# create AND push it (this triggers the Image workflow) +go run ./cmd/release -push +``` + +Flags: `-remote` (default `origin`), `-version` (default `v2.0.0`, the GA +version the candidates lead up to), `-push`, and `-dry-run`. The tag is created +on your current `HEAD`, so check out the commit you intend to release first. + +### Cutting one by hand + +1. Make sure your local checkout is up to date and on the branch you are + releasing from: + + ```bash + git checkout v2-next + git pull --ff-only + ``` + +2. Confirm CI is green for the commit you are about to tag. + +3. Create an annotated tag and push it: + + ```bash + git tag -a v2.0.0-rc1 -m "v2.0.0-rc1" + git push origin v2.0.0-rc1 + ``` + +4. The Image workflow runs automatically. When it finishes, images are + available at `ghcr.io//{konnector,backend}:v2.0.0-rc1`, and OCI + charts at `oci://ghcr.io//charts/{konnector-v2,backend-v2}` + with version `2.0.0-rc1`. + +5. (Optional) Create a GitHub Release from the tag and mark it as a + pre-release: + + ```bash + gh release create v2.0.0-rc1 --prerelease --generate-notes + ``` + +Repeat with `-rc2`, `-rc3`, … as needed until the candidate is stable. + +## Cutting the GA release + +Once a release candidate is deemed stable, tag the same commit (or the tip of +the release branch) as the final version: + +```bash +git tag -a v2.0.0 -m "v2.0.0" +git push origin v2.0.0 +gh release create v2.0.0 --generate-notes +``` + +## Creating a release branch + +Once `v2.0.0` ships, create a long-lived `release-2.0` branch so that +`v2-next`/`main` can move on to the next minor version while patch releases can +still be cut from the stable line. + +1. Branch from the GA tag (or the commit you released): + + ```bash + git checkout -b release-2.0 v2.0.0 + git push origin release-2.0 + ``` + +2. Wire the branch into CI so pushes and PRs against it run the test suite. In + [.github/workflows/ci.yaml](../.github/workflows/ci.yaml), add the branch to + both the `push` and `pull_request` branch lists: + + ```yaml + on: + push: + branches: + - main + - v2-next + - release-2.0 + pull_request: + branches: + - main + - v2-next + - release-2.0 + ``` + + (The Image workflow triggers on `v*` tags regardless of branch, so it needs + no change.) + +### Patch releases from a release branch + +Cherry-pick or merge fixes into `release-2.0`, then tag the patch version from +that branch: + +```bash +git checkout release-2.0 +git pull --ff-only +# ... land fixes here ... +git tag -a v2.0.1 -m "v2.0.1" +git push origin v2.0.1 +gh release create v2.0.1 --generate-notes +``` + +## Naming conventions + +Documentation publication is separate from binary releases. The +[v2 preview publisher](README.md) deploys +`v2` without moving `latest` or the site's default redirect, including +when v2 release-candidate tags exist. Promoting v2 to the default docs +requires a separate, explicit change. + +| Kind | Example | Cut from | +|------------------|----------------|-----------------| +| Release candidate| `v2.0.0-rc1` | `v2-next` | +| GA release | `v2.0.0` | `v2-next` | +| Release branch | `release-2.0` | tag `v2.0.0` | +| Patch release | `v2.0.1` | `release-2.0` | +| Next minor branch| `release-2.1` | tag `v2.1.0` | diff --git a/docs/content/.pages b/docs/content/.pages index 8af9ab093..eb74d4c17 100644 --- a/docs/content/.pages +++ b/docs/content/.pages @@ -1,6 +1,7 @@ nav: - Home: - index.md + - Community: community - Setup: setup - Usage: usage - Contributing: contributing diff --git a/docs/content/blog/assets/kbind-v2-getting-started/checkout-db.yaml b/docs/content/blog/assets/kbind-v2-getting-started/checkout-db.yaml new file mode 100644 index 000000000..67b9c644a --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-getting-started/checkout-db.yaml @@ -0,0 +1,8 @@ +apiVersion: startup.example/v1 +kind: Database +metadata: + name: checkout-db + namespace: default +spec: + plan: starter + storageGB: 10 diff --git a/docs/content/blog/assets/kbind-v2-getting-started/database-binding.yaml b/docs/content/blog/assets/kbind-v2-getting-started/database-binding.yaml new file mode 100644 index 000000000..d068a693a --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-getting-started/database-binding.yaml @@ -0,0 +1,36 @@ +apiVersion: core.kbind.io/v1alpha1 +kind: Connection +metadata: + name: database-provider +spec: + kubeconfigSecretRef: + namespace: kbind + name: database-provider-kubeconfig + key: kubeconfig + schema: + source: CRD +--- +apiVersion: core.kbind.io/v1alpha1 +kind: ClusterBinding +metadata: + name: startup-databases +spec: + connectionRef: + name: database-provider + apis: + - name: databases.startup.example + relatedResources: + - group: "" + resource: secrets + direction: FromProvider + selector: + labelSelector: + matchLabels: + databases.startup.example/related: checkout-db + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + databases.startup.example/related: checkout-db diff --git a/docs/content/blog/assets/kbind-v2-getting-started/provider-database.yaml b/docs/content/blog/assets/kbind-v2-getting-started/provider-database.yaml new file mode 100644 index 000000000..d6549f909 --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-getting-started/provider-database.yaml @@ -0,0 +1,73 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: databases.startup.example + labels: + core.kbind.io/exported: "true" +spec: + group: startup.example + names: + plural: databases + singular: database + kind: Database + listKind: DatabaseList + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + required: [plan, storageGB] + properties: + plan: + type: string + enum: [starter, growth] + storageGB: + type: integer + minimum: 1 + status: + type: object + properties: + phase: + type: string + additionalPrinterColumns: + - name: Plan + type: string + jsonPath: .spec.plan + - name: StorageGB + type: integer + jsonPath: .spec.storageGB + - name: Phase + type: string + jsonPath: .status.phase +--- +# Static demo values. No database server is provisioned by this example. +apiVersion: v1 +kind: Secret +metadata: + name: checkout-db-credentials + namespace: default + labels: + databases.startup.example/related: checkout-db +type: Opaque +stringData: + host: checkout-db.internal.example + username: checkout + password: local-demo-only +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: checkout-db-settings + namespace: default + labels: + databases.startup.example/related: checkout-db +data: + max_connections: "20" diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/binding-bundle.jpeg b/docs/content/blog/assets/kbind-v2-service-onboarding/binding-bundle.jpeg new file mode 100644 index 000000000..9f54a774d Binary files /dev/null and b/docs/content/blog/assets/kbind-v2-service-onboarding/binding-bundle.jpeg differ diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/catalog.png b/docs/content/blog/assets/kbind-v2-service-onboarding/catalog.png new file mode 100644 index 000000000..85b7f192e Binary files /dev/null and b/docs/content/blog/assets/kbind-v2-service-onboarding/catalog.png differ diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/checkout-db.yaml b/docs/content/blog/assets/kbind-v2-service-onboarding/checkout-db.yaml new file mode 100644 index 000000000..67b9c644a --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-service-onboarding/checkout-db.yaml @@ -0,0 +1,8 @@ +apiVersion: startup.example/v1 +kind: Database +metadata: + name: checkout-db + namespace: default +spec: + plan: starter + storageGB: 10 diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/connected-cluster.png b/docs/content/blog/assets/kbind-v2-service-onboarding/connected-cluster.png new file mode 100644 index 000000000..131d581a3 Binary files /dev/null and b/docs/content/blog/assets/kbind-v2-service-onboarding/connected-cluster.png differ diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/database-catalog.yaml b/docs/content/blog/assets/kbind-v2-service-onboarding/database-catalog.yaml new file mode 100644 index 000000000..4f2d2a463 --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-service-onboarding/database-catalog.yaml @@ -0,0 +1,36 @@ +apiVersion: catalog.kbind.io/v1alpha1 +kind: Export +metadata: + name: startup-databases +spec: + title: Startup Databases + description: A simulated database service for the checkout application. + apis: + - name: databases.startup.example + defaults: + conflictPolicy: Fail + relatedResources: + - group: "" + resource: secrets + direction: FromProvider + selector: + labelSelector: + matchLabels: + databases.startup.example/related: checkout-db + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + databases.startup.example/related: checkout-db +--- +apiVersion: catalog.kbind.io/v1alpha1 +kind: Collection +metadata: + name: startup-stack +spec: + title: Startup Stack + description: Shared services for a growing startup. + exports: + - name: startup-databases diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/login.png b/docs/content/blog/assets/kbind-v2-service-onboarding/login.png new file mode 100644 index 000000000..1a214e9cb Binary files /dev/null and b/docs/content/blog/assets/kbind-v2-service-onboarding/login.png differ diff --git a/docs/content/blog/assets/kbind-v2-service-onboarding/provider-database.yaml b/docs/content/blog/assets/kbind-v2-service-onboarding/provider-database.yaml new file mode 100644 index 000000000..d6549f909 --- /dev/null +++ b/docs/content/blog/assets/kbind-v2-service-onboarding/provider-database.yaml @@ -0,0 +1,73 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: databases.startup.example + labels: + core.kbind.io/exported: "true" +spec: + group: startup.example + names: + plural: databases + singular: database + kind: Database + listKind: DatabaseList + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + required: [plan, storageGB] + properties: + plan: + type: string + enum: [starter, growth] + storageGB: + type: integer + minimum: 1 + status: + type: object + properties: + phase: + type: string + additionalPrinterColumns: + - name: Plan + type: string + jsonPath: .spec.plan + - name: StorageGB + type: integer + jsonPath: .spec.storageGB + - name: Phase + type: string + jsonPath: .status.phase +--- +# Static demo values. No database server is provisioned by this example. +apiVersion: v1 +kind: Secret +metadata: + name: checkout-db-credentials + namespace: default + labels: + databases.startup.example/related: checkout-db +type: Opaque +stringData: + host: checkout-db.internal.example + username: checkout + password: local-demo-only +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: checkout-db-settings + namespace: default + labels: + databases.startup.example/related: checkout-db +data: + max_connections: "20" diff --git a/docs/content/blog/posts/2026-02-14-kube-bind-internals.md b/docs/content/blog/posts/2026-02-14-kube-bind-internals.md index 46ff4a27d..5a2519296 100644 --- a/docs/content/blog/posts/2026-02-14-kube-bind-internals.md +++ b/docs/content/blog/posts/2026-02-14-kube-bind-internals.md @@ -9,7 +9,10 @@ authors: # Deep Dive: Understanding kube-bind Internals -> **Note:** Just want to get started quickly? Check out our [Quick Start Guide](2026-02-14-kube-bind-quickstart.md) which sets up everything automatically with `kubectl bind dev create`. This article explains the machinery under the hood—the "Hard Way". +!!! note "Historical 0.x article" + This article is preserved from the 0.x documentation. Its commands and API names are not v2 instructions, use the [v2 quickstart](../../setup/quickstart.md). + +> **Note:** Just want to get started quickly? Check out our [Quick Start Guide](2026-02-14-kube-bind-quickstart.md) which sets up everything automatically with `kubectl bind dev create`. This article explains the machinery under the hood, the "Hard Way". If you’ve ever tried to make one cluster consume resources from another, you’ve probably had to deal with complicated networking setups, VPN tunnels, duplicated Custom Resource Definitions (CRDs), or custom-built controllers to keep everything in sync. @@ -160,8 +163,7 @@ To ensure authentication works correctly and enable cross-cluster connectivity, sudo sh -c "echo '127.0.0.1 kube-bind-backend.kube-bind.svc provider-control-plane' >> /etc/hosts" ``` -**Windows**: -Add `127.0.0.1 kube-bind-backend.kube-bind.svc` to `C:\Windows\System32\drivers\etc\hosts`. +**Windows**: Add `127.0.0.1 kube-bind-backend.kube-bind.svc` to `C:\Windows\System32\drivers\etc\hosts`. Now, install the backend using Helm, configuring it to use this domain: @@ -209,8 +211,7 @@ Since we are running locally in Kind without an Ingress, we need to port-forward kubectl port-forward svc/kube-bind-backend -n kube-bind 8080:8080 --context kind-provider ``` -![Kube Bind Authentication Required](images/auth-required.png) -_If you visit `http://kube-bind-backend.kube-bind.svc:8080` in your browser, you'll see this screen. This is normal and confirms the backend is running!_ +![Kube Bind Authentication Required](images/auth-required.png) _If you visit `http://kube-bind-backend.kube-bind.svc:8080` in your browser, you'll see this screen. This is normal and confirms the backend is running!_ ### Step 3: Exporting an API Service @@ -341,8 +342,7 @@ Check the Konnector pods: kubectl get po -n kube-bind ``` -Output: -We can see the konnector pods running in the `kube-bind` namespace. +Output: We can see the konnector pods running in the `kube-bind` namespace. ```text NAME READY STATUS RESTARTS AGE diff --git a/docs/content/blog/posts/2026-02-14-kube-bind-quickstart.md b/docs/content/blog/posts/2026-02-14-kube-bind-quickstart.md index 46bd5f8b5..05951b5d6 100644 --- a/docs/content/blog/posts/2026-02-14-kube-bind-quickstart.md +++ b/docs/content/blog/posts/2026-02-14-kube-bind-quickstart.md @@ -9,6 +9,9 @@ authors: # Getting Started with kube-bind: The Quick Way +!!! note "Historical 0.x article" + This article is preserved from the 0.x documentation. Its commands and API names are not v2 instructions, use the [v2 quickstart](../../setup/quickstart.md). + `kube-bind` facilitates service sharing between Kubernetes clusters. It allows a **Service Provider** cluster to export APIs and a **Consumer** cluster to bind to them, projecting the resources into the consumer's cluster. This enables seamless cross-cluster consumption without complex networking or federation. Here is what we will build: diff --git a/docs/content/blog/posts/2026-02-22-kube-bind-keycloak.md b/docs/content/blog/posts/2026-02-22-kube-bind-keycloak.md index 83dff8e02..8f97264ff 100644 --- a/docs/content/blog/posts/2026-02-22-kube-bind-keycloak.md +++ b/docs/content/blog/posts/2026-02-22-kube-bind-keycloak.md @@ -9,9 +9,12 @@ authors: # Securing kube-bind with Keycloak: A Production-Ready OIDC Setup +!!! note "Historical 0.x article" + The Keycloak walkthrough is preserved from the 0.x documentation. Backend flags and callbacks have changed, use the [v2 OIDC configuration](../../developers/backend/oidc/index.md). + In this tutorial, I'll be showing you how to integrate Keycloak into `kube-bind` so that authentication is handled by an external identity provider instead of the embedded mock one. -If you've been following along from the [previous posts](2026-02-14-kube-bind-internals.md), you know that `kube-bind` lets you project APIs from a provider cluster into a consumer cluster. To do that securely, it uses OIDC for authentication. In the quickstart guide, we used the embedded OIDC provider — which is great for tinkering locally, but absolutely not something you'd ship to production. +If you've been following along from the [previous posts](2026-02-14-kube-bind-internals.md), you know that `kube-bind` lets you project APIs from a provider cluster into a consumer cluster. To do that securely, it uses OIDC for authentication. In the quickstart guide, we used the embedded OIDC provider, which is great for tinkering locally, but absolutely not something you'd ship to production. In production, you want a proper identity provider. One that manages users, groups, tokens, and sessions correctly. For this, we'll be making use of Keycloak. @@ -47,7 +50,7 @@ graph TB Konnector --> BoundCRD ``` -The key difference from the dev setup is steps 2 and 3 — instead of clicking through a mock login screen, users are redirected to Keycloak's real login page. `kube-bind` validates the resulting tokens against Keycloak's OIDC discovery endpoint. +The key difference from the dev setup is steps 2 and 3, instead of clicking through a mock login screen, users are redirected to Keycloak's real login page. `kube-bind` validates the resulting tokens against Keycloak's OIDC discovery endpoint. ## Prerequisites @@ -56,7 +59,7 @@ You'll need: - [kind](https://kind.sigs.k8s.io/) - [kubectl](https://kubernetes.io/docs/tasks/tools/) - [Helm](https://helm.sh/) 3.x -- The `kube-bind` CLI — see [Quick Start](2026-02-14-kube-bind-quickstart.md) for installation +- The `kube-bind` CLI, see [Quick Start](2026-02-14-kube-bind-quickstart.md) for installation > **Note:** We'll use port-forwarding here to keep things simple. A production setup would use a proper Ingress or Gateway with TLS. See [Installation with Helm](../../setup/helm.md) for that. @@ -168,8 +171,7 @@ Wait for it to come up (Heads up: this chart deploys a **StatefulSet**, not a De kubectl rollout status statefulset/keycloak -n keycloak --timeout=120s ``` -Patch the service to expose port 8443 for OIDC compatibility since we're -technically running the cluster in our local machine. +Patch the service to expose port 8443 for OIDC compatibility since we're technically running the cluster in our local machine. ```bash kubectl patch service keycloak-http -n keycloak --type='json' -p='[ @@ -196,14 +198,14 @@ Log in with `admin` / `admin123`. You should see the Keycloak admin console. This is the most important step. We need to set up a few things in Keycloak: -1. A **Realm** — a logical namespace for our identity space -2. A **Client** — representing the `kube-bind` backend -3. A **Group** — to control which users can bind services -4. A **User** — so we have someone to log in as +1. A **Realm**, a logical namespace for our identity space +2. A **Client**, representing the `kube-bind` backend +3. A **Group**, to control which users can bind services +4. A **User**, so we have someone to log in as ### Create a Realm -In the top-left corner of the admin console, you'll see a **Manage realms** option; click it. You'll see a list of realms, one of which is named `master`. We won't be using that one. Click on the **Create realm** button. +In the top-left corner of the admin console, you'll see a **Manage realms** option, click it. You'll see a list of realms, one of which is named `master`. We won't be using that one. Click on the **Create realm** button. ![Create Keycloak Realm](images/keycloak-create-realm.png) @@ -398,7 +400,7 @@ Run the login command: kubectl bind login http://kube-bind.local:8080 ``` -Your browser will open — and instead of the mock login page, you'll see **Keycloak's real login form**. Log in with `platform-operator` and the password you set earlier. +Your browser will open, and instead of the mock login page, you'll see **Keycloak's real login form**. Log in with `platform-operator` and the password you set earlier. ![Keycloak Login Form](images/keycloak-login-form.png) @@ -481,7 +483,7 @@ NAME AGE wyatt-earp 4s ``` -The resource is created in the consumer cluster and synced to the provider — all authenticated through Keycloak. +The resource is created in the consumer cluster and synced to the provider, all authenticated through Keycloak. --- diff --git a/docs/content/blog/posts/2026-11-24-kbind-v2-getting-started.md b/docs/content/blog/posts/2026-11-24-kbind-v2-getting-started.md new file mode 100644 index 000000000..791ded012 --- /dev/null +++ b/docs/content/blog/posts/2026-11-24-kbind-v2-getting-started.md @@ -0,0 +1,290 @@ +--- +title: "kbind v2: Getting Started" +description: "Connect two Kubernetes clusters with kbind v2 and synchronize a simulated Database API without a backend." +icon: material/database-sync +date: 2026-11-24 +authors: + - olamilekan000 +slug: kbind-v2-getting-started +--- + +# kbind v2: Getting Started + +*Part 1: Connect two Kubernetes clusters and explore the new API model.* + +Kubernetes gives us a familiar way to request services: declare what we want in a resource and let a controller work toward that desired state. Consuming a service often means installing its operator in every cluster that needs it. **kbind**, formerly kube-bind, offers another approach: providers operate services centrally while consumers create and inspect resources in their own clusters using familiar tools such as `kubectl`. + +A consumer-side agent called the **konnector** synchronizes resource specifications to the provider and brings status back. In v2, this synchronization core is separated from the optional backend for authentication, catalog discovery, and credential issuance. We’ll start with the core, using a startup’s checkout database as our example. + + + +## What changed in v2? + +The basic relationship stays familiar: the consumer declares desired state, and the provider operates the service. What changes is the machinery connecting them. + +| Earlier kube-bind model | v2 | +|---|---| +| Provider connection spread across binding objects and credentials | An explicit `Connection` references provider credentials | +| Earlier binding/export machinery | `Binding` and `ClusterBinding` select APIs to synchronize | +| Backend-driven binding protocol | Core objects can be supplied directly; backend onboarding is optional | +| `BoundSchema` intermediates | CRDs are pulled directly or synthesized from OpenAPI | +| Namespace mapping and isolation modes | The stock engine preserves scope, namespace, and name | +| Permission claims and reference machinery | Explicit selectors for related Secrets and ConfigMaps | + +The core uses three resource kinds under `core.kbind.io/v1alpha1`: + +| Kind | Purpose | +|---|---| +| `Connection` | Connect to a provider and control API discovery and schema delivery | +| `ClusterBinding` | Synchronize selected APIs across the consumer cluster | +| `Binding` | Synchronize selected namespaced APIs within one consumer namespace | + +A Kubernetes Secret supplies the provider kubeconfig. The optional service layer adds catalog `Export` and `Collection` resources, plus an IAM `Grant` for credential issuance. We’ll cover those in Part 2. + +Earlier objects such as `APIServiceBinding`, `BoundSchema`, and `APIServiceNamespace` no longer drive the core. The new consumer-side `ClusterBinding` also has a different meaning from the old provider-side kind. These are new APIs, not manifests you can upgrade by changing `apiVersion`. Existing deployments need a deliberate migration; there is no supported automatic conversion of old bindings. [Migration guide](../../usage/migration.md) + +## Example: + +Imagine a startup whose application team needs a database for its checkout service. The team declares this in its own cluster: + +```yaml +apiVersion: startup.example/v1 +kind: Database +metadata: + name: checkout-db + namespace: default +spec: + plan: starter + storageGB: 10 +``` + +The provider receives the request, and the consumer receives the resulting status. We’ll also synchronize a credentials Secret and a settings ConfigMap from the provider. + +**This is a simulated database API.** We’ll create real Kubernetes resources and verify synchronization, but we won’t provision PostgreSQL or another database server. The credentials are static demo values, and we’ll manually simulate the provider controller’s status update. + +## 1. Prepare the source and samples + +You need Docker running, kind, kubectl, Git, make, and Go matching the repository’s `go.mod`. This walkthrough uses the v2 development source and disposable clusters. + +Clone the repository and select the revision used for this example: + +```bash +git clone --branch v2-next https://github.com/kbind-dev/kbind.git +cd kbind +git checkout 85d25389c44c57cee5b324eb1559533535f172cc + +make konnector +``` + +Save these three manifests in the root of your `kbind` checkout: + +| File | Applied to | Contents | +|---|---|---| +| [provider-database.yaml](../assets/kbind-v2-getting-started/provider-database.yaml) | Provider | Database CRD, credentials Secret, settings ConfigMap | +| [database-binding.yaml](../assets/kbind-v2-getting-started/database-binding.yaml) | Consumer | Connection and ClusterBinding | +| [checkout-db.yaml](../assets/kbind-v2-getting-started/checkout-db.yaml) | Consumer | The database request | + +Run the remaining commands from that checkout root. + +## 2. Create the provider and consumer clusters + +Use fresh clusters with these names: + +```bash +kind create cluster --name startup-provider \ + --kubeconfig "$PWD/provider.kubeconfig" --wait 120s + +kind create cluster --name startup-consumer \ + --kubeconfig "$PWD/consumer.kubeconfig" --wait 120s +``` + +Both kubeconfigs use host-mapped endpoints. We’ll therefore run the konnector on our workstation. Those addresses would not work unchanged inside a Pod in another cluster. + +## 3. Publish the Database API + +Apply the provider sample and wait for its CRD: + +```bash +kubectl --kubeconfig=provider.kubeconfig \ + apply -f provider-database.yaml + +kubectl --kubeconfig=provider.kubeconfig wait \ + --for=condition=Established \ + crd/databases.startup.example --timeout=120s +``` + +The CRD defines `Database` with `spec.plan`, `spec.storageGB`, and `status.phase`. It also carries the export label: + +```yaml +metadata: + name: databases.startup.example + labels: + core.kbind.io/exported: "true" +``` + +For CRD-based discovery, that label opts the API into kbind’s export discovery. Provider RBAC separately controls what the supplied credentials can access. The same manifest creates `checkout-db-credentials` and `checkout-db-settings` on the provider, ready for related-resource synchronization. + +## 4. Connect the consumer + +Install the three core API definitions: + +```bash +kubectl --kubeconfig=consumer.kubeconfig apply \ + -f sdk/config/crd/core.kbind.io_connections.yaml \ + -f sdk/config/crd/core.kbind.io_clusterbindings.yaml \ + -f sdk/config/crd/core.kbind.io_bindings.yaml + +kubectl --kubeconfig=consumer.kubeconfig wait \ + --for=condition=Established \ + crd/connections.core.kbind.io \ + crd/clusterbindings.core.kbind.io \ + crd/bindings.core.kbind.io \ + --timeout=120s +``` + +Create the namespace and credential Secret: + +```bash +kubectl --kubeconfig=consumer.kubeconfig create namespace kbind + +kubectl --kubeconfig=consumer.kubeconfig -n kbind \ + create secret generic database-provider-kubeconfig \ + --from-file=kubeconfig=provider.kubeconfig +``` + +This copies administrator credentials for the disposable provider into the consumer. Use restricted credentials and secure Secret delivery for a real deployment. Keep these generated kubeconfigs out of version control. + +Now apply the binding: + +```bash +kubectl --kubeconfig=consumer.kubeconfig \ + apply -f database-binding.yaml +``` + +Open that file to see the relationship. `Connection/database-provider` references the credential Secret and selects CRD-based schema discovery. `ClusterBinding/startup-databases` references that Connection, selects `databases.startup.example`, and defines selectors for the related resources. + +**The Connection establishes the provider link; the binding activates synchronization for the selected API.** + +## 5. Start the konnector + +In a second terminal, from the same checkout: + +```bash +KUBECONFIG="$PWD/consumer.kubeconfig" ./bin/konnector +``` + +Leave it running. Back in the first terminal, wait for the connection, binding, and imported Database CRD: + +```bash +kubectl --kubeconfig=consumer.kubeconfig wait \ + --for=condition=Ready \ + connection/database-provider \ + clusterbinding/startup-databases \ + --timeout=120s + +kubectl --kubeconfig=consumer.kubeconfig wait \ + --for=condition=Established \ + crd/databases.startup.example --timeout=120s +``` + +The consumer now serves the Database API without running a database-specific controller. + +## 6. Request the checkout database + +Create the request on the consumer: + +```bash +kubectl --kubeconfig=consumer.kubeconfig \ + apply -f checkout-db.yaml +``` + +Wait for the provider copy, then verify both requested fields: + +```bash +kubectl --kubeconfig=provider.kubeconfig -n default wait \ + --for=create database/checkout-db --timeout=120s + +kubectl --kubeconfig=provider.kubeconfig -n default wait \ + --for=jsonpath='{.spec.plan}'=starter \ + database/checkout-db --timeout=120s + +kubectl --kubeconfig=provider.kubeconfig -n default wait \ + --for=jsonpath='{.spec.storageGB}'=10 \ + database/checkout-db --timeout=120s +``` + +These checks establish that the desired state reached the provider. A real database controller would act on that provider-side resource. + +## 7. Return status to the application team + +Simulate the provider controller reporting that the database is ready: + +```bash +kubectl --kubeconfig=provider.kubeconfig -n default \ + patch database checkout-db --subresource=status --type=merge \ + -p '{"status":{"phase":"Ready"}}' +``` + +Wait for that status on the consumer: + +```bash +kubectl --kubeconfig=consumer.kubeconfig -n default wait \ + --for=jsonpath='{.status.phase}'=Ready \ + database/checkout-db --timeout=120s + +kubectl --kubeconfig=consumer.kubeconfig -n default get databases +``` + +Expected output: + +```text +NAME PLAN STORAGEGB PHASE +checkout-db starter 10 Ready +``` + +The application team can inspect its request and the provider’s reported state from its own cluster. + +## 8. Verify credentials and settings synchronization + +The binding selects the provider’s labeled Secret and ConfigMap independently of the Database instance. Wait for their consumer copies: + +```bash +kubectl --kubeconfig=consumer.kubeconfig -n default wait \ + --for=create \ + secret/checkout-db-credentials \ + configmap/checkout-db-settings \ + --timeout=120s +``` + +Check ownership without printing Secret data: + +```bash +kubectl --kubeconfig=consumer.kubeconfig -n default get \ + secret/checkout-db-credentials configmap/checkout-db-settings \ + -o 'custom-columns=NAME:.metadata.name,BINDING:.metadata.annotations.core\.kbind\.io/related-binding' + +kubectl --kubeconfig=consumer.kubeconfig \ + get clusterbinding startup-databases \ + -o jsonpath='{.metadata.uid}{"\n"}' +``` + +Both `BINDING` values should match the ClusterBinding UID. The related resources were created on the provider; the consumer manifests contain only the binding inputs and the Database request. + +## 9. Clean up + +Stop the konnector with Ctrl-C, then remove the disposable clusters and credentials: + +```bash +kind delete cluster --name startup-consumer +kind delete cluster --name startup-provider + +rm consumer.kubeconfig provider.kubeconfig +``` + +For existing deployments, follow the documented unbinding procedure while controllers and credentials remain available. Binding deletion can trigger cleanup of synchronized resources. [Unbinding guidance](../../usage/gitops.md#pruning-is-unbinding) + +## Coming in Part 2 + +We supplied credentials and bindings directly. A provider serving multiple consumers also needs an onboarding workflow: authenticate the consumer, show available services, and issue credentials. + +In [kbind v2: From Core Sync to Service Onboarding](2026-11-26-kbind-v2-service-onboarding.md), we’ll add the optional backend and explore `Export`, `Collection`, and `Grant`. The backend will produce the same core inputs we created manually here. diff --git a/docs/content/blog/posts/2026-11-26-kbind-v2-service-onboarding.md b/docs/content/blog/posts/2026-11-26-kbind-v2-service-onboarding.md new file mode 100644 index 000000000..d38c8f593 --- /dev/null +++ b/docs/content/blog/posts/2026-11-26-kbind-v2-service-onboarding.md @@ -0,0 +1,262 @@ +--- +title: "kbind v2: From Core Sync to Service Onboarding" +description: "Publish a Database offering, authenticate consumers, and bind services through the optional kbind v2 backend." +icon: material/database-sync +date: 2026-11-26 +authors: + - olamilekan000 +slug: kbind-v2-service-onboarding +--- + +# kbind v2: From Core Sync to Service Onboarding + +*Part 2: Publish a service and let the backend handle onboarding.* + +In [Part 1](2026-11-24-kbind-v2-getting-started.md), we connected two Kubernetes clusters by supplying provider credentials, a Connection, and a ClusterBinding directly. The konnector sent our `checkout-db` specification to the provider and returned its status to the consumer. That is the core of kbind: consumers work with APIs in their own clusters while providers operate the services elsewhere. + +Supplying those inputs manually is useful for learning and automation. A provider serving application teams also needs a way to present its services, authenticate consumers, and issue credentials. The optional backend supplies that workflow. We’ll use the same simulated Database API, this time discovering and binding it through the catalog and CLI. + + + +## What the backend adds + +Three provider-side APIs describe the service layer: + +| Kind | API group | Purpose | +|---|---|---| +| `Export` | `catalog.kbind.io/v1alpha1` | Describe a service offering, its APIs, and binding defaults | +| `Collection` | `catalog.kbind.io/v1alpha1` | Group offerings for browsing | +| `Grant` | `iam.kbind.io/v1alpha1` | Record issued access and the associated credential resources | + +The backend combines a gateway for authentication and HTTP requests with an issuer that provisions credentials. Binding an Export creates or updates a Grant, waits for issuance, and returns a bundle containing a Secret, Connection, and ClusterBinding. Those are the same core inputs we supplied in Part 1. The konnector then talks directly to the provider API; the gateway is outside the synchronization path. + +## Prepare a fresh environment + +Use fresh clusters for this article. Reusing Part 1’s consumer would leave a manual binding managing the same API. You need Docker, kind, kubectl, Git, make, and Go matching `go.mod`. + +```bash +git clone --branch v2-next https://github.com/kbind-dev/kbind.git kbind-onboarding +cd kbind-onboarding +git checkout 85d25389c44c57cee5b324eb1559533535f172cc + +make backend konnector bind +install -m 0755 bin/bind bin/kubectl-bind +export PATH="$PWD/bin:$PATH" +``` + +Save these three manifests in the root of this checkout: + +| File | Purpose | +|---|---| +| [provider-database.yaml](../assets/kbind-v2-service-onboarding/provider-database.yaml) | Exported Database CRD and static related resources | +| [database-catalog.yaml](../assets/kbind-v2-service-onboarding/database-catalog.yaml) | Database offering and its Collection | +| [checkout-db.yaml](../assets/kbind-v2-service-onboarding/checkout-db.yaml) | Consumer’s Database request | + +Run all commands from the checkout root. The example synchronizes a simulated API, not a running database server. Its Secret contains demonstration values, and we’ll patch status to simulate a service controller. + +```bash +kind create cluster --name startup-services-provider \ + --kubeconfig "$PWD/services-provider.kubeconfig" --wait 120s +kind create cluster --name startup-services-consumer \ + --kubeconfig "$PWD/services-consumer.kubeconfig" --wait 120s +``` + +## Start the backend and publish the offering + +In a second terminal at the checkout root, start the provider backend: + +```bash +KUBECONFIG="$PWD/services-provider.kubeconfig" ./bin/backend \ + --oidc-mock --external-url=http://localhost:8080 +``` + +Leave it running. `--oidc-mock` starts a development identity provider that automatically approves logins. Use a real OIDC configuration for deployments beyond this local exercise. The backend installs its service-layer CRDs; back in the first terminal, wait for them before applying the samples: + +```bash +kubectl --kubeconfig=services-provider.kubeconfig wait \ + --for=condition=Established \ + crd/exports.catalog.kbind.io crd/collections.catalog.kbind.io \ + crd/grants.iam.kbind.io --timeout=120s + +kubectl --kubeconfig=services-provider.kubeconfig apply \ + -f provider-database.yaml -f database-catalog.yaml + +kubectl --kubeconfig=services-provider.kubeconfig wait \ + --for=condition=Ready \ + exports.catalog.kbind.io/startup-databases --timeout=120s +``` + +Open `database-catalog.yaml`. The Export `startup-databases` selects `databases.startup.example` and supplies defaults for copying the credentials Secret and settings ConfigMap from the provider. The Collection `startup-stack` groups that offering for browsing. Collections do not grant access or bind their members as a unit. + +Export readiness confirms that the named CRD exists and has the export label. It does not mean a database controller is running or that an individual database is healthy. Related-resource selectors choose what to synchronize; they do not narrow the issued RBAC to those labels. The default cluster-wide issuer grants Secret reads across provider namespaces for this offering, so use a disposable provider and review [credential scope](../../developers/backend/index.md#credential-scope-and-installer-privileges) before adapting it to shared infrastructure. + +## Prepare the consumer + +Install the core definitions: + +```bash +kubectl --kubeconfig=services-consumer.kubeconfig apply \ + -f sdk/config/crd/core.kbind.io_connections.yaml \ + -f sdk/config/crd/core.kbind.io_clusterbindings.yaml \ + -f sdk/config/crd/core.kbind.io_bindings.yaml + +kubectl --kubeconfig=services-consumer.kubeconfig wait \ + --for=condition=Established \ + crd/connections.core.kbind.io crd/clusterbindings.core.kbind.io \ + crd/bindings.core.kbind.io --timeout=120s +``` + +In a third terminal at the checkout root, start the konnector: + +```bash +KUBECONFIG="$PWD/services-consumer.kubeconfig" ./bin/konnector +``` + +Both processes run on the workstation because these kubeconfigs use host-mapped endpoints. We have not copied the provider administrator kubeconfig into a consumer Secret. The backend will issue a service-account credential when we bind the offering. + +## Log in and bind the service + +Open `http://localhost:8080` in your browser. The landing page introduces the provider and offers a **Sign in to browse the catalog** button. Click it to continue. With `--oidc-mock`, sign-in automatically approves the demo identity and takes you to the catalog; no username or password is required. A backend configured with a real OIDC provider redirects you to that provider’s login flow instead. + +[![The kbind sign-in screen in dark mode with its Sign in to browse the catalog button](../assets/kbind-v2-service-onboarding/login.png)](../assets/kbind-v2-service-onboarding/login.png) + +*The browser entry point before authentication. All screenshots in this article use dark mode. The live UI follows your browser’s light or dark color preference.* + +Browser and CLI sessions are separate. To follow the terminal workflow, return to the first terminal and authenticate the CLI as well: + +```bash +kubectl bind login http://localhost:8080 +kubectl bind catalog +``` + +The CLI login command opens a browser for authentication and saves its own session. The catalog should include `startup-databases`, titled **Startup Databases**, in **Startup Stack**. You can also browse the catalog at `http://localhost:8080`. + +[![The kbind catalog showing Startup Databases in the Startup Stack collection](../assets/kbind-v2-service-onboarding/catalog.png)](../assets/kbind-v2-service-onboarding/catalog.png) + +*The offering shows its API and the related Secrets and ConfigMaps selected for provider-to-consumer copying.* + +```bash +kubectl bind export startup-databases \ + --kubeconfig=services-consumer.kubeconfig \ + --install-konnector=false +``` + +The konnector is already running, so we skip installation. The CLI requests a binding, redeems a one-time bundle URL, and applies the generated objects to the consumer. Unlike Part 1, we do not author a Connection, binding manifest, or provider credential Secret ourselves. + +The browser’s **Bind** button offers the same bundle through a download dialog: + +[![The Startup Databases bundle dialog with download and copy options](../assets/kbind-v2-service-onboarding/binding-bundle.jpeg)](../assets/kbind-v2-service-onboarding/binding-bundle.jpeg) + +*The browser offers a one-time bundle download and copy commands. A downloaded bundle contains credentials; encrypt its Secret or use a secret manager before storing it in Git.* + +## Inspect what was created + +Inspect both sides without exposing credentials: + +```bash +kubectl --kubeconfig=services-provider.kubeconfig get grants.iam.kbind.io +kubectl --kubeconfig=services-consumer.kubeconfig get connections,clusterbindings +``` + +The gateway generates a Grant name from the Export and authenticated identity. That name is also used for the consumer Connection, ClusterBinding, and kubeconfig Secret. There is one Grant in this fresh provider; capture its name for the remaining commands: + +```bash +GRANT=$(kubectl --kubeconfig=services-provider.kubeconfig \ + get grants.iam.kbind.io -o jsonpath='{.items[0].metadata.name}') + +kubectl --kubeconfig=services-consumer.kubeconfig wait \ + --for=condition=Ready connection/"$GRANT" clusterbinding/"$GRANT" \ + --timeout=120s + +kubectl --kubeconfig=services-consumer.kubeconfig wait \ + --for=condition=Established crd/databases.startup.example --timeout=120s +``` + +The issuer provisions the Grant’s service account, token, and RBAC on the provider. The consumer Secret contains the issued kubeconfig. The core engine uses it to discover and synchronize APIs, independently of the CLI session. + +## Request the database and verify synchronization + +```bash +kubectl --kubeconfig=services-consumer.kubeconfig apply -f checkout-db.yaml + +kubectl --kubeconfig=services-provider.kubeconfig -n default wait \ + --for=create database/checkout-db --timeout=120s +kubectl --kubeconfig=services-provider.kubeconfig -n default wait \ + --for=jsonpath='{.spec.storageGB}'=10 database/checkout-db --timeout=120s + +kubectl --kubeconfig=services-provider.kubeconfig -n default \ + patch database checkout-db --subresource=status --type=merge \ + -p '{"status":{"phase":"Ready"}}' + +kubectl --kubeconfig=services-consumer.kubeconfig -n default wait \ + --for=jsonpath='{.status.phase}'=Ready database/checkout-db --timeout=120s +kubectl --kubeconfig=services-consumer.kubeconfig -n default get databases +``` + +Expected output: + +```text +NAME PLAN STORAGEGB PHASE +checkout-db starter 10 Ready +``` + +The offering’s defaults also activate related-resource copying. Verify that the copies belong to this generated binding: + +```bash +kubectl --kubeconfig=services-consumer.kubeconfig -n default wait \ + --for=create secret/checkout-db-credentials configmap/checkout-db-settings \ + --timeout=120s +kubectl --kubeconfig=services-consumer.kubeconfig -n default get \ + secret/checkout-db-credentials configmap/checkout-db-settings \ + -o 'custom-columns=NAME:.metadata.name,BINDING:.metadata.annotations.core\.kbind\.io/related-binding' +kubectl --kubeconfig=services-consumer.kubeconfig get clusterbinding "$GRANT" \ + -o jsonpath='{.metadata.uid}{"\n"}' +``` + +Both `BINDING` values should match the ClusterBinding UID. These are static provider resources selected by the Export’s defaults, not credentials generated by a database operator. + +For a provider-side inventory, try: + +```bash +kubectl bind clusters +kubectl bind instances startup-databases +``` + +Cluster visibility follows the konnector’s heartbeat, so allow time for the first renewal. These inventories help locate connected consumers and synchronized objects; use resource status and the checks above to assess the actual service state. + +[![The Clusters view showing a live consumer with one synchronized Database](../assets/kbind-v2-service-onboarding/connected-cluster.png)](../assets/kbind-v2-service-onboarding/connected-cluster.png) + +*The Clusters view shows the connected consumer, its bound offering, and one synchronized Database.* + +## Clean up access and resources + +A login session, a one-time bundle URL, and an issued provider credential have separate lifetimes. Session expiry does not revoke the service-account credential. Deleting an Export does not revoke existing Grants either. Delete a Grant while the issuer is running to remove its provisioned credentials. + +For this disposable exercise, keep both host processes running while draining the consumer first: + +```bash +kubectl --kubeconfig=services-consumer.kubeconfig -n default \ + delete database checkout-db --timeout=120s +kubectl --kubeconfig=services-provider.kubeconfig -n default wait \ + --for=delete database/checkout-db --timeout=120s +kubectl --kubeconfig=services-consumer.kubeconfig \ + delete clusterbinding "$GRANT" --timeout=120s +kubectl --kubeconfig=services-consumer.kubeconfig \ + delete connection "$GRANT" --timeout=120s +kubectl --kubeconfig=services-provider.kubeconfig \ + delete grants.iam.kbind.io "$GRANT" --timeout=120s +``` + +Then stop the backend and konnector with Ctrl-C and remove the clusters and kubeconfigs: + +```bash +kind delete cluster --name startup-services-consumer +kind delete cluster --name startup-services-provider +rm services-consumer.kubeconfig services-provider.kubeconfig +``` + +The CLI caches its localhost session in the platform’s kbind config file; deleting the clusters does not remove that session entry. See [CLI session storage](../../usage/catalog.md#cli-sessions-and-cluster-selection) and the [credential lifecycle guide](../../usage/catalog.md#revoke-and-retire-an-offering) when adapting this workflow. + +## From manual inputs to onboarding + +Part 1 made the synchronization inputs visible by creating them directly. Here, the backend produced them after authentication and service selection. The consumer still declared `checkout-db` locally, the provider still received its specification, and status still returned through the konnector. Choose direct manifests for automation or the backend for a catalog and credential-issuance workflow; both lead to the same core objects. diff --git a/docs/content/community/index.md b/docs/content/community/index.md index a4746e690..b53da219d 100644 --- a/docs/content/community/index.md +++ b/docs/content/community/index.md @@ -4,12 +4,12 @@ kbind is built and maintained by an open community. We welcome new contributors, ## Communication channels -- **Slack:** [`#kube-bind`](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io). +- **Slack:** [`#kbind-dev`](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io). - **Mailing list:** [kube-bind-dev](https://groups.google.com/g/kube-bind-dev) for development discussions and meeting invites. ## Community meetings -We hold bi-weekly community meetings — every second Thursday at 11am EST (5pm CET). The meetings are open to everyone. +We hold bi-weekly community meetings, every second Thursday at 11am EST (5pm CET). The meetings are open to everyone. - **Get the invite:** join the [kube-bind-dev mailing list](https://groups.google.com/g/kube-bind-dev). - **Agenda and notes:** the shared [community meeting notes document](https://docs.google.com/document/d/1qztpKOmdZu5iWq_4N9n3AZpcAPuPhBiGNbje5GPg0iM) holds upcoming and past agendas. Please add your name and topic before the call. diff --git a/docs/content/contributing/index.md b/docs/content/contributing/index.md index 7082c9a78..03cf70a6a 100644 --- a/docs/content/contributing/index.md +++ b/docs/content/contributing/index.md @@ -1,23 +1,19 @@ # Contributing to kbind -kbind is [Apache 2.0 licensed](https://github.com/kbind-dev/kbind/tree/main/LICENSE) and we accept contributions via -GitHub pull requests. +kbind is [Apache 2.0 licensed](https://github.com/kbind-dev/kbind/tree/main/LICENSE) and we accept contributions via GitHub pull requests. Please read the following guide if you're interested in contributing to kube-bind. ## Certificate of Origin -By contributing to this project you agree to the Developer Certificate of -Origin (DCO). This document was created by the Linux Kernel community and is a -simple statement that you, as a contributor, have the legal right to make the -contribution. See the [DCO](https://github.com/kbind-dev/kbind/tree/main/DCO) file for details. +By contributing to this project you agree to the Developer Certificate of Origin (DCO). This document was created by the Linux Kernel community and is a simple statement that you, as a contributor, have the legal right to make the contribution. See the [DCO](https://github.com/kbind-dev/kbind/tree/main/DCO) file for details. ## Getting Started ### Prerequisites 1. Clone this repository. -2. [Install Go](https://golang.org/doc/install) (currently 1.22). +2. [Install Go](https://golang.org/doc/install) using the version declared in `go.mod`. 3. Install [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl). More on the development environment setup can be found in the [developer guide](../developers/dev-environment/index.md). @@ -39,28 +35,20 @@ Finally, we welcome and value all types of contributions, beyond "just code"! Ot ### Getting your PR Merged -The `kbind` project uses `OWNERS` files to denote the collaborators who can assist you in getting your PR merged. There -are two roles: reviewer and approver. Merging a PR requires sign off from both a reviewer and an approver. +The `kbind` project uses `OWNERS` files to denote the collaborators who can assist you in getting your PR merged. There are two roles: reviewer and approver. Merging a PR requires sign off from both a reviewer and an approver. ## Community Roles ### Reviewers -Reviewers are responsible for reviewing code for correctness and adherence to standards. Oftentimes reviewers will -be able to advise on code efficiency and style as it relates to golang or project conventions as well as other considerations -that might not be obvious to the contributor. +Reviewers are responsible for reviewing code for correctness and adherence to standards. Oftentimes reviewers will be able to advise on code efficiency and style as it relates to golang or project conventions as well as other considerations that might not be obvious to the contributor. ### Approvers -Approvers are responsible for sign-off on the acceptance of the contribution. In essence, approval indicates that the -change is desired and good for the project, aligns with code, API, and system conventions, and appears to follow all required -process including adequate testing, documentation, follow ups, or notifications to other areas who might be interested -or affected by the change. +Approvers are responsible for sign-off on the acceptance of the contribution. In essence, approval indicates that the change is desired and good for the project, aligns with code, API, and system conventions, and appears to follow all required process including adequate testing, documentation, follow ups, or notifications to other areas who might be interested or affected by the change. Approvers are also reviewers. ### Management of `OWNERS` Files -If a reviewer or approver no longer wishes to be in their current role it is requested that a PR -be opened to update the `OWNERS` file. `OWNERS` files may be periodically reviewed and updated based on project activity -or feedback to ensure an acceptable contributor experience is maintained. +If a reviewer or approver no longer wishes to be in their current role it is requested that a PR be opened to update the `OWNERS` file. `OWNERS` files may be periodically reviewed and updated based on project activity or feedback to ensure an acceptable contributor experience is maintained. diff --git a/docs/content/developers/architecture.md b/docs/content/developers/architecture.md index cd0ba4777..8d8d53cee 100644 --- a/docs/content/developers/architecture.md +++ b/docs/content/developers/architecture.md @@ -1,353 +1,57 @@ # Architecture Overview -This document provides detailed architecture diagrams and explanations for how kube-bind handles resource synchronization between consumer and provider clusters, with a focus on isolation strategies and namespace mapping. +This is development-focused documentation intended to explain resource synchronization between consumer and provider clusters. For user-facing behavior, see the [Synchronization User Guide](../usage/synchronization.md). -This is development-focused documentation intended to help contributors understand the internal workings of kube-bind. -If you are looking for user-focused documentation, please refer to the [Synchronization User Guide](../usage/synchronization.md). +v2 separates synchronization from service discovery, authentication, and credential issuance. A core-only deployment runs one consumer-side konnector and no kbind-specific provider controller. -## Cluster-Scoped Resources +## Core control loop -Cluster-scoped resources (like Sheriffs in our examples) can use different isolation strategies to control how they are placed on the provider cluster and how their associated secrets are isolated. +| Package | Responsibility | +| --- | --- | +| `cmd/konnector` | Wire the consumer manager, multicluster manager, provider, and reconcilers | +| `engine/connection` | Resolve credential Secrets, pin cluster identity, discover APIs, handle schema policies and heartbeat Leases | +| `engine/provider` | Engage Ready Connections as multicluster-runtime provider clusters, disengage unavailable ones | +| `engine/binding` | Reconcile ClusterBinding/Binding readiness, selected APIs, related resources, and cleanup | +| `engine/crdpull` | Install and update consumer CRDs from provider CRDs | +| `engine/openapi` | Synthesize consumer CRDs from provider discovery and OpenAPI v3 | +| `engine/sync` | Start per-binding/GVR syncers, reconcile spec/status and ownership, and stop obsolete syncers | +| `engine/remote` | Read kubeconfigs and determine provider identity | +| `engine/mapper` | Compile-time object-key mapping interface | -### Architecture Flow +The consumer manager watches core resources. A Ready Connection supplies the credentials for an engaged provider cluster. Syncers use that cluster's client for writes, API reader for fresh reads, and cache watches for provider changes. A periodic resync is a backstop, not the primary status transport. -``` -CONSUMER CLUSTER PROVIDER CLUSTER (Backend) -================ ========================== - -┌─────────────────────────────┐ ┌────────────────────────────────────────────┐ -│ Namespace: wild-west │ │ Contract Namespace (per consumer): │ -│ - Secret: sheriff-badge- │──────────▶│ kube-bind- │ -│ credentials (ref) │ Sync │ │ -│ - Secret: sheriff-juris- │ │ APIServiceNamespace CR: │ -│ diction-config (label) │ │ metadata.name: wild-west │ -└─────────────────────────────┘ │ status.namespace: (varies by isolation)│ - └────────────────────────────────────────────┘ -┌─────────────────────────────┐ -│ Sheriff: wyatt-earp │──────────▶ PROVIDER CLUSTER (varies by isolation) -│ (cluster-scoped) │ Sync See isolation strategies below ↓ -│ spec.intent │ -│ spec.secretRefs: [...] │ -└─────────────────────────────┘ - ▲ - │ Status updates - └──────────────────────────────── -``` - -### Isolation Strategies for Cluster-Scoped Resources - -#### 1. IsolationPrefixed - -``` -┌────────────────────────────────────────────┐ -│ [cc-prefixed] IsolationPrefixed: │ -│ Sheriff: -wyatt-earp │ -│ (cluster-scoped, prefixed name) │ -│ Secrets in namespace: │ -│ kube-bind--wild-west │ -│ (APIServiceNamespace mapping) │ -└────────────────────────────────────────────┘ -``` - -**How it works:** -- Sheriff resource name is prefixed with consumer ID: `-wyatt-earp` -- Sheriff remains cluster-scoped on provider -- Secrets are isolated via namespace mapping: `wild-west` → `kube-bind--wild-west` -- Multiple consumers can safely coexist with different prefixed resources - -**Use case:** When you want cluster-scoped resources on the provider but need to support multiple consumers safely. - -#### 2. IsolationNone - -``` -┌────────────────────────────────────────────┐ -│ [cc-none] IsolationNone: │ -│ Sheriff: wyatt-earp │ -│ (cluster-scoped, same name on both!) │ -│ ⚠ Last write wins between consumers │ -│ Secrets in namespace: wild-west │ -│ (Same namespace name on both sides!) │ -└────────────────────────────────────────────┘ -``` - -**How it works:** -- Sheriff resource keeps the same name on both sides: `wyatt-earp` -- Sheriff remains cluster-scoped on provider -- **Namespace mapping is 1:1**: `wild-west` → `wild-west` (same name!) -- **⚠️ WARNING:** No isolation! Multiple consumers share the same namespace. This is possible but discouraged. -- Last write wins if multiple consumers create the same resource - -**Use case:** Single consumer scenarios or when you explicitly want shared resources. **Not recommended for multi-consumer environments.** - -#### 3. IsolationNamespaced - -``` -┌────────────────────────────────────────────┐ -│ [cc-namespaced] IsolationNamespaced: │ -│ Sheriff: wyatt-earp │ -│ (CRD toggled to NamespaceScoped) │ -│ in namespace: │ -│ kube-bind--wild-west │ -│ Secrets in same namespace (isolated) │ -└────────────────────────────────────────────┘ -``` - -**How it works:** -- Sheriff CRD is toggled from ClusterScoped to NamespaceScoped on the provider -- Sheriff is placed in consumer-specific namespace: `kube-bind--wild-west` -- Secrets are in the same namespace (isolated) -- Namespace mapping: `wild-west` → `kube-bind--wild-west` +When a Connection loses readiness, the provider disengages and its syncers stop. Recovery creates a fresh engaged cluster and rebuilds syncers, rather than retaining clients and caches tied to a dead connection. Leader election gates the consumer controllers and provider engagement together. -**Use case:** When you want the strongest isolation and are willing to modify the CRD scope on the provider. +For Kubernetes, cluster identity uses the `kube-system` namespace UID, on kcp-like providers it uses the `LogicalCluster` UID when available. This is identity pinning, not a replacement for TLS verification or RBAC. -### Key Insights for Cluster-Scoped Resources +## Service layer -The isolation strategy determines **BOTH** how Sheriff resources are placed **AND** how namespaces are mapped: - -- **IsolationNone**: Same namespace name on both sides (`wild-west` → `wild-west`) - - ⚠️ **NO isolation for secrets!** Multiple consumers can exist but share the same namespace (discouraged) - -- **IsolationPrefixed**: Sheriff name prefixed, secrets isolated via namespace mapping - - (`wild-west` → `kube-bind--wild-west`) - -- **IsolationNamespaced**: Sheriff becomes namespaced, secrets isolated in same namespace - - (`wild-west` → `kube-bind--wild-west`) - -## Namespaced Resources - -Namespaced resources (like Cowboys in our examples) always use the ServiceNamespaced isolation strategy, regardless of the isolation parameter. - -### Architecture Flow +`cmd/backend` wires independently enabled gateway, issuer, and reaper modules. The gateway embeds the static UI from `web/`. The CLI in `cli/` is an HTTP client for that gateway. +```mermaid +sequenceDiagram + participant U as CLI / browser + participant G as Gateway + participant I as Issuer + participant P as Provider API server + participant C as Consumer konnector + U->>G: Authenticate and select Export + G->>P: Create or update Grant + I->>P: Provision ServiceAccount, RBAC, token + U->>G: Redeem one-time bundle ticket + G-->>U: Secret + Connection + ClusterBinding + U->>C: Apply bundle to consumer + C->>P: Discover, synchronize, heartbeat ``` -CONSUMER CLUSTER PROVIDER CLUSTER (Backend) -================ ========================== - -┌─────────────────────────────┐ ┌────────────────────────────────────────────┐ -│ Namespace: wild-west │ │ Contract Namespace (per consumer): │ -│ │──────────▶│ kube-bind- │ -│ Cowboy: billy-the-kid │ Sync │ │ -│ (namespaced) │ │ APIServiceNamespace CR: │ -│ spec.intent │ │ metadata.name: wild-west │ -│ spec.secretRefs: [...] │ │ status.namespace: ─────────────────┐ │ -│ │ │ kube-bind--wild-west│ │ -│ - Secret: colt-45-permit │ └────────────────────────────────────────┼───┘ -│ (ref) │ │ -│ - Secret: cowboy-gang- │ ACTUAL PROVIDER NAMESPACE: ◀─────────────┘ -│ affiliation (label) │ ┌────────────────────────────────────────────┐ -└─────────────────────────────┘ │ Namespace: kube-bind--wild- │ - ▲ │ west │ - │ Status updates │ │ - └────────────────────────────────│ Cowboy: billy-the-kid (namespaced) │ - │ - Secret: colt-45-permit │ - │ - Secret: cowboy-gang-affiliation │ - │ │ - │ RBAC (for secret access): │ - │ - Role: kube-binder-export-wild-west- │ - │ cowboys (in this namespace) │ - │ - RoleBinding: ... (in this namespace) │ - └────────────────────────────────────────────┘ -``` - -### InformerScope Variations - -Namespaced resources support two informer scope configurations: - -#### 1. NamespacedScope (nn) - -``` -┌────────────────────────────────────────────────────────────────────┐ -│ [nn] Namespaced → Namespaced (informerScope=NamespacedScope): │ -│ - Consumer: Cowboy in namespace wild-west │ -│ - Provider: Cowboy in namespace kube-bind--wild-west │ -│ - Konnector watches only its own namespace on provider side │ -│ - Natural isolation via namespaces │ -└────────────────────────────────────────────────────────────────────┘ -``` - -**How it works:** -- Consumer resource is namespaced: `wild-west/billy-the-kid` -- Provider resource is namespaced: `kube-bind--wild-west/billy-the-kid` -- Konnector watches **only its own namespace** on the provider side -- RBAC uses namespace-scoped Roles and RoleBindings - -**Use case:** Most efficient for namespaced resources, minimizes RBAC and watch scope. - -#### 2. ClusterScope (nc) - -``` -┌────────────────────────────────────────────────────────────────────┐ -│ [nc] Namespaced → Cluster (informerScope=ClusterScope): │ -│ - Consumer: Cowboy in namespace wild-west │ -│ - Provider: Cowboy in namespace kube-bind--wild-west │ -│ - Konnector watches cluster-wide on provider side │ -│ - Still isolated via namespaces, but different RBAC model │ -└────────────────────────────────────────────────────────────────────┘ -``` - -**How it works:** -- Consumer resource is namespaced: `wild-west/billy-the-kid` -- Provider resource is namespaced: `kube-bind--wild-west/billy-the-kid` -- Konnector watches **cluster-wide** on the provider side -- RBAC uses ClusterRoles and ClusterRoleBindings -**Use case:** When you need cluster-wide visibility or have specific RBAC requirements. +Once credentials and the bundle exist, the core does not require the gateway to remain online. Grant revocation still requires the issuer to remove provisioned credentials. The optional reaper observes provider-side heartbeat Leases and removes stale Grants under its configured policy. -### Key Insights for Namespaced Resources +## Extension points and boundaries -Namespaced resources **ALWAYS** use the ServiceNamespaced isolation strategy: +`backend/auth.Authenticator` provides a gateway identity and optional login routes. `backend/issuer.Issuer` provisions and revokes credentials. The in-tree issuer is Kubernetes-specific, kcp workspace issuance requires a separate implementation. -- The `isolation` parameter **only applies to cluster-scoped resources** -- Each consumer gets its own provider namespace via APIServiceNamespace mapping -- Namespace mapping is always: `wild-west` → `kube-bind--wild-west` -- The `informerScope` parameter only affects whether the konnector watches at namespace or cluster level -- Secrets are always isolated per consumer - -## Complete Test Lifecycle - -The end-to-end test validates the complete binding and synchronization flow: - -### Setup Phase - -1. **Create provider workspace (kcp)** - - Install kube-bind CRDs - - Start backend server (HTTP API for binding) - - Bootstrap example CRDs (Cowboys/Sheriffs) - - Apply templates (template-cowboys.yaml / template-sheriffs.yaml) - -2. **Create consumer workspaces** - - Start konnector on each consumer (watches APIServiceBinding) - -### Binding Phase - -3. **Login to provider** - - Simulate browser auth flow - - Save credentials to kube-bind-config.yaml - -4. **List templates & collections** - - Verify backend returns templates - - Verify collections exist - -5. **Bind API** - - Send BindableResourcesRequest with templateRef and clusterIdentity - - Backend creates on provider: - - Contract namespace: `kube-bind-` - - APIServiceExportRequest - - APIServiceNamespace: `wild-west` → `kube-bind--wild-west` - - RBAC resources for secret access - - Backend returns BindingResourceResponse with CRDs, RBAC manifests - -6. **Apply binding on consumer** - - Create APIServiceBinding (watched by konnector) - - Apply CRDs - - Wait for CRD to be established - -### Synchronization & Verification Phase - -7. **Create instance on consumer** - - Create resource (Cowboy or Sheriff) in namespace `wild-west` - - Create associated secrets - -8. **Verify sync to provider** - - Instance created on provider with ClusterNamespaceAnnotation - - Extract providerContractNamespace and providerObjectNamespace - -9. **Verify namespace pre-seeding & RBAC** - - APIServiceNamespace created with status.namespace populated - - Actual provider namespace exists - - RBAC resources created (ClusterRole/Role + Bindings) - -10. **Test bi-directional sync** - - Update spec on consumer → synced to provider - - Update status on provider → synced to consumer - -11. **Verify secret sync** - - Referenced secret (spec.secretRefs) synced to provider namespace - - Label-selected secret synced - -12. **Test deletion** - - Delete on consumer → deleted on provider - -### Multi-Consumer Isolation Verification - -Running with 2 consumers validates: -- Each consumer gets isolated contract namespace -- Each consumer gets isolated provider namespace (except with IsolationNone) -- Secrets are properly isolated (except with IsolationNone) -- For cluster-scoped resources with IsolationNone, last-write-wins -- For cluster-scoped resources with IsolationPrefixed, resources are name-prefixed -- For cluster-scoped resources with IsolationNamespaced, provider CRD is toggled to NamespaceScoped - -## RBAC Infrastructure - -### Exported resources - -Exported resources always use cluster-scoped RBACs: - -- Aggregating `kube-binder-exports` ClusterRole - - Bound with `kube-binder-exports` ClusterRoleBinding to `/kube-binder` ServiceAccount - -This aggregating ClusterRole includes all subsequent ClusterRoles that are created for each APIServiceExport. - -- `kube-binder--` ClusterRole for each APIServiceExport - - Each resource in the APIServiceExport is granted `"get", "list", "watch", "create", "update", "patch", "delete"` set of verbs. - - Aggregates into `kube-binder-exports` ClusterRole. - -### Claimed resources - -Claimed resources use namespace- or cluster-scoped RBACs depending on the resource scope of the claimed resource itself, as well as backend's informer scope. - -For cluster-scoped informers: - -**Scope of the claimed resource** | **Informer scope** | **What happens** ---- | --- | --- -cluster | cluster | Creates ClusterRole & ClusterRoleBinding -namespace | cluster | Creates ClusterRole & ClusterRoleBinding - -For namespace-scoped informers: - -**Scope of the claimed resource** | **Informer scope** | **What happens** ---- | --- | --- -cluster | namespace | Creates ClusterRole & ClusterRoleBinding -namespace | namespace | Creates Role & RoleBinding - -Regardless of the configuration, claimed resources are granted `"get", "list", "watch", "create", "update", "patch", "delete"` set of verbs. - -## Implementation Details - -### Code Structure - -- **Isolation strategies**: `pkg/konnector/controllers/cluster/serviceexport/isolation/` - - `none.go`: No isolation, same names/namespaces on both sides - - `prefixed.go`: Prefix resource names with consumer ID - - `namespaced.go`: Convert cluster-scoped to namespaced - - `servicenamespaced.go`: APIServiceNamespace-based mapping for namespaced resources - -- **Controller logic**: `pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go` - - Determines which isolation strategy to use based on resource scope and configuration - - Lines 247-284: Strategy selection logic - -### Strategy Selection Logic - -```go -switch { -case schema.Spec.Scope == apiextensionsv1.NamespaceScoped: - // ALWAYS use ServiceNamespaced for namespaced resources - isolationStrategy = isolation.NewServiceNamespaced(...) - -case export.Spec.Isolation == kubebindv1alpha2.IsolationNone: - isolationStrategy = isolation.NewNone(...) - -case export.Spec.Isolation == kubebindv1alpha2.IsolationPrefixed: - isolationStrategy = isolation.NewPrefixed(...) - -case export.Spec.Isolation == kubebindv1alpha2.IsolationNamespaced: - isolationStrategy = isolation.NewNamespaced(...) -} -``` +`engine/mapper.Mapper` translates namespace/name keys for synced API instances. Its two methods must round-trip. Install a custom implementation through `sync.WithMapper(...)` in an out-of-tree build, there is no `mapper` CRD field or flag. The shipped mapper is `Identity`. Mapping does not change resource scope, and related-resource synchronization does not yet use this interface. -## References +The provider's RBAC is the authorization boundary. Conflict markers protect against accidental ownership collisions, they do not prevent a holder of overprivileged credentials from bypassing the konnector. -- Test implementation: `test/e2e/bind/happy-case_test.go` -- API types: `sdk/apis/kubebind/v1alpha2/apiserviceexport_types.go` -- Isolation strategies: `pkg/konnector/controllers/cluster/serviceexport/isolation/` +The historical [slim-core proposal](https://github.com/kbind-dev/kbind/blob/v2-next/docs/proposals/v2-slim-core.md) and [extended-layer proposal](https://github.com/kbind-dev/kbind/blob/v2-next/docs/proposals/v2-extended.md) explain design decisions. They include earlier names and planned behavior, the [user guides](../usage/api-concepts.md) and implementation describe the current contract. diff --git a/docs/content/developers/backend/.pages b/docs/content/developers/backend/.pages index f68314ff3..2d2399af9 100644 --- a/docs/content/developers/backend/.pages +++ b/docs/content/developers/backend/.pages @@ -1,3 +1,4 @@ nav: - index.md - HTTP: http + - OIDC: oidc diff --git a/docs/content/developers/backend/http/.pages b/docs/content/developers/backend/http/.pages index 35f34ac32..99f490834 100644 --- a/docs/content/developers/backend/http/.pages +++ b/docs/content/developers/backend/http/.pages @@ -1,3 +1,4 @@ nav: + - index.md - cluster-binding.md - api-binding.md diff --git a/docs/content/developers/backend/http/api-binding.md b/docs/content/developers/backend/http/api-binding.md index 9104a2b2a..85b261684 100644 --- a/docs/content/developers/backend/http/api-binding.md +++ b/docs/content/developers/backend/http/api-binding.md @@ -1,50 +1,25 @@ # API Binding -## Overview - -```mermaid -sequenceDiagram - autonumber - participant consumer-cluster as Consumer cluster - participant client as Client - participant provider-cluster as Provider cluster - participant provider-backend as Provider backend - - - %% Create APIServiceExportRequest - client->>provider-cluster: Create "APIServiceExportRequest" - - par Provider - provider-backend->>provider-cluster: Get "APIServiceExportRequest" - loop For each "APIServiceExportRequest.spec.resources" - provider-backend->>provider-cluster: Create "APIServiceExport" - end - provider-backend->>provider-cluster: Set "APIServiceExportRequest.status.phase" - and Client - loop Every 1 second for 10 minutes - client->>provider-cluster: Get "APIServiceExportRequest" - client->>client: Verify "APIServiceExportRequest"
(.status.phase == Succeeded)" - end - end - - %% Create APIServiceBindings - loop For each "APIServiceExportRequest.spec.resources" - client->>consumer-cluster: Create "APIServiceBinding" - end +v2 binding terminates in ordinary consumer-side Kubernetes objects rather than request/response CRDs. + +## Request + +An authenticated caller posts an Export name to `POST /api/bind`: + +```json +{"export":"widgets"} ``` -## Contracts +The gateway requires a ready Export, creates or updates the caller's Grant, and waits for the issuer to provision credentials. The response contains `grant`, `pickupURL`, and `expiresAt`. + +## Pickup and apply -**APIServiceExportRequest** +`GET /api/bundle/{token}` consumes the pickup ticket once and returns a kubeconfig Secret, Connection, and ClusterBinding. The ticket defaults to a five-minute lifetime, the issued credentials remain usable until revoked. -In case the _APIServiceExportRequest_ is accepted, the provider backend **must** ensure that +The bundle does not include the konnector or core CRDs. Install those first, then apply the bundle using the CLI, kubectl, or an existing GitOps workflow. -* for each `APIServiceExportRequest.spec.resources` an `APIServiceExport` is created -* each `APIServiceExport` is created in the namespace of the `APIServiceExportRequest` -* each `APIServiceExport` is created with a name following the pattern `resource.resource + "." + resource.group` -* the `APIServiceExportRequest.status.phase` is set to `Succeeded` +## Revocation -In case the _APIServiceExportRequest_ is declined, the provider backend **must** ensure that +Deleting the provider Grant asks the issuer to remove its credentials. This does not remove the consumer's core objects or automatically delete synced provider instances. For normal teardown, unbind while credentials still work. -* the `APIServiceExportRequest.status.terminalMessage` is set to a human readable message describing the reason -* the `APIServiceExportRequest.status.phase` is set to `Failed` +See [catalog and issuance](../../../usage/catalog.md) for the lifecycle and the [HTTP reference](index.md) for status codes, authentication, and pickup semantics. diff --git a/docs/content/developers/backend/http/cluster-binding.md b/docs/content/developers/backend/http/cluster-binding.md index 02e90cd8d..071cf209d 100644 --- a/docs/content/developers/backend/http/cluster-binding.md +++ b/docs/content/developers/backend/http/cluster-binding.md @@ -1,70 +1,17 @@ # Cluster Binding -## Overview +In v2, connecting a consumer has two separate operations: install the konnector, then apply a core bundle that establishes a provider Connection. There is no separate cluster-registration handshake or stored consumer kubeconfig. -```mermaid -sequenceDiagram - autonumber - participant consumer-cluster as Consumer cluster - participant client as Client - participant provider-backend as Provider backend - participant authentication-provider as Authentication Provider +## Install the konnector - %% Get provider information - client->>+provider-backend: GET "${PROVIDER_BINDING_URL}" - provider-backend->>-client: 200 "BindingProvider" +`GET /api/konnector` returns the core CRDs, namespace, RBAC, ServiceAccount, and Deployment without credentials. It is public and has no server-side write effects. Installing these objects alone does not make the consumer appear in the provider inventory. - client->>client: Verify "BindingProvider" +## Connect a provider - %% Authenticate to provider - client-->>authentication-provider: Authenticate to provider +The [API binding flow](api-binding.md) returns a Secret, Connection, and ClusterBinding. After application, the konnector connects directly to the provider and renews a heartbeat Lease. - %% Bind to API - provider-backend->>client: 200 "BindingResponse" +`GET /api/clusters` builds the inventory from these Leases and Grants. It is authenticated, but its output is not filtered to the caller's identity. - client->>consumer-cluster: Ensure kubeconfig secret +When explicitly enabled, `POST /api/apply` can install the konnector or apply a bundle using a submitted consumer kubeconfig. This sends consumer credentials through the gateway, local CLI or GitOps apply does not. - loop For each "BindingResponse.requests" - client->>consumer-cluster: Bind remote API to consumer cluster - end -``` - -## Contracts - -**BindingResponse** - -In case the cluster binding request is accepted, the provider backend **must** ensure that - -* the kubeconfig returned in the `BindingResponse` contains a current context -* the configured current context points to the "cluster namespace" -* the `ClusterBinding` object named "cluster" exists in the "cluster namespace" -* the secret referenced by `ClusterBinding.spec.kubeconfigSecretRef.name` exists -* the key of the secret referenced by `ClusterBinding.spec.kubeconfigSecretRef.key` contains a valid kubeconfig -* the configured current context points to a user with at least the following permissions in the "cluster namespace" (here expressed as RBAC rules) - ```yaml - - apiGroups: ["kube-bind.io"] - resources: ["apiserviceexportrequests"] - verbs: ["create", "delete", "patch", "update", "get", "list", "watch"] - - - apiGroups: ["kube-bind.io"] - resources: ["apiserviceexports"] - verbs: ["get", "watch", "list"] - - apiGroups: ["kube-bind.io"] - resources: ["apiserviceexports/status"] - verbs: ["get", "patch", "update"] - - - apiGroups: ["kube-bind.io"] - resources: ["apiservicenamespaces"] - verbs: ["create", "delete", "patch", "update", "get", "list", "watch"] - - - apiGroups: ["kube-bind.io"] - resources: ["clusterbindings"] - verbs: ["get", "watch", "list"] - - apiGroups: ["kube-bind.io"] - resources: ["clusterbindings/status"] - verbs: ["get", "patch", "update"] - - - apiGroups: [""] - resources: ["secrets"] - verbs: ["get", "watch", "list"] - ``` +See the [HTTP reference](index.md) for request bodies and responses. diff --git a/docs/content/developers/backend/http/index.md b/docs/content/developers/backend/http/index.md new file mode 100644 index 000000000..775aa4cc6 --- /dev/null +++ b/docs/content/developers/backend/http/index.md @@ -0,0 +1,203 @@ +# HTTP API + +This reference describes the implemented `cmd/backend` binary and gateway protocol. See [deployment](../index.md) for Helm, OIDC, HTTPS, and RBAC configuration, and [catalog usage](../../../usage/catalog.md) for the lifecycle. + +## Authentication conventions + +**Authenticated** in the tables means either: + +- A `kbind_session` cookie issued by the gateway's OIDC login flow. +- `Authorization: Bearer ` containing that same signed, encrypted session token. +- When `--kubernetes-auth=true`, a provider-cluster bearer token successfully verified through Kubernetes TokenReview. + +An arbitrary OIDC ID/access token is not a gateway session token. The Kubernetes authenticator is additive, the binary still configures OIDC when the gateway is enabled. Bearer extraction takes precedence over the session cookie. + +Authenticated APIs do not implement per-Export entitlements or caller-filtered inventories. OIDC groups and TokenReview groups are recorded, not used to authorize catalog operations. + +### Read and inventory endpoints + +| Method | Path | Authentication | Response and semantics | +| --- | --- | --- | --- | +| `GET` | `/api/provider` | None | `{name, version?, authMethods, applyEnabled}`. Binary authenticator names are `oidc` and optionally `kubernetes`. | +| `GET` | `/api/me` | Authenticated | `{subject, displayName?, groups?}` for the caller. | +| `GET` | `/api/catalog` | Authenticated | `{exports: [...], collections?: [...]}`. Only ready Exports and Collections with visible members are included. | +| `GET` | `/api/catalog/{export}/instances` | Authenticated | `{export, instances: [...]}`. Current Export's provider-side managed objects and related-resource metadata, best effort per API. Unknown Export: `404`. Unlike catalog browsing, this lookup does not require the Export to be Ready. | +| `GET` | `/api/clusters` | Authenticated | `{clusters: [...], pending?: [...]}` derived from provider Grants and heartbeat Leases. No consumer kubeconfig is stored or returned. | +| `GET` | `/api/konnector` | None | Applyable YAML: core CRDs, `kbind` namespace, konnector RBAC/ServiceAccount/Deployment, with the configured konnector image. No credentials and no side effects on GET. | +| `GET` | `/api/healthz` | None | Plain text `ok`, HTTP `200`, process check only. | + +Catalog Export responses contain `name`, `title`, `apis`, optional `description`, `iconURL`, `docs`, and `relatedResources`. Related-resource rows have `resource`, `direction`, and an optional human-readable `selector` summary, not the complete Kubernetes selector structure. + +Clusters contain `uid`, `lastHeartbeat`, `live`, and `bindings`, binding rows include `grant`, `export`, identity/subject, boundary namespace, heartbeat, `live`, and `apis` with `name` and `syncedCount`. A cluster is live if any binding's Lease is renewed within twice its lease duration. + +Instance rows contain `api`, `namespace` when namespaced, `name`, `createdAt`, and consumer UID/identity when attributable. Related rows additionally have `related: true` and `direction`. The endpoint never returns Secret data. The [inventory guide](../../../usage/catalog.md#cluster-and-instance-inventories) explains attribution and best-effort omissions. + +### Bind, pickup, and apply + +| Method | Path | Authentication | Important semantics | +| --- | --- | --- | --- | +| `POST` | `/api/bind` | Authenticated | JSON body `{"export":"widgets"}`. Create/update the identity's Grant, wait for issuer Ready, then return `{grant, pickupURL, expiresAt}`. `pickupURL` is currently relative to the gateway root. | +| `GET` | `/api/bundle/{token}` | Possession of token, no session required | Single-use pickup. Default response is YAML containing Secret + Connection + ClusterBinding. `Accept: application/json` returns `{"bundle":[...objects...]}` instead. | +| `POST` | `/api/apply` | Authenticated, route enabled only by `--enable-apply` | JSON body with base64 consumer `kubeconfig`, optional `export`, and optional `installKonnector`. Apply directly from the gateway. Returns `{"applied":["Kind/name",...]}`. | + +Bind behavior: + +- Body must contain a nonempty `export`, no namespace, binding-kind, conflict-policy override, or collection-bind parameter exists. +- Unknown Export: `404`. Non-ready Export or provider-side failure: `502`. +- Issuer wait timeout: `504`, normally after 30 seconds. There is no command-line flag for this timeout. Retry the bind after checking the issuer and token controller, the deterministic Grant prevents duplicate records for the same identity/Export. +- Every successful bind replaces any unused pickup token for that Grant. The default pickup expiry is five minutes, not the credential lifetime. + +Pickup behavior: + +- Unknown, expired, or previously consumed token: `410`. +- Consumption is recorded atomically on the Grant before bundle assembly. Later assembly/response failure requires a new bind, not a retry of the same URL. A provider read/assembly failure can return `502` after consumption. +- YAML download uses a `.yaml` attachment filename. JSON contains the same object material, including credentials. +- The issued kubeconfig uses a long-lived ServiceAccount token. Pickup expiry, browser logout, and session expiry do not revoke it. +- Treat the URL and response as secrets. Exclude them from shared caches, request logs, analytics, and link scanners. + +Apply behavior: + +```json +{ + "export": "widgets", + "kubeconfig": "", + "installKonnector": true +} +``` + +`export` may be omitted for konnector installation only. Omitting `export` with `installKonnector: false` is rejected. With an Export, the handler follows the same Grant provisioning path but builds and applies the bundle directly, without consuming a pickup URL. It ensures the `kbind` namespace even when installation is skipped. + +Malformed JSON/base64/kubeconfig and “nothing to do” requests return `400`, issuance timeout returns `504`, provider or apply failures generally return `502`. Disabling the feature leaves `/api/apply` unregistered, clients should use `/api/provider.applyEnabled`, not assume a particular disabled-route status. + +The gateway must be able to reach the consumer API and use the submitted kubeconfig from its own environment. Base64 is not encryption. Server-side apply forces field ownership, and operations are sequential, not transactional. An error does not imply earlier objects were rolled back. + +### Browser and OIDC endpoints + +| Method | Path | Authentication | Behavior | +| --- | --- | --- | --- | +| `GET` | `/` | Page itself is public | Embedded static app, its authenticated API calls send an unauthenticated browser to `/login`. | +| `GET` | `/login` | None | Login page with OIDC sign-in. | +| `GET` | `/api/auth/oidc/login` | None | Start code+PKCE login, optional `redirect` selects final landing location. | +| `GET` | `/api/auth/oidc/callback` | Valid OIDC flow/state cookie | Exchange code, verify ID token and nonce, issue session, redirect. | +| `GET` | `/api/auth/logout` | None | Clear the session cookie and redirect to `/login`, not bearer-token or Grant revocation. | + +Login `redirect` accepts a local path (default `/`) or an HTTP(S) URL whose host is exactly `localhost`, `127.0.0.1`, or `::1`. A loopback redirect gets the session token appended as the `token` query parameter for the CLI. External hosts and scheme-relative redirects are rejected with `400`. + +Login-state cookie `kbind_oidc_state` has a browser Max-Age of ten minutes and path `/api/auth/oidc/`. The session cookie uses the configured session TTL and path `/`. Both are HttpOnly and SameSite=Lax, Secure depends on `r.TLS`, not `--external-url` or forwarded headers. The state token is encoded using the same codec/keys as sessions, the cookie's ten-minute Max-Age should not be confused with a separate server-side flow store. + +The app's Catalog and Clusters are in-page views, not additional REST endpoints or browser deep-link routes. There is no browser token-management page, Export editor, Grant revoke endpoint, or `/api/auth/refresh`. + +### Error envelopes + +Gateway handlers normally return `{"error":"message"}` for errors: authentication failures are `401`, malformed bind/apply requests `400`, upstream Kubernetes failures commonly `502`. OIDC handlers and standard HTTP routing/file-serving errors may be plain text instead. Do not assume every non-2xx response is JSON. + +### Calling with a provider-cluster token + +For an existing provider ServiceAccount `portal` in namespace `default`, when TokenReview authentication is enabled: + +```sh +TOKEN="$(kubectl --context=provider -n default create token portal)" +curl -fsS https://bind.example.com/api/catalog \ + -H "Authorization: Bearer $TOKEN" +curl -fsS https://bind.example.com/api/bind \ + -H "Authorization: Bearer $TOKEN" \ + -H 'Content-Type: application/json' \ + --data '{"export":"widgets"}' +unset TOKEN +``` + +The response's `pickupURL` can be retrieved without that bearer token. Download once into a protected file, inspect it, and apply using a consumer kubeconfig after core installation. This is also possible with a valid kbind session bearer token, the CLI normally handles issuance and pickup itself. + +## Binary flags + +Flags below are defined in `cmd/backend/main.go`. Duration values use Go duration syntax such as `30s`, `5m`, or `12h`. See `./bin/backend -help` for library-added logging and Kubernetes client flags as well. + +### Modules and CRDs + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--enable-gateway` | `true` | HTTP API and UI. `modules.gateway` | +| `--enable-issuer` | `true` | Grant provisioning and Export validation controllers. `modules.issuer` | +| `--enable-reaper` | `false` | Lease-based stale Grant sweeper. `modules.reaper` | +| `--enable-apply` | `false` | Add browser-apply route to gateway. `modules.apply` | +| `--install-crds` | `true` | Install/refresh service-layer CRDs at process startup, independently of enabled modules. Helm's `installCRDs` controls templates only, pass this flag in `extraArgs` to disable process self-install. | + +### Gateway and issued kubeconfigs + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--listen-address` | `:8080` | HTTP bind address. Chart constructs `:`, `listenPort: 8080` | +| `--provider-name` | `kbind` | Human-facing provider name. `providerName` | +| `--external-url` | Empty | Public gateway base URL used to default OIDC callback. Empty falls back to `http://localhost` plus listen address, intended for a `:PORT` dev address. `externalURL` | +| `--pickup-ttl` | `5m` | One-time pickup URL lifetime, not credential TTL. `pickupTTL` | +| `--konnector-image` | `ghcr.io/kbind-dev/konnector:latest` | Image in `/api/konnector` manifests and browser installation. `konnectorImage` | +| `--external-address` | Empty | Provider API URL embedded in issued kubeconfigs, empty uses backend REST config host. `externalAddress` | +| `--external-ca-file` | Empty | PEM CA bundle embedded in issued kubeconfigs, empty uses token Secret `ca.crt`. No direct chart value, supply file and `extraArgs`. | +| `--issuer-scope` | `Cluster` | Granted-resource RBAC in all namespaces (`Cluster`) or boundary-only (`Namespace`). `issuerScope` | + +`externalURL` and `externalAddress` are different endpoints. The first is reached by browser/CLI clients, the second by the consumer konnector. Namespace scope does not remap namespaces or change the bundle's `ClusterBinding` kind. + +### Sessions + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--cookie-signing-key` | Empty | Standard base64 text of HMAC key bytes, use 32/64 bytes. Empty generates a random per-process 64-byte key. `cookieKeys.existingSecret`, key `signingKey` | +| `--cookie-encryption-key` | Empty | Standard base64 text of AES key bytes (16/24/32). Empty generates a random per-process 32-byte key. Same Secret, key `encryptionKey` | +| `--session-ttl` | `12h` | Session token and session cookie lifetime. `sessionTTL` | + +Both keys must match across replicas. Missing either key breaks that part of cross-replica/restart continuity. The binary has no direct environment-variable configuration for these flags, the chart injects Secret values into environment variables and expands them in container arguments. + +### OIDC and Kubernetes authentication + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--oidc-issuer-url` | Empty | OIDC discovery issuer. Required for gateway except mock mode. `oidc.issuerURL` | +| `--oidc-client-id` | Empty | OIDC client ID. Required for gateway except mock mode. `oidc.clientID` | +| `--oidc-client-secret` | Empty | Confidential client's secret, as required by issuer registration. `oidc.existingSecret`, key `clientSecret` | +| `--oidc-ca-file` | Empty | PEM CA bundle for OIDC HTTPS, empty uses system roots. A supplied bundle replaces the root pool. No direct chart mount/value, supply file and `extraArgs`. | +| `--oidc-username-claim` | `sub` | Required nonempty string claim used in stable subject. `oidc.usernameClaim` | +| `--oidc-groups-claim` | Empty | Optional string or string-array groups claim. Empty means no groups. `oidc.groupsClaim` | +| `--oidc-scopes` | `openid,profile,email` | Comma-separated requested scopes. `oidc.scopes` | +| `--oidc-redirect-url` | Empty | Defaults to `/api/auth/oidc/callback`. `oidc.redirectURL` | +| `--oidc-mock` | `false` | Embedded auto-approving development issuer, replaces normal OIDC config. `oidc.mock` | +| `--oidc-mock-listen` | Empty | Fixed mock issuer address or random localhost port when empty. Chart uses `127.0.0.1:`, default chart port `5556`. | +| `--kubernetes-auth` | `false` | Additionally accept provider tokens via TokenReview. `kubernetesAuth` | + +Mock mode is not safe for production. There is no public flag to skip TLS verification for a real OIDC issuer, configure trust correctly. + +### Reaper + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--reaper-ttl` | `30m` | Silence threshold for matching heartbeat Leases, or Ready age with no renewed Lease. `reaper.ttl` | +| `--reaper-revoke` | `false` | Delete stale Grants, issuer finalizer revokes credentials. `reaper.revoke` | +| `--reaper-delete-boundary` | `false` | When revoking, also delete boundary namespace if no other non-deleting Grant shares it. `reaper.deleteBoundary` | +| `--reaper-interval` | `1m` | Sweep cadence. `reaper.interval` | + +When `--reaper-revoke=false`, stale marking is non-destructive. Boundary deletion only operates inside revocation, setting it alone does not enable deletion. This policy is separate from the inventory's two-lease-duration Live/Stale display. + +### Controller manager + +| Flag | Binary default | Meaning / Helm value | +| --- | --- | --- | +| `--metrics-bind-address` | `:8086` | Controller-manager metrics, chart constructs `:`. | +| `--health-probe-bind-address` | `:8082` | Controller-manager health/readiness listener, chart constructs `:`. | +| `--leader-elect` | `false` | Leader election for issuer/reaper controllers. Chart enables for `leaderElect: true` or `replicaCount > 1`. | +| `--leader-election-id` | `backend.kbind.io` | Leader-election Lease name. `leaderElectionID` | + +The manager exists only when issuer or reaper is enabled. These addresses are not gateway endpoints, gateway-only processes do not start this manager. The binary also registers controller-runtime's `--zap-*` logging flags. + +## Helm-specific settings and caveats + +The chart is **`deploy/charts/backend-v2`**: + +- Image defaults: repository `ghcr.io/kbind-dev/backend`, empty `image.tag` falling back to source `appVersion: "0.0.0"`. Override with an image actually built/published from the intended v2 revision. +- Gateway Service: `service.type: ClusterIP`, `service.port: 80`, `listenPort: 8080`. No Ingress/TLS or NetworkPolicy templates are included. +- `replicaCount: 1`, `leaderElect: false`, and no existing cookie key Secret by default. Increasing replicas automatically enables election, **not** key sharing. +- `rbac.create: true` provisions powerful provider administration permissions. `rbac.syncedResourceGroups: ["*"]` enables broad read inventory, narrow it deliberately. Module flags do not prune RBAC rules. +- `serviceAccount.create`, `serviceAccount.name`, and `serviceAccount.annotations` configure the runtime identity. +- `extraArgs` appends binary flags. CA files still need a Deployment mount customization, there are no generic extra-volume values. +- `installCRDs: false` alone does not disable the process's CRD self-install. +- The OIDC issuer/client ID template requirements apply even if the gateway module is disabled. + +Read [backend setup](../index.md) before exposing a deployment. In particular, HTTPS termination does not make the HTTP backend set Secure cookies, browser apply forwards consumer credentials, and the default issued scope is not namespace-isolated tenancy. diff --git a/docs/content/developers/backend/index.md b/docs/content/developers/backend/index.md index 06e3dced6..089b85a10 100644 --- a/docs/content/developers/backend/index.md +++ b/docs/content/developers/backend/index.md @@ -1,79 +1,193 @@ # Backend -The kube-bind backend provides service export and binding capabilities for single Kubernetes clusters acting as backend or many clusters with support for multiple cluster providers through the multicluster-runtime architecture. +The backend adds a catalog, browser login, credential issuance, and provider-side inventory to kbind. It runs **on or against the provider cluster**. The consumer runs the konnector, not the backend. -## Architecture +You do not need a backend to use the core `Connection`, `ClusterBinding`, and `Binding` APIs with credentials supplied by another system. See [installation](../../setup/helm.md) and the [GitOps workflow](../../usage/gitops.md) for that path. -Starting with v0.5.0, the backend leverages `sigs.k8s.io/multicluster-runtime` for enhanced cluster management capabilities. +## Modules and placement -### Key Components +One `backend` binary contains independently enabled modules: -- **MultiCluster Runtime Integration**: Built on `sigs.k8s.io/multicluster-runtime` for provider-agnostic cluster operations -- **Provider Support**: Extensible provider system supporting different backend implementations -- **Manager Architecture**: Uses `mcmanager.Manager` for cluster-aware resource management +| Module | Binary flag / Helm value | Default | Responsibility | +| --- | --- | --- | --- | +| Gateway | `--enable-gateway` / `modules.gateway` | `true` | HTTP API, embedded browser UI, login, catalog, bundle pickup, inventories | +| Issuer | `--enable-issuer` / `modules.issuer` | `true` | Reconcile Grants into Kubernetes credentials, validate Exports | +| Reaper | `--enable-reaper` / `modules.reaper` | `false` | Mark stale Grants using heartbeat Leases, optionally revoke and delete boundaries | +| Browser apply | `--enable-apply` / `modules.apply` | `false` | Add `POST /api/apply` to the gateway | -### Supported Providers +The gateway fronts exactly one provider: the Kubernetes configuration used by the backend process. The binary resolves that configuration through controller-runtime/client-go, using `KUBECONFIG` or an in-cluster ServiceAccount. Changing a user's gateway session does not select a different provider. -- **Default Provider**: Standard Kubernetes cluster support -- **kcp Provider**: Integration with [kcp](https://www.kcp.io/) through `github.com/kcp-dev/multicluster-provider` +Gateway-only deployments need an issuer running elsewhere for new binds to finish. Reaper revocation also needs the issuer to process Grant finalizers. Issuer-only deployments need no OIDC configuration **in the binary**, the current Helm template nevertheless requires `oidc.issuerURL` and `oidc.clientID` unless `oidc.mock` is true, even with `modules.gateway: false`. -## Configuration +The bundled issuer is for plain Kubernetes: it provisions namespaces, ServiceAccounts, RBAC, and Secret-based ServiceAccount tokens. There is no selectable built-in kcp issuer. -The backend can be configured to use different providers: +## Development: run against a provider -```bash -./bin/backend \ - --multicluster-runtime-provider kcp \ - --apiexport-endpointslice-name=kube-bind.io \ - # ... other options +From this v2 source checkout, with a provider kubeconfig and the Go version required by `go.mod`: + +```sh +make backend +KUBECONFIG=./provider.kubeconfig ./bin/backend \ + --oidc-mock \ + --external-url=http://localhost:8080 \ + --external-address=https://PROVIDER-API-REACHABLE-FROM-CONSUMER +``` + +Open `http://localhost:8080` and sign in. The default startup installs or refreshes the `catalog.kbind.io` and `iam.kbind.io` CRDs, so this kubeconfig must permit CRD writes as well as the backend's other operations. + +`--oidc-mock` starts a local issuer and **auto-approves every login as the mock user**. It is only for an isolated development environment. It does not simulate production access policy or user separation. The default mock listen port is random, set `--oidc-mock-listen=127.0.0.1:5556` when a stable, port-forwardable issuer URL is needed. + +For an in-cluster development deployment, explicitly select a backend image built from this checkout: + +```sh +helm upgrade --install backend ./deploy/charts/backend-v2 \ + --kube-context=provider \ + --namespace=kbind-backend --create-namespace \ + --set fullnameOverride=kbind-backend \ + --set image.repository=ghcr.io/kbind-dev/backend \ + --set image.tag=dev \ + --set oidc.mock=true \ + --set externalURL=http://localhost:8080 \ + --set externalAddress=https://PROVIDER-API-REACHABLE-FROM-CONSUMER ``` -### Provider Configuration +The `dev` image must already be available to that cluster, this command does not build, publish, or load it. For example, `make image-backend` builds `ghcr.io/kbind-dev/backend:dev` locally. Load it into your development cluster or push your own tagged image first. + +Forward both the gateway and the chart's fixed mock issuer port: + +```sh +kubectl --context=provider -n kbind-backend \ + port-forward deployment/kbind-backend 8080:8080 5556:5556 +``` + +The host browser and backend must both be able to reach the issuer URL. A mock login cannot work through a gateway-only port-forward when the issuer port is unreachable. + +## Production prerequisites + +Before deploying: + +1. Install the provider's service CRDs and service controllers. The backend catalogs APIs, it does not implement the services behind them. +2. Choose a backend image and a konnector image from the intended v2 revision. The source chart has placeholder `version` and `appVersion` **`0.0.0`**, an empty `image.tag` therefore selects `ghcr.io/kbind-dev/backend:0.0.0`. Override it. The installer/CLI default konnector image is **`ghcr.io/kbind-dev/konnector:latest`**, not the chart's version. +3. Provide an HTTPS gateway URL, a trusted OIDC issuer, and an OIDC client with the callback `https://YOUR-GATEWAY/api/auth/oidc/callback`. +4. Provide a provider API address reachable from the **consumer konnector**. An in-cluster address such as `https://kubernetes.default.svc` is usually not suitable for a consumer in another cluster. +5. Review the backend and issued-credential RBAC described below. Authenticated access to this gateway is a significant trust decision. + +Use the local chart at `deploy/charts/backend-v2`, not a v0.x chart path or an assumed released v2 chart version. For images you build yourself: + +```sh +make image-backend BACKEND_IMAGE=registry.example.com/platform/backend:v2-example +make image IMAGE=registry.example.com/platform/konnector:v2-example +docker push registry.example.com/platform/backend:v2-example +docker push registry.example.com/platform/konnector:v2-example +``` + +Replace the registry and illustrative tags with your own published, revision-pinned images. Configure registry credentials using `imagePullSecrets` when required. + +### OIDC and shared session keys + +Create the following Secrets in the release namespace. Populate the OIDC client secret using your normal secret-management process, its key must be `clientSecret`. Do not put real secrets in a committed values file. + +```sh +kubectl --context=provider create namespace kbind-backend +kubectl --context=provider -n kbind-backend create secret generic kbind-oidc \ + --from-literal=clientSecret="$OIDC_CLIENT_SECRET" +kubectl --context=provider -n kbind-backend create secret generic kbind-cookie-keys \ + --from-literal=signingKey="$(openssl rand -base64 64)" \ + --from-literal=encryptionKey="$(openssl rand -base64 32)" +``` + +`signingKey` and `encryptionKey` contain **base64 text** of the random key bytes. Kubernetes Secret storage encodes that text again in `.data`, do not substitute raw bytes for the text expected by the backend flags. Recommended decoded sizes are 32 or 64 bytes for the HMAC signing key, and 16, 24, or 32 bytes for the AES encryption key. + +Example `backend-values.yaml`: + +```yaml +fullnameOverride: kbind-backend +replicaCount: 2 +image: + repository: registry.example.com/platform/backend + tag: v2-example +konnectorImage: registry.example.com/platform/konnector:v2-example +providerName: Example platform +externalURL: https://bind.example.com +externalAddress: https://provider-api.example.com:6443 +issuerScope: Cluster +modules: + gateway: true + issuer: true + reaper: false + apply: false +oidc: + issuerURL: https://sso.example.com + clientID: kbind + existingSecret: kbind-oidc + usernameClaim: sub + groupsClaim: groups + scopes: openid,profile,email,groups +cookieKeys: + existingSecret: kbind-cookie-keys +sessionTTL: 12h +pickupTTL: 5m +rbac: + syncedResourceGroups: + - example.org + - "" +``` + +Request the `groups` scope only if your identity provider supports it. The empty API group above enables inventory reads of ConfigMaps as well as the example custom API, adjust the groups to what your catalog uses. + +```sh +helm upgrade --install backend ./deploy/charts/backend-v2 \ + --kube-context=provider \ + --namespace=kbind-backend \ + --values=backend-values.yaml +kubectl --context=provider -n kbind-backend rollout status deployment/kbind-backend +``` + +The chart exposes a ClusterIP Service on port 80, targeting HTTP port 8080. It does **not** create an Ingress, Gateway API route, TLS certificate, or NetworkPolicy. Supply those through your platform. + +### HTTPS and cookies + +The binary serves HTTP with `ListenAndServe`, it has no TLS-certificate flags. Terminate HTTPS at a trusted proxy and restrict direct access to the backend. Use HTTPS for production gateway, OIDC, and provider API endpoints. -#### kcp Provider +Important current behavior: -When using the kcp provider (`--multicluster-runtime-provider kcp`), the backend: +- Both `kbind_session` and `kbind_oidc_state` are `HttpOnly`, `SameSite=Lax` cookies. The session cookie uses `/`, the login-state cookie uses `/api/auth/oidc/`. +- The cookie `Secure` attribute is set only when the backend request has `r.TLS != nil`. With this binary's HTTP listener behind TLS termination it is **not automatically set**, even when `externalURL` is HTTPS. `X-Forwarded-Proto` does not change that behavior. Configure the HTTPS proxy to add `Secure` to both cookies, and verify the browser's actual `Set-Cookie` responses. +- The encrypted, signed session token is accepted either as the cookie or as `Authorization: Bearer `. This is a kbind session token, not an arbitrary OIDC ID token or access token. +- Sessions default to 12 hours. There is no refresh endpoint or per-session server-side revocation store. Browser logout clears the cookie, an already copied bearer token remains usable until expiry or key replacement. +- Missing keys produce random per-process keys. Supply **both** shared keys for restart-stable sessions and multiple gateway replicas. Replacing the keys invalidates existing sessions and in-progress login state. -- Connects to kcp workspaces through APIExports -- Manages resources across logical clusters -- Supports advanced multi-tenancy features -- Enables workspace-based isolation +OIDC uses authorization code flow with PKCE, state, and nonce validation. `oidc.usernameClaim` defaults to `sub`, the resulting identity subject is `#`. Changing the issuer or username claim can create new identities, Grants, and boundary namespaces. Groups are recorded as identity metadata, they are not an Export authorization policy. -#### Default Provider +For a private OIDC CA, the binary supports `--oidc-ca-file`. For a provider CA that differs from the ServiceAccount token Secret's `ca.crt`, use `--external-ca-file`. These are distinct trust paths. The chart has no direct CA-file or extra-volume values: make the files available with an appropriate Deployment customization and pass the flags through `extraArgs`. Merely passing a local filename in Helm values does not mount that file into the container. -The default provider works with standard Kubernetes clusters and provides: +### Kubernetes TokenReview authentication -- Direct cluster connectivity -- Namespace-based isolation -- Standard RBAC integration +Set `kubernetesAuth: true` (binary: `--kubernetes-auth`) to additionally accept provider-cluster bearer tokens. The backend submits a TokenReview to its provider, the chart includes `create` on `authentication.k8s.io/tokenreviews`. The identity subject is `kubernetes#`. -## API Changes +This is for API integrations that already hold a provider identity. It is not a second interactive login method in the browser or CLI, and does not replace OIDC configuration in the gateway binary. `kubectl bind login` still uses OIDC. See the [HTTP reference](http/index.md) for request examples. -The backend now supports the v1alpha2 API with significant architectural improvements: +The gateway authenticates callers but does not perform per-Export entitlement checks or caller-scoped inventory filtering. Every authenticated caller can browse the ready catalog, bind its Exports, and read the provider's cluster and instance inventories. TokenReview verifies identity, not authorization to those operations. Do not expose this as a tenant-isolated marketplace without an additional access-control design. -- **Resource-Based Exports**: APIServiceExport now uses resource references instead of embedded CRDs -- **BoundSchema Support**: Integration with BoundSchema resources for better schema management -- **Multi-Resource Support**: Single exports can reference multiple CRDs efficiently +## Credential scope and installer privileges -## Controllers +`issuerScope: Cluster` is the default. Each Grant gets permissions on its named APIs across provider namespaces, including their `/status` resources, plus namespace creation. Related-resource rules add Secret/ConfigMap access: read-only for `FromProvider`, read/write for `FromConsumer`. -The backend includes several controllers for managing the export/binding lifecycle: +`issuerScope: Namespace` puts those resource permissions only in the identity's boundary namespace. It does not rename namespaces, change the generated `ClusterBinding` into a `Binding`, or authorize cluster-scoped resources. Identity-preserving sync requires compatible consumer namespace names and provider list/watch permissions, do not treat this setting as a transparent drop-in isolation switch for the default cluster-wide bundle. -- **ClusterBinding Controller**: Manages cluster binding lifecycle -- **ServiceExport Controller**: Handles APIServiceExport resources -- **ServiceExportRequest Controller**: Processes export requests -- **ServiceNamespace Controller**: Manages namespace isolation +Both scopes include cluster-wide CRD reads, a read of `kube-system` for provider identity, and heartbeat Lease permissions inside the boundary. Related-resource selectors constrain konnector sync, **not** Kubernetes RBAC: the issued role does not restrict reads to the selected labels or names. -## Deployment Limitations +The backend's own chart RBAC includes namespace/credential management, `escalate` and `bind` on Roles/ClusterRoles, and wildcard inventory reads by default. Narrow `rbac.syncedResourceGroups`, and use reviewed custom RBAC with `rbac.create: false` if necessary. Disabling a module does not automatically remove its chart RBAC. -### Session Storage +Keep browser apply off unless intentionally granting the gateway access to consumer API endpoints and credentials. The browser sends an entire base64-encoded kubeconfig, base64 is not encryption. Use a trusted, self-contained kubeconfig, avoid local-file and exec-plugin dependencies, restrict gateway egress, and exclude credentials/request bodies from logs. CLI apply keeps the consumer kubeconfig local, it does not use `/api/apply`. -The backend currently uses in-memory session storage for OIDC authentication sessions. This creates the following limitation: +All built-in install/apply paths use server-side apply with **forced field ownership**. They can overwrite drift in existing kbind installation resources. Review the embedded konnector's broad cluster RBAC, pin its image, and do not mix automatic install/upgrade with a separately managed Helm installation without understanding the ownership consequences. -- **Single Replica Constraint**: The backend cannot be run with replicas > 1 due to the lack of external session storage implementation -- **Session Persistence**: Sessions are not persisted across backend restarts -- **Load Balancer Issues**: If deployed behind a load balancer with multiple replicas, users may lose their sessions when requests are routed to different backend instances +## CRDs, replicas, and operations -**Workaround**: Deploy the backend as a single replica (replicas: 1) until external session storage support is implemented. +- `installCRDs` in Helm controls chart-rendered service-layer CRDs only. `--install-crds` independently defaults to `true` in the process. To manage CRDs out of band, install them first, set `installCRDs: false`, and add `--install-crds=false` to `extraArgs`. +- With `replicaCount > 1`, the chart enables leader election automatically. Gateway replicas serve requests independently, issuer/reaper controllers run under leader election. Set shared session keys yourself: the chart does not enforce their presence. +- Pickup state lives in Grant annotations, not gateway memory. It works across replicas. Back up provider Kubernetes state according to your credential and recovery policy, sessions also depend on the key Secret. +- `/api/healthz` is a process HTTP check, not proof of functioning OIDC, catalog validation, or credential issuance. Check an actual login, a ready Export, and a bind before declaring the deployment usable. -**Future Enhancement**: Implementation of external session storage (Redis, database, etc.) would resolve this limitation and enable high availability deployments. See https://github.com/kube-bind/kube-bind/issues/424 +Enable the reaper conservatively with `modules.reaper: true` and `reaper.revoke: false`. Review its `Stale` conditions before enabling revocation. The [catalog guide](../../usage/catalog.md) describes lifecycle and destructive cleanup. Consult the [flag and endpoint reference](http/index.md) and [troubleshooting](../../usage/troubleshooting.md) for operational detail. diff --git a/docs/content/developers/backend/oidc/index.md b/docs/content/developers/backend/oidc/index.md index c54395ced..c654f5410 100644 --- a/docs/content/developers/backend/oidc/index.md +++ b/docs/content/developers/backend/oidc/index.md @@ -5,13 +5,14 @@ weight: 30 # OIDC Authentication -The kube-bind backend supports OpenID Connect (OIDC) authentication for securing API access. There are two modes of operation: external OIDC providers and an embedded OIDC provider for development. +The kbind backend supports OpenID Connect (OIDC) authentication for securing API access. There are two modes of operation: external OIDC providers and an embedded OIDC provider for development. ## External OIDC Provider (Production) For production deployments, use an external OIDC provider such as: + - Dex -- Keycloak +- Keycloak - Auth0 - Google - Microsoft Azure AD @@ -19,131 +20,75 @@ For production deployments, use an external OIDC provider such as: ### Configuration -Configure the backend to use an external OIDC provider with these flags: +Configure the backend using the v2 flags: ```bash ---oidc-type=external ---oidc-issuer-url=https://your-oidc-provider.com ---oidc-issuer-client-id=your-client-id ---oidc-issuer-client-secret=your-client-secret ---oidc-callback-url=https://your-backend.com/callback ---oidc-authorize-url=https://your-oidc-provider.com/auth ---oidc-ca-file=/path/to/ca-bundle.pem # Optional: for custom CA certificates ---oidc-allowed-groups=group1,group2,group3 # Optional: restrict access to specific groups ---oidc-allowed-users=user1,user2,user3 # Optional: restrict access to specific users +./bin/backend \ + --external-url=https://bind.example.com \ + --oidc-issuer-url=https://your-oidc-provider.com \ + --oidc-client-id=your-client-id \ + --oidc-client-secret="$OIDC_CLIENT_SECRET" \ + --oidc-redirect-url=https://bind.example.com/api/auth/oidc/callback ``` -**Note**: When using external OIDC providers, at least one of `--oidc-allowed-groups` or `--oidc-allowed-users` must be specified for security reasons. +Register the exact callback with your issuer. Use `--oidc-ca-file` for a private CA, `--oidc-username-claim` for the stable identity claim (default `sub`), and `--oidc-groups-claim` if groups should be recorded. ### External OIDC Flow -1. User initiates authentication by accessing a protected endpoint -2. Backend redirects user to the external OIDC provider's authorization endpoint -3. User authenticates with the OIDC provider -4. OIDC provider redirects back to the backend's callback URL with authorization code -5. Backend exchanges authorization code for ID token and access token -6. Backend validates the tokens and establishes user session -7. User can now access protected APIs with valid session +1. User initiates authentication by accessing the gateway login page. +2. Backend redirects to the OIDC authorization endpoint with state, nonce, and PKCE. +3. User authenticates with the OIDC provider. +4. Provider redirects to the backend callback with an authorization code. +5. Backend exchanges the code, verifies the ID token, and issues a signed, encrypted session. +6. User accesses protected APIs using the session cookie or token. ## Embedded OIDC Provider (Development Only) -For development and testing purposes, kube-bind includes an embedded OIDC provider that eliminates the need to set up an external authentication service. - -### Configuration - -Configure the backend to use the embedded OIDC provider: +For development and testing, kbind includes an embedded provider that avoids setting up an external authentication service: ```bash ---oidc-type=embedded ---oidc-callback-url=https://your-backend.com/callback ---oidc-issuer-url=https://your-backend.com # The backend serves as the OIDC provider ---oidc-allowed-groups=group1,group2,group3 # Optional: restrict access to specific groups ---oidc-allowed-users=user1,user2,user3 # Optional: restrict access to specific users +./bin/backend --oidc-mock --external-url=http://localhost:8080 ``` ### Embedded OIDC Flow -1. Backend starts up and initializes the embedded OIDC server using mockoidc -2. The embedded OIDC server automatically generates: - - Client ID and client secret - - Signing keys for tokens - - OIDC discovery endpoints (`/.well-known/openid_configuration`) -3. User initiates authentication by accessing a protected endpoint -4. Backend redirects user to its own embedded OIDC authorization endpoint -5. User authenticates with the embedded provider (typically accepts any credentials for development) -6. Embedded OIDC provider redirects back to the backend's callback URL -7. Backend validates the tokens (self-issued) and establishes user session -8. User can now access protected APIs with valid session - -### Development Mode Warning +1. Backend initializes the mock OIDC issuer and its client credentials. +2. User starts login through the gateway. +3. The mock issuer auto-approves the fixed development identity. +4. Backend completes the same callback and session flow. -When using embedded OIDC, the backend displays a prominent warning message at startup to remind developers that this mode is not suitable for production use. +The mock issuer uses a separate port. With port forwarding, expose that port as well as the gateway, see [Backend setup](../index.md#development-run-against-a-provider). ## Security Considerations ### External OIDC (Production) -- Use HTTPS for all endpoints -- Validate OIDC provider certificates -- Use strong client secrets -- Configure proper redirect URI restrictions -- Monitor for security updates to the OIDC provider - -### Embedded OIDC (Development Only) -- **NEVER use in production** - provides no real security -- Accepts any credentials for authentication -- Intended only for local development and testing -- Does not persist user data between restarts - -## Access Control - -The kube-bind backend provides fine-grained access control through OIDC group and user-based authorization. When a user successfully authenticates via OIDC, the backend automatically creates RBAC resources to control access to cluster binding operations. - -### Access Control Flags -- `--oidc-allowed-groups`: List of OIDC groups allowed to access bindings inside the cluster. Users must be members of at least one of these groups to gain access. -- `--oidc-allowed-users`: List of specific OIDC users allowed to access bindings inside the cluster. +- Use HTTPS for all endpoints and validate provider certificates. +- Use strong client secrets and exact redirect URI restrictions. +- Share both signing and encryption keys across gateway replicas. +- Configure the TLS proxy to add `Secure` to session and login-state cookies: the HTTP backend does not infer it from `externalURL` or forwarded headers. +- Monitor for security updates to the OIDC provider. -**Important**: For external OIDC providers, at least one of these flags must be specified. This validation ensures that access control is properly configured in production environments. - -### How Access Control Works - -1. **RBAC Resource Creation**: For each cluster, the controller automatically creates: - - A `ClusterRole` named `kube-bind-oidc-user` with permissions to perform binding operations - - A `ClusterRoleBinding` that binds the role to the specified groups and users +### Embedded OIDC (Development Only) -2. **Group-based Access**: Users who are members of groups listed in `--oidc-allowed-groups` are granted access via RBAC subject entries of kind `Group`. +- **Never use in production**: every login is auto-approved. +- It is intended only for isolated local development and testing. +- It does not model distinct users or production authorization. -3. **User-based Access**: Individual users listed in `--oidc-allowed-users` are granted access via RBAC subject entries of kind `User`. +## Access Control -4. **Embedded OIDC Special Behavior**: When using embedded OIDC (`--oidc-type=embedded`), the `system:authenticated` group is automatically added to the allowed groups list, providing access to all authenticated users during development. +v2 does not have `--oidc-allowed-groups` or `--oidc-allowed-users`. OIDC groups are identity metadata, not per-Export authorization. All authenticated gateway callers can bind ready Exports and read the provider's inventories. Control access to the gateway accordingly, do not assume the old group-based binding policy is still enforced. -### Example Configuration - -```bash -# Restrict access to specific groups and users ---oidc-allowed-groups=kube-bind-admins,platform-team ---oidc-allowed-users=admin@example.com,operator@example.com -``` - -This configuration would create RBAC bindings allowing: -- All members of the `kube-bind-admins` group -- All members of the `platform-team` group -- The specific users `admin@example.com` and `operator@example.com` +Provider-cluster bearer tokens can additionally be authenticated using `--kubernetes-auth` and TokenReview. This does not replace gateway OIDC login configuration. See [authentication conventions](../http/index.md#authentication-conventions). ## Troubleshooting ### Common Issues -1. **Certificate validation failures**: Use `--oidc-ca-file` to specify custom CA certificates -2. **Callback URL mismatches**: Ensure the callback URL matches what's configured in your OIDC provider -3. **Token validation errors**: Check that the issuer URL matches between provider and backend configuration -4. **Network connectivity**: Verify the backend can reach the external OIDC provider -5. **Access control validation errors**: When using external OIDC, ensure at least one of `--oidc-allowed-groups` or `--oidc-allowed-users` is specified - -### Debug Logging +1. **Certificate validation failures**: configure `--oidc-ca-file` with the issuer's trusted CA. +2. **Callback URL mismatches**: register `/api/auth/oidc/callback` at the public gateway URL. +3. **Token validation errors**: confirm the issuer URL and configured username claim. +4. **Network connectivity**: verify both browser and backend can reach the issuer. +5. **Sessions lost across replicas/restarts**: configure both shared session keys. -Enable debug logging to troubleshoot OIDC issues: - -```bash ---v=2 # Increase verbosity for more detailed logs -``` \ No newline at end of file +See the [backend reference](../http/index.md) for complete flags and cookie lifetimes. diff --git a/docs/content/developers/dev-environment/index.md b/docs/content/developers/dev-environment/index.md index 3abce299d..b04344d4b 100644 --- a/docs/content/developers/dev-environment/index.md +++ b/docs/content/developers/dev-environment/index.md @@ -12,3 +12,14 @@ All the instructions assume you have already cloned the kube-bind repository and * You can use [kcp](kcp.md) for a lightweight backend system. * You can also use [kind](kind.md) for a more full-featured local Kubernetes cluster. + +For v2, check out `v2-next` and use the Go version in `go.mod`: + +```bash +git clone --branch v2-next https://github.com/kbind-dev/kbind.git +cd kbind +make build +make konnector backend bind +``` + +The root module references `sdk/` locally, no workspace file is required. See [Testing changes](../testing-changes.md) for the unit and envtest suites. diff --git a/docs/content/developers/dev-environment/kcp.md b/docs/content/developers/dev-environment/kcp.md index dae7446c3..c1674a143 100644 --- a/docs/content/developers/dev-environment/kcp.md +++ b/docs/content/developers/dev-environment/kcp.md @@ -1,19 +1,16 @@ --- description: > - How to setup a development environment for contributing to kube-bind. + How to use a kcp provider with the v2 core. title: kcp --- # Development Environment using kcp -All the instructions assume you have already cloned the kube-bind repository and have Go installed. +All the instructions assume you have already cloned the kbind repository and have Go installed. -kcp requires initial setup to be run before it can be used. This includes setting up workspace/provider -and setting up all the `APIResourceSchemas` and `APIExports`. +kcp requires initial setup before it can be used. This includes setting up the provider workspace and its `APIResourceSchemas` and `APIExports`. This is not required if you control the setup with your own scripts. -This is not required if you are doing deeper integration, and controlling the setup with your own scripts. - -It's good to have the kcp CLI installed to help with workspace management: +It's useful to have the kcp CLI installed for workspace management: ```bash kubectl krew index add kcp-dev https://github.com/kcp-dev/krew-index.git @@ -24,148 +21,54 @@ kubectl krew install kcp-dev/create-workspace ## Preparation -Start kcp: - -```bash -make run-kcp -``` - -## Backend - -### Bootstrap kcp - -This is a dedicated step to set up kcp with required workspaces and `APIExports` for kube-bind: - -```bash -cp .kcp/admin.kubeconfig .kcp/backend.kubeconfig -export KUBECONFIG=.kcp/backend.kubeconfig - -./bin/kcp-init --kcp-kubeconfig $KUBECONFIG -``` - -### Run the Backend - -```bash -kubectl ws use :root:kube-bind - -go run ./cmd/backend \ - --multicluster-runtime-provider kcp \ - --oidc-issuer-url=http://127.0.0.1:8080/oidc \ - --oidc-callback-url=http://127.0.0.1:8080/api/callback \ - --oidc-type=embedded \ - --pretty-name="BigCorp.com" \ - --namespace-prefix="kube-bind-" \ - --schema-source apiresourceschemas \ - --consumer-scope=cluster -``` +Start kcp and populate the provider workspace using the [kcp documentation](https://docs.kcp.io/). v2 does not include the old `make run-kcp` or `kcp-init` bootstrap helpers. -Optionally add `--fronend=http://localhost:3000` to point to local frontend (must be running -separately). - -This process will keep running, so open a new terminal. +The workspace should expose only the service APIs intended for consumers. Give the provider credential discovery/OpenAPI access, the required instance permissions, and read access to `logicalclusters.core.kcp.io/cluster`. ## Provider ### Kubeconfig Setup -Copy the kubeconfig to the provider and create provider workspace: - -```bash -cp .kcp/admin.kubeconfig .kcp/provider.kubeconfig -export KUBECONFIG=.kcp/provider.kubeconfig -kubectl ws use :root -kubectl create-workspace provider --enter -``` - -### APIExport - -Bind the APIExport to the provider workspace: - -```bash -kubectl kcp bind apiexport root:kube-bind:kube-bind.io \ - --accept-permission-claim clusterrolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim clusterroles.rbac.authorization.k8s.io \ - --accept-permission-claim customresourcedefinitions.apiextensions.k8s.io \ - --accept-permission-claim serviceaccounts.core \ - --accept-permission-claim configmaps.core \ - --accept-permission-claim secrets.core \ - --accept-permission-claim subjectaccessreviews.authorization.k8s.io \ - --accept-permission-claim namespaces.core \ - --accept-permission-claim roles.rbac.authorization.k8s.io \ - --accept-permission-claim rolebindings.rbac.authorization.k8s.io \ - --accept-permission-claim apiresourceschemas.apis.kcp.io -``` - -### Create CRD in provider +Use a self-contained kubeconfig pointing at the selected logical cluster. Confirm the workspace identity: ```bash -kubectl apply -f contrib/kcp/deploy/examples/apiexport.yaml -kubectl apply -f contrib/kcp/deploy/examples/apiresourceschema-cowboys.yaml -kubectl apply -f contrib/kcp/deploy/examples/apiresourceschema-sheriffs.yaml -kubectl kcp bind apiexport root:provider:cowboys-stable - -kubectl apply -f deploy/examples/template-cowboys.yaml -kubectl apply -f deploy/examples/template-sheriffs.yaml -kubectl apply -f deploy/examples/collection.yaml +kubectl --kubeconfig=provider.kubeconfig get logicalcluster cluster ``` -### Retrieve the LogicalCluster - -```bash -kubectl get logicalcluster -# NAME PHASE URL -# cluster Ready https://192.168.2.166:6443/clusters/2myqz7lt9i0u5kzb -``` +The konnector pins that LogicalCluster UID. On a CRD-less provider, choose `schema.source: OpenAPI` explicitly, the current `Auto` path does not fall back when CRD listing returns an error. ## Consumer ### Initialization -Now we gonna initiate consumer: - -```bash -cp .kcp/admin.kubeconfig .kcp/consumer.kubeconfig -export KUBECONFIG=.kcp/consumer.kubeconfig - -kubectl ws use :root -kubectl ws create consumer --enter -``` +Install the konnector and its three core CRDs on a Kubernetes consumer using the [installation guide](../../setup/helm.md). Deliver the provider kubeconfig as a Secret in the consumer's `kbind` namespace. ### Binding -Bind the thing: - -```bash -./bin/kubectl-bind login http://127.0.0.1:8080 --cluster 1nso4d2rvleempdp -./bin/kubectl-bind --dry-run --cluster-identity-namespace default -o yaml > apiserviceexport.yaml - -# Extract secret for binding process. Note that secret name is not the same as output from command above. Check secret -# name by running `kubectl get secret -n kube-bind` -kubectl get secrets -n kube-bind -o jsonpath='{.items[0].data.kubeconfig}' | base64 -d > remote.kubeconfig - -namespace=$(yq '.contexts[0].context.namespace' remote.kubeconfig) - -./bin/kubectl-bind apiservice \ - --remote-kubeconfig remote.kubeconfig \ - --remote-namespace "$namespace" \ - --skip-konnector \ - -f apiserviceexport.yaml \ - -v 6 +```yaml +apiVersion: core.kbind.io/v1alpha1 +kind: Connection +metadata: + name: workspace-provider +spec: + kubeconfigSecretRef: + namespace: kbind + name: workspace-provider + key: kubeconfig + schema: + source: OpenAPI + pullPolicy: Bound + updatePolicy: Always ``` -This will keep running, so switch to a new terminal. +Add a Binding or ClusterBinding selecting the actual `.` names in that workspace. See [API concepts](../../usage/api-concepts.md) for the manifest and [schema limits](../../usage/api-concepts.md#schema-updates-and-fidelity) before relying on synthesized validation or multi-version behavior. ### Launch Konnector -Start konnector: +For a host-run development process rather than a Pod: ```bash -./bin/konnector --lease-namespace default --kubeconfig .kcp/consumer.kubeconfig --server-address ":9090" +KUBECONFIG=consumer.kubeconfig go run ./cmd/konnector ``` -Create example resources in consumer: - -```bash -kubectl apply -f deploy/examples/cr-cowboy.yaml -kubectl apply -f deploy/examples/cr-sheriff.yaml -``` +The core preserves namespace, name, and scope. It does not provision workspaces or translate cluster-scoped APIs into namespaced APIs. The optional backend's in-tree issuer is Kubernetes-specific, its former multicluster-provider flags are not part of the v2 backend. diff --git a/docs/content/developers/dev-environment/kind.md b/docs/content/developers/dev-environment/kind.md index 8e84ea4dc..67933d296 100644 --- a/docs/content/developers/dev-environment/kind.md +++ b/docs/content/developers/dev-environment/kind.md @@ -1,129 +1,118 @@ --- description: > - How to setup a development environment for contributing to kube-bind. + Set up a local provider and consumer for kbind development. title: kind --- # Development Environment using kind -All the instructions assume you have already cloned the kube-bind repository and have Go installed. - -This guide will walk you through setting up kube-bind between two Kubernetes clusters, where - -* **Provider cluster**: - * Deploys kube-bind backend - * Provides kube-bind compatible backend for MangoDB resources -* **Consumer cluster**: - * Provides an application consuming MangoDBs from the provider cluster - -This guide works best on Linux. macOS and Windows users may need to adjust some commands accordingly. +This guide sets up a provider backend, a consumer konnector, and a Widget catalog offering for the [Quickstart](../../setup/quickstart.md). Both processes run on your workstation against two kind clusters. ## Pre-requisites -To start, you'll need the following tools available in your system: +- [Docker](https://docs.docker.com/get-docker/), [kind](https://kind.sigs.k8s.io/), and [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl). +- A v2 source checkout and Go matching `go.mod`. +- The [kubectl bind plugin](../../setup/kubectl-plugin.md) installed. -* [`kind`](https://kind.sigs.k8s.io/docs/user/quick-start/#installation) -* [`kubectl`](https://kubernetes.io/docs/tasks/tools/) -* [`kubectl-bind`](https://github.com/kube-bind/kube-bind/releases/latest) (a kubectl plugin) -* [`jq`](https://jqlang.github.io/jq/download/) -* port 8080 and 6443 open on your localhost +Use disposable clusters. The kubeconfigs below contain administrator credentials, keep them out of version control and remove them after the demo. Run commands from the repository root. -To install `kubectl-bind` plugin, please download the archive for your platform from the link above, -extract it, and place the `kubectl-bind` executable in your system's `$PATH`. +## Setup -!!! note - **Tip:** In case of encountering `Too many open files` error when deploying the Kind clusters, - run following commands: +Create the two clusters and save their kubeconfigs: - ```sh - sudo sysctl fs.inotify.max_user_watches=524288 - sudo sysctl fs.inotify.max_user_instances=512 - ``` +```bash +kind create cluster --name provider +kind create cluster --name consumer - See the [kind documentation](https://kind.sigs.k8s.io/docs/user/known-issues/#pod-errors-due-to-too-many-open-files) - for more details. +kind get kubeconfig --name provider > provider.kubeconfig +kind get kubeconfig --name consumer > consumer.kubeconfig +make backend konnector +``` -## Setup +These kubeconfigs use workstation endpoints. They work for the host-run processes below, not for konnector Pods in another cluster. -Run `kubectl bind dev create`, which will automatically create two Kind clusters (provider and consumer), -deploy kube-bind backend in the provider cluster, and print required commands to bind the consumer -cluster to the provider. +## Provider -This command will create two Kind clusters named `kind-provider` and `kind-consumer`, set up a -Docker network for them to communicate, and install kube-bind backend in the provider cluster and -establish right `hostAlias` entries for communication between clusters. +In a second terminal, start the backend: -```sh -kubectl bind dev create +```bash +KUBECONFIG="$PWD/provider.kubeconfig" ./bin/backend \ + --oidc-mock --external-url=http://localhost:8080 ``` -You should see output similar to this: - -```sh -kubectl bind dev create -🧪 EXPERIMENTAL: kube-bind dev command is in preview -📦 Requirements: Docker must be installed and running -Warning: Could not automatically add host entry. Please run: -echo '127.0.0.1 kube-bind.dev.local' | sudo tee -a /etc/hosts -Kind cluster kind-provider already exists, skipping creation -Wrote kubeconfig kind-provider.kubeconfig -Helm chart installed successfully -Provider cluster IP address: 192.168.155.2 -Creating kind cluster kind-consumer with network kube-bind-dev -Kind cluster kind-consumer created -Wrote kubeconfig kind-consumer.kubeconfig -🚀 kube-bind dev environment is ready! - -- Provider cluster kubeconfig: kind-provider.kubeconfig -- Consumer cluster kubeconfig: kind-consumer.kubeconfig -- kube-bind server URL: http://kube-bind.dev.local:8080 -- Next steps: -1. Run login to authenticate to the provider cluster: - -kubectl bind login http://kube-bind.dev.local:8080 - -2. Run bind to bind an API service from the provider to the consumer cluster: - -KUBECONFIG=kind-consumer.kubeconfig kubectl bind --konnector-host-alias 192.168.155.2:kube-bind.dev.local +Leave it running. Mock OIDC automatically approves logins and is for this local development environment only. The backend installs its catalog and IAM CRDs. + +Back in the first terminal, wait for the catalog APIs and seed the example: + +```bash +kubectl --kubeconfig=provider.kubeconfig \ + wait --for=condition=Established --timeout=120s \ + crd/exports.catalog.kbind.io crd/collections.catalog.kbind.io +kubectl --kubeconfig=provider.kubeconfig \ + apply -f hack/tilt/seed/widgets.yaml +kubectl --kubeconfig=provider.kubeconfig \ + wait --for=condition=Ready exports.catalog.kbind.io/widgets --timeout=120s ``` -!!! note - Note `/etc/hosts` modification and 2 commands to run to bind the consumer cluster. +The manifest installs the Widget CRD, related Secret and ConfigMap, an Export, and a Collection. It does not include a Widget controller. -## Login to Provider Cluster +## Consumer -This should give you UI authorization screen. +Install the core CRDs: ```bash -kubectl bind login http://kube-bind.dev.local:8080 +kubectl --kubeconfig=consumer.kubeconfig apply \ + -f sdk/config/crd/core.kbind.io_connections.yaml \ + -f sdk/config/crd/core.kbind.io_clusterbindings.yaml \ + -f sdk/config/crd/core.kbind.io_bindings.yaml +kubectl --kubeconfig=consumer.kubeconfig \ + wait --for=condition=Established --timeout=120s \ + crd/connections.core.kbind.io crd/clusterbindings.core.kbind.io \ + crd/bindings.core.kbind.io ``` -## Bind First Provider API Service +In a third terminal, start the konnector: ```bash -export KUBECONFIG=kind-consumer.kubeconfig -kubectl bind --konnector-host-alias 192.168.155.2:kube-bind.dev.local +KUBECONFIG="$PWD/consumer.kubeconfig" ./bin/konnector ``` -Now in the consumer cluster you should see these CRDs: +Leave it running. Do not also install a konnector Deployment on this consumer. -```bash -kubectl get crd -NAME CREATED AT -apiservicebindings.kube-bind.io 2025-11-12T08:10:48Z -mangodbs.mangodb.com 2025-11-12T08:10:56Z -``` +## Login and bind a service + +The environment is ready: + +| Setting | Value | +| --- | --- | +| Provider kubeconfig | `provider.kubeconfig` | +| Consumer kubeconfig | `consumer.kubeconfig` | +| Backend URL | `http://localhost:8080` | +| Catalog Export | `widgets` | -Try creating an example MangoDB resource and observe it being synced to provider clusters: +Return to the [Quickstart](../../setup/quickstart.md#quick-development-setup) to log in, bind the Widget API, and create an instance. + +The example Secret and ConfigMap are copied from the provider after binding. For instance status updates, simulate the service controller: ```bash -kubectl bind dev example | kubectl create -f - -KUBECONFIG=kind-consumer.kubeconfig kubectl get mangodbs.mangodb.com -KUBECONFIG=kind-provider.kubeconfig kubectl get mangodbs.mangodb.com +kubectl --kubeconfig=provider.kubeconfig -n default \ + patch widget my-widget --subresource=status --type=merge \ + -p '{"status":{"phase":"Running"}}' +kubectl --kubeconfig=consumer.kubeconfig -n default \ + wait --for=jsonpath='{.status.phase}'=Running widget/my-widget --timeout=120s ``` +See [Synchronization](../../usage/synchronization.md) for spec, status, related resources, and unbinding behavior. + ## Cleanup -```sh -kind bind dev delete +Stop both host processes with Ctrl-C. Remove only the disposable clusters and credentials created for this walkthrough: + +```bash +kind delete cluster --name consumer +kind delete cluster --name provider +rm provider.kubeconfig consumer.kubeconfig +unset KUBECONFIG ``` + +For shared clusters, [unbind](../../usage/synchronization.md#unbinding-and-deletion) while the konnector and credentials still work instead of deleting the clusters. diff --git a/docs/content/developers/index.md b/docs/content/developers/index.md index 5e290d829..96b46798f 100644 --- a/docs/content/developers/index.md +++ b/docs/content/developers/index.md @@ -4,3 +4,9 @@ Welcome to the kube-bind developer documentation! This section contains informat ## Developer Guide +- [Architecture](architecture.md) +- [Development environments](dev-environment/index.md) +- [Backend](backend/index.md) +- [Konnector](konnector/index.md) +- [Publishing a release](publishing-a-release.md) +- [Testing changes](testing-changes.md) diff --git a/docs/content/developers/konnector/controllers/.pages b/docs/content/developers/konnector/controllers/.pages index 322ecd430..254fd00a0 100644 --- a/docs/content/developers/konnector/controllers/.pages +++ b/docs/content/developers/konnector/controllers/.pages @@ -1,4 +1,5 @@ nav: - konnector.md - - apiservicebinding.md - - Cluster: cluster + - connection.md + - binding.md + - synchronization.md diff --git a/docs/content/developers/konnector/controllers/apiservicebinding.md b/docs/content/developers/konnector/controllers/apiservicebinding.md deleted file mode 100644 index 7557373d7..000000000 --- a/docs/content/developers/konnector/controllers/apiservicebinding.md +++ /dev/null @@ -1,36 +0,0 @@ -# APIServiceBindings - -The APIServiceBinding controller watches `APIServiceBindings` and the referenced `Secrets` in the **consumer -cluster**. - -It is responsible for: - -* validating the kubeconfig stored in the secrets referenced by `APIServiceBindings` - -## Overview - -```mermaid -flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call for APIServiceBinding"]) - - get_kubeconfig_secret(["Get referenced kubeconfig secret"]) - is_kubeconfig_valid{"kubeconfig
valid?"} - - set_condition_secret_valid_to_true(["Set condition 'SecretValid' to true"]) - set_condition_secret_valid_to_false(["Set condition 'SecretValid' to false"]) - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> get_kubeconfig_secret - get_kubeconfig_secret --> is_kubeconfig_valid - - is_kubeconfig_valid --> |yes| set_condition_secret_valid_to_true - is_kubeconfig_valid --> |no| set_condition_secret_valid_to_false - - set_condition_secret_valid_to_true --> stop - set_condition_secret_valid_to_false --> stop -``` diff --git a/docs/content/developers/konnector/controllers/binding.md b/docs/content/developers/konnector/controllers/binding.md new file mode 100644 index 000000000..e08708410 --- /dev/null +++ b/docs/content/developers/konnector/controllers/binding.md @@ -0,0 +1,97 @@ +# Binding Controllers + +The ClusterBinding and Binding controllers watch their respective binding objects and referenced `Connections` in the **consumer cluster**. Both use the reconciliation logic in `engine/binding`. + +They are responsible for: + +* Resolving a Ready Connection and validating the requested exported APIs. +* Installing or reading consumer schemas according to the Connection's policies. +* Synchronizing selected related Secrets and ConfigMaps. +* Reporting bound APIs, schema hashes, conflict counts, and readiness. +* Cleaning up instances and related-resource copies when a binding is deleted. + +A ClusterBinding operates cluster-wide. A Binding limits instance selection and related-resource processing to its namespace, but does not change CRD scope or make the dynamic instance informers namespace-scoped. + +## Overview + +The chart shows normal reconciliation after the cleanup finalizer has been added. Binding and Connection events trigger reconciliation, with a 30-second periodic refresh for related resources and conflict counts. + +```mermaid +flowchart TD + start(["Binding or Connection event
or periodic reconciliation"]) + get_binding(["Get binding"]) + exists{"Binding
exists?"} + connection{"Referenced Connection
exists and is Ready?"} + pending(["Set Ready=False
with Pending"]) + provider(["Build provider client
from Connection credentials"]) + schemas(["For each requested API
Check export and process its schema"]) + counts(["Record boundAPIs and schema hashes
Count instance conflict annotations"]) + missing{"Any APIs
not exported?"} + not_exported(["Set Ready=False
with APINotExported"]) + waiting{"Waiting for an OpenAPI-source
consumer CRD?"} + related(["Sync selected related Secrets and ConfigMaps
Remove copies that no longer match"]) + conditions(["Update Conflicts
Set Synced=True and Ready=True"]) + status(["Persist changed status
Requeue after 30 seconds"]) + stop(["Stop"]) + + start --> get_binding + get_binding --> exists + exists -->|no| stop + exists -->|yes| connection + connection -->|no| pending + connection -->|yes| provider + provider --> schemas + schemas --> counts + counts --> missing + missing -->|yes| not_exported + missing -->|no| waiting + waiting -->|yes| pending + waiting -->|no| related + related --> conditions + pending --> status + not_exported --> status + conditions --> status + status --> stop +``` + +For `CRD`, reconciliation pulls each exported provider schema with creation and updates controlled by `pullPolicy` and `updatePolicy`. For `OpenAPI`, it synthesizes a missing consumer CRD unless `pullPolicy: None`. An existing OpenAPI-source CRD is read, not refreshed by this controller. + +A forbidden CRD pull sets `PermissionDenied=True` and `Ready=False`. Other API errors are returned for retry. Conflicts can coexist with `Ready=True`, and `Synced=True` describes setup, not proof that every instance has reached the provider. Instance synchronization runs separately. + +## Deletion + +```mermaid +flowchart TD + start(["Deleting binding with cleanup finalizer"]) + provider(["Try to obtain provider credentials"]) + next_api{"More APIs
to clean up?"} + covered{"Another non-deleting binding
lists this API?"} + schema{"Consumer CRD provides
a usable API version?"} + drain(["Drain instances in scope
Release their syncer finalizers"]) + cluster_binding{"ClusterBinding?"} + remove_crd(["Delete consumer CRD"]) + related(["Delete related-resource copies
owned by this binding"]) + release(["Remove binding cleanup finalizer"]) + stop(["Stop"]) + + start --> provider + provider --> next_api + next_api -->|yes| covered + covered -->|yes| next_api + covered -->|no| schema + schema -->|no| next_api + schema -->|yes| drain + drain --> cluster_binding + cluster_binding -->|yes| remove_crd + cluster_binding -->|no| next_api + remove_crd --> next_api + next_api -->|no| related + related --> release + release --> stop +``` + +Draining requests deletion only for owned provider copies, unless an instance uses `deletion-policy: Orphan`. Provider-client and provider-read failures can leave copies behind, but actual provider-delete errors can block cleanup. Binding cleanup does not wait for provider finalizers as normal instance deletion does. + +The overlap check is API-wide, not a comparison of namespaces or Connections. A last ClusterBinding can delete the consumer CRD even when it was externally installed. A namespaced Binding keeps the shared CRD. Read the [cleanup limits](../../../usage/synchronization.md#delete-a-binding) before changing overlapping bindings or relying on automatic pruning. + +Implementation: [binding reconcilers](https://github.com/kbind-dev/kbind/blob/v2-next/engine/binding/reconciler.go), [related resources](https://github.com/kbind-dev/kbind/blob/v2-next/engine/binding/related.go), and [cleanup](https://github.com/kbind-dev/kbind/blob/v2-next/engine/binding/cleanup.go). diff --git a/docs/content/developers/konnector/controllers/cluster/.pages b/docs/content/developers/konnector/controllers/cluster/.pages deleted file mode 100644 index 0c64bf6c6..000000000 --- a/docs/content/developers/konnector/controllers/cluster/.pages +++ /dev/null @@ -1,5 +0,0 @@ -nav: - - clusterbinding.md - - apiservicenamespace.md - - apiservicebinding.md - - apiserviceexport.md diff --git a/docs/content/developers/konnector/controllers/cluster/apiservicebinding.md b/docs/content/developers/konnector/controllers/cluster/apiservicebinding.md deleted file mode 100644 index 32d9aa9e9..000000000 --- a/docs/content/developers/konnector/controllers/cluster/apiservicebinding.md +++ /dev/null @@ -1,101 +0,0 @@ -# APIServiceBindings - -The APIServiceBinding controller watches `APIServiceBindings`, and `CRDs` in the **consumer cluster** and `APIServiceExports` in the **provider cluster**. - -It is responsible for: - -* synchronizing `APIServiceExports` in the **provider cluster** to `CRDs` in the **consumer cluster** - -## Overview - -```mermaid -flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call - for APIServiceBinding"]) - - is_apiservicebinding_owned{"binding
owned?"} - set_apiservicebinding_condition_connected_to_true(["Set condition - 'Connected' - to true"]) - set_apiservicebinding_condition_connected_to_true2(["Set condition 'Connected' - to true"]) - - set_apiservicebinding_condition_connected_to_false(["Set condition 'Connected' - to false"]) - set_apiservicebinding_condition_connected_to_false2(["Set condition 'Connected' - to false"]) - - set_apiservicebinding_condition_schemainsync_to_true(["Set condition 'SchemaInSync' - to true"]) - - get_apiserviceexport(["Get provider - APIServiceExport"]) - is_apiserviceexport_present{"export
exists?"} - - get_apiserviceexportrequest(["Get provider - APIServiceExportRequest"]) - is_apiserviceexportrequest_in_failed_state{"Is APIServiceExportRequest
in failed state?"} - - get_bound_schemas(["Get provider - BoundSchemas referenced in - APIServiceExport"]) - bound_schema_fetch_successful(["Fetching BoundSchemas - succeed?"]) - reference_bound_schema(["Reference BoundSchema - in APIServiceBinding - status"]) - convert_boundschema_to_crd(["Convert BoundSchema - to CRD"]) - - - get_crd(["Get CRD"]) - create_crd(["Create CRD"]) - update_crd(["Update CRD"]) - is_crd_present{"CRD
exists?"} - is_crd_owned{"CRD
owned?"} - - get_clusterbinding(["Get ClusterBinding"]) - set_apiservicebinding_provider_name(["Set provider name"]) - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> is_apiservicebinding_owned - - is_apiservicebinding_owned --> |yes| get_apiserviceexport - get_apiserviceexport --> is_apiserviceexport_present - is_apiserviceexport_present --> |yes| set_apiservicebinding_condition_connected_to_true2 - is_apiserviceexport_present --> |no| get_apiserviceexportrequest - get_apiserviceexportrequest --> is_apiserviceexportrequest_in_failed_state - is_apiserviceexportrequest_in_failed_state --> |yes| set_apiservicebinding_condition_connected_to_false2 - is_apiserviceexportrequest_in_failed_state --> |no| set_apiservicebinding_condition_connected_to_false2 - - set_apiservicebinding_condition_connected_to_false2 --> stop - set_apiservicebinding_condition_connected_to_true2 --> get_bound_schemas - get_bound_schemas --> bound_schema_fetch_successful - bound_schema_fetch_successful --> |yes| reference_bound_schema - bound_schema_fetch_successful --> |no| set_apiservicebinding_condition_connected_to_false - reference_bound_schema --> convert_boundschema_to_crd - set_apiservicebinding_condition_connected_to_false --> stop - - convert_boundschema_to_crd --> get_crd - - get_crd --> is_crd_present - is_crd_present --> |no| create_crd - is_crd_present --> |yes| is_crd_owned - create_crd --> update_crd - - update_crd --> set_apiservicebinding_condition_connected_to_true - set_apiservicebinding_condition_connected_to_true --> set_apiservicebinding_condition_schemainsync_to_true - - is_crd_owned --> |yes| update_crd - is_crd_owned --> |no| set_apiservicebinding_condition_connected_to_false - - set_apiservicebinding_condition_schemainsync_to_true --> get_clusterbinding - get_clusterbinding --> set_apiservicebinding_provider_name - is_apiservicebinding_owned --> |no| stop - set_apiservicebinding_provider_name --> stop -``` diff --git a/docs/content/developers/konnector/controllers/cluster/apiserviceexport.md b/docs/content/developers/konnector/controllers/cluster/apiserviceexport.md deleted file mode 100644 index c6faae788..000000000 --- a/docs/content/developers/konnector/controllers/cluster/apiserviceexport.md +++ /dev/null @@ -1,105 +0,0 @@ -# APIServiceExports - -The APIServiceExport controller watches `APIServiceExports` and the referenced resources in the **provider cluster**. - -Starting with v1alpha2, the APIServiceExport has been refactored to use a resource-based model instead of embedded CRD specifications. - -## Key Changes in v1alpha2 - -- **Resource-Based Model**: `APIServiceExportSpec` now uses `Resources []APIServiceExportResource` instead of embedded CRD specs -- **Multi-Resource Support**: One APIServiceExport can reference multiple CRDs more efficiently -- **BoundSchema Integration**: Works with the new `BoundSchema` resource type for tracking bound schemas in consumer clusters - -## Controller Responsibilities - -* Ensuring the existence and validity of `APIServiceExports`. -* Managing the lifecycle of `APIServiceExports` by starting and stopping spec and status syncers and controllers. -* Checking `APIServiceBinding` condition and setting `ConsumerInSync` condition in `APIServiceExport` -* Managing resource references and their associated schemas. - -## Overview - -```mermaid -flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call - for APIServiceExport"]) - is_apiserviceexport_present{"APIServiceExport
exists?"} - - get_bound_schemas(["Get referenced - BoundSchemas"]) - get_bound_schemas2(["Get referenced - BoundSchemas"]) - is_bound_schema_present{"BoundSchema
exists?"} - update_bound_schema(["Update BoundSchema - status"]) - - stop_apiserviceexport_sync(["Stop APIServiceExport sync"]) - - get_binding(["Get referenced - APIServiceBinding"]) - get_binding2(["Get referenced - APIServiceBinding"]) - - is_binding_present{"APIServiceBinding
exists?"} - is_binding_present2{"APIServiceBinding
exists?"} - - is_binding_schemainsync{"APIServiceBinding
has SchemaInSync?"} - start_new_syncer(["Start new syncer"]) - - set_apiserviceexport_condition_connected_to_true(["Set condition - 'Connected' to true"]) - set_apiserviceexport_condition_connected_to_false(["Set - condition 'Connected' -to false"]) - set_apiserviceexport_condition_consumerinsync_to_true(["Set condition - 'ConsumerInSync' to true"]) - set_apiserviceexport_condition_consumerinsync_to_false(["Set condition - 'ConsumerInSync' to false"]) - - get_crd(["Get referenced - CustomResourceDefinition"]) - copy_crd_conditions(["Copy CRD conditions - to APIServiceExport - conditions"]) - set_summary_condition(["Set summary - of all conditions - on APIServiceExport"]) - - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> is_apiserviceexport_present - is_apiserviceexport_present --> |no| stop - is_apiserviceexport_present --> |yes| get_binding - - get_binding --> is_binding_present - is_binding_present --> |yes| get_bound_schemas - is_binding_present --> |no| stop_apiserviceexport_sync - stop_apiserviceexport_sync --> stop - - get_bound_schemas --> is_bound_schema_present - is_bound_schema_present --> |yes| start_new_syncer - is_bound_schema_present --> |no| stop_apiserviceexport_sync - stop_apiserviceexport_sync --> stop - - start_new_syncer --> get_binding2 - get_binding2 --> is_binding_present2 - is_binding_present2 --> |yes| set_apiserviceexport_condition_connected_to_true - is_binding_present2 --> |no| set_apiserviceexport_condition_connected_to_false - set_apiserviceexport_condition_connected_to_false --> set_apiserviceexport_condition_consumerinsync_to_false - set_apiserviceexport_condition_connected_to_true --> is_binding_schemainsync - is_binding_schemainsync --> |yes| set_apiserviceexport_condition_consumerinsync_to_true - set_apiserviceexport_condition_consumerinsync_to_true --> get_bound_schemas2 - is_binding_schemainsync --> |no| set_apiserviceexport_condition_consumerinsync_to_false - set_apiserviceexport_condition_consumerinsync_to_false --> get_bound_schemas2 - - get_bound_schemas2 --> get_crd - get_crd --> copy_crd_conditions - copy_crd_conditions --> set_summary_condition - set_summary_condition --> update_bound_schema - update_bound_schema --> stop -``` diff --git a/docs/content/developers/konnector/controllers/cluster/apiservicenamespace.md b/docs/content/developers/konnector/controllers/cluster/apiservicenamespace.md deleted file mode 100644 index 48f502e44..000000000 --- a/docs/content/developers/konnector/controllers/cluster/apiservicenamespace.md +++ /dev/null @@ -1,32 +0,0 @@ -# APIServiceNamespaces - -The APIServiceNamespace controller watches `Namespaces` in the **consumer cluster** and `APIServiceNamespaces` in the **provider cluster**. - -It is responsible for: - -* synchronizing `Namespaces` in the **consumer cluster** with `APIServiceNamespaces` in the **provider cluster** - -## Overview - -```mermaid -flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call for APIServiceNamespace"]) - - get_namespace(["Get associated namespace"]) - is_namespace_present(["namespace
exists?"]) - - delete_api_service_namespace(["Delete APIServiceNamespace"]) - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> get_namespace - get_namespace --> is_namespace_present - - is_namespace_present --> |yes| stop - is_namespace_present --> |no| delete_api_service_namespace - delete_api_service_namespace --> stop -``` diff --git a/docs/content/developers/konnector/controllers/cluster/boundschema.md b/docs/content/developers/konnector/controllers/cluster/boundschema.md deleted file mode 100644 index cb3955b53..000000000 --- a/docs/content/developers/konnector/controllers/cluster/boundschema.md +++ /dev/null @@ -1,42 +0,0 @@ -# BoundSchema - -The BoundSchema controller manages `BoundSchema` resources in the consumer cluster, introduced in v1alpha2. - -`BoundSchema` represents bound API resource schemas in consumer clusters and tracks the underlying status of synced resources. - -## Key Features - -- **Schema Validation**: Ensures the bound schema is valid and properly applied -- **Drift Detection**: Monitors for differences between expected and actual schema state -- **Condition Management**: Provides status conditions for validation and drift detection - -## BoundSchema Structure - -```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: BoundSchema -metadata: - labels: - kube-bind.io/exported: "true" - name: cowboys.wildwest.dev - namespace: kube-bind-flsd8 -spec: - group: wildwest.dev - informerScope: Namespaced - names: - kind: Cowboy - listKind: CowboyList - plural: cowboys - singular: cowboy - scope: Namespaced - versions: ... -``` - -## Integration with APIServiceExport - -BoundSchema works closely with the APIServiceExport resource-based model: - -1. APIServiceExport references multiple resources via `Resources []APIServiceExportResource` -2. Each resource can map to a BoundSchema in the consumer cluster -3. BoundSchema tracks the actual application and status of these schemas -4. This enables better multi-resource management and status tracking \ No newline at end of file diff --git a/docs/content/developers/konnector/controllers/cluster/clusterbinding.md b/docs/content/developers/konnector/controllers/cluster/clusterbinding.md deleted file mode 100644 index a15ae0d83..000000000 --- a/docs/content/developers/konnector/controllers/cluster/clusterbinding.md +++ /dev/null @@ -1,86 +0,0 @@ -# ClusterBindings - -The ClusterBinding controller watches `Secrets` (referenced by `APIServiceBindings`) in the **consumer -cluster** and `ClusterBindings`, the referenced `Secrets`, and `APIServiceExport` in the **provider -cluster**. - -It is responsible for: - -* synchronizing the secret referenced by the `ClusterBinding` in the **provider cluster** to the secret referenced by the `APIServiceBindings` in the **consumer cluster** -* reporting heartbeat to `ClusterBinding` in the **provider cluster** -* reporting konnector version `ClusterBinding` in the **provider cluster** -* reporting heartbeat to all `APIServiceBindings` managed by `ClusterBinding` in the **consumer cluster** - -## Overview - -```mermaid -flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call for ClusterBinding"]) - - update_cluster_binding(["Update ClusterBinding"]) - is_cluster_binding_update_successful{"update
successful?"} - - get_cluster_binding_kubeconfig_secret(["Get referenced provider kubeconfig secret"]) - is_cluster_binding_kubeconfig_secret_valid{"secret
valid?"} - - set_cluster_binding_condition_secret_valid_to_true(["Set condition 'SecretValid' to true"]) - set_cluster_binding_condition_secret_valid_to_false(["Set condition 'SecretValid' to false"]) - set_cluster_binding_condition_valid_version_to_true(["Set condition 'ValidVersion' to true"]) - set_cluster_binding_condition_valid_version_to_false(["Set condition 'ValidVersion' to false"]) - set_cluster_binding_condition_ready(["Set condition 'Ready' to summary"]) - - set_cluster_binding_status_last_heartbeat(["Set status 'LastHeartbeatTime' to now"]) - set_cluster_binding_status_konnector_version(["Set status 'KonnectorVersion'"]) - - get_api_binding_kubeconfig_secret(["Get consumer kubeconfig secret"]) - create_api_binding_kubeconfig_secret(["Create consumer kubeconfig secret"]) - update_api_binding_kubeconfig_secret(["Update consumer kubeconfig secret"]) - is_api_binding_kubeconfig_secret_present{"secret
exists?"} - - set_api_binding_status_heartbeating_to_true(["Set APIServiceBinding conditions 'Heartbeating' to true"]) - set_api_binding_status_heartbeating_to_false(["Set APIServiceBinding conditions 'Heartbeating' to false"]) - - get_konnector_version(["Get konnector version"]) - is_konnector_version_valid{"version
valid?"} - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> get_cluster_binding_kubeconfig_secret - get_cluster_binding_kubeconfig_secret --> is_cluster_binding_kubeconfig_secret_valid - - is_cluster_binding_kubeconfig_secret_valid --> |yes| get_api_binding_kubeconfig_secret - get_api_binding_kubeconfig_secret --> is_api_binding_kubeconfig_secret_present - is_api_binding_kubeconfig_secret_present --> |yes| update_api_binding_kubeconfig_secret - is_api_binding_kubeconfig_secret_present --> |no| create_api_binding_kubeconfig_secret - update_api_binding_kubeconfig_secret --> set_cluster_binding_condition_secret_valid_to_true - create_api_binding_kubeconfig_secret --> set_cluster_binding_condition_secret_valid_to_true - - is_cluster_binding_kubeconfig_secret_valid --> |no| set_cluster_binding_condition_secret_valid_to_false - - set_cluster_binding_condition_secret_valid_to_true --> set_cluster_binding_status_last_heartbeat - set_cluster_binding_condition_secret_valid_to_false --> set_cluster_binding_status_last_heartbeat - - set_cluster_binding_status_last_heartbeat --> get_konnector_version - get_konnector_version --> is_konnector_version_valid - - is_konnector_version_valid --> |yes| set_cluster_binding_status_konnector_version - set_cluster_binding_status_konnector_version --> set_cluster_binding_condition_valid_version_to_true - - is_konnector_version_valid --> |no| set_cluster_binding_condition_valid_version_to_false - - set_cluster_binding_condition_valid_version_to_true --> set_cluster_binding_condition_ready - set_cluster_binding_condition_valid_version_to_false --> set_cluster_binding_condition_ready - - set_cluster_binding_condition_ready --> update_cluster_binding - update_cluster_binding --> is_cluster_binding_update_successful - - is_cluster_binding_update_successful --> |yes| set_api_binding_status_heartbeating_to_true - is_cluster_binding_update_successful --> |no| set_api_binding_status_heartbeating_to_false - - set_api_binding_status_heartbeating_to_true --> stop - set_api_binding_status_heartbeating_to_false --> stop -``` diff --git a/docs/content/developers/konnector/controllers/connection.md b/docs/content/developers/konnector/controllers/connection.md new file mode 100644 index 000000000..71c101cd3 --- /dev/null +++ b/docs/content/developers/konnector/controllers/connection.md @@ -0,0 +1,105 @@ +# Connection Controller + +The Connection controller watches `Connections` and their referenced `Secrets` in the **consumer cluster**. It is implemented in `engine/connection`. + +It is responsible for: + +* Validating the provider kubeconfig and pinning provider/consumer identities. +* Discovering exported APIs and recording the active schema source. +* Installing schemas eagerly when `pullPolicy: All`. +* Maintaining an automatic ClusterBinding when `autoBind` is enabled. +* Renewing the provider heartbeat Lease and protecting credentials during cleanup. + +## Overview + +The chart below shows a non-deleting Connection. Successful reconciliation requeues after 30 seconds by default, so newly exported APIs are discovered without requiring a Secret or Connection edit. + +```mermaid +flowchart TD + start(["Connection or Secret event
or periodic reconciliation"]) + get_connection(["Get Connection"]) + exists{"Connection
exists?"} + finalizers(["Ensure cleanup finalizers
on Connection and available Secret"]) + added{"Connection finalizer
just added?"} + credentials{"Provider kubeconfig
usable?"} + invalid(["Set SecretValid=False
and Ready=False"]) + identity(["Set SecretValid=True
Read and verify cluster identities"]) + connected{"Provider identity readable
and matches pinned UID?"} + unavailable(["Record identity failure
Set Ready=False"]) + pin(["Record cluster UIDs
Set Connected=True"]) + discover(["Discover exported APIs
Record activeSchemaSource and exportedAPIs"]) + pull_all{"pullPolicy
is All?"} + install(["Pull or synthesize all exported CRDs
Honor updatePolicy"]) + auto_bind{"autoBind
enabled?"} + binding(["Update managed ClusterBinding
Delete it if no APIs are exported"]) + heartbeat(["Attempt to renew provider Lease"]) + ready(["Set Ready=True"]) + status(["Persist changed status
Requeue after 30 seconds"]) + stop(["Stop"]) + + start --> get_connection + get_connection --> exists + exists -->|no| stop + exists -->|yes| finalizers + finalizers --> added + added -->|yes| stop + added -->|no| credentials + credentials -->|no| invalid + invalid --> status + credentials -->|yes| identity + identity --> connected + connected -->|no| unavailable + unavailable --> status + connected -->|yes| pin + pin --> discover + discover --> pull_all + pull_all -->|yes| install + pull_all -->|no| auto_bind + install --> auto_bind + auto_bind -->|yes| binding + auto_bind -->|no| heartbeat + binding --> heartbeat + heartbeat --> ready + ready --> status + status --> stop +``` + +Provider identity/discovery RBAC denials set `PermissionDenied=True` and `Ready=False`. Other API errors are returned for retry rather than continuing through the success path. Heartbeat errors are logged but do not prevent Ready. + +`CRD` discovery uses the export label. `OpenAPI` uses discovery and OpenAPI v3. `Auto` tries CRDs first and switches to OpenAPI only after a successful list with no exports, not after a list error. `Bound` defers installation to binding reconciliation, and `None` leaves creation to an external manager. + +## Deletion + +```mermaid +flowchart TD + start(["Deleting Connection"]) + finalizer{"Cleanup finalizer
present?"} + auto_bind{"autoBind
enabled?"} + remove_binding(["Request deletion of
the managed ClusterBinding"]) + references{"Any bindings still
reference this Connection?"} + wait_bindings(["Set Ready=False with DrainingBindings
Requeue after 2 seconds"]) + shared_secret{"Another non-deleting Connection
uses the same Secret?"} + release_secret(["Remove Secret cleanup finalizer
if the Secret still exists"]) + release_connection(["Remove Connection cleanup finalizer"]) + stop(["Stop"]) + + start --> finalizer + finalizer -->|no| stop + finalizer -->|yes| auto_bind + auto_bind -->|yes| remove_binding + auto_bind -->|no| references + remove_binding --> references + references -->|yes| wait_bindings + wait_bindings --> stop + references -->|no| shared_secret + shared_secret -->|yes| release_connection + shared_secret -->|no| release_secret + release_secret --> release_connection + release_connection --> stop +``` + +Explicit bindings are not deleted by this controller. They must be removed separately while credentials and the konnector are still available. Releasing the Secret finalizer does not itself delete the Secret. + +See [API concepts](../../../usage/api-concepts.md) for schema policies and credential-rotation limits, and [lifecycle](../../../usage/synchronization.md) for heartbeat and deletion behavior. + +Implementation: [Connection reconciler](https://github.com/kbind-dev/kbind/blob/v2-next/engine/connection/reconciler.go). diff --git a/docs/content/developers/konnector/controllers/konnector.md b/docs/content/developers/konnector/controllers/konnector.md index a41434f3f..a3581ca7a 100644 --- a/docs/content/developers/konnector/controllers/konnector.md +++ b/docs/content/developers/konnector/controllers/konnector.md @@ -1,60 +1,72 @@ -# konnector +# Konnector -The konnector implements the main reconciliation loop and watches `APIServiceBindings` and the referenced `Secrets` in the **consumer cluster**. +The konnector coordinates the consumer controllers and a provider-cluster connection for each Ready `Connection`. The `connection-provider` controller in `engine/provider` watches `Connections` in the **consumer cluster**. It is responsible for: -* starting / stopping a set of controllers per service provider +* Starting a provider client and cache when a Connection becomes Ready. +* Making that provider available to the multicluster manager. +* Stopping the provider cache when its Connection disappears or loses readiness. + +The [Connection controller](connection.md) validates credentials and discovers APIs. The [Binding controllers](binding.md) prepare consumer schemas, and the [Synchronization controllers](synchronization.md) start or stop instance syncers. These replace the old `APIServiceBinding` and per-provider controller arrangement. ## Overview ```mermaid flowchart TD - %% Nodes - start@{ shape: start } - stop@{ shape: stop } - - enqueue_reconcile(["Enqueue reconcile call for APIServiceBinding"]) - - get_kubeconfig_secret(["Get referenced kubeconfig secret"]) - is_kubeconfig_empty{"kubeconfig
empty?"} - - get_controller_context_for_binding(["Get controller context for binding"]) - is_controller_context_for_binding_present{"context
exists?"} - is_controller_context_current{"context
up-to-date?"} - is_controller_context_used{"context
in use?"} - - get_controller_context_for_kubeconfig(["Get controller context for kubeconfig"]) - is_controller_context_for_kubeconfig_present{"context
exists?"} - - create_controller_context_for_binding(["Create controller context for binding"]) - add_binding_to_controller_context(["Add binding to controller context"]) - remove_binding_from_controller_context(["Remove binding from controller context"]) - - start_controllers(["Start controllers"]) - stop_controllers(["Stop controllers"]) - - %% Transitions - start --> enqueue_reconcile - enqueue_reconcile --> get_kubeconfig_secret - get_kubeconfig_secret --> get_controller_context_for_binding - get_controller_context_for_binding --> is_controller_context_for_binding_present - - is_controller_context_for_binding_present -->|yes| is_controller_context_current - is_controller_context_current -->|yes| is_kubeconfig_empty - is_controller_context_current -->|no| remove_binding_from_controller_context - remove_binding_from_controller_context --> is_controller_context_used - is_controller_context_used -->|yes| stop - is_controller_context_used -->|no| stop_controllers - stop_controllers --> stop - - is_controller_context_for_binding_present -->|no| is_kubeconfig_empty - is_kubeconfig_empty -->|yes| stop - is_kubeconfig_empty -->|no| get_controller_context_for_kubeconfig - get_controller_context_for_kubeconfig --> is_controller_context_for_kubeconfig_present - is_controller_context_for_kubeconfig_present -->|yes| add_binding_to_controller_context - add_binding_to_controller_context --> stop - is_controller_context_for_kubeconfig_present -->|no| create_controller_context_for_binding - create_controller_context_for_binding --> start_controllers - start_controllers --> stop + start(["Connection event"]) + get_connection(["Get Connection"]) + connection_exists{"Connection
exists?"} + manager_ready{"Multicluster manager
available?"} + connection_ready{"Connection
Ready?"} + already_engaged{"Provider already
engaged?"} + get_credentials(["Read referenced Secret
and build provider configuration"]) + start_cache(["Create provider client and cache
Start cache and wait for sync"]) + engage(["Engage provider with
the multicluster manager"]) + disengage(["Cancel provider cache
Remove engaged provider"]) + retry(["Requeue after 2 seconds"]) + stop(["Stop"]) + + start --> get_connection + get_connection --> connection_exists + connection_exists -->|no| disengage + connection_exists -->|yes| manager_ready + manager_ready -->|no| retry + manager_ready -->|yes| connection_ready + connection_ready -->|no| disengage + connection_ready -->|yes| already_engaged + already_engaged -->|yes| stop + already_engaged -->|no| get_credentials + get_credentials --> start_cache + start_cache --> engage + engage --> stop + disengage --> stop + retry --> stop ``` + +Configuration, cache-start, and engagement errors are returned for retry. A failed engagement cancels the new cache and removes its entry. Connection events also enqueue the managed-CRD controller, which stops instance syncers when readiness is lost. Recovery creates a fresh provider client/cache, and syncers are rebuilt against that new provider. + +An already-engaged Ready Connection is left unchanged. Updating a valid credential Secret alone does not rebuild its client, see [credential rotation](../../../usage/api-concepts.md#credentials-and-cluster-identity). + +## Runtime options + +The konnector runs against the **consumer** kubeconfig, or uses its in-cluster ServiceAccount. Provider credentials come from each Connection's referenced Secret, not from the konnector's own Kubernetes identity. + +```bash +go run ./cmd/konnector --help +``` + +| Flag | Default | Purpose | +| --- | --- | --- | +| `--metrics-bind-address` | `:8085` | Metrics listener, `0` disables it | +| `--health-probe-bind-address` | `:8081` | `/healthz` and `/readyz` listener | +| `--leader-elect` | `false` | Run only the elected replica's consumer controllers and provider engagement | +| `--leader-election-id` | `konnector.kbind.io` | Leader-election Lease name | + +The binary also exposes controller-runtime's kubeconfig and Zap logging flags, use its `--help` output for those options. There are no flags for legacy isolation modes, namespace remapping, schema selection, or per-provider credentials: schema and credential configuration belongs in the [core API](../../../reference/crd/index.md#corekbindiov1alpha1). + +The chart forces leader election when `replicaCount > 1`. Outside the chart, enable it explicitly for multiple replicas. Probe success indicates the process is serving, not that every Connection or binding is Ready. Inspect those objects' conditions to assess synchronization health. + +See [Konnector configuration](../index.md) for chart values and consumer RBAC, and [troubleshooting](../../../usage/troubleshooting.md) for runtime status. + +Implementation: [process setup](https://github.com/kbind-dev/kbind/blob/v2-next/cmd/konnector/main.go) and [Connection provider](https://github.com/kbind-dev/kbind/blob/v2-next/engine/provider/connection_provider.go). diff --git a/docs/content/developers/konnector/controllers/synchronization.md b/docs/content/developers/konnector/controllers/synchronization.md new file mode 100644 index 000000000..f4fe957ba --- /dev/null +++ b/docs/content/developers/konnector/controllers/synchronization.md @@ -0,0 +1,136 @@ +# Synchronization Controllers + +The managed-CRD controller watches kbind-managed `CustomResourceDefinitions` and their `Connections` in the **consumer cluster**. It starts a dynamic instance syncer for each selected group/version/resource, or GVR. Both are implemented in `engine/sync`. + +They are responsible for: + +* Starting, stopping, and rebuilding syncers as CRDs and provider connections change. +* Selecting instances covered by a Ready ClusterBinding or namespaced Binding. +* Applying consumer spec to owned provider objects and copying provider status back. +* Reporting ownership conflicts without overwriting foreign objects. +* Deleting owned provider copies before releasing consumer instance finalizers. + +## Overview + +The managed-CRD controller resolves the provider from the CRD's `core.kbind.io/connection` annotation. A missing annotation or an API error is returned for retry. + +```mermaid +flowchart TD + start(["Managed CRD or Connection event"]) + crd{"CRD exists
and is not deleting?"} + connection{"Connection Ready
and localClusterUID set?"} + engaged{"Provider client and cache
engaged?"} + current{"Existing syncer has current generation
and the same provider instance?"} + stop_old(["Stop the previous syncer"]) + version(["Choose storage or served version
Build consumer informer and instance controller"]) + watches(["Watch consumer and provider instances
Watch bindings covering this API"]) + run(["Start controller and informer
Wait for cache sync and record syncer"]) + stop_syncer(["Stop existing syncer"]) + wait_provider(["Stop existing syncer
Requeue after 2 seconds"]) + stop(["Stop"]) + + start --> crd + crd -->|no| stop_syncer + crd -->|yes| connection + connection -->|no| stop_syncer + connection -->|yes| engaged + engaged -->|no| wait_provider + engaged -->|yes| current + current -->|yes| stop + current -->|no| stop_old + stop_old --> version + version --> watches + watches --> run + run --> stop + stop_syncer --> stop + wait_provider --> stop +``` + +The generation check detects schema changes. Comparing the provider instance also detects re-engagement after an outage, so a syncer cannot keep the old client/cache simply because the CRD generation is unchanged. + +## Instance reconciliation + +Consumer events, binding events, and provider cache events enqueue instances. Provider events are filtered by consumer-cluster UID and mapped back to the consumer object key. Reads of provider objects use the engaged cluster's API reader, while writes use its client. + +```mermaid +flowchart TD + start(["Consumer, provider, or binding event"]) + object{"Consumer object
exists?"} + resolve(["Resolve covering binding
ClusterBinding before namespaced Binding"]) + deleting{"Consumer object
deleting?"} + cleanup(["Run instance deletion"]) + bound{"Covering binding
Ready?"} + map_key(["Map consumer key to provider key"]) + finalizer{"Syncer finalizer
already present?"} + add_finalizer(["Add finalizer and requeue"]) + target(["Read provider object"]) + ownership{"Provider target ownership?"} + adopt{"conflictPolicy
is Adopt?"} + conflict(["Record conflict annotation
and Warning Event"]) + namespace(["Ensure provider namespace
for a new namespaced object"]) + apply(["Clear old conflict marker
Apply spec and ownership markers"]) + status(["Read provider object again
Copy status if present"]) + stop(["Stop"]) + + start --> object + object -->|no| stop + object -->|yes| resolve + resolve --> deleting + deleting -->|yes| cleanup + cleanup --> stop + deleting -->|no| bound + bound -->|no| stop + bound -->|yes| map_key + map_key --> finalizer + finalizer -->|no| add_finalizer + add_finalizer --> stop + finalizer -->|yes| target + target --> ownership + ownership -->|absent| namespace + namespace --> apply + ownership -->|ours| apply + ownership -->|no ownership markers| adopt + ownership -->|owned by another| conflict + adopt -->|yes| apply + adopt -->|no| conflict + conflict --> stop + apply --> status + status --> stop +``` + +Ownership requires both the consumer-cluster UID and consumer-object UID. `Adopt` accepts only markerless objects, never objects owned by another consumer/object. Spec apply uses server-side apply with forced field ownership. An absent provider status does not clear an existing consumer status. + +Forbidden namespace creation or spec apply emits a Warning Event and retries after 30 seconds. Other API errors are returned for retry. Successful instance reconciliation schedules a ten-minute backstop, with watches and the consumer informer's resync providing additional triggers. + +## Instance deletion + +```mermaid +flowchart TD + start(["Deleting consumer object"]) + finalizer{"Syncer finalizer
present?"} + orphan{"deletion-policy
is Orphan?"} + read_provider(["Read mapped provider object"]) + owned{"Provider copy exists
and is ours?"} + delete_copy(["Request provider deletion
Requeue after 2 seconds"]) + release(["Remove consumer syncer finalizer"]) + stop(["Stop"]) + + start --> finalizer + finalizer -->|no| stop + finalizer -->|yes| orphan + orphan -->|yes| release + orphan -->|no| read_provider + read_provider --> owned + owned -->|yes| delete_copy + delete_copy --> stop + owned -->|no| release + release --> stop +``` + +This path runs even if the binding is no longer Ready. An owned provider object must disappear before its consumer finalizer is released. Provider read/delete errors are retried, not treated as absence. Foreign objects are left untouched. + +The stock `Mapper` preserves scope, namespace, and name. It is a compile-time extension point for instance keys, not a CRD isolation flag. Related-resource sync remains in binding reconciliation and does not use that mapper. + +See [Resource Synchronization](../../../usage/synchronization.md) for conflict policy, finalizers, related-resource selection, and supported behavior. + +Implementation: [managed-CRD controller](https://github.com/kbind-dev/kbind/blob/v2-next/engine/sync/crd_controller.go), [binding resolution](https://github.com/kbind-dev/kbind/blob/v2-next/engine/sync/resolve.go), and [instance syncer](https://github.com/kbind-dev/kbind/blob/v2-next/engine/sync/syncer.go). diff --git a/docs/content/developers/konnector/index.md b/docs/content/developers/konnector/index.md index e3310cffc..6f07a2f6a 100644 --- a/docs/content/developers/konnector/index.md +++ b/docs/content/developers/konnector/index.md @@ -1 +1,101 @@ # konnector + +The konnector runs on the consumer and synchronizes APIs from provider clusters. In v2 it is the only running component required by the core. + +- [Konnector](controllers/konnector.md): provider engagement, managers, and runtime options. +- [Connection controller](controllers/connection.md): credentials, identity, discovery, and heartbeat. +- [Binding controllers](controllers/binding.md): API selection, schema delivery, and cleanup. +- [Synchronization](controllers/synchronization.md): per-API spec/status watches and ownership. + +See [Architecture](../architecture.md) for the package layout. + +## Deployment + +Start with [Installation with Helm](../../setup/helm.md). The konnector runs in the consumer cluster and connects directly to provider Kubernetes APIs. It needs no kbind controller or kbind CRDs on a plain Kubernetes provider. + +### Local kind images + +For an existing kind consumer, build and load the image rather than pushing it: + +```bash +export IMAGE_REPOSITORY=kbind-local/konnector +export IMAGE_TAG="git-$(git rev-parse --short=12 HEAD)" +make image IMAGE="$IMAGE_REPOSITORY:$IMAGE_TAG" +kind load docker-image "$IMAGE_REPOSITORY:$IMAGE_TAG" --name consumer +``` + +Use those values with the Helm command and select `kind-consumer` as its context. Build for the consumer nodes' architecture and use a new tag for uncommitted changes. For a private registry, configure `imagePullSecrets`. + +The Pod must be able to reach each provider endpoint using the CA and credentials in its Connection Secret. A workstation's `127.0.0.1` kind endpoint is not reachable from a consumer Pod. With two kind clusters on the same Docker network, use an address reachable across that network and covered by the provider serving certificate. Keep TLS verification enabled. + +### Chart configuration + +| Value | Default | Meaning | +| --- | --- | --- | +| `image.repository`, `image.tag` | repository plus placeholder appVersion | Set both explicitly for this branch. | +| `installCRDs` | `true` | Install the three core CRDs as Helm templates. | +| `replicaCount` | `1` | Number of Pods, only one should actively reconcile. | +| `leaderElect` | `false` | Automatically forced on when `replicaCount > 1`. | +| `leaderElectionID` | `konnector.kbind.io` | Consumer-side leader-election Lease name. | +| `rbac.boundResourceGroups` | `["*"]` | Consumer API groups the engine can synchronize. | +| `metrics.port` | `8085` | Controller-runtime metrics endpoint. | +| `healthProbe.port` | `8081` | `/healthz` and `/readyz` endpoints. | +| `extraArgs` | `[]` | Additional konnector arguments, including logging flags. | + +For multiple replicas, the chart supplies leader-election RBAC and enables election. Do not deploy independent active releases against the same consumer. The probes are process checks, not proof that a Connection or instance is syncing. + +## RBAC and credentials + +### Consumer permissions + +The chart manages core objects and their status/finalizers, CRDs, credential Secrets, namespaces, and Events. By default, it also grants ordinary CRUD/watch operations on **all API groups and resources**. Review this broad access before a shared deployment. + +For example, narrow the configurable resource rule to Widget APIs: + +```yaml +rbac: + boundResourceGroups: + - example.org +``` + +Pass the values with `helm ... -f your-values.yaml`. This does not narrow the chart's separate access to core kbind objects, CRDs, or credential Secrets. + +For related resources, supply the additional consumer RBAC they need. The chart's fixed Secret rule allows reads and updates for credentials, but not creation/deletion of related Secret copies. There is no fixed ConfigMap rule. Add narrowly scoped rules for the related resource kinds and direction rather than granting all core resources through the empty API group. + +A namespaced Binding restricts which instances synchronize, not informer permissions. Current instance informers watch cluster-wide on both sides, so a namespace-only Role is not sufficient. + +### Provider permissions + +Use dedicated credentials for the intended provider boundary, not a production administrator kubeconfig. + +| Operation | Required provider access | +| --- | --- | +| Identify plain Kubernetes | Read Namespace `kube-system`. | +| Identify a kcp logical cluster | Read `logicalclusters.core.kcp.io/cluster`, a forbidden result is not ignored. | +| Discover CRD exports | List CRDs and get selected CRDs in `apiextensions.k8s.io`. | +| Discover OpenAPI exports | Read discovery endpoints and `/openapi/v3` documents. | +| Sync instances | Cluster-wide get/list/watch for the selected APIs, create/patch/update/delete for targets. | +| Materialize a namespace | Create namespaces, the engine attempts a create even if the namespace may already exist. | +| Sync related objects | List/read selected sources, read/list/create/patch/delete targets according to direction. | +| Heartbeat | Get/create/update Leases in the kubeconfig context namespace, or `kbind` when unset. | + +Provider RBAC and network boundaries control access. Export labels are not authorization. Namespace/name mapping is identity-only, credentials with a default namespace do not redirect objects into it. + +Store the provider kubeconfig in a consumer Secret and reference its explicit namespace/name/key from a Connection. The chart does not create credentials. See [API concepts](../../usage/api-concepts.md#credentials-and-cluster-identity) for immutable references, identity pinning, and rotation. + +## Manage CRDs outside Helm + +For a GitOps-managed lifecycle, install the core manifests before the release: + +```bash +kubectl --context="$CONSUMER_CONTEXT" apply \ + -f sdk/config/crd/core.kbind.io_connections.yaml \ + -f sdk/config/crd/core.kbind.io_clusterbindings.yaml \ + -f sdk/config/crd/core.kbind.io_bindings.yaml +``` + +Set `installCRDs: false` from the first Helm installation. Do not switch an existing release from `true` to `false` without planning the migration. These are rendered templates, not Helm's retained `crds/` directory, so removing them from a release can delete them and their custom resources. + +The rest of `sdk/config/crd` contains optional catalog and IAM CRDs. Installing the three named files keeps a core-only deployment minimal. + +Before uninstalling, unbind while the controller and credentials still work, delete Connections after bindings drain, and remove credential Secrets after their finalizers are released. Removing the controller or CRDs first bypasses normal teardown. See [Unbinding and deletion](../../usage/synchronization.md#unbinding-and-deletion). diff --git a/docs/content/developers/publishing-a-release.md b/docs/content/developers/publishing-a-release.md index 6860f5463..452cfb87b 100644 --- a/docs/content/developers/publishing-a-release.md +++ b/docs/content/developers/publishing-a-release.md @@ -1,133 +1,19 @@ ---- -description: > - Information on the kube-bind release process. ---- +# Publishing a release -# Publishing a New kube-bind Release +v2 releases are driven by version tags. The Image workflow publishes versioned `konnector` and `backend` images plus the `konnector-v2` and `backend-v2` OCI charts. Final tags also publish CLI archives, prerelease tags do not update krew. -!!! note - You currently need write access to the [kube-bind/kube-bind](https://github.com/kube-bind/kube-bind) repository to perform these - tasks. +## Release candidates -## Create git Tags +From the intended checkout, inspect the next release-candidate tag: -### Prerequisite - Make Sure You Have a GPG Signing Key - -1. -2. -3. - -### Create the Tags - -kube-bind has 3 go modules, and a unique tag is needed for each module every time we create a new release. - -1. `git fetch` from the main kube-bind repository (kube-bind/kube-bind) to ensure you have the latest commits -2. Tag the main module - 1. If your git remote for kube-bind/kube-bind is named something other than `upstream`, change `REF` accordingly - 2. If you are creating a release from a release branch, change `main` in `REF` accordingly, or you can - make `REF` a commit hash. - - ```shell - REF=upstream/main - TAG=v0.6.0 - git tag --sign --message "$TAG" "$TAG" "$REF" - ``` - - 3. Tag the `sdk` module, following the same logic as above for `REF` and `TAG` - - ```shell - REF=upstream/main - TAG=v0.6.0 - git tag --sign --message "sdk/$TAG" "sdk/$TAG" "$REF" - ``` - -4. Tag the `cli` module, following the same logic as above for `REF` and `TAG` - - ```shell - REF=upstream/main - TAG=v0.6.0 - git tag --sign --message "cli/$TAG" "cli/$TAG" "$REF" - ``` - -### Push the Tags - - ```shell - REMOTE=upstream - TAG=v0.6.0 - git push "$REMOTE" "$TAG" "sdk/$TAG" "cli/$TAG" - ``` - -### Create a Release Branch - -Set `REMOTE`, `REF`, and `VERSION` as appropriate. - -```shell -REMOTE=upstream -REF="$REMOTE/main" -VERSION=0.6 # e.g. 1.2 -git checkout -b "release-$VERSION" "$REF" -git push "$REMOTE" "release-$VERSION" -``` - -Once you tag and push the new release branch, don't forget to run the documentation deployment as described in [Trigger Documentation Deployment](#trigger-documentation-deployment). - -## If it's a New Minor Version - -If this is the first release of a new minor version (e.g. the last release was v0.7.x, and you are releasing the first -0.8.x version), follow the following steps. - -Otherwise, you can skip to [Generate release notes](#generate-release-notes). - -## Generate Release Notes - -To generate release notes from the information in PR descriptions you should use Kubernetes' [release-notes](https://github.com/kubernetes/release/tree/master/cmd/release-notes) tool. -This tool will use the `release-notes` blocks in PR descriptions and the `kind/` labels on those PRs to find user-facing changes and categorize them. -You can run the command below to install the latest version of it: - -```shell -go install k8s.io/release/cmd/release-notes@latest +```bash +go run ./cmd/release -remote upstream -dry-run ``` -To use `release-notes` you will need to generate a GitHub API token (Settings -> Developers settings -> Personal access tokens -> Fine-grained tokens). A token with _Public Repositories (read-only)_ repository access and no further permissions is sufficient. Store the token somewhere safe and export it as `GITHUB_TOKEN` environment variable. - -Then, run the `release-notes` tool (set `PREV_VERSION` to the version released before the one you have just released). - -```shell -TAG=v0.6.0 -PREV_TAG=v0.5.1 -release-notes \ - --required-author='' \ - --org kube-bind \ - --repo kube-bind \ - --branch main \ - --start-rev $PREV_TAG \ - --end-rev $TAG \ - --output CHANGELOG.md -``` - -Don't commit the `CHANGELOG.md` to the repository, just keep it around to update the release on GitHub (next step). - -## Review/Edit/Publish the Release in GitHub - -The [goreleaser](https://github.com/kube-bind/kube-bind/actions/workflows/goreleaser.yml) workflow automatically creates a draft GitHub release for each tag. - -1. Navigate to the draft release for the tag you just pushed. You'll be able to find it under the [releases](https://github.com/kube-bind/kube-bind/releases) page. -2. If the release notes have been pre-populated, delete them. -3. Copy release notes from the `CHANGELOG.md` file you generated in the previous step. -4. Publish the release. - -## Trigger Documentation Deployment - -Documentation for the respective release branch needs to be triggered manually after the release branch has been pushed. +Only when ready to create and publish it, use the helper's `-push` option. The remote must point to the intended release repository. -1. Navigate to the [Generate and push docs](https://github.com/kube-bind/kube-bind/actions/workflows/docs-gen-and-push.yaml) GitHub Action. -2. Hit the "Run workflow" button, run workflow against `release-$VERSION`. -3. Make sure the triggered workflow ran and deployed a new version of the documentation to [https://docs.kube-bind.io/main/](https://docs.kube-bind.io/main). +See the maintained [release procedure](https://github.com/kbind-dev/kbind/blob/v2-next/docs/RELEASING.md) for manual tags, final releases, and maintenance branches. -## Notify +## Documentation - 1. Create an email addressed to kube-bind-dev@googlegroups.com with: - 1. Subject: `[release] ` e.g. `[release] v0.5.0` - 2. In the body, include noteworthy changes - 3. Provide a link to the release in GitHub for the full release notes - 2. Post a message in the [#kube-bind](https://kubernetes.slack.com/archives/C021U8WSAFK) Slack channel +The v2 docs publisher uses `v2` without changing the site's root redirect or `latest` alias. Tags do not automatically promote v2 documentation to the default. Local build and publishing instructions live in `docs/README.md`. diff --git a/docs/content/developers/testing-changes.md b/docs/content/developers/testing-changes.md index fdd13fa6f..0e11e932f 100644 --- a/docs/content/developers/testing-changes.md +++ b/docs/content/developers/testing-changes.md @@ -1,83 +1,73 @@ --- description: > - How to test changes made to kube-bind in your development environment. -weight: 30 + How to test changes made to kbind in your development environment. title: Testing Changes --- # Testing code changes -When making changes to kube-bind, it's important to test them in a realistic multi-cluster environment. +Use the v2 source branch rather than `main`, which still describes the 0.x implementation: -Follow [development setup instructions](../developers/development-setup/) to set up your development environment using kcp. -kcp allows you to simulate multiple clusters using logical clusters. +```bash +git clone --branch v2-next https://github.com/kbind-dev/kbind.git +cd kbind +make build +make konnector backend bind +``` +The root module builds the engine, backend, and CLI. `sdk/` is a separate Go module with a local `replace` in the root `go.mod`, a `go.work` file is not required. Use the Go version declared in `go.mod` (currently 1.26.2). The binaries are `bin/konnector`, `bin/backend`, and `bin/bind`. -# Testing helm chart changes +## Run a change locally -By default, in helm chart, the backend component does not have TLS enabled, and the embedded OIDC server is not used. -To test changes related to TLS or OIDC, you need to enable them explicitly by setting the appropriate Helm values. +Start with the [two-cluster walkthrough](dev-environment/kind.md). Running the konnector on your workstation against the consumer kubeconfig makes engine changes easy to iterate without rebuilding an image. -To test basic Helm-install flow you will need GatewayAPI enabled kubernetes cluster with cert-manager installed. -By default it will use TLS termination at the Gateway level. +The [backend setup](backend/index.md) covers a local gateway with mock OIDC. Never use mock authentication on an exposed production endpoint. The gateway UI is embedded from `web/`, the v2 UI does not require the old npm frontend build. +For in-cluster runs, build and load or push explicitly tagged images: ```bash -# Use a specific development version: -# VERSION=0.0.0-9fd9281e661c0d9a426a941111d3d8b08019ebc1 +make image IMAGE=ghcr.io/kbind-dev/konnector:dev +make image-backend BACKEND_IMAGE=ghcr.io/kbind-dev/backend:dev ``` -And run full helm install command with additional parameters: +These commands build locally, they do not publish the images. Use the `deploy/charts/konnector-v2` and `deploy/charts/backend-v2` charts and override their image tags to match. The legacy chart directory names without `-v2` do not exist in this branch. + +## Tests + ```bash -helm upgrade \ - --install \ - --namespace kube-bind \ - --create-namespace \ - --set certManager.enabled=true \ - --set certManager.clusterIssuer=letsencrypt-prod \ - --set backend.oidc.issuerUrl=https://auth.genericcontrolplane.io \ - --set backend.oidc.clientId=platform-mesh \ - --set backend.oidc.clientSecret=Z2Fyc2lha2FsYmlzdmFuZGVuekWplCg== \ - --set backend.oidc.callbackUrl=https://kube-bind.genericcontrolplane.io/api/callback \ - --set gatewayApi.enabled=true \ - --set gatewayApi.gateway.className=nginx \ - --set gatewayApi.gateway.httpPort=80 \ - --set gatewayApi.gateway.httpsPort=443 \ - --set 'gatewayApi.gateway.tls.certificateRefs[0].name=backend-tls-cert' \ - --set 'gatewayApi.route.hostnames[0]=kube-bind.genericcontrolplane.io' \ - --set gatewayApi.route.path=/ \ - --set gatewayApi.route.pathType=PathPrefix \ - --set image.tag=${VERSION} \ - kube-bind \ - ./deploy/charts/backend +make test +make test-e2e ``` -After the deployment at minimum url should be accessible: +Unit tests run without external Kubernetes setup. The envtest suite starts two in-process Kubernetes API servers and the real engine controllers. `make test-e2e` obtains API-server binaries through `setup-envtest`. + +Run related tests together when iterating: ```bash - curl https://kube-bind.genericcontrolplane.io - - - - - - - Kube Bind - - - - -
- - -% +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@release-0.21 use 1.34.1 -p path)" \ + go test ./test/e2e -run 'TestSlimCore(HappyCase|NamespacedBinding)$' \ + -count=1 -timeout=600s ``` +The suite covers schema policies, OpenAPI and kcp-like discovery, related resources, conflicts, cleanup, and stop-on-disengage. `TestBackendFullLoop` adds gateway issuance, bundle pickup, provider-fenced credentials, heartbeat, and revocation. Envtest is not a real provider operator or a full kcp deployment. + +The repository also has `make test-e2e-kind` for a containerized run with Docker, kind, Helm, and kubectl. The Tilt helper still refers to the old chart directory names, use the step-by-step quickstart instead of relying on `make tilt` for this preview. + +### Demo scripts -# Local dev environment testing +`make demo` runs `hack/demo.sh`, which creates or reuses `kbind-provider` and `kbind-consumer` kind clusters and writes administrator kubeconfigs under `/tmp`. It prints a command for running the konnector on your workstation. -If you changed helm charts and neet to test them in local development environment you can do the following: + +`hack/e2e.sh` builds and loads an image, installs the konnector chart, and deletes its named clusters on exit unless `KEEP=1`. Inspect it before use. Its `NAMESPACE` override does not rewrite the fixed `kbind` Secret reference in `config/samples/binding.yaml`. For explicit cluster selection and manual cleanup, use the [kind walkthrough](dev-environment/kind.md). + +## API changes + +Edit types in `sdk/apis/{core,catalog,iam}/v1alpha1`, then regenerate the deep-copy code, CRDs, and packaged manifests: ```bash - ./bin/kubectl-bind dev create --chart-path ./deploy/charts/backend -``` \ No newline at end of file +make helm-sync-crds +``` + +This includes the core CRDs embedded by `pkg/konnectorinstall`, service CRDs in `pkg/servicecrds`, and both charts' copies. Run `make generate-docs` to refresh local API and CLI references. + +Release tags publish images and OCI Helm charts with explicit versions. Final tags also trigger CLI release artifacts, prerelease tags do not. See the [release procedure](https://github.com/kbind-dev/kbind/blob/v2-next/docs/RELEASING.md). diff --git a/docs/content/high-level.png b/docs/content/images/high-level.png similarity index 100% rename from docs/content/high-level.png rename to docs/content/images/high-level.png diff --git a/docs/content/images/overview.png b/docs/content/images/overview.png new file mode 100644 index 000000000..0fb82e207 Binary files /dev/null and b/docs/content/images/overview.png differ diff --git a/docs/content/index.md b/docs/content/index.md index 45f134481..77c5c1dc9 100644 --- a/docs/content/index.md +++ b/docs/content/index.md @@ -2,40 +2,69 @@ ## Overview -kbind (formerly known as kube-bind) is a project that aims to provide better support for service providers and consumers that reside in distinct Kubernetes clusters. -We are actively working towards a stable release, and welcome feedback from the community. +kbind (formerly known as kube-bind) is a project that aims to provide better support for service providers and consumers that reside in distinct Kubernetes clusters. We are actively working towards a stable release, and welcome feedback from the community. -![High-level architecture diagram](high-level.png) +This documentation covers **v2**. The [0.x documentation](https://docs.kbind.dev/latest/) remains the default. See [Moving from 0.x](usage/migration.md) before upgrading an existing installation. -- A service provider defines its API contract in terms of CRDs and associated permission claims/limitations, and exports it for use from other clusters. -- Service consumers identify the services they want to consume using CLI or Web UI. +![High-level architecture diagram](images/high-level.png) + +The diagram illustrates provider/consumer separation. In v2, authentication through an identity provider is optional, and namespace isolation must be arranged by the deployment rather than automatic namespace remapping. + +- A service provider defines its API contract in terms of CRDs and credential RBAC, and labels the CRDs for export. +- Service consumers identify the services they want to consume using the optional catalog, CLI or Web UI, or apply core bindings directly through GitOps. - The service CRDs get installed in the service consumer clusters, with objects of the defined kinds written and read by the service consumers. - The service provider indirectly reads and writes those objects as the interface to the service that it provides. - The service provider does not inject controllers/operators into the service consumer's cluster. - A single vendor-neutral, OpenSource agent - `konnector` per consumer cluster connects it with the requested services. +The v2 core consumes a kubeconfig Secret, a `Connection`, and `ClusterBinding` or namespaced `Binding` objects. The backend is optional, and the shipped syncer preserves resource scope, namespace, and name. + +## v2 Architecture + +```mermaid +flowchart LR + subgraph Consumer + B["Secret + Connection + bindings"] + K[Konnector] + C[Custom resources] + B --> K + C --> K + end + subgraph Provider + P[Custom resources] + O[Service operator] + G["Optional backend: catalog, auth, issuer, reaper"] + P <--> O + end + K -- "spec up" --> P + P -- "status down" --> K + K --> C + G -. "one-apply bundle" .-> B +``` + +The optional backend produces the bundle, synchronization runs directly between the consumer's konnector and the provider API server, not through the gateway. See [Architecture Overview](developers/architecture.md) for the controller layout. + ## Getting Started -- **[Quickstart](./setup/quickstart.md)** - Get up and running with kbind quickly -- **[Setup Guide](./setup/index.md)** - Complete installation and deployment options -- **[Usage Guide](./usage/index.md)** - Learn the core concepts and APIs +- **[Quickstart](setup/quickstart.md)** - Get up and running with kbind quickly +- **[Setup Guide](setup/index.md)** - Complete installation and deployment options +- **[Usage Guide](usage/index.md)** - Learn the core concepts and APIs ## Contributing -We ❤️ our contributors! If you're interested in helping us out, please head over to our [Contributing](./contributing/index.md) -guide. +We ❤️ our contributors! If you're interested in helping us out, please head over to our [Contributing](contributing/index.md) guide. ## Getting in touch There are several ways to communicate with us: -- The [`#kube-bind` channel](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io). +- The [`#kbind-dev` channel](https://kubernetes.slack.com/archives/C046PRXNJ4W) in the [Kubernetes Slack workspace](https://slack.k8s.io). - Our mailing lists: - [kube-bind-dev](https://groups.google.com/g/kube-bind-dev) for development discussions. -- Our bi-weekly community meetings — every second Thursday at 11am EST (5pm CET). +- Our bi-weekly community meetings, every second Thursday at 11am EST (5pm CET). - By joining the [kube-bind-dev mailing list](https://groups.google.com/g/kube-bind-dev), you should receive an invite. - See our [community meeting notes document](https://docs.google.com/document/d/1qztpKOmdZu5iWq_4N9n3AZpcAPuPhBiGNbje5GPg0iM) for upcoming and past agendas. -See the [community page](./community/index.md) for more details. +See the [community page](community/index.md) for more details. diff --git a/docs/content/reference/index.md b/docs/content/reference/index.md index f531b8580..3368150f0 100644 --- a/docs/content/reference/index.md +++ b/docs/content/reference/index.md @@ -1,3 +1,14 @@ # Reference -This chapter provides automatically generated references for the kube-bind `kubectl` plugin and APIs included in kube-bind. +These references describe the code in the v2 checkout used to build this site. Kubernetes API pages are generated from `sdk/apis`, the CLI page is generated from `cli/cmd`. No generator fetches API definitions from the 0.x `main` branch. + +| Surface | Reference | +| --- | --- | +| Consumer connection, binding, and schema policy | [core.kbind.io](crd/index.md#corekbindiov1alpha1) | +| Provider catalog offerings and collections | [catalog.kbind.io](crd/index.md#catalogkbindiov1alpha1) | +| Provider credential issuance record | [iam.kbind.io](crd/index.md#iamkbindiov1alpha1) | +| CLI command syntax and flags | [CLI](cli/index.md) | +| Optional gateway endpoints and backend options | [Backend](../developers/backend/http/index.md) | +| Consumer agent options | [Konnector](../developers/konnector/controllers/konnector.md) | + +The [API concepts guide](../usage/api-concepts.md) explains which objects to create and how they fit together. Generated type descriptions are not a promise that every syntactically valid combination is supported, consult the [synchronization limits](../usage/synchronization.md). diff --git a/docs/content/setup/helm.md b/docs/content/setup/helm.md index 287a240c4..525b39b2f 100644 --- a/docs/content/setup/helm.md +++ b/docs/content/setup/helm.md @@ -1,312 +1,56 @@ --- description: > - Install kube-bind on an existing Kubernetes cluster via the official Helm chart. + Install kbind on an existing Kubernetes cluster via the Helm charts. --- # Installation with Helm -kube-bind can be installed on an existing Kubernetes cluster using the official Helm OCI charts. -The backend chart is available as an OCI image for service providers, with konnector charts coming soon for service consumers. +The konnector chart runs in the consumer cluster. The optional backend chart provides a catalog, authentication, and credentials on the provider. -## Quick Start +## Prerequisites -## Prerequisites & Setup Guides +- A Kubernetes consumer cluster and Helm 3. +- A v2 source checkout and an image built from that checkout. +- A provider API reachable from the consumer cluster. -The following prerequisites are required. Click the links below for detailed setup instructions: +This preview uses the local charts. Do not use a 0.x chart or assume a `latest` image contains v2. -- **[Kubernetes cluster](#kubernetes-cluster)** - A running Kubernetes cluster -- **[Helm 3.x](#helm)** - Package manager for Kubernetes -- **[cert-manager](#cert-manager-setup)** - For TLS certificate management -- **[OIDC provider](#oidc-provider-setup)** - For authentication (Dex, Keycloak, etc.) -- **[Gateway API](#gateway-api-setup)** - (Optional) For advanced ingress management +## Install the Konnector -### Install kube-bind Backend - -1. **Get the latest chart version:** - - Visit the [releases page](https://github.com/kube-bind/kube-bind/releases) or check available versions: - - ```bash - # For latest tag version (recommended for production): - VERSION=$(curl -s https://api.github.com/repos/kube-bind/kube-bind/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/v//') - - # Or use a specific development version: - # VERSION=0.0.0-9fd9281e661c0d9a426a941111d3d8b08019ebc1 - ``` - -2. **Configure your values:** - - Edit `deploy/charts/backend/examples/values-local-development.yaml` and replace the placeholder values: - - `### REPLACE ME ###` with your actual OIDC credentials - - Update hostnames to match your setup - -3. **Install the backend using OCI chart:** - -!!! note - To install production configuration, you will need to have an OIDC provider. - For more information, just check out the [quickstart guide](./quickstart.md). - -```bash - # Using latest release version -helm upgrade \ - --install \ - --namespace kube-bind \ - --create-namespace \ - --set certManager.enabled=true \ - --set certManager.clusterIssuer=letsencrypt-prod \ - --set backend.oidc.issuerUrl=https://auth.example.com \ - --set backend.oidc.clientId=platform-mesh \ - --set backend.oidc.clientSecret= \ - --set backend.oidc.callbackUrl=https://kube-bind.example.com/api/callback \ - --set gatewayApi.enabled=true \ - --set gatewayApi.gateway.className=nginx \ - --set gatewayApi.gateway.httpsPort=443 \ - --set 'gatewayApi.gateway.tls.certificateRefs[0].name=backend-tls-cert' \ - --set 'gatewayApi.route.hostnames[0]=kube-bind.example.com' \ - --set gatewayApi.route.path=/ \ - --set gatewayApi.route.pathType=PathPrefix \ - --set image.tag=v${VERSION} \ - kube-bind oci://ghcr.io/kbind-dev/charts/backend --version ${VERSION} -``` - -4. **Seed with example resources (optional):** - -```bash -kubectl apply -f deploy/examples/crd-foo.yaml -kubectl apply -f deploy/examples/crd-mangodb.yaml -kubectl apply -f deploy/examples/template-foo.yaml -kubectl apply -f deploy/examples/template-mangodb.yaml -kubectl apply -f deploy/examples/collection.yaml -``` - -That's it! Your kube-bind backend is now ready to use. - ---- - -### Helm - -Install Helm 3.x from [https://helm.sh/docs/intro/install/](https://helm.sh/docs/intro/install/) - -**Note**: Helm 3.8+ is required for OCI chart support. Enable experimental OCI support if needed: - -```bash -export HELM_EXPERIMENTAL_OCI=1 -``` - -### Gateway API Setup - -Install gateway API CRDs and controller for advanced ingress management. Kube-bind supports Gateway API for routing traffic to the backend service. - -Follow the official Gateway API installation instructions: -https://gateway-api.sigs.k8s.io/guides/ - -```bash -kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.4.0/standard-install.yaml -``` - -We used NGINX Gateway controller for testing. Install it as follows: - -```bash -helm upgrade --install ngf oci://ghcr.io/nginx/charts/nginx-gateway-fabric --create-namespace -n nginx-gateway -``` - -### cert-manager Setup - -Install cert-manager for automatic TLS certificate management: - -```bash -helm repo add jetstack https://charts.jetstack.io -helm repo update - -helm upgrade \ - --install \ - --namespace cert-manager \ - --create-namespace \ - --version v1.18.2 \ - --set crds.enabled=true \ - --atomic \ - cert-manager jetstack/cert-manager -``` - -#### Configure Let's Encrypt (Optional) - -Create a ClusterIssuer for automatic certificate provisioning: +From the repository root, build and push an image to a registry you control: ```bash -kubectl apply -f - < /tmp/dex-values.yaml <` format for each commit to main - -### Finding Available Versions - -**Release versions:** - -```bash -# List all releases -curl -s https://api.github.com/repos/kube-bind/kube-bind/releases | grep '"tag_name"' | head -5 - -# Get latest release version -VERSION=$(curl -s https://api.github.com/repos/kube-bind/kube-bind/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/v//') -echo "Latest version: ${VERSION}" -``` +Repeat `helm upgrade --install` with the new image tag to upgrade. Before uninstalling, [unbind resources](../usage/synchronization.md#unbinding-and-deletion) while the konnector and provider credentials still work. With `installCRDs: true`, Helm uninstall also removes the core CRDs. See [CRD lifecycle](../developers/konnector/index.md#manage-crds-outside-helm) before changing who manages them. diff --git a/docs/content/setup/kcp-setup.md b/docs/content/setup/kcp-setup.md deleted file mode 100644 index 394839f62..000000000 --- a/docs/content/setup/kcp-setup.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -description: > - Set up kube-bind with kcp provider for advanced multi-cluster scenarios. ---- - -# kcp Setup - -This guide shows how to set up kube-bind with the kcp provider where workspaces are treated as separate clusters. - -## Prerequisites - -- [kcp](https://github.com/kcp-dev/kcp) instance running and accessible -- kube-bind binaries built (`make build`) - -## Setup Steps - -1. Start kcp - -```bash -make run-kcp -``` - -## Backend - -2. Bootstrap backend workspace: -```bash -cp .kcp/admin.kubeconfig .kcp/provider.kubeconfig -export KUBECONFIG=.kcp/provider.kubeconfig -kubectl ws create provider --enter - -kubectl apply -f deploy/crd -``` - -Apply example manifests: - -```bash -kubectl apply -f deploy/examples/crd-cowboys.yaml -kubectl apply -f deploy/examples/crd-sheriffs.yaml -kubectl apply -f deploy/examples/collection.yaml -kubectl apply -f deploy/examples/template-cowboys.yaml -kubectl apply -f deploy/examples/template-sheriffs.yaml -``` - - -3. Run the backend: -``` -go run ./cmd/backend \ - --oidc-issuer-url=http://127.0.0.1:8080/oidc \ - --oidc-callback-url=http://127.0.0.1:8080/api/callback \ - --oidc-type=embedded \ - --pretty-name="BigCorp.com" \ - --namespace-prefix="kube-bind-" \ - --consumer-scope=cluster \ - --isolation=None -``` - -This process will keep running, so open a new terminal. - -## Consumer - -4. Copy the kubeconfig to the provider and create provider workspace: -```bash -export KUBECONFIG=.kcp/admin.kubeconfig -kubectl ws create consumer --enter -``` - -5. Login into the backend and bind: - -```bash -./bin/kubectl-bind login http://127.0.0.1:8080 - -./bin/kubectl-bind --cluster-identity-namespace default --dry-run -o yaml > apiserviceexport.yaml - -# Extract secret for binding process. Note that secret name is not the same as output from command above. Check secret -# name by running `kubectl get secret -n kube-bind` -kubectl get secrets -n kube-bind -o jsonpath='{.items[0].data.kubeconfig}' | base64 -d > remote.kubeconfig - -namespace=$(yq '.contexts[0].context.namespace' remote.kubeconfig) - -./bin/kubectl-bind apiservice --remote-kubeconfig remote.kubeconfig -f apiserviceexport.yaml --skip-konnector --remote-namespace $namespace - -# run konnector in different terminal -export KUBECONFIG=.kcp/admin.kubeconfig -go run ./cmd/konnector/ --lease-namespace default -``` - -# Create an instance - -```bash -kubectl apply -f deploy/examples/cr-cowboy.yaml -kubectl apply -f deploy/examples/cr-sheriff.yaml -``` diff --git a/docs/content/setup/kind-setup.md b/docs/content/setup/kind-setup.md deleted file mode 100644 index cc39f09bf..000000000 --- a/docs/content/setup/kind-setup.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -description: > - Setup kind cluster for local kube-bind development and testing. ---- - -# kind Setup - -This guide walks you through setting up a local Kubernetes cluster using [kind](https://kind.sigs.k8s.io/) for kube-bind development and testing. - -## Prerequisites - -- [kind](https://kind.sigs.k8s.io/) installed -- [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed - - -## Setup Steps - -We will need 2 kind clusters (or more) to simulate service provider and consumer clusters. -We will use experimental support for dedicated networking between kind clusters to allow direct communication. - -```bash -# Create provider cluster -export KIND_EXPERIMENTAL_DOCKER_NETWORK=kube-bind -kind create cluster --name provider -kubectl cluster-info --context kind-provider - -helm upgrade \ - --install \ - --namespace kube-bind \ - --create-namespace \ - kube-bind oci://ghcr.io/kbind-dev/charts/backend --version 0.0.0-a50df39d7e4c71f7808f4209ec23f294c5ac8f86 - -helm upgrade \ - --install \ - --namespace kube-bind \ - --create-namespace \ - --set image.repository=ghcr.io/mjudeikis/kube-bind/backend \ - --set image.tag=c27e82a \ - --set examples.enabled=true \ - kube-bind ./deploy/charts/backend \ No newline at end of file diff --git a/docs/content/setup/kubectl-plugin.md b/docs/content/setup/kubectl-plugin.md index 8a04cf66f..a3af9935f 100644 --- a/docs/content/setup/kubectl-plugin.md +++ b/docs/content/setup/kubectl-plugin.md @@ -1,70 +1,66 @@ --- description: > - How to install and use the kubectl bind plugin. + Install and use the kubectl bind plugin. --- # kubectl bind Plugin -The `kubectl bind` plugin is the primary command-line interface for interacting with kube-bind services. It provides both interactive web UI access and command-line binding capabilities for connecting to remote service providers. +The `kubectl bind` plugin is the command-line interface for interacting with kbind services. It connects to remote service providers, browses their catalogs, and binds APIs into your cluster. ## Installation === "Krew" - Install the plugin using [krew](https://krew.sigs.k8s.io/): - - ```bash - kubectl krew index add bind https://github.com/kube-bind/krew-index.git - kubectl krew install bind/bind - ``` + [Krew](https://krew.sigs.k8s.io/) installs released versions of the plugin, not this unreleased v2 preview. Use **Manual Build** for this preview rather than installing a 0.x release. === "Manual Build" - Build and install from source: + Build and install from source using the Go version declared in `go.mod`: ```bash - git clone https://github.com/kube-bind/kube-bind.git - cd kube-bind - make build - cp bin/kubectl-bind /usr/local/bin/ + git clone --branch v2-next https://github.com/kbind-dev/kbind.git + cd kbind + make bind + mkdir -p "$HOME/.local/bin" + install -m 0755 bin/bind "$HOME/.local/bin/kubectl-bind" + export PATH="$HOME/.local/bin:$PATH" + kubectl bind --help ``` + Keep `$HOME/.local/bin` on your shell's `PATH`. Installing the build output as `kubectl-bind` makes it available as `kubectl bind`. + === "Binary Download" - Download pre-built binaries from the [releases page](https://github.com/kube-bind/kube-bind/releases): + Published CLI archives are available on the [releases page](https://github.com/kbind-dev/kbind/releases). Choose a v2 release explicitly, not the latest 0.x release. For this unreleased branch, use **Manual Build**. + + After extracting an archive for your operating system and architecture, install its `kubectl-bind` binary: ```bash - # Download and install for Linux/macOS - OS=$(uname | tr '[:upper:]' '[:lower:]') - ARCH=$(uname -m | sed 's/x86_64/amd64/' | sed 's/aarch64/arm64/') - VERSION=$(curl -s https://api.github.com/repos/kube-bind/kube-bind/releases/latest | grep '"tag_name"' | cut -d'"' -f4) - curl -LO https://github.com/kube-bind/kube-bind/releases/download/${VERSION}/kubectl-bind_${VERSION#v}_${OS}_${ARCH}.tar.gz - tar -xzf kubectl-bind_${VERSION#v}_${OS}_${ARCH}.tar.gz - sudo mv bin/kubectl-bind /usr/local/bin/kubectl-bind + mkdir -p "$HOME/.local/bin" + install -m 0755 kubectl-bind "$HOME/.local/bin/kubectl-bind" + export PATH="$HOME/.local/bin:$PATH" ``` ## Basic Usage -The main plugin command is `kubectl bind` which opens the kube-bind web UI in your browser for interactive service binding. +With the [v2 konnector installed](helm.md) in your consumer cluster: ```bash -# Login to a kube-bind server first kubectl bind login https://my-kube-bind-server.example.com - -# Open kube-bind UI for current server context -kubectl bind +kubectl bind catalog +kubectl bind export widgets --kubeconfig=./consumer.kubeconfig --install-konnector=false +kubectl --kubeconfig=./consumer.kubeconfig get connections,clusterbindings ``` -The plugin provides several subcommands including `login`, `templates`, `collections`, and `apiservice` for different binding workflows. +Replace `widgets` with an Export from the catalog. To use the Web UI, open the provider URL in your browser. In v2, binding uses `export ` rather than bare `kubectl bind`. -For complete command reference and examples, see the [CLI Reference](../reference/index.md). +See the [CLI reference](../reference/cli/index.md) for all commands and the [catalog guide](../usage/catalog.md) for sessions, credentials, and bundle handling. ## Quick Start -1. Install the plugin using Krew or build from source -2. Login to your kube-bind server: `kubectl bind login ` -3. Open the web UI: `kubectl bind` -4. Browse and bind to available services through the interface - -For detailed setup instructions, see the [Quickstart Guide](./quickstart.md). +1. Build and install the v2 plugin using **Manual Build**. +2. Install the consumer konnector using the [Helm guide](helm.md). +3. Log in to your provider with `kubectl bind login `. +4. Browse with `kubectl bind catalog` and bind an Export with `kubectl bind export `. +For a local example, follow the [Quickstart Guide](quickstart.md). diff --git a/docs/content/setup/quickstart.md b/docs/content/setup/quickstart.md index 9ffe4553b..8cdde0eea 100644 --- a/docs/content/setup/quickstart.md +++ b/docs/content/setup/quickstart.md @@ -1,6 +1,6 @@ --- description: > - Get started with kube bind. + Get started with kbind. --- # Quickstart @@ -8,110 +8,94 @@ description: > ## Prerequisites - [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) -- [kube-bind CLI](kubectl-plugin.md) installed +- For the backend walkthrough: [kubectl bind plugin](kubectl-plugin.md) installed -## Start with kube-bind +To try synchronization without a backend or login, follow the +[core-only GitOps example](../usage/gitops.md#try-the-core-without-a-backend). -### Quick Development Setup - -**Note:** This setup requires Docker as it uses advanced network configuration to minimize external DNS dependencies and enable inter-cluster connectivity. - -For a quick development environment with local Kind clusters, use the `kubectl bind dev` command: - -```bash -kubectl bind dev create -``` - -Example output: -```bash -kube-bind Development Environment Setup - -EXPERIMENTAL: kube-bind dev command is in preview -Requirements: Docker must be installed and running - -Host entry exists for kube-bind.dev.local -✓ Host entry exists for kube-bind.dev.local -Kind cluster kind-provider already exists, skipping creation -Wrote kubeconfig kind-provider.kubeconfig -Helm chart installed successfully -Creating kind cluster kind-consumer with network kube-bind-dev -Kind cluster kind-consumer created -Wrote kubeconfig kind-consumer.kubeconfig -kube-bind dev environment is ready! - -Configuration: -• Provider cluster kubeconfig: kind-provider.kubeconfig -• Consumer cluster kubeconfig: kind-consumer.kubeconfig -• kube-bind server URL: http://kube-bind.dev.local:8080 - -Next Steps: - -1. Login to authenticate to the provider cluster: -kubectl bind login http://kube-bind.dev.local:8080 +## Start with kbind -2. Bind an API service from provider to consumer: -KUBECONFIG=kind-consumer.kubeconfig kubectl bind --konnector-host-alias 192.168.155.2:kube-bind.dev.local -``` - - -This command will: +### Quick Development Setup -- Create two Kind clusters: `kind-provider` (API provider) and `kind-consumer` (API consumer) -- Deploy the kube-bind backend to the provider cluster -- Generate kubeconfig files for both clusters -- Set up local DNS entries for `kube-bind.dev.local` -- Start the kube-bind server at `http://kube-bind.dev.local:8080` +For a local development environment, follow the [kind setup guide](../developers/dev-environment/kind.md). It creates a provider cluster and a consumer cluster, starts the backend and konnector, and adds the Widget API to the catalog. Docker, kind, and Go are required. After the development environment is ready, you can: 1. **Authenticate to the provider cluster:** - ```bash - kubectl bind login http://kube-bind.dev.local:8080 - ``` - This will open a browser for authentication and save the configuration. -2. **Bind API services from provider to consumer:** + ```bash + kubectl bind login http://localhost:8080 + ``` - Bind using CLI (step 2) in the output. + This opens a browser for authentication and saves the session. - ```bash - KUBECONFIG=kind-consumer.kubeconfig kubectl bind --konnector-host-alias :kube-bind.dev.local - ``` - This opens the kube-bind web UI where you can select and bind API services. +2. **Bind an API service from provider to consumer:** -3. **Verify bound resources:** - ```bash - KUBECONFIG=kind-consumer.kubeconfig kubectl get crd - KUBECONFIG=kind-consumer.kubeconfig kubectl get apiservicebindings -n kube-bind - ``` + ```bash + kubectl bind catalog + kubectl bind export widgets --kubeconfig=consumer.kubeconfig \ + --install-konnector=false + ``` + + The development setup already runs the konnector, so skip installing another copy. You can also browse the catalog at `http://localhost:8080`. -4. **Create example resource** - ```bash - kubectl bind dev example | KUBECONFIG=kind-consumer.kubeconfig kubectl create -f - - ``` +3. **Verify bound resources:** -5. **Check resource synced to provider** - ```bash - KUBECONFIG=kind-provider.kubeconfig kubectl get mangodbs.mangodb.com -A - ``` + ```bash + export KUBECONFIG="$PWD/consumer.kubeconfig" + kubectl get connections,clusterbindings + kubectl wait --for=condition=Established crd/widgets.example.org --timeout=120s + ``` + +4. **Create an example resource:** + + ```bash + kubectl apply -f - <<'EOF' + apiVersion: example.org/v1 + kind: Widget + metadata: + name: my-widget + namespace: default + spec: + size: large + EOF + ``` + +5. **Check the resource synced to the provider:** + + ```bash + kubectl --kubeconfig=provider.kubeconfig -n default \ + wait --for=create widget/my-widget --timeout=120s + kubectl --kubeconfig=provider.kubeconfig -n default get widgets + ``` + +6. **Verify status returns to the consumer:** + + The sample has no Widget service controller. Simulate its status update on the + provider, then wait for the consumer to receive it: + + ```bash + kubectl --kubeconfig=provider.kubeconfig -n default \ + patch widget my-widget --subresource=status --type=merge \ + -p '{"status":{"phase":"Running"}}' + kubectl --kubeconfig=consumer.kubeconfig -n default \ + wait --for=jsonpath='{.status.phase}'=Running widget/my-widget --timeout=120s + ``` + +For other service APIs, see the [integration examples](../usage/integrations/index.md). When finished, follow the development guide's [cleanup](../developers/dev-environment/kind.md#cleanup). ### Production Deployment -For production deployments, you can deploy a kube-bind backend using helm: - -- **[Using Helm Chart](helm.md)** - Recommended for production deployments +For an in-cluster deployment, use the [Helm charts](helm.md) to install the consumer konnector and optional provider backend. -Once you have a kube-bind backend running (either development or production), you can connect to it: +Once you have a backend running, either locally or in a cluster, you can connect to it: -### Connect to kube-bind Server +### Connect to kbind Server ```bash kubectl bind login https://my-kube-bind-server.example.com -``` - -### Open kube-bind Web UI and bind services - -```bash -kubectl bind ``` +### Open kbind Web UI and bind services + +Open your provider's URL in a browser to browse the catalog and bind services. For the same workflow from the CLI, use `kubectl bind catalog` and `kubectl bind export `. diff --git a/docs/content/usage/.pages b/docs/content/usage/.pages index 38cc5f7da..90a116ac8 100644 --- a/docs/content/usage/.pages +++ b/docs/content/usage/.pages @@ -2,4 +2,8 @@ nav: - index.md - api-concepts.md - synchronization.md + - catalog.md + - gitops.md - integrations + - migration.md + - troubleshooting.md diff --git a/docs/content/usage/api-concepts.md b/docs/content/usage/api-concepts.md index bd3c5b01b..ca636a500 100644 --- a/docs/content/usage/api-concepts.md +++ b/docs/content/usage/api-concepts.md @@ -1,516 +1,191 @@ --- title: API Concepts -description: | - Deep dive into kube-bind's core API types, their relationships, and how they work together to enable cross-cluster service binding. +description: > + Core API types, their relationships, and cross-cluster service binding. weight: 210 --- -# kube-bind API Concepts +# kbind API Concepts -This guide provides a comprehensive overview of kube-bind's core API types and how they work together to enable secure, cross-cluster service binding. +This guide provides an overview of kbind's core API types, their relationships, and how they work together to enable cross-cluster service binding. ## Overview -kube-bind uses several specialized Kubernetes custom resources to orchestrate the export and import of APIs between clusters. Understanding these types and their relationships is essential for effective use of kube-bind. +The v2 slim core is three consumer-side resources in **`core.kbind.io/v1alpha1`**. It connects Kubernetes APIs using declarative objects, it is not an API request proxy. -## APIServiceExportTemplate +| Kind | Scope | Responsibility | +| --- | --- | --- | +| `Connection` | Cluster | Reference provider credentials, pin cluster identity, discover exported APIs, and choose schema policy. | +| `ClusterBinding` | Cluster | Activate synchronization for listed APIs across the consumer. | +| `Binding` | Namespace | Activate synchronization for listed namespaced APIs in this namespace. | -**Purpose**: Defines a reusable template for exporting a group of related APIs and their permission requirements. +The konnector reconciles them in the consumer. A plain Kubernetes provider needs its own API/controller, credentials and RBAC, and exported CRD labels, not these core CRDs. The optional [backend](../developers/backend/index.md) and [catalog](catalog.md) add onboarding and discovery workflows without changing this core contract. -**Used by**: Service providers -**Scope**: Cluster-scoped -**Lifecycle**: Long-lived template definition +See the [core API reference](../reference/crd/index.md#corekbindiov1alpha1) for field definitions. These pages describe the current, unreleased implementation, policy limitations below matter even where the API types describe a broader intent. -### Key Features +## Connection -- **Resource Grouping**: Combines multiple related CRDs into a single bindable service -- **Permission Claims**: Specifies additional resources the service needs access to -- **Namespace Management**: Defines namespaces that should be created on the provider & consumer side -- **Reusability**: Can be bound by multiple consumers +**Purpose**: Establish the provider link and choose schema policy. **Used by**: Service consumers. **Scope**: Cluster-scoped. ### Structure ```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExportTemplate +apiVersion: core.kbind.io/v1alpha1 +kind: Connection metadata: - name: my-service-template + name: provider spec: - scope: Cluster # or Namespace - description: "A comprehensive service template" - - # Core APIs being exported - resources: - - group: example.com - resource: widgets - versions: ["v1", "v1alpha1"] - - group: example.com - resource: gadgets - versions: ["v1"] - - # Additional resources the service needs access to - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - component: my-service - references: - - resource: widgets - group: example.com - jsonPath: - name: spec.secretRef.name - namespace: spec.secretRef.namespace - - # Pre-created namespaces for this service. These will be owned by provider (service owned). - namespaces: - - name: my-service-system - description: "System namespace for service components" -``` - -### Template vs Instance - -- **Template**: The definition (APIServiceExportTemplate) - shared and reusable -- **Instance**: The actual export (APIServiceExport) - created per binding - -## APIServiceExport - -**Purpose**: Represents an active, instantiated export of a specific set of CRD's and permission claims to consumer clusters. - -**Used by**: Automatically created by konnector agents -**Scope**: Namespaced -**Lifecycle**: Created when consumers bind to templates - -### Key Features - -- **Instance Management**: One APIServiceExport per contract per binding -- **Status Tracking**: Reports synchronization status and conditions -- **Automatic Lifecycle**: Created/updated/deleted by the konnector agent - -### Structure - -```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExport + kubeconfigSecretRef: + namespace: kbind + name: provider-kubeconfig + key: kubeconfig + schema: + source: CRD + pullPolicy: Bound + updatePolicy: Always +--- +apiVersion: core.kbind.io/v1alpha1 +kind: Binding metadata: - name: widgets-export-consumer123 - namespace: kube-bind-provider-ns + name: widgets + namespace: team-a spec: - # The CRD being exported - resources: - - group: example.com - resource: widgets - versions: ["v1"] - - # Permission claims for this specific export - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - component: widget-service - consumer: consumer123 - - # How isolation is done at the provider side - isolation: Prefixed - # informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - # - # Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - # This is more efficient than watching each namespace individually. - # Namespaced: The konnector has permission to watch only single namespaces. - # This is more resource intensive. And it means cluster-scoped resources cannot be exported. - informerScope: Cluster - -status: - conditions: - - lastTransitionTime: "2025-11-14T12:02:29Z" - status: "True" - type: Connected - - lastTransitionTime: "2025-11-14T12:02:30Z" - status: "True" - type: ConsumerInSync - - lastTransitionTime: "2025-11-14T12:02:25Z" - status: "True" - type: ProviderInSync + connectionRef: + name: provider + apis: + - name: widgets.example.org + conflictPolicy: Fail ``` -### Relationship to Templates +Create `team-a` separately. The Connection reference has no namespace because Connections are cluster-scoped. Each `apis[].name` is `.`, not a Kind, a version, or a URL. -``` -APIServiceExportTemplate (1) - ↓ (consumer binding creates) -APIServiceExportRequest (1) - ↓ (provider processes) -APIServiceExport + BoundSchema (1) - ↕ (bidirectional sync) -APIServiceBinding (consumer side) -``` +The Connection can exist before its Secret, and the Binding before its Connection, controllers retry when dependencies appear. The CRD definitions themselves must already exist. -## APIServiceExportRequest +### Credentials and cluster identity -**Purpose**: Represents a consumer's request to bind to a specific service template. +`spec.kubeconfigSecretRef` is the only credential reference in the core. It contains a required Secret namespace and name and an optional key defaulting to `kubeconfig`. The Secret may be in any namespace the konnector is authorized to read, it is not implicitly resolved in the Binding namespace. -**Used by**: Service consumers (via CLI/UI) -**Scope**: Namespaced (on consumer side) -**Lifecycle**: Created during binding process, short lived until APIServiceExport is established. +The **reference is immutable**, but the Secret data can be updated. Keep credentials self-contained and usable in the konnector's environment. A kubeconfig that relies on your workstation's files, exec plugin, or interactive login is not automatically usable inside the stock container. -### Key Features +On first successful connection, the engine records: -- **Binding Initiation**: Starts the binding process between consumer and provider -- **Authentication Context**: Contains OAuth2 flow details and credentials -- **Template Reference**: Points to the specific template being requested -- **Status Tracking**: Reports binding progress and any errors - -### Structure +- `status.remoteClusterUID`: provider identity. +- `status.localClusterUID`: consumer identity. -```yaml -apiVersion: kube-bind.io/v1alpha1 -kind: APIServiceExportRequest -metadata: - name: my-widget-service-binding - namespace: default -spec: - # Consumer-specific configuration. Matches template and export specification. - resources: - - group: example.com - resource: widgets - versions: ["v1"] - - permissionClaims: - - group: core - resource: configmaps - # Selector for claimed resources. NamedResources, LabelSelector and References - OR'ed together. - selector: - # namedResources: - # - name: - # namespace: - # labelSelector: - # Standard label selector syntax - # references: - # - group: - # resource: - # versions: [] - # jsonPath: - # name: - # namespace: - - -status: - conditions: - - lastTransitionTime: "2025-11-14T12:02:25Z" - status: "True" - type: Ready - - lastTransitionTime: "2025-11-14T12:02:25Z" - status: "True" - type: ExportsReady - phase: Succeeded -``` +It identifies a cluster using the `core.kcp.io/v1alpha1` LogicalCluster named `cluster` when available, otherwise the `kube-system` Namespace UID. A forbidden identity read is reported rather than silently skipped. The API makes each recorded UID immutable once set. -## APIServiceBinding +Subsequent reconciliations compare the provider identity with the pinned UID. Replacing Secret data with a kubeconfig for a different cluster produces `ClusterIdentityChanged`, it must not silently move existing objects to a new provider. Use a new Connection and a deliberate unbind/rebind workflow for a new provider identity. -**Purpose**: Represents the consumer-side binding to a provider service, containing the applied CRDs and managing the resource synchronization. +**Credential rotation limitation:** the Connection rereads Secret data, but an already-engaged instance-sync client is not rebuilt merely because a valid Secret changed while the Connection stayed Ready. After rotating credentials for the same provider, restart the konnector (or its deployment) and verify instance sync before revoking the old credential. The core does not renew tokens itself. -**Used by**: Automatically created by consumer konnector agents -**Scope**: Namespaced (on consumer side) -**Lifecycle**: Created when APIServiceExportRequest is processed, long-lived +The engine adds `core.kbind.io/cleanup` to the Connection and its referenced Secret. The Secret finalizer keeps credentials available during teardown, the engine does not delete the Secret for you. -### Key Features +### Provider export boundary -- **Resource Sync**: Manages bidirectional resource synchronization with provider -- **Connection State**: Tracks connection health and authentication status +With the CRD source, label an API on the provider: -### Structure - -```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceBinding -metadata: - name: sheriffs -spec: - # Secret for connecticity to the provider cluster. - kubeconfigSecretRef: - key: kubeconfig - name: kubeconfig-xbm9b - namespace: kube-bind -status: - # boundSchemas are provider side schema tracking object, used by this connection/binding. - boundSchemas: - - group: wildwest.dev - resource: sheriffs - # other generic statuses & conditions - conditions: - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: Ready - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: Connected - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: Heartbeating - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: InformersSynced - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: SchemaInSync - - lastTransitionTime: "2025-11-18T07:16:52Z" - status: "True" - type: SecretValid - # permissionClaims used by this connection/binding - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - app: sheriff - references: - - group: wildwest.dev - jsonPath: - name: spec.secretRefs.#.name - namespace: spec.secretRefs.#.namespace - resource: sheriffs - providerPrettyName: BigCorp.com +```bash +kubectl --context=provider label crd widgets.example.org \ + core.kbind.io/exported=true --overwrite ``` -## BoundSchema +Only the exact value `"true"` matches. Discovery normally refreshes every 30 seconds and appears in `Connection.status.exportedAPIs`. -**Purpose**: Contains the actual CRD definitions and schema information for resources bound from a provider. +This is an opt-in discovery filter, not an RBAC mechanism. A user with CRD read permission can still read unlabelled CRDs outside kbind. The konnector also needs independent instance permissions. -**Used by**: Created alongside APIServiceExport on provider side -**Scope**: Namespaced (on provider side) -**Lifecycle**: Mirrors APIServiceExport lifecycle +With OpenAPI, there is no exported-label check. The discovery/API boundary exposed by the provider credentials determines candidates, built-in Kubernetes groups are excluded. Not all discovery responses are filtered by object-level RBAC, so a discovered API is not proof that its instances can be read or written. -### Key Features +### Schema source and policies -- **Schema Storage**: Contains complete CRD definitions to sync to consumers -- **Version Management**: Handles multiple API versions and schema evolution -- **Validation Rules**: Includes OpenAPI schemas and validation logic -- **Resource Metadata**: Additional metadata about the exported resources +Defaults are `source: Auto`, `pullPolicy: Bound`, `updatePolicy: Always`, and `autoBind: false`. -### Structure - -```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: BoundSchema -metadata: - name: widgets-schema-consumer123 - namespace: kube-bind-provider-ns - ownerReferences: - - apiVersion: kube-bind.io/v1alpha2 - kind: APIServiceExport - name: widgets-export-consumer123 -spec: - group: wildwest.dev - informerScope: Cluster - names: - kind: Sheriff - listKind: SheriffList - plural: sheriffs - singular: sheriff - scope: Cluster - versions: - - name: v1alpha1 - schema: - # Complete OpenAPI schema definition - served: true - storage: true - subresources: - status: {} - # Complete OpenAPI schema definition - -status: - acceptedNames: - kind: Sheriff - listKind: SheriffList - plural: sheriffs - singular: sheriff - conditions: - - lastTransitionTime: "2025-11-14T12:02:34Z" - status: "True" - type: Ready - - lastTransitionTime: "2025-11-14T12:02:34Z" - message: the initial names have been accepted - reason: InitialNamesAccepted - status: "True" - type: Established - - lastTransitionTime: "2025-11-14T12:02:29Z" - message: no conflicts found - reason: NoConflicts - status: "True" - type: NamesAccepted -``` +#### Source -## APIServiceNamespace +| Source | Current behavior | +| --- | --- | +| `CRD` | List provider CRDs labelled `core.kbind.io/exported: "true"` and read selected CRD definitions. Recommended for an explicit opt-in on ordinary Kubernetes. | +| `OpenAPI` | Discover non-built-in APIs and synthesize consumer CRDs using `/openapi/v3`. Useful for CRD-less providers. No CRD label gate. | +| `Auto` | Try labelled CRD discovery first. A successful list with exports selects CRD, a successful list with no exports falls through to OpenAPI. | -**Purpose**: Manages namespace mapping and isolation between provider and consumer clusters. +**Auto is not a fallback for a failed CRD list.** The current code returns list errors, including `Forbidden`, instead of falling back. Choose `OpenAPI` explicitly when CRDs cannot be listed. Conversely, use `CRD` explicitly when an empty label selection should export nothing: Auto can otherwise discover unlabelled APIs through OpenAPI. -**Used by**: Automatically managed by konnector agents -**Scope**: Namespaced (on provider side) -**Lifecycle**: Created as needed during resource synchronization or by provider, when namespace is desired on consumer side. +Inspect `status.activeSchemaSource` rather than assuming which source Auto selected. -### Key Features +#### Which schemas are installed? -- **Namespace Isolation**: Ensures consumer resources don't conflict -- **Mapping Logic**: Handles namespace translation between clusters -- **Resource Organization**: Groups related resources per consumer -- **Automatic Management**: Created/deleted as bindings change +| `pullPolicy` | Effect | +| --- | --- | +| `Bound` | Install only APIs named by a Binding or ClusterBinding. | +| `All` | Install all discovered exported APIs, even without bindings. | +| `None` | Do not create missing consumer CRDs, an external manager supplies them. | -## Complete Binding Flow +Installing a schema does not activate instance sync. A Binding/ClusterBinding is still required unless `autoBind` supplies one. -The correct flow from template to active binding: +With `None` and the **CRD** source, the engine still reads the provider CRD and stamps existing consumer CRDs with its managed and Connection markers. With the **OpenAPI** source, existing CRDs are only read: you must supply the markers yourself for the sync controller to discover them: -### 1. Template Definition (Provider) ```yaml -APIServiceExportTemplate → defines service contract +metadata: + labels: + core.kbind.io/managed: "true" + annotations: + core.kbind.io/connection: provider ``` -### 2. Consumer Request -```yaml -APIServiceExportRequest → consumer requests binding -``` +`None` does **not** protect a manually supplied CRD against ClusterBinding cleanup. See [GitOps](gitops.md) before sharing CRD ownership. -### 3. Provider Processing -```yaml -APIServiceExport + BoundSchema → provider creates export with schema -``` +#### Schema updates and fidelity -### 4. Consumer Binding -```yaml -APIServiceBinding → consumer applies CRDs and establishes sync -``` +`updatePolicy: Always` follows provider CRD spec changes for the CRD source. `Once` prevents subsequent spec updates. Neither is a compatibility check or a storage migration strategy. -### 5. Bidirectional Sync -```yaml -Provider Resources ↔ Consumer Resources (via konnector agents) -``` +Current limitations: -### Structure +- A CRD-source pull keeps **one version**: the provider storage version, or the first served version if no storage version is found. It serves that version locally and forces conversion to `None`, removing the conversion webhook configuration. +- Validation, defaults, and subresources present in that selected CRD version can be retained, but provider admission webhooks and controllers are not installed. Local acceptance does not guarantee provider acceptance. +- OpenAPI synthesis can expose multiple discovered versions, with the discovery-preferred version selected for storage. It installs no conversion webhook, this does not reproduce provider-side multi-version conversion. +- OpenAPI `$ref` schemas are replaced with permissive object schemas preserving unknown fields, not fully resolved. CEL/defaulting fidelity and provider admission behavior are not guaranteed. Short names, printer columns, and scale subresources are not reconstructed, discovered status subresources are. +- With **OpenAPI + Bound**, the binding only synthesizes when the consumer CRD is absent. `Always` currently does not refresh an existing bound-only OpenAPI CRD. The `All` path does reconcile synthesized schemas repeatedly. +- `Once` does not stamp an arbitrary existing CRD into management. Use an intentional externally managed workflow rather than assuming any preinstalled schema is adopted. -```yaml -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceNamespace -metadata: - # name presents namespace on consumer side - name: wild-west - # provider namespace, 1:1 mapped to consumer - namespace: kube-bind-t5gf9 - ownerReferences: - - apiVersion: kube-bind.io/v1alpha2 - blockOwnerDeletion: true - controller: true - kind: APIServiceExport - name: sheriffs - uid: fbd6c04e-e134-4156-89f4-4b31fea16657 -spec: {} -status: - # namespace, assigned on provider cluster - namespace: kube-bind-t5gf9-wild-west -``` +Review consumer CRDs and run representative API validation/sync tests before exposing a provider API to applications. The provider remains authoritative for execution and admission. -### Namespace Isolation Modes +## ClusterBinding and Binding -kube-bind supports different isolation strategies: +**Purpose**: Activate synchronization for the selected APIs. **Used by**: Service consumers. **Scope**: Cluster-wide (`ClusterBinding`) or one namespace (`Binding`). -- **Prefixed**: Consumer namespace becomes `{consumer-id}-{original-name}` -- **Namespaced**: Consumer resources go into dedicated provider namespaces -- **None**: For dedicated provider clusters where isolation isn't needed +### Namespace selection and overlapping bindings -## API Relationships and Data Flow +A ClusterBinding covers all namespaces for a namespaced API, or the entire API for a cluster-scoped resource. A Binding covers only its own namespace and cannot activate cluster-scoped instance sync. There is no namespace label selector, namespace allowlist field, per-instance selector, or runtime rename/scope-conversion policy in the core. -``` -┌─────────────────────────────────────┐ Provider Cluster -│ │ -│ APIServiceExportTemplate │ -│ │ │ -│ ▼ (processes request) │ -│ APIServiceExport ──► APIServiceNamespace -│ + │ │ -│ BoundSchema │ │ -│ │ │ │ -│ ▼ (schema sync) │ │ -└─────────┼───────────────────┼───────┘ - │ │ - [Secure Connection] │ - │ │ -┌─────────▼───────────────────▼───────┐ Consumer Cluster -│ │ -│ APIServiceExportRequest │ -│ │ │ -│ ▼ (creates binding) │ -│ APIServiceBinding ◄─── Applied CRDs│ -│ │ │ │ -│ ▼ │ │ -│ Available APIs │ │ -│ │ │ │ -│ ▼ (resource sync) │ │ -│ Synchronized Resources ────┘ │ -│ │ -└─────────────────────────────────────┘ -``` +The stock mapper preserves namespace and name. `team-a/my-widget` on the consumer becomes `team-a/my-widget` on the provider. A provider kubeconfig's default namespace controls the heartbeat location, **not** this mapping. -## Permission Claims Deep Dive +The CRD remains cluster-scoped even when a Binding is namespaced. Users in other namespaces can see/use that API if their local RBAC permits it, but their instances do not sync without a covering binding. Informers still read cluster-wide. -Permission claims are a critical concept that determines what additional resources a service can access beyond its own CRDs. +Avoid overlapping bindings for an API. The resolver checks ClusterBindings before namespaced Bindings, including when the ClusterBinding is not Ready. It returns the first match at a given scope, there is no supported priority or merge policy among peers. A managed consumer CRD pins one Connection for its syncer, so binding the same API to different providers is not supported routing. -### Claim Types +### Automatic binding -#### Label Selector Claims -Select resources based on labels: -```yaml -permissionClaims: -- group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - component: my-service - environment: production -``` +`spec.autoBind: true` makes the engine maintain a ClusterBinding **named after the Connection**, listing every exported API and owned by that Connection. Newly discovered exports can therefore start syncing without another user action. Reserve that name, do not also manage it as an independent GitOps object. -#### Named Resource Claims -Select specific resources by name: -```yaml -permissionClaims: -- group: "" - resource: configmaps - selector: - namedResources: - - name: service-config - namespace: kube-system - - name: feature-flags - namespace: default -``` +When there are no exports, the reconciler deletes that ClusterBinding. Changing `autoBind` to `false` stops maintaining it but currently does **not** remove an already-created binding. Delete that binding deliberately if the goal is to stop syncing. -#### Reference Claims (Dynamic) -Select resources based on references from other objects: -```yaml -permissionClaims: -- group: "" - resource: secrets - selector: - references: - - resource: widgets - group: example.com - jsonPath: - name: spec.secretRef.name - namespace: spec.secretRef.namespace -``` +## Export, Collection, and Grant + +The optional service layer uses `Export` to describe an offering, `Collection` to group offerings, and `Grant` to record issued credentials. They are cluster-scoped resources on the provider, in the `catalog.kbind.io` and `iam.kbind.io` groups. See [Catalog and Grants](catalog.md) for their structures. -### Claim Evaluation +## Complete Binding Flow -Permission claims are evaluated when: +1. **Provider definition**: expose service APIs and credential RBAC, optionally with a catalog Export. +2. **Consumer request**: bind an Export through the optional CLI/backend, or prepare core manifests directly. +3. **Provider processing**: the optional issuer provisions a Grant's credentials. +4. **Consumer binding**: apply the Secret, Connection, and bindings with the konnector installed. +5. **Bidirectional sync**: consumer spec flows up and provider status flows down. -1. **Template binding occurs** - Initial claim evaluation +### Observing progress -2. **Reference sources change** - Dynamic re-evaluation for reference claims +Connection status reports identities, active schema source, exports, and conditions such as `SecretValid`, `Connected`, `PermissionDenied`, and `Ready`. Although `SchemaInSync` is defined in the API, the current Connection reconciler does not populate it. -3. **Resource labels change** - Re-evaluation for label selector claims +Binding status reports `boundAPIs`, schema hashes, conflict counts, and conditions including `Ready`, `Synced`, `Conflicts`, and `PermissionDenied`. `Synced=True` is a setup-level result, not a per-object delivery acknowledgement. Conflicting objects can coexist with a ready binding, some instance RBAC errors appear only as Events/logs. ## Related Documentation -- [CRD Reference](../../reference/crd/kube-bind.io/) - Complete API specifications -- [CLI Reference](../../reference/) - Command-line tool documentation +Use [Synchronization](synchronization.md) for the data path and lifecycle, and [Troubleshooting](troubleshooting.md) to inspect actual object delivery. diff --git a/docs/content/usage/catalog.md b/docs/content/usage/catalog.md new file mode 100644 index 000000000..ae72e69ec --- /dev/null +++ b/docs/content/usage/catalog.md @@ -0,0 +1,321 @@ +# Catalog, issuance, and inventories + +The optional backend turns exported provider APIs into a browsable catalog and issues the credentials needed to bind them. All service-layer resources below live on the **provider** and are cluster-scoped: + +| Resource | API | Purpose | +| --- | --- | --- | +| `Export` | `catalog.kbind.io/v1alpha1` | Describe an offering, its APIs, and binding defaults | +| `Collection` | `catalog.kbind.io/v1alpha1` | Group Exports for browsing | +| `Grant` | `iam.kbind.io/v1alpha1` | Record an identity's issued API access and credential artifacts | + +These are not consumer sync instructions. The konnector consumes the core Secret, Connection, and binding objects produced at the end of issuance. See [API concepts](api-concepts.md), the [catalog API reference](../reference/crd/index.md#catalogkbindiov1alpha1), and the [IAM API reference](../reference/crd/index.md#iamkbindiov1alpha1). + +## Publish an offering + +Start with a running [backend](../developers/backend/index.md) and a provider API that actually implements your service. In this checkout the sample API is **`widgets.example.org`**, not `widgets.example.com`. + +From the repository root: + +```sh +kubectl --context=provider apply -f config/samples/provider-widget-crd.yaml +``` + +The sample CRD already has `core.kbind.io/exported: "true"`. For an existing CRD: + +```sh +kubectl --context=provider label crd widgets.example.org \ + core.kbind.io/exported=true --overwrite +``` + +The label is the core's export declaration. Creating a catalog Export does not label a CRD, install it, or start a controller that implements it. + +Save the following as `widgets-catalog.yaml`: + +```yaml +apiVersion: catalog.kbind.io/v1alpha1 +kind: Export +metadata: + name: widgets +spec: + title: Widgets + description: A demonstration API for managed widgets. + docs: https://example.org/widgets + apis: + - name: widgets.example.org + defaults: + conflictPolicy: Fail + relatedResources: + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/shared: "true" +--- +apiVersion: catalog.kbind.io/v1alpha1 +kind: Collection +metadata: + name: examples +spec: + title: Example services + description: APIs for learning the binding workflow. + exports: + - name: widgets +``` + +```sh +kubectl --context=provider apply -f widgets-catalog.yaml +kubectl --context=provider wait --for=condition=Ready \ + exports.catalog.kbind.io/widgets --timeout=60s +kubectl --context=provider get exports.catalog.kbind.io,collections.catalog.kbind.io +``` + +The issuer module's Export controller verifies that **every named CRD** exists with the export label. Missing or unexported APIs produce `Ready=False` with reason `APINotExported`. The gateway hides non-ready Exports and refuses to bind them. This readiness condition does not check service-controller health, API-specific business logic, or an individual consumer's connectivity. + +Collections are presentation only. Their `exports` entries refer to Export names, not CRD names. They cannot be bound as a unit, and do not grant access. The HTTP catalog includes only their ready members, and omits Collections with no visible members. There is no Collection readiness controller. + +### Related resources + +The example offering declares provider-to-consumer ConfigMap sync. Create an object that matches its label: + +```yaml +apiVersion: v1 +kind: Namespace +metadata: + name: widget-demo +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: widget-settings + namespace: widget-demo + labels: + widgets.example.org/shared: "true" +data: + endpoint: https://widgets.example.org +``` + +Apply this YAML on the provider. With the default cluster-wide bundle and compatible credentials, the related ConfigMap keeps its name and namespace on the consumer. It is not a JSONPath-followed reference from a Widget. + +Rules support only `secrets` and `configmaps` in the core API group, with `FromProvider` or `FromConsumer` direction. Select by Kubernetes `labelSelector`, exact `names`, or both. There is no reference-following selector. An omitted selector is broad, use explicit selectors, especially for Secrets. + +For example, an additional rule can send selected consumer credentials to the provider: + +```yaml +group: "" +resource: secrets +direction: FromConsumer +selector: + labelSelector: + matchLabels: + widgets.example.org/input: "true" + names: + - widget-input +``` + +This fragment belongs under `spec.defaults.relatedResources`. It is an explicit authorization and data-flow decision, not an automatic dependency discovery feature. Do not add it unless those consumer Secrets should leave their cluster. + +Related-resource selectors control sync, not issued RBAC. In default `issuerScope: Cluster`, a `FromProvider` Secret rule grants Secret reads across provider namespaces, not only the selected Secrets. A `FromConsumer` rule adds write permissions too. Review [credential scope](../developers/backend/index.md#credential-scope-and-installer-privileges) before publishing secret-bearing offerings. + +### How defaults propagate + +The gateway copies an Export's `spec.apis`, `spec.defaults.conflictPolicy`, and `spec.defaults.relatedResources` into the Grant. Bundle assembly copies those fields from the Grant into a generated **`ClusterBinding`**. + +The Grant is a resolved record, not a live reference to Export defaults. Editing an Export alone does not change existing Grants or consumer bindings. Binding the same Export again as the same identity updates that Grant's spec from the current Export and returns a new bundle. Apply that bundle to update the consumer. + +`Fail` is the core's default conflict policy. `Adopt` can take over an unowned object, but does not authorize stealing another binding's managed object. The catalog has no defaults for namespace remapping, arbitrary object templates, or a namespaced `Binding` output, those are not gateway bind options. + +## Browse and bind + +Using the [v2 CLI](../setup/kubectl-plugin.md): + +```sh +kubectl bind login https://bind.example.com +kubectl bind catalog +kubectl bind export widgets \ + --kubeconfig=./consumer.kubeconfig \ + --install-konnector=false +``` + +This example assumes the konnector and core CRDs are already installed. `export` otherwise defaults to installing/upgrading the konnector, choose a matching image explicitly if you use that behavior. + +In the browser: + +1. Open the gateway root, sign in, and choose **Catalog**. +2. Inspect the offering's API names, description, documentation link, and related-resource direction/selector hints. +3. Click **Bind**. The gateway provisions a Grant and opens a one-time bundle dialog. +4. Choose **Download bundle** or use the displayed `curl | kubectl apply` command once. Downloading and then attempting the same pickup URL again will fail, apply the downloaded file instead. + +Install the konnector before applying a downloaded bundle. **Clusters → Connect a cluster** provides the install command and manifest download. This does not establish a provider Connection by itself. + +The dialog also has **Copy kbind command**. That command requires its own CLI login and makes a fresh bind request, it does not redeem the dialog's existing ticket. If browser apply is enabled by the operator, the UI additionally allows you to paste a consumer kubeconfig for installation or bind-and-apply. This sends consumer credentials through the gateway. Prefer local CLI or reviewed manifest apply when that trust is not appropriate. + +The browser does not edit Exports/Collections, delete Grants, choose an existing cluster as an apply target, or create service instances. Use Kubernetes tools for those operations. An inventory entry is not a stored consumer credential. + +### CLI sessions and cluster selection + +`kubectl bind login` opens the gateway's OIDC login URL and listens for the browser's callback on a random localhost port. Login times out after five minutes. `--no-browser` prints the URL instead, but the browser must still reach that localhost listener. It is not a device-code login. + +The last successful login selects the default gateway. Override it with `kubectl bind catalog --server=https://other-bind.example.com`. The URL is a gateway, not a Kubernetes API server. Use an explicit `http://` scheme for local development. + +The CLI keeps bearer credentials in `kbind/config.json` under Go's `os.UserConfigDir()`: + +| Platform | Usual location | +| --- | --- | +| Linux | `$XDG_CONFIG_HOME/kbind/config.json`, or `~/.config/kbind/config.json` | +| macOS | `~/Library/Application Support/kbind/config.json` | +| Windows | `%AppData%\kbind\config.json` | + +New files use mode `0600` where supported. This is not an encrypted credential vault, protect existing file permissions too. There is no CLI logout command. Removing the cached token forgets it locally but does not revoke credentials, and browser sign-out does not invalidate a copied session token. The CLI has no Kubernetes-token login mode, though the backend can support [TokenReview authentication](../developers/backend/index.md#kubernetes-tokenreview-authentication). + +Consumer selection follows client-go loading: `--kubeconfig`, then `KUBECONFIG`, then the normal kubeconfig and its current context. There are no `--context` or `--namespace` overrides. Use a dedicated consumer kubeconfig when managing several clusters. + +### Installing through the CLI + +To install without Helm, choose a built v2 image available to your cluster: + +```sh +kubectl bind connect --kubeconfig=./consumer.kubeconfig \ + --konnector-image=registry.example.com/platform/konnector:v2-example +kubectl --kubeconfig=./consumer.kubeconfig -n kbind \ + rollout status deployment/konnector +``` + +Replace the illustrative image. The compiled `latest` default is not a v2 guarantee. `connect` installs locally embedded manifests without contacting the gateway or requiring login. It has no print-only or dry-run mode. It does not register a consumer in the provider inventory, that requires a bound Connection to start heartbeating. + +`export` also installs by default. Use `--install-konnector=false` for an existing Helm/GitOps-managed konnector, or pass `--konnector-image` to select the image explicitly. Installation and bundle apply use server-side apply with forced field ownership and can overwrite another manager's fields. They are not transactional, failure can leave earlier objects installed. Review the [installer permissions](../developers/konnector/index.md#rbac-and-credentials). + +The public gateway endpoint `/api/konnector` serves a separate installation manifest using the backend's `konnectorImage` setting. Download and inspect it before applying. Its image can differ from the CLI's. + +## Binding and bundle pickup + +The gateway flow is: + +1. Authenticate the caller and require a ready Export. +2. Create or update one Grant for `(Export name, identity subject)`. +3. Wait up to 30 seconds for the issuer's `Ready=True`. +4. Return a one-time pickup URL and its expiration. +5. Redeem that URL for the consumer bundle. + +There are no bind-request CRDs, request phases, approval queues, or browser device-code polling in this protocol. + +The Grant name is `-`, where the hash is the first ten hexadecimal characters of SHA-256 of the identity subject. The provider boundary namespace is `kbind-` and is shared by the identity's Grants. OIDC subjects are `#`, TokenReview subjects are `kubernetes#`. + +The issuer creates a ServiceAccount and token Secret per Grant, resource-specific RBAC, and a Lease permission home in the boundary namespace. The token Secret is populated by Kubernetes' ServiceAccount token controller. `Grant.status` reports `namespace`, `serviceAccount`, `tokenSecret`, and conditions. + +The bundle always contains: + +| Object | Name / namespace | Purpose | +| --- | --- | --- | +| `v1/Secret` | Grant name, namespace `kbind` | `stringData.kubeconfig` with the provider token, endpoint, CA, and boundary context namespace | +| `core.kbind.io/v1alpha1/Connection` | Grant name, cluster-scoped | Reference the kubeconfig Secret | +| `core.kbind.io/v1alpha1/ClusterBinding` | Grant name, cluster-scoped | Select the Grant's APIs and resolved defaults | + +It does not include the core CRDs, konnector Deployment, `kbind` namespace, or service instances. CLI install/apply can supply installation and namespace prerequisites, plain `kubectl apply` of the bundle cannot. + +### Three different lifetimes + +| Item | Default lifetime | What expiry/revocation means | +| --- | --- | --- | +| Browser/CLI session | 12 hours | Log in again to call authenticated gateway APIs | +| Pickup URL | 5 minutes, one successful consumption | Bind again for a new pickup URL | +| Issued provider credential | Long-lived Secret-based SA token | Remains usable independently of session/pickup expiry until revoked or otherwise invalidated | + +The one-time token is stored on the Grant as a hash and expiry, not gateway memory. Optimistic concurrency enforces single consumption across replicas. A new bind replaces any outstanding pickup for the same Grant. A used, expired, or unknown token returns HTTP `410`. + +Pickup consumes the token **before** assembling the bundle. If the response fails, is lost, or credential assembly fails after consumption, bind again, there is no retryable download ticket. Protect pickup URLs like passwords: possession is sufficient to retrieve the credentials without a session. + +`kubectl bind export widgets -o yaml` is the GitOps path. It still provisions and picks up a real Grant, but does not apply to the consumer. Secure the credential material before storing it in Git. See [GitOps](gitops.md). + +### Direct Grant management + +Normally the gateway creates Grants. Trusted provider automation can also create them through Kubernetes: + +```yaml +apiVersion: iam.kbind.io/v1alpha1 +kind: Grant +metadata: + name: widgets-automation +spec: + identity: + subject: https://sso.example.com#automation + displayName: Widget automation + exportName: widgets + apis: + - name: widgets.example.org + conflictPolicy: Fail + relatedResources: + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/shared: "true" +``` + +The issuer provisions from this spec. It does not resolve `exportName` back to an Export, validate caller entitlement, or mint a pickup URL simply because a Grant exists. Direct Grant writers are trusted credential administrators. The illustrative name above is not the gateway's deterministic name, binding through the gateway would use its own record. For a complete gateway-issued bundle, use the bind API rather than hand-authoring Grant status or pickup annotations. + +## Revoke and retire an offering + +Inspect provider records: + +```sh +kubectl --context=provider get grants.iam.kbind.io +kubectl --context=provider get grants.iam.kbind.io GRANT_NAME -o yaml +``` + +Revoke a specific Grant: + +```sh +kubectl --context=provider delete grants.iam.kbind.io GRANT_NAME +``` + +The issuer's `iam.kbind.io/cleanup` finalizer removes that Grant's ServiceAccount, token Secret, ClusterRole/ClusterRoleBinding, and Role/RoleBinding. The issuer must be running for finalizer cleanup to complete. Do not remove the finalizer as a substitute for credential revocation. + +Ordinary revocation keeps the provider boundary namespace and synced objects. It also does not remove consumer Secrets, Connections, bindings, or CRDs. Consumers should deliberately disengage through their [core lifecycle](api-concepts.md) rather than assume provider credential revocation cleaned up their cluster. + +Deleting an Export removes it from catalog/bind lookup but does not delete its existing Grants or revoke their tokens. Removing a CRD's export label makes the catalog Export non-ready after reconciliation, it is not a credential revocation operation either. Revoke outstanding Grants explicitly when retiring access. + +Deleting a Grant is not a permanent deny-list entry: an authenticated caller can bind an offering again while it remains available. Plan gateway access and offering withdrawal as well as credential cleanup. + +### Reaper policy + +The reaper is disabled by default. With it enabled: + +- `reaper.ttl` / `--reaper-ttl` defaults to **30 minutes**. +- `reaper.interval` / `--reaper-interval` defaults to **1 minute**. +- `reaper.revoke` defaults to `false`: mark `Stale=True` and add `iam.kbind.io/stale-since`, but retain credentials. +- `reaper.deleteBoundary` defaults to `false` and only has an effect when revocation is enabled. + +It reads managed heartbeat Leases in the Grant's boundary namespace. Matching uses the Lease's `core.kbind.io/connection` annotation and the generated Connection/Grant name. If matching Leases exist, the newest matching renewal determines staleness (`LeaseExpired`). Without a matching Lease, another fresh Lease in the same boundary conservatively keeps the Grant alive, accommodating renamed Connections. A fully silent boundary becomes stale. If no renewed Lease exists, the reaper waits one TTL after the Grant's Ready transition (`NoLease`). Fresh heartbeats clear prior stale markings. + +With revocation enabled, the reaper deletes stale Grants and the issuer finalizer revokes their credentials. With boundary deletion also enabled, it can delete the namespace and everything in it, but skips deletion while another non-deleting Grant shares that identity. + +This is **not** complete cleanup of a consumer's synced objects. Default cluster-scoped credentials reproduce consumer namespace names, many provider objects can therefore live outside the credential boundary. Boundary deletion does not delete those namespaces or cluster-scoped objects. + +Coordinate destructive policy with outages, paused consumers, and GitOps rollouts. A downloaded-but-not-applied bundle may be revoked as never connected. The reaper's TTL is independent of the inventory's Live/Stale display threshold. + +## Cluster and instance inventories + +The browser's **Clusters** view and `kubectl bind clusters` use `GET /api/clusters`. There is no cluster registration resource or browser `/clusters` page route, the browser switches views within the app. + +The inventory correlates Grants with managed Leases using the Connection name and consumer cluster UID annotations. It reports: + +- Consumer UID, latest heartbeat, and whether any binding is live. +- Per-binding Grant, Export, identity, boundary namespace, and heartbeat. +- Best-effort counts of managed provider objects per API and consumer UID. +- Pending Grants without a usable matching Lease (`NeverConnected` in the CLI). + +“Live” means a renewal within twice `leaseDurationSeconds`, a missing duration uses 60 seconds, hence a 120-second grace window. It is not a guarantee that every resource is syncing correctly. “NeverConnected” means the inventory found no matching Lease, not proof the bundle was never applied: renamed Connections, deleted Leases, or missing annotations can also prevent correlation. + +`GET /api/catalog/{export}/instances`, the browser's **Synced instances** expander, and `kubectl bind instances [export]` show **provider-side** object metadata, not service health or a remote consumer object browser: + +- Bound-API rows are objects carrying the core managed label, with consumer UID and identity attribution when the Lease/Grant link is available. +- Related `FromConsumer` rows are managed provider copies marked as related resources, the listing applies name restrictions, but is not a strict per-Grant or label-selector-filtered inventory. +- Related `FromProvider` rows are provider originals matching the declared label selector (and names if supplied). Without a `labelSelector`, these originals are omitted even if a names-only sync rule is valid. Consumer-side copies are not inspected. Secret payloads are not returned by this endpoint. + +Counts and instance lists are best effort. Unreadable/unavailable APIs can yield zero counts or omitted rows instead of failing the entire view. Multiple Exports sharing an API can show the same objects, the inventory is not accounting by individual Grant. It also follows the current Export definition, not every historical Grant's defaults. + +All authenticated gateway callers can read these inventories, they are not filtered to the caller's identity. If results are unexpected, inspect provider Grants and Leases and follow [troubleshooting](troubleshooting.md). diff --git a/docs/content/usage/gitops.md b/docs/content/usage/gitops.md new file mode 100644 index 000000000..c0c504fc1 --- /dev/null +++ b/docs/content/usage/gitops.md @@ -0,0 +1,223 @@ +# GitOps + +The v2 core accepts ordinary Kubernetes YAML. You can manage a Connection and its explicit bindings with your existing GitOps controller, no browser onboarding or continuously running CLI is required. + +## Try the core without a backend + +This local example uses the existing demo samples to supply credentials, a Connection, +and a ClusterBinding directly. It needs no backend, catalog, login, or `kubectl bind` +plugin. Use a v2 source checkout, Go matching `go.mod`, Docker, kind, and kubectl. +Run commands from the repository root. + +The demo creates or reuses kind clusters named `kbind-provider` and `kbind-consumer`. +Use fresh, disposable clusters with those names: the script applies sample resources +and replaces its credential Secret. It writes administrator kubeconfigs under `/tmp` +and copies the provider kubeconfig into a consumer Secret. These credentials are for +this local demo only; use restricted provider credentials and secure Secret delivery +for a real deployment. + +### Prepare the two clusters + +```sh +make konnector +make demo +``` + +The script installs the exported Widget CRD and related Secret/ConfigMap on the provider. +On the consumer it installs API definitions, creates the credential Secret, and applies +`config/samples/binding.yaml`. That file connects `demo-provider` to the Secret and +selects `widgets.example.org` through ClusterBinding `widgets`. + +In a second terminal at the repository root, start the konnector and leave it running: + +```sh +KUBECONFIG=/tmp/kbind-consumer.kubeconfig ./bin/konnector +``` + +These kubeconfigs use host-mapped endpoints, so this example runs the konnector on your +workstation. They are not suitable for a konnector Pod in another cluster. + +### Verify synchronization + +In the first terminal, wait for readiness before creating a Widget: + +```sh +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig wait \ + --for=condition=Ready connection/demo-provider clusterbinding/widgets --timeout=120s +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig wait \ + --for=condition=Established crd/widgets.example.org --timeout=120s +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig apply -f config/samples/widget.yaml +kubectl --kubeconfig /tmp/kbind-provider.kubeconfig -n default wait \ + --for=create widget/my-widget --timeout=120s +kubectl --kubeconfig /tmp/kbind-provider.kubeconfig -n default wait \ + --for=jsonpath='{.spec.size}'=large widget/my-widget --timeout=120s +``` + +There is no Widget service controller in this demo. Simulate its status update on the +provider and verify that it reaches the consumer: + +```sh +kubectl --kubeconfig /tmp/kbind-provider.kubeconfig -n default patch widget my-widget \ + --subresource=status --type=merge -p '{"status":{"phase":"Running"}}' +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig -n default wait \ + --for=jsonpath='{.status.phase}'=Running widget/my-widget --timeout=120s +``` + +The binding also copies the provider's related Secret and ConfigMap. Check their +ownership markers without printing Secret data: + +```sh +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig -n default wait \ + --for=create secret/widgets-connection configmap/widgets-tuning --timeout=120s +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig -n default get \ + secret/widgets-connection configmap/widgets-tuning \ + -o 'custom-columns=NAME:.metadata.name,BINDING:.metadata.annotations.core\.kbind\.io/related-binding' +kubectl --kubeconfig /tmp/kbind-consumer.kubeconfig get clusterbinding widgets \ + -o jsonpath='{.metadata.uid}{"\n"}' +``` + +Both `BINDING` values should match the ClusterBinding UID. The consumer sample creates +only the Widget; the konnector creates these related copies. + +### Clean up + +Stop the host konnector with Ctrl-C, then remove only the disposable demo clusters and +their credential files: + +```sh +kind delete cluster --name kbind-consumer +kind delete cluster --name kbind-provider +rm /tmp/kbind-consumer.kubeconfig /tmp/kbind-provider.kubeconfig +``` + +For an existing deployment, follow [Pruning is unbinding](#pruning-is-unbinding) instead +of deleting clusters. To manage the same core inputs declaratively, continue below. + +## Separate definitions, credentials, and generated state + +Manage these layers deliberately: + +1. Install the three core CRDs and the konnector. +2. Create application/credential namespaces and deliver provider credentials securely. +3. Apply Connections and explicit Bindings/ClusterBindings. +4. Wait for the bound consumer CRDs to become Established before applying their instances. + +Connections and bindings tolerate arriving before their dependencies, but Kubernetes rejects unknown kinds before a CRD exists. Use your GitOps tool's existing dependency/wave/health mechanisms rather than relying on YAML document order. + +Keep these out of Git: + +- Plaintext provider kubeconfigs and base64-only Secret manifests containing credentials. +- Controller-written `status`, UIDs, resource versions, finalizers, and managed fields. +- Generated autoBind ClusterBindings, unless you instead turn autoBind off and manage explicit bindings. +- Consumer copies of `FromProvider` related resources. + +Use an existing encrypted-Secret or external-secret workflow for credentials. The resulting Kubernetes Secret must have the namespace, name, and data key referenced by the Connection. + +## Obtain a bundle from a provider + +With the [CLI](../setup/kubectl-plugin.md) installed and logged in: + +```sh +kubectl bind export widgets -o yaml > widgets-bundle.yaml +``` + +This provisions a real Grant and redeems a one-time pickup URL, it is not a dry run. YAML is the only supported output format. This mode does not read the consumer kubeconfig, install the konnector, create namespaces, or apply resources, even when `--install-konnector` is true. + +Install the core CRDs, konnector, and `kbind` namespace separately. The bundle contains a long-lived provider token in plaintext YAML. Encrypt its Secret or use a secret manager before committing anything. + +Pickup expiry does not expire a saved bundle's credentials. The provider's optional reaper can revoke Grants that have not yet heartbeated, so coordinate its TTL with rollout timing. See [bundle lifetimes](catalog.md#three-different-lifetimes). + +## An explicit application binding + +After creating `team-a` and delivering `kbind/provider-kubeconfig`: + +```yaml +apiVersion: core.kbind.io/v1alpha1 +kind: Connection +metadata: + name: provider +spec: + kubeconfigSecretRef: + namespace: kbind + name: provider-kubeconfig + key: kubeconfig + schema: + source: CRD + pullPolicy: Bound + updatePolicy: Always + autoBind: false +--- +apiVersion: core.kbind.io/v1alpha1 +kind: Binding +metadata: + name: widgets + namespace: team-a +spec: + connectionRef: + name: provider + apis: + - name: widgets.example.org + conflictPolicy: Fail +``` + +A namespaced Binding is often preferable when only one application's namespace should sync. It is not a namespaced CRD or a replacement for provider/consumer RBAC. + +Use an explicit API allowlist rather than `autoBind: true` if newly exported provider APIs require review. Use `source: CRD` when provider labels must remain the opt-in boundary, Auto can fall through to OpenAPI when no labelled CRDs are found. + +## Choose one schema owner + +### Konnector-managed schemas + +With `pullPolicy: Bound` or `All`, avoid also reconciling the same consumer CRD spec from Git. `updatePolicy: Always` can overwrite competing changes with the provider schema. + +`Once` stops subsequent schema spec updates, but is not a version selector or approval queue. Test compatibility before changing policies, and note the [OpenAPI update limitation](api-concepts.md#schema-updates-and-fidelity). + +### Externally managed schemas + +Use `pullPolicy: None` when Git owns the consumer CRD spec. Supply the correct group, resource, scope, usable storage version, status schema/subresource, and compatible validation yourself. + +For OpenAPI-source Connections, include these markers in the consumer CRD: + +```yaml +metadata: + labels: + core.kbind.io/managed: "true" + annotations: + core.kbind.io/connection: provider +``` + +For CRD-source Connections, the engine stamps these markers on an existing CRD. Configure your GitOps tool not to fight those metadata changes. + +**Important:** `None` means “do not install the schema,” not “never manage or delete this CRD.” Last-ClusterBinding cleanup currently deletes the referenced CRD even under `None`. Prefer a carefully controlled Binding lifecycle, disable destructive automatic pruning for shared resources, and read [unbinding behavior](synchronization.md#delete-a-binding). + +Likewise, core CRDs included by the Helm chart are ordinary release templates. If Git owns those three definitions, use `installCRDs: false` from the initial Helm install, do not hand their lifecycle back and forth casually. + +## Drift and ownership + +For bound instances, Git should normally manage consumer `spec`, not provider copies or consumer `status`. The konnector force-applies its fields to owned provider copies, so a second provider-side GitOps manager for those same fields will compete with it. + +An existing foreign provider object is not adopted by default. `conflictPolicy: Adopt` is an explicit and potentially destructive decision for a markerless object, not a generic way to suppress drift. It does not steal objects marked for another consumer. + +Avoid managing the same API through multiple overlapping bindings or different Connections. The current resolver is not a multi-provider routing system. Also avoid editing a binding's API list or Connection reference as though it performed an atomic migration: cleanup operates on deletion and the current spec, not an inventory of all previous specs. + +## Rotate without replacing identity + +Keep `kubeconfigSecretRef` stable and update the Secret's data for the same provider cluster. The reference and pinned identities are immutable. + +After delivering new valid credentials, restart the konnector to rebuild engaged instance clients, then verify spec/status round-tripping before revoking the old credentials. Secret updates alone do not guarantee hot rotation of an already-engaged client. + +A different provider identity requires a new Connection and an explicit migration. Do not try to overwrite `remoteClusterUID`. + +## Pruning is unbinding + +Removing a binding from Git and allowing it to be pruned invokes the same destructive cleanup as `kubectl delete`. Removing a last ClusterBinding can delete the consumer CRD and every instance of that API. + +For a planned removal: + +1. Pause automatic recreation/pruning while coordinating the change. +2. Back up relevant consumer resources and annotate instances with `core.kbind.io/deletion-policy: Orphan` if provider copies must remain. +3. Delete and verify instances or bindings while the controller and credentials work. +4. Delete Connections after explicit bindings have drained. +5. Remove credential Secrets, then the controller/CRDs if no longer needed. + +Do not prune the credentials, namespace, CRDs, and controller first. Cleanup finalizers preserve ordering in common cases, but they are not a distributed rollback mechanism. See [Troubleshooting](troubleshooting.md) for incomplete teardown. diff --git a/docs/content/usage/index.md b/docs/content/usage/index.md index 822627891..9b3d0bf48 100644 --- a/docs/content/usage/index.md +++ b/docs/content/usage/index.md @@ -15,11 +15,11 @@ kube-bind operates on three fundamental concepts: ### Service Provider -The cluster that **exports** APIs and resources, making them available for other clusters to consume. Service providers create templates and handle permission claims. +The cluster that **exports** APIs and resources, making them available for other clusters to consume. Service providers label exported CRDs, grant credential RBAC, and optionally publish catalog Exports. ### Service Consumer -The cluster that **imports** and uses APIs from service providers. Consumers bind to templates and get access to resources through a secure, controlled process. +The cluster that **imports** and uses APIs from service providers. Consumers apply a Connection and bindings directly, or obtain a bundle through the optional backend. ### Konnector Agent @@ -27,29 +27,21 @@ The component that establishes and maintains the secure connection between provi ## Key API Types -### APIServiceExportTemplate +### Connection -**Purpose**: Defines a reusable service template that groups related CRDs and permission claims. -**Used by**: Service providers -**Scope**: Template definition for multiple consumers +**Purpose**: References provider credentials, discovers APIs, and controls schema delivery. **Used by**: Service consumers **Scope**: Cluster-scoped on the consumer -### APIServiceExport +### ClusterBinding and Binding -**Purpose**: Represents an active export of a specific CRD to consumer clusters. -**Used by**: Automatically created by konnector agents -**Scope**: Per-CRD export instance +**Purpose**: Select the APIs whose instances should synchronize. **Used by**: Service consumers **Scope**: Cluster-wide or one consumer namespace -### APIServiceExportRequest +### Export and Collection -**Purpose**: Consumer's request to bind to a specific service template. -**Used by**: Service consumers (via CLI/UI) -**Scope**: Per-binding request +**Purpose**: Describe and group offerings in the optional catalog. **Used by**: Service providers **Scope**: Cluster-scoped on the provider -### APIServiceNamespace +### Grant -**Purpose**: Manages namespace mapping and isolation between provider and consumer clusters. -**Used by**: Automatically managed by konnector agents -**Scope**: Per-namespace sync +**Purpose**: Record issued credentials and resolved APIs. **Used by**: The optional backend's gateway and issuer **Scope**: Cluster-scoped on the provider ## Documentation Structure @@ -57,28 +49,29 @@ The component that establishes and maintains the secure connection between provi Deep dive into the core API types, their relationships, and how they work together in the kube-bind ecosystem. -### [Template References](template-references.md) +### [Catalog and Grants](catalog.md) -Advanced guide for using dynamic resource selection through references in templates. +Publish offerings, issue credentials, and inspect connected consumers. ## Common Workflows ### For Service Providers -1. **Create templates** defining what APIs and resources to export, including permission claims +1. **Export APIs** with CRD labels and RBAC, optionally describing them as catalog Exports. 2. **Implement service** to act on the synced/bound objects so it can be returned to the consumer/user. ### For Service Consumers 1. **Authenticate** to the kube-bind backend -1. **Discover available templates** through the web UI or CLI -2. **Request bindings** to specific templates -3. **Authenticate and authorize** access through OAuth2 flows +2. **Discover available Exports** through the web UI or CLI +3. **Request a bundle** for a specific Export and apply it to the consumer 4. **Use imported APIs** in their local cluster +The core-only alternative is to supply credentials and bindings directly through [GitOps](gitops.md), with no backend login. + ### For Platform Operators -1. **Deploy kube-bind infrastructure** on both provider and consumer sides (if using GitOps) +1. **Deploy the konnector** on the consumer and the optional backend on the provider 2. **Configure authentication** and security policies 3. **Monitor connections** and resource synchronization @@ -88,11 +81,13 @@ If you're new to kube-bind: 1. **Start with the [Quickstart Guide](../setup/quickstart.md)** for a hands-on introduction 2. **Review [API Concepts](api-concepts.md)** to understand the fundamental types -3. **Check the [Reference Documentation](../reference/)** for complete API specifications +3. **Check the [Reference Documentation](../reference/index.md)** for complete API specifications The konnector agents establish a secure, authenticated connection that allows: - **API schema synchronization** from provider to consumer -- **Resource data flow** based on permission claims -- **Namespace isolation** and mapping -- **Authentication and authorization** enforcement +- **Spec up / status down** resource data flow +- **Selected Secret and ConfigMap synchronization** +- **Provider access** governed by credential RBAC + +The stock syncer does not rename namespaces or convert resource scope. Review [synchronization](synchronization.md) when designing a shared provider. diff --git a/docs/content/usage/integrations/cert-manager.md b/docs/content/usage/integrations/cert-manager.md index ba252580d..2f0a66005 100644 --- a/docs/content/usage/integrations/cert-manager.md +++ b/docs/content/usage/integrations/cert-manager.md @@ -9,25 +9,29 @@ weight: 10 ## Setup -The following sections will guide you through the one-time setup that is required for providing -certificates using cert-manager and kube-bind. +The following sections will guide you through the one-time setup that is required for providing certificates using cert-manager and kube-bind. + +Follow the [prerequisites](index.md#prerequisites), then select the provider: + +```bash +kubectl config use-context provider +``` ### Install cert-manager -Install cert-manager in your Kubernetes cluster, where kube-bind backend is running, if you haven't -already. You can follow the [official installation guide](https://cert-manager.io/docs/installation/kubernetes/). +Install cert-manager in your Kubernetes cluster, where kube-bind backend is running, if you haven't already. You can follow the [official installation guide](https://cert-manager.io/docs/installation/kubernetes/). ### Export the Certificate CRD To export the cert-manager `Certificate` CRD, add the kube-bind export label to it: ```bash -kubectl label crd certificates.cert-manager.io kube-bind.io/exported=true --overwrite +kubectl label crd certificates.cert-manager.io core.kbind.io/exported=true --overwrite ``` ### Create a SelfSigned Issuer -```yaml +```bash kubectl apply -f - < 18000/TCP,18001/TCP,18002/TCP,19001/TCP,9443/TCP 4d23h -envoy-kube-bind-wz2g5-default-my-lb-gw-9f962ab2 LoadBalancer 10.96.231.200 80:32515/TCP 4d19h +kubectl --context=provider get services -n envoy-gateway-system ``` -Port forward the related service. +Port forward the related service for `my-lb`. ```bash -kubectl -n envoy-gateway-system port-forward service/envoy-kube-bind-wz2g5-default-my-lb-gw-9f962ab2 8888:80 +kubectl --context=provider -n envoy-gateway-system port-forward service/ 8888:80 ``` Send the request through the gateway service to your backend application. diff --git a/docs/content/usage/migration.md b/docs/content/usage/migration.md new file mode 100644 index 000000000..762dff395 --- /dev/null +++ b/docs/content/usage/migration.md @@ -0,0 +1,44 @@ +# Moving from 0.x + +v2 replaces the 0.x API model and binding protocol. **There is no automatic conversion or supported in-place upgrade of existing bindings.** Keep the [0.x documentation](https://docs.kbind.dev/latest/) for existing deployments, use separate test clusters to evaluate v2 first. + +## Concepts that carry over + +The consumer is still the source of desired state. The provider runs the service implementation. The konnector still sends spec to the provider and returns status to the consumer, connecting outward from the consumer. + +The API objects and operational responsibilities around that loop have changed: + +| 0.x concept | v2 replacement or change | +| --- | --- | +| `kube-bind.io` API group and its `v1alpha1`/`v1alpha2` kinds | `core.kbind.io/v1alpha1`, `catalog.kbind.io/v1alpha1`, and `iam.kbind.io/v1alpha1`, new objects, not a version-field edit | +| Consumer `APIServiceBinding` and connection bookkeeping | `Connection` references credentials, `ClusterBinding` or `Binding` chooses APIs and sync scope | +| `APIServiceExportTemplate` | Optional catalog `Export` | +| Legacy `Collection` | New catalog `Collection` grouping Exports, create a new manifest | +| `APIServiceExportRequest` / binding handshake | Optional HTTP `/api/bind` produces a one-apply core bundle | +| Per-consumer `APIServiceExport` | Provider opt-in labels and core discovery, optional `Grant` records service-layer issuance | +| `BoundSchema` / old schema intermediates | Core pulls CRDs or synthesizes them from OpenAPI, controlled by `Connection.spec.schema` | +| `APIServiceNamespace` / mapped provider namespaces | No equivalent in stock core, namespace and name stay unchanged | +| `Prefixed`, `Namespaced`, and `None` isolation modes | Identity mapping only in the shipped binary, no scope conversion | +| Permission claims and JSONPath reference following | Credential RBAC plus explicit `relatedResources` selectors for Secrets/ConfigMaps | +| Backend required for the binding protocol | Backend optional, directly apply the Secret, Connection, and bindings | + +The new `ClusterBinding` shares a name with an old kind, not its group, schema, or meaning. Use fully qualified resource names when inspecting clusters that contain both API groups. + +## Plan an explicit cutover + +1. Inventory the APIs, objects, credentials, namespace mapping, related Secrets/ConfigMaps, and cleanup policies in your current installation. Back up both clusters' relevant resources and service data. +2. Choose a provider boundary that works with identity mapping. A 0.x object named with a consumer prefix or stored in a mapped namespace is not the same v2 target. +3. Install v2 on an isolated consumer. Use the [core quickstart](../setup/quickstart.md) to establish the new workflow. Keep the old konnector away from APIs and objects managed by the new one. +4. Recreate provider credentials and exported-API policy, then author new [core manifests](api-concepts.md). For the service layer, create [Exports and Collections](catalog.md) and obtain a new v2 bundle. +5. Recreate representative instances and validate schema behavior, spec ownership, status delivery, related resources, RBAC, and cleanup before planning a service-specific data migration. +6. Drain and retire old bindings using the cleanup behavior documented for their original release. Retain backups and credentials until the intended cleanup has completed. + +Do not run both syncers against the same target objects as a migration shortcut. Do not switch `conflictPolicy` to `Adopt` just to bypass an unexplained collision: v2 adoption can take over an unowned target, not a target marked as owned by a different binding. + +## Integration changes + +The old cert-manager, Crossplane, CloudNativePG, and kro recipes are not v2 installation instructions. Their service operators may still run on a provider, but each offering needs a new Export or explicit core binding, v2-compatible schemas, matching names and scopes, and sufficient RBAC. + +Review multi-version CRDs, conversion webhooks, built-in Kubernetes resource dependencies, and service-specific Secret references individually. v2's related-resource selectors do not follow arbitrary JSONPath references. The previous `Namespaced` isolation mode cannot be reproduced by changing a chart value or a `Mapper`. + +See [synchronization](synchronization.md) for the shipped semantics and [architecture](../developers/architecture.md) for extension points. diff --git a/docs/content/usage/synchronization.md b/docs/content/usage/synchronization.md index 58da65f1f..e59c2155c 100644 --- a/docs/content/usage/synchronization.md +++ b/docs/content/usage/synchronization.md @@ -1,173 +1,192 @@ --- title: Resource Synchronization -description: | - Overview over the general resource synchronization logic and different isolation modes. +description: > + Resource synchronization, ownership, and lifecycle between consumer and provider clusters. weight: 220 --- # Resource Synchronization -This document describes the way kube-bind synchronizes Kubernetes resources across clusters. +This section outlines how kbind synchronizes objects between two kinds of clusters: + +* The **provider cluster** is run by a service provider and hosts a service, operator, or other Kubernetes API. The optional backend offers these APIs through a catalog. +* The **consumer clusters** are where end users consume services/APIs offered by providers. + +There is a 1:n relationship: one provider can serve many consumer clusters. ## Overview -kube-bind synchronizes objects between two kinds of clusters: +The konnector turns managed consumer CRDs into per-resource sync controllers. A Ready Connection supplies the provider client, and a Ready Binding or ClusterBinding selects which consumer instances participate. See [API concepts](api-concepts.md) for scope, schema delivery, and overlapping-binding restrictions. -* The **provider cluster** is run by a service provider and hosts a service, operator, or any other kind of Kubernetes API. This is also where there kube-bind **backend** is running in order to offer these APIs to consumers. -* The **consumer clusters** are where endusers consume services/APIs offered by providers. +### Sync Direction -There exists a 1:n relationship, where one provider cluster can be connected to from many different consumer clusters. +The consumer clusters represent the source of truth for desired state, and the provider holds copies of those objects. During synchronization, spec is copied from consumer to provider and status is copied in the opposite direction. -### Cluster Namespaces +| Data | Direction | Behavior | +| --- | --- | --- | +| Bound instance `spec` | Consumer → provider | Server-side apply using field manager `kbind-konnector`, with force ownership after the object-ownership check. | +| Bound instance `status` | Provider → consumer | Copies the provider status through the consumer status subresource. | +| Related Secret/ConfigMap payload | Configured per entry | Server-side apply using `kbind-konnector-related`. | -In kube-bind, each successful `bind` operation yields a new, so-called "cluster namespace" on the provider cluster. This namespace contains all kube-bind-related resources, like `APIServiceExports` or `BoundSchemas` and is communicated to the consumer by being included in the provided kubeconfig. +Instance namespace/name are unchanged. The engine does not copy arbitrary consumer labels, annotations, owner references, or finalizers to the provider, it writes its own management and ownership metadata. Top-level fields other than `spec` are not a generic object replication interface. -By default the cluster namespaces are named `kube-bind-[random string]`, like `kube-bind-hd73s`. Their name also serves as a unique identifier for this "contract" between consumer and provider and is used in other places, for example as a prefix in the `prefixed` cluster isolation mode. +Status is copied when the provider object contains it. Absence of provider status does not actively clear an existing consumer status. APIs intended for status round-tripping need an appropriate status schema/subresource on the consumer. -### Sync Direction +Consumer changes and provider watch events drive synchronization. Provider events also allow desired consumer specs to repair provider drift. There are periodic resyncs as a backstop, this is asynchronous reconciliation, not a cross-cluster transaction or a synchronous admission guarantee. -In the kube-bind architecture, the consumer clusters represent the source of truth (the actual desired state by the enduser) and the provider clusters merely contain copies of those objects. +### Connectivity -During the synchronization, +The object synchronization logic lives in the konnector, an agent running on each consumer cluster. It reads a local Secret containing a kubeconfig for the provider. Connections and bindings in the consumer describe what to synchronize. -* the **spec** (desired state) of an object is copied from the consumer cluster to the provider and -* the **status** (if any) is copied in the opposite direction, to the consumer. +This design allows consumer clusters to be mostly firewalled off, but requires provider API servers to be reachable from consumers. No inbound provider connection to the consumer is needed for core synchronization. -kube-bind will continuously watch the object and its copy on both clusters and update the other side as needed. +### RBAC -### Connectivity +Provider credentials govern what the konnector may access. Object ownership checks do not protect against direct use of overprivileged credentials. A namespaced Binding restricts sync selection but does not make the current dynamic informers namespace-scoped. See [RBAC and credentials](../developers/konnector/index.md#rbac-and-credentials). -The object synchronization logic lives in the kube-bind **konnector**, a Kubernetes agent that runs on each *consumer cluster*. It reads a local Secret that contains a kubeconfig pointing to **a specific namespace** on the *provider cluster*. In this namespace the konnector will find all resources describing the resources to sync (chiefly `APIServiceExports`, `APIServiceNamespaces` and `BoundSchemas`). +## Cluster Isolation -!!! note - This kubeconfig is automatically generated as part of the `kubectl bind` handshake with a service provider. +Namespaced resources retain the same namespace and name on each side. Cluster-scoped resources remain cluster-scoped. The built-in v2 mapper does not provide `Prefixed` or `Namespaced` isolation strategies, choose compatible provider namespaces, credentials, or dedicated clusters/workspaces instead. -This design allows consumer clusters to be mostly firewalled off, but requires provider clusters to not only be reachable from all consumers, but also to ensure multiple consumers do not conflict with each other. This is achieved by a combination of RBAC and isolation modes, which are described further down in this document. +## Ownership and conflicts -### RBAC +Provider instance copies carry: -Great care must be taken to ensure multiple consumers do not collide with each other on a single provider cluster. To achieve this, kube-bind offers two different informer scoping options: +```yaml +metadata: + labels: + core.kbind.io/managed: "true" + annotations: + core.kbind.io/consumer-cluster-uid: "" + core.kbind.io/consumer-object-uid: "" +``` -* `namespaced` will make the konnector watch and inform on each relevant namespace on the provider cluster individually. -* `cluster` will instead make the konnector use a cluster-scoped (global) informer. This scoping method requires the konnector to have much wider permissions, but is more performant. +The ownership check uses **both UIDs**, not just the managed label or the object's name. Instance ownership is tied to the source object, not to a Binding UID. -Regardless of scoping mode, the konnector itself will take care to not overwrite/touch other consumers' objects. This however does not mean that an attacker with access to the konnector kubeconfig could not exploit an RBAC policy that is too wide. +`spec.conflictPolicy` on a binding controls a preexisting provider target: -## Cluster Isolation +- **`Fail`** (default): leave the target untouched and report a conflict. +- **`Adopt`**: take ownership only when both consumer ownership annotations are absent. This can overwrite fields through forced server-side apply, so use it only after reviewing the existing object. +- Neither policy takes an object carrying another consumer/object's ownership markers. Partial markers also count as foreign ownership. -This section outlines how kube-bind deals with differently scoped Kubernetes objects. +A conflict produces `core.kbind.io/conflict` on the consumer instance and a Warning Event (`ForeignObjectExists` or `OwnedByAnother`). A best-effort `Synced=False` instance condition may be pruned by the API's status schema, the annotation is the durable diagnostic. -In Kubernetes, an object can be either namespaced or cluster-scoped. This scope greatly affects how kube-bind processes the object. +Bindings count conflict annotations on a periodic reconciliation, normally every 30 seconds. `Conflicts=True` does not necessarily make `Ready` or `Synced` false, and unrelated objects can continue syncing. -### Namespaced +Deleting a conflicting consumer object does not delete the foreign provider object. Recreating an orphaned consumer instance gives it a new UID, so its retained provider copy will not automatically become owned by the new instance. -For namespaced objects (like a `Deployment`), kube-bind will map the consumer-side namespace to a unique, but random provider-side namespace: first the konnector will create an `APIServiceNamespace` object on the provider cluster (inside the cluster namespace), with the name of the consumer-side namespace (so a namespace `app1` will lead to an `APIServiceNamespace` `app1` in the cluster namespace). After this, the konnector waits until the backend has assigned this `APIServiceNamespace` a provider-side namespace to use. Once that namespace is present in the `APIServiceNamespace`'s status, the konnector will use it for all objects originating in the same consumer-side namespace. +## Related Secrets and ConfigMaps -In YAML, this means +Add `spec.relatedResources` to either binding kind: ```yaml -# consumer-side object - -apiVersion: provider.example.com/v1 -kind: MangoDB -metadata: - name: my-first-db - namespace: team1 -spec: - size: large +relatedResources: + - group: "" + resource: secrets + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/related: "true" + - group: "" + resource: configmaps + direction: FromConsumer + selector: + names: + - widget-settings ``` -will lead to +Use the core group (`""`), only `secrets` and `configmaps` are supported. `FromProvider` copies provider → consumer, `FromConsumer` copies consumer → provider. -```yaml -# provider-side objects +Selection and copying are deliberately simple: -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceNamespace -metadata: - name: team1 # name of the namespace from the consumer - namespace: kube-bind-hd73d # cluster namespace -spec: {} -status: - # a common implementation in the backend is to construct the provider-side - # namespace by just concatenating the two values, like so: - namespace: kube-bind-hd73d-team1 +- A Binding selects within its namespace, a ClusterBinding lists across namespaces. +- Names match exactly. If names and a label selector are both provided, **both** must match. +- An omitted/empty selector matches everything in scope. Avoid this for Secrets. +- Selection is independent of individual API instances. There is no JSONPath/reference following or owner-reference traversal. +- Namespace/name are preserved. The payload fields copied are `data`, `stringData`, `binaryData`, `type`, and `immutable` when present, not arbitrary source metadata. +- Copies carry the binding UID in `core.kbind.io/related-binding`. +- A target with a different or absent related-binding marker is left untouched, even under `conflictPolicy: Adopt`. These collisions are silently skipped and are not included in instance conflict counts. ---- -apiVersion: v1 -kind: Namespace -metadata: - name: kube-bind-hd73d-team1 +Related-resource sync runs in binding reconciliation, normally every 30 seconds, rather than using the instance watch path. Source changes may take that long to appear. ---- -apiVersion: provider.example.com/v1 -kind: MangoDB -metadata: - name: my-first-db - namespace: kube-bind-hd73d-team1 -spec: - size: large -``` +Copies belonging to the binding are deleted when they no longer match the current selector or when the binding is deleted. Source objects are not deleted. Use **one entry per resource kind and direction**: current garbage collection is keyed by binding UID and kind, not individual selector, so multiple entries for the same target kind/direction can delete each other's copies. Likewise, removing an entire entry does not run cleanup for that removed entry, clean up its copies before removing it. -!!! note - For natively namespaced resources (those that are namespaced in both the provider and consumer cluster), this is always the strategy being used by the konnector. The other isolation modes only influence how the konnector deals with cluster-scoped objects in the consumer cluster. +Related copies are not exempted by an instance's deletion policy. Namespace creation and source/target RBAC are still required. Review who can label provider Secrets before selecting them into consumers. -### Cluster-Scoped +## Heartbeat and disengagement -Cluster-scoped objects require a different approach to isolation than namespaced objects. kube-bind offers three different so-called isolation strategies to deal with them. The strategy to use is configured globally via the `--isolation` CLI flag on the kube-bind backend and will from there affect all services offered by that backend. +On a successful Connection reconciliation, normally every 30 seconds, the engine creates or renews a plain `coordination.k8s.io/v1` Lease on the provider: -#### None Strategy +- Namespace: the provider kubeconfig's current-context namespace, or `kbind` if unset. +- Name: Connection name plus `-` and the first ten characters of the local cluster UID. +- `holderIdentity`: the full consumer cluster UID. +- `leaseDurationSeconds`: `60`. +- Managed label and consumer-UID/Connection annotations. -The `none` strategy provides no consumer-separation at all. Any cluster-scoped object on the consumer side is copied 1:1 to the provider side. +This heartbeat is distinct from the konnector's consumer-side leader-election Lease. Heartbeat failure is best-effort: it does not block instance sync or make the Connection unready. The core neither reaps expired Leases nor garbage-collects abandoned consumers based on them, that requires an optional [backend](../developers/backend/index.md) reaper or your own operations. -!!! warning - Due to the obvious downsides of this approach, `none` should be used only in special circumstances. +When a Connection becomes not Ready, the provider cache is disengaged and its per-API instance syncers stop. When it becomes Ready again, syncers are rebuilt against the newly engaged provider. Objects and CRDs are not deleted merely because connectivity is lost. This is different from unbinding. -#### Prefixed Strategy +There is no `suspend` field. Do not use credential corruption as a pause mechanism. For planned downtime, stop the konnector and understand that existing finalizers remain, for permanent removal, use the cleanup sequence below. -The `prefixed` strategy is kube-bind's default strategy and will use the name of the cluster namespace as a prefix for object names. +## Unbinding and deletion -In YAML, this means +### Delete one consumer instance -```yaml -# consumer-side -apiVersion: provider.example.com/v1 -kind: MangoDB -metadata: - name: my-first-db -spec: - size: large -``` +The engine places `core.kbind.io/syncer` on the consumer instance before its first provider write. On normal deletion it: -will lead to +1. Reads the provider target and checks both ownership UIDs. +2. Deletes only a copy it owns. +3. Waits for the provider object to disappear before releasing the consumer finalizer. -```yaml -# provider-side -apiVersion: provider.example.com/v1 -kind: MangoDB -metadata: - name: kube-bind-hd73d-my-first-db -spec: - size: large +An unreachable provider or a provider-side finalizer can therefore hold normal instance deletion open. + +To keep an instance's provider copy, set the exact annotation value **before** deleting the consumer instance or unbinding: + +```bash +kubectl --context=consumer -n team-a annotate widget my-widget \ + core.kbind.io/deletion-policy=Orphan --overwrite ``` -This strategy works well for separating objects, but +`Orphan` releases the instance finalizer without deleting the provider copy. It does not remove the provider ownership markers and does not keep a consumer instance alive when its CRD is deleted. + +### Delete a binding + +Bindings use `core.kbind.io/cleanup`. Deleting one stops it being selected for new instance sync and runs cleanup: + +| Deleted object | Expected cleanup when no other binding lists the API | +| --- | --- | +| Namespaced Binding | Delete owned provider instance copies in that namespace, release consumer instance finalizers, retain the shared CRD and consumer instances. | +| ClusterBinding | Drain instances across the API, then delete the consumer CRD, which deletes its consumer instances. | +| Either | Delete owned related-resource copies for the currently declared related-resource entries. | -* requires a broad RBAC policy, which will always grant too many permissions, and -* would technically break for Kubernetes objects with names close to the maximum allowed length (253 characters). +**This is destructive for a last ClusterBinding**, including a CRD installed manually with `pullPolicy: None`. The cleanup path does not limit CRD deletion to schemas originally created by that binding. -#### Namespaced Strategy +Current cleanup limits: -!!! note - Not to be confused with the strategy used for natively namespaced resources, described earlier. +- If any other non-deleting binding anywhere lists the same API, cleanup skips that API as a whole. It does not calculate remaining namespace/Connection coverage. Overlapping bindings can therefore leave provider copies or consumer finalizers outside the remaining coverage. +- Instance cleanup is best-effort if credentials cannot be built or provider reads fail, provider copies may remain. Actual provider delete errors can still block cleanup. +- Unlike normal instance deletion, binding cleanup does not wait for every provider object's finalizers to finish after requesting deletion. +- Namespaces and heartbeat Leases are not removed. An unbound schema pulled only by `pullPolicy: All` is not automatically removed on Connection deletion. +- Editing `apis`, `connectionRef`, or related-resource entries is not a cleanup transaction for the previous spec. Remove old instances/copies deliberately before changing scope or provider. -The `namespaced` strategy will convert cluster-scoped objects into namespaced ones. +Back up resources, avoid overlapping ownership, and verify both sides after teardown. + +### Delete the Connection last + +Keep the controller running and credentials valid throughout: + +```bash +kubectl --context=consumer -n team-a delete bindings.core.kbind.io widgets --timeout=120s +kubectl --context=consumer delete connection provider --timeout=120s +kubectl --context=consumer -n kbind delete secret provider-kubeconfig +``` -For this to work, the original CRD on the provider cluster has to be **namespaced**. The backend will turn it into a cluster-scoped CRD (stored in the `BoundSchema`), so on the consumer cluster, all objects are cluster-scoped. +Use `delete clusterbinding` instead when that is what you created. -During synchronization, the konnector will then place each cluster-scoped object into the cluster namespace (`kube-bind-hd73d`) on the provider side. +A deleting Connection waits for **all referencing bindings** to disappear. It does not delete your explicit bindings, `Ready=False` with reason `DrainingBindings` means you must finish their teardown. A Connection with `autoBind: true` explicitly deletes its generated ClusterBinding as part of deletion. -This strategy provides excellent isolation between consumers, but requires that the original CRD from the provider still makes sense to the consumer when it's suddenly cluster-scoped. For example, if references were to be used, especially to Secrets in the same namespace, this concept would get mangled to some degree during the synchronization. +After references drain, the Connection releases its own cleanup finalizer and the credential Secret's finalizer, unless another active Connection references that Secret. Do not remove the konnector or the core CRDs before this completes. -!!! warning - At the moment, when the backend is started with `--isolation=namespaced`, it will convert **all namespaced CRDs** in all ServiceExports to become cluster-scoped on the consumer side, even if you intended for a namespaced CRD to stay namespaced on both sides of the sync. +Use `kubectl` for unbinding, the v2 CLI has no unbind command. Cleanup is implemented by these controllers. For stuck teardown, see [Troubleshooting](troubleshooting.md#deletion-is-stuck). diff --git a/docs/content/usage/troubleshooting.md b/docs/content/usage/troubleshooting.md new file mode 100644 index 000000000..2df9f4368 --- /dev/null +++ b/docs/content/usage/troubleshooting.md @@ -0,0 +1,165 @@ +# Troubleshooting + +Start with the Connection, then the binding, then actual instances. A running Pod or `Synced=True` binding alone does not prove that every object was delivered. + +Examples below use `consumer` and `provider` context names, replace them with yours. Do not include raw kubeconfigs, tokens, Secret contents, or unredacted connection details in bug reports. + +## Collect the current state + +```bash +kubectl --context=consumer get connections,clusterbindings +kubectl --context=consumer get bindings.core.kbind.io -A +kubectl --context=consumer get connection provider -o yaml +kubectl --context=consumer -n team-a get bindings.core.kbind.io widgets -o yaml +kubectl --context=consumer get crd widgets.example.org -o yaml +kubectl --context=consumer -n team-a describe widget my-widget +kubectl --context=consumer -n team-a get events --sort-by=.lastTimestamp +kubectl --context=consumer -n kbind logs \ + -l app.kubernetes.io/instance=konnector -c konnector --tail=200 +``` + +For the [Quickstart](../setup/quickstart.md), substitute Connection `demo-provider`, ClusterBinding `widgets`, and namespace `default`, logs are in the host konnector terminal. + +Record the image tag or source commit, Kubernetes versions, schema source/policies, condition reasons/messages, and a redacted minimal reproducer. + +## Connection does not become Ready + +| Symptom | What to check | +| --- | --- | +| `SecretValid=False`, reason `SecretNotFound` | The referenced Secret namespace/name/key, nonempty kubeconfig data, and parse errors in the condition message. The same reason is used for malformed or unusable kubeconfig, not only missing Secrets. | +| `Connected=False`, reason `Pending` | Provider endpoint reachability, TLS CA/server name, credential validity, and identity-read errors. | +| `PermissionDenied=True`, reason `Forbidden` | Provider identity/discovery RBAC. Test with the same identity as the Secret, not your administrator context. | +| `ClusterIdentityChanged` | The Secret now points to a different provider UID. Restore the original endpoint/credentials, or use a new Connection with deliberate migration. | +| `DrainingBindings` | The Connection is deleting but explicit referencing bindings still exist. Finish their cleanup first. | + +The API requires an explicit namespace in `kubeconfigSecretRef`, it does not infer the konnector namespace. An omitted key defaults to `kubeconfig`. + +To confirm a Secret exists without exposing its data: + +```bash +kubectl --context=consumer -n kbind get secret provider-kubeconfig \ + -o custom-columns=NAME:.metadata.name,TYPE:.type +``` + +A workstation kubeconfig using a local exec plugin or file paths may be unusable in the stock image. A short-lived bearer token can expire, the core does not renew it. + +For Pod deployments, verify the provider URL is reachable from the consumer network. `https://127.0.0.1:...` refers to the consumer Pod itself, not your workstation or a kind provider node. Fix the endpoint and certificate configuration instead of disabling TLS verification. + +`SchemaInSync` is defined in the API but not currently emitted by the Connection reconciler. Do not wait on that condition. + +## An API is missing or the binding says APINotExported + +For `schema.source: CRD`: + +```bash +kubectl --context=provider get crd widgets.example.org --show-labels +kubectl --context=provider get crds -l core.kbind.io/exported=true +kubectl --context=consumer get connection provider \ + -o jsonpath='{.status.activeSchemaSource}{"\n"}{.status.exportedAPIs}{"\n"}' +``` + +The provider CRD must be labelled `core.kbind.io/exported: "true"`. The binding API name must be the full plural/group name, such as `widgets.example.org`, not `Widget` or `example.org/v1`. + +Allow about 30 seconds for discovery. If provider credentials cannot list CRDs, `Auto` currently returns that error, it does not fall back on Forbidden. Use `OpenAPI` explicitly for a CRD-less provider. If an empty label selection should export nothing, use explicit `CRD`, because Auto can fall through to OpenAPI when a successful CRD list contains no exports. + +For `OpenAPI`, the provider must expose usable discovery and `/openapi/v3` schemas. Kubernetes built-in groups are excluded. Missing documents or unusable schemas can cause individual resources to be skipped. The label filter does not apply to this source. + +Removing an export label is not a credential revocation or guaranteed cleanup operation. Revoke access using provider authorization and unbind explicitly when retiring an API. + +## Binding is Ready but instances do not sync + +Check all of the following: + +1. The consumer CRD exists and is Established. +2. It has `core.kbind.io/managed: "true"` and `core.kbind.io/connection` naming the intended Connection. +3. That Connection is Ready and has nonempty identity UIDs. +4. A Ready binding covers the instance's namespace. A namespaced Binding cannot activate a cluster-scoped API. +5. No overlapping ClusterBinding takes precedence over the intended Binding. +6. Provider and consumer credentials have the required cluster-wide list/watch access. +7. Provider create/patch and namespace-create operations are allowed. +8. There is no foreign provider object or provider admission rejection. + +Read the ownership/conflict markers: + +```bash +kubectl --context=consumer -n team-a get widget my-widget \ + -o jsonpath='{.metadata.annotations.core\.kbind\.io/conflict}{"\n"}' +kubectl --context=provider -n team-a get widget my-widget -o yaml +``` + +`Synced=True` reports binding setup, not a per-instance acknowledgment. In particular, with CRD source and `pullPolicy: None`, a binding can currently report success even if the externally managed consumer CRD is absent. With OpenAPI source and `None`, a preinstalled CRD also needs management markers supplied by you. + +Instances keep their namespace/name. A kubeconfig context's namespace only sets the heartbeat namespace, it does not re-home objects. A provider credential scoped to a different namespace is not sufficient. + +Provider-side per-instance failures may appear as Warning Events or logs even while binding `PermissionDenied=False`. A namespaced Binding does not make the current dynamic informers namespace-scoped. + +After rotating a valid kubeconfig, an existing engaged client may still use its previous credentials. Restart the konnector and recheck actual delivery. With a chart deployment, use the deployment name from: + +```bash +kubectl --context=consumer -n kbind get deployment \ + -l app.kubernetes.io/instance=konnector +``` + +Then run `kubectl --context=consumer -n kbind rollout restart deployment/` and wait for the rollout. + +## Conflicts + +`ForeignObjectExists` means the provider target has no consumer ownership markers. `OwnedByAnother` means its markers do not match this consumer cluster and object UID. + +Inspect the provider target and determine which system should own it. If intentional, `conflictPolicy: Adopt` can take a markerless target, but may overwrite its fields. It never steals another marked object's ownership. Do not remove ownership annotations simply to force adoption. + +The consumer conflict annotation and Events are more reliable than a custom resource's `status.conditions`, which its schema may prune. Binding conflict counts normally refresh every 30 seconds and cover instance conflicts only. + +## Schema or status differs from the provider + +CRD-source pulls retain one version and remove conversion webhooks. OpenAPI synthesis does not faithfully reproduce all validation/defaulting, referenced schemas, conversion behavior, printer columns, or subresources. Neither path installs the provider's admission webhooks or controllers. + +Check: + +- The consumer CRD storage/served version and its status subresource/schema. +- Whether `updatePolicy: Once` intentionally pins a schema. +- Whether `pullPolicy: None` leaves updates to your external CRD manager. +- Whether you are using `OpenAPI + Bound`, which currently does not refresh an already-installed CRD under `Always`. +- Provider admission errors: local schema acceptance does not prove the provider accepts a spec. +- Whether the provider object has status at all. The demo has no real Widget controller, the quickstart patches status manually. + +The engine copies only bound instance `spec` up and `status` down, not arbitrary labels, annotations, or top-level payload fields. See [schema fidelity](api-concepts.md#schema-updates-and-fidelity). + +## Related resources do not appear + +Check the declared direction and source namespace. `FromProvider` means create the source on the provider, not on the consumer. The demo defines its source Secret/ConfigMap in `config/samples/provider-widget-crd.yaml`; apply that file on the provider. Apply `config/samples/widget.yaml` only on the consumer. See the [core-only example](gitops.md#try-the-core-without-a-backend) for commands that verify copying and ownership. + +Check selectors, source/target RBAC, and target ownership. A foreign Secret/ConfigMap is silently left untouched, `Adopt` and binding instance conflict counts do not apply to these collisions. Source labels are not copied to the target. + +Wait for the binding's periodic reconciliation, normally 30 seconds. An omitted selector matches every object in scope. Avoid multiple selectors represented as separate entries for the same resource/direction: their garbage collection can conflict. Removing a whole related-resource entry can leave its prior copies behind. + +If you narrowed chart `rbac.boundResourceGroups`, add the necessary related Secret/ConfigMap permissions explicitly. The fixed credential-Secret rule alone does not allow creation/deletion of synced Secret copies. + +## No heartbeat Lease + +Look in the provider kubeconfig context namespace, or `kbind` if unset: + +```bash +kubectl --context=provider get leases -A -l core.kbind.io/managed=true +``` + +Check Lease read/create/update and namespace permissions. Heartbeat errors do not make a healthy sync fail, the engine logs them at verbosity 2. `/readyz` is also only a process probe, not a heartbeat check. + +Core does not delete stale Leases or reap disconnected consumers. Those actions belong to the optional backend or your operations. + +## Deletion is stuck + +Keep the konnector running. Inspect `metadata.deletionTimestamp`, `metadata.finalizers`, Events, and controller logs on: + +- The consumer instance (`core.kbind.io/syncer`). +- Its provider copy, including provider-controller finalizers. +- The Binding/ClusterBinding (`core.kbind.io/cleanup`). +- The Connection and referenced Secret (`core.kbind.io/cleanup`). + +Normal instance deletion waits for the owned provider object to be gone. Restore provider access or resolve the provider controller's cleanup failure. If retaining the provider object is intentional, the [Orphan policy](synchronization.md#delete-one-consumer-instance) releases the consumer sync finalizer once the engine can reconcile it. + +A Connection waits for all explicit bindings referencing it, deleting only the Connection will not delete those bindings. Delete bindings first and let them finish, then the Connection, then its Secret. Stop the controller or uninstall Helm only afterward. + +Binding teardown is best-effort in some provider-read/credential failure cases, so a completed delete is not proof that every remote copy disappeared. Check the provider after cleanup. Overlapping bindings and in-place scope edits can also leave old copies/finalizers behind, see [cleanup limits](synchronization.md#delete-a-binding). + +Do not blindly strip finalizers or delete CRDs to unblock an operation. This bypasses ownership-aware cleanup and can lose consumer data or abandon provider resources. If the controller cannot be recovered, back up the affected resources, verify ownership and remote cleanup manually, and treat any finalizer removal as an explicit disaster-recovery action. diff --git a/docs/generators/cli-doc/go.mod b/docs/generators/cli-doc/go.mod deleted file mode 100644 index 5f3af5553..000000000 --- a/docs/generators/cli-doc/go.mod +++ /dev/null @@ -1,165 +0,0 @@ -module github.com/kube-bind/kube-bind/docs/generators/cli-doc - -go 1.26.9 - -replace ( - github.com/kube-bind/kube-bind => ../../../ - github.com/kube-bind/kube-bind/cli => ../../../cli - github.com/kube-bind/kube-bind/sdk => ../../../sdk -) - -require ( - github.com/kcp-dev/kcp v0.31.4 - github.com/kube-bind/kube-bind/cli v0.7.1 - github.com/spf13/cobra v1.10.2 -) - -require ( - al.essio.dev/pkg/shellescape v1.6.0 // indirect - dario.cat/mergo v1.0.2 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/BurntSushi/toml v1.6.0 // indirect - github.com/MakeNowJust/heredoc v1.0.0 // indirect - github.com/Masterminds/goutils v1.1.1 // indirect - github.com/Masterminds/semver/v3 v3.4.0 // indirect - github.com/Masterminds/sprig/v3 v3.3.0 // indirect - github.com/Masterminds/squirrel v1.5.4 // indirect - github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/blang/semver/v4 v4.0.0 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/chai2010/gettext-go v1.0.3 // indirect - github.com/clipperhouse/uax29/v2 v2.7.0 // indirect - github.com/containerd/containerd v1.7.36 // indirect - github.com/containerd/errdefs v1.0.0 // indirect - github.com/containerd/errdefs/pkg v0.3.0 // indirect - github.com/containerd/log v0.1.0 // indirect - github.com/containerd/platforms v0.2.1 // indirect - github.com/cyphar/filepath-securejoin v0.6.1 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/distribution/reference v0.6.0 // indirect - github.com/docker/go-connections v0.7.0 // indirect - github.com/docker/go-units v0.5.0 // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch v5.9.11+incompatible // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect - github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f // indirect - github.com/fatih/color v1.19.0 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-errors/errors v1.5.1 // indirect - github.com/go-gorp/gorp/v3 v3.1.0 // indirect - github.com/go-logr/logr v1.4.4 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.5 // indirect - github.com/go-openapi/swag v0.26.0 // indirect - github.com/go-openapi/swag/cmdutils v0.26.0 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.26.0 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect - github.com/gobwas/glob v0.2.3 // indirect - github.com/google/btree v1.1.3 // indirect - github.com/google/gnostic-models v0.7.1 // indirect - github.com/google/go-cmp v0.7.0 // indirect - github.com/google/uuid v1.6.0 // indirect - github.com/gosuri/uitable v0.0.4 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/huandu/xstrings v1.5.0 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/jmoiron/sqlx v1.4.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.18.5 // indirect - github.com/kube-bind/kube-bind v0.7.1 // indirect - github.com/kube-bind/kube-bind/sdk v0.7.1 // indirect - github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect - github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect - github.com/lib/pq v1.12.3 // indirect - github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/mattn/go-colorable v0.1.14 // indirect - github.com/mattn/go-isatty v0.0.21 // indirect - github.com/mattn/go-runewidth v0.0.23 // indirect - github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/go-wordwrap v1.0.1 // indirect - github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/moby/docker-image-spec v1.3.1 // indirect - github.com/moby/moby/api v1.54.2 // indirect - github.com/moby/moby/client v0.4.1 // indirect - github.com/moby/term v0.5.2 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect - github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect - github.com/muesli/reflow v0.3.0 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/onsi/gomega v1.39.1 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.1 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.20.1 // indirect - github.com/rubenv/sql-migrate v1.8.1 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect - github.com/shopspring/decimal v1.4.0 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect - github.com/spf13/cast v1.10.0 // indirect - github.com/spf13/pflag v1.0.10 // indirect - github.com/x448/float16 v0.8.4 // indirect - github.com/xlab/treeprint v1.2.0 // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect - go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.23.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/time v0.15.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect - google.golang.org/grpc v1.83.1 // indirect - google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect - gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect - gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - helm.sh/helm/v3 v3.20.2 // indirect - k8s.io/api v0.36.0 // indirect - k8s.io/apiextensions-apiserver v0.36.0 // indirect - k8s.io/apimachinery v0.36.0 // indirect - k8s.io/apiserver v0.36.0 // indirect - k8s.io/cli-runtime v0.36.0 // indirect - k8s.io/client-go v0.36.0 // indirect - k8s.io/component-base v0.36.0 // indirect - k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f // indirect - k8s.io/kubectl v0.36.0 // indirect - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 // indirect - oras.land/oras-go/v2 v2.6.2 // indirect - sigs.k8s.io/controller-runtime v0.23.3 // indirect - sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect - sigs.k8s.io/kind v0.31.0 // indirect - sigs.k8s.io/kustomize/api v0.21.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect - sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.0 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect -) diff --git a/docs/generators/cli-doc/go.sum b/docs/generators/cli-doc/go.sum deleted file mode 100644 index 7098b9a79..000000000 --- a/docs/generators/cli-doc/go.sum +++ /dev/null @@ -1,465 +0,0 @@ -al.essio.dev/pkg/shellescape v1.6.0 h1:NxFcEqzFSEVCGN2yq7Huv/9hyCEGVa/TncnOOBBeXHA= -al.essio.dev/pkg/shellescape v1.6.0/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= -dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= -dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= -github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= -github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= -github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= -github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= -github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= -github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= -github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= -github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= -github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= -github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM= -github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= -github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= -github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/bshuster-repo/logrus-logstash-hook v1.0.0 h1:e+C0SB5R1pu//O4MQ3f9cFuPGoOVeF2fE4Og9otCc70= -github.com/bshuster-repo/logrus-logstash-hook v1.0.0/go.mod h1:zsTqEiSzDgAa/8GZR7E1qaXrhYNDKBYy5/dWPTIflbk= -github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= -github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= -github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chai2010/gettext-go v1.0.3 h1:9liNh8t+u26xl5ddmWLmsOsdNLwkdRTg5AG+JnTiM80= -github.com/chai2010/gettext-go v1.0.3/go.mod h1:y+wnP2cHYaVj19NZhYKAwEMH2CI1gNHeQQ+5AjwawxA= -github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= -github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= -github.com/containerd/containerd v1.7.36 h1:HyMsOG5kmp1LQsGzqwI6Ts06T4VpYZbszfDZYB0bW5w= -github.com/containerd/containerd v1.7.36/go.mod h1:ozI//0TomTCLPhQREnx0IXDIQMg+Fk7yTtg9fNvU8EQ= -github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= -github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= -github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= -github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= -github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= -github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= -github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= -github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= -github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= -github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= -github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= -github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= -github.com/cyphar/filepath-securejoin v0.6.1 h1:5CeZ1jPXEiYt3+Z6zqprSAgSWiggmpVyciv8syjIpVE= -github.com/cyphar/filepath-securejoin v0.6.1/go.mod h1:A8hd4EnAeyujCJRrICiOWqjS1AX0a9kM5XL+NwKoYSc= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/distribution/distribution/v3 v3.0.0 h1:q4R8wemdRQDClzoNNStftB2ZAfqOiN6UX90KJc4HjyM= -github.com/distribution/distribution/v3 v3.0.0/go.mod h1:tRNuFoZsUdyRVegq8xGNeds4KLjwLCRin/tTo6i1DhU= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/docker-credential-helpers v0.8.2 h1:bX3YxiGzFP5sOXWc3bTPEXdEaZSeVMrFgOr3T+zrFAo= -github.com/docker/docker-credential-helpers v0.8.2/go.mod h1:P3ci7E3lwkZg6XiHdRKft1KckHiO9a2rNtyFbZ/ry9M= -github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= -github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= -github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8= -github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= -github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= -github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= -github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= -github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= -github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f h1:Wl78ApPPB2Wvf/TIe2xdyJxTlb6obmF18d8QdkxNDu4= -github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f/go.mod h1:OSYXu++VVOHnXeitef/D8n/6y4QV8uLHSFXX4NeXMGc= -github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= -github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/foxcpp/go-mockdns v1.2.0 h1:omK3OrHRD1IWJz1FuFBCFquhXslXoF17OvBS6JPzZF0= -github.com/foxcpp/go-mockdns v1.2.0/go.mod h1:IhLeSFGed3mJIAXPH2aiRQB+kqz7oqu8ld2qVbOu7Wk= -github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= -github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= -github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs= -github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= -github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= -github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= -github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= -github.com/go-openapi/swag v0.26.0 h1:GVDXCmfvhfu1BxiHo8/FA+BbKmhecHnG3varjON5/RI= -github.com/go-openapi/swag v0.26.0/go.mod h1:82g3193sZJRbocs7bNCqGfIgq8pkuwVwCfhKIRlEQF0= -github.com/go-openapi/swag/cmdutils v0.26.0 h1:iowihOcvq7y4egO8cOq0dmfohz6wfeQ63U1EnuhO2TU= -github.com/go-openapi/swag/cmdutils v0.26.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.26.0 h1:CmZp+ZT7HrmFwrC3GdGsXBq2+42T1bjKBapcqVpIs3c= -github.com/go-openapi/swag/netutils v0.26.0/go.mod h1:5iK+Ok3ZohWWex1C50BFTPexi03UaPwjW4Oj8kgrpwo= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= -github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= -github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= -github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= -github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= -github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= -github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= -github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE= -github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gosuri/uitable v0.0.4 h1:IG2xLKRvErL3uhY6e1BylFzG+aJiwQviDDTfOKeKTpY= -github.com/gosuri/uitable v0.0.4/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/golang-lru/arc/v2 v2.0.5 h1:l2zaLDubNhW4XO3LnliVj0GXO3+/CGNJAg1dcN2Fpfw= -github.com/hashicorp/golang-lru/arc/v2 v2.0.5/go.mod h1:ny6zBSQZi2JxIeYcv7kt2sH2PXJtirBN7RDhRpxPkxU= -github.com/hashicorp/golang-lru/v2 v2.0.5 h1:wW7h1TG88eUIJ2i69gaE3uNVtEPIagzhGvHgwfx2Vm4= -github.com/hashicorp/golang-lru/v2 v2.0.5/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= -github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= -github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= -github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kcp-dev/kcp v0.31.4 h1:OIy9ULzc7VBnieoAWfPcXpH/jRQwSdaYGQXQA6atyUQ= -github.com/kcp-dev/kcp v0.31.4/go.mod h1:V/JPoevUr3ihiXEAmJ6JG1MdyeNzfHRthffxywMWYfU= -github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= -github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -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= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw= -github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= -github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= -github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= -github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= -github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= -github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= -github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= -github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw= -github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= -github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= -github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= -github.com/miekg/dns v1.1.57 h1:Jzi7ApEIzwEPLHWRcafCN9LZSBbqQpxjt/wpgvg7wcM= -github.com/miekg/dns v1.1.57/go.mod h1:uqRjCRUuEAA6qsOiJvDd+CFo/vW+y5WR6SNmHE55hZk= -github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= -github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= -github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= -github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= -github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= -github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg= -github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= -github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY= -github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ= -github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= -github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= -github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= -github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/onsi/ginkgo/v2 v2.28.1 h1:S4hj+HbZp40fNKuLUQOYLDgZLwNUVn19N3Atb98NCyI= -github.com/onsi/ginkgo/v2 v2.28.1/go.mod h1:CLtbVInNckU3/+gC8LzkGUb9oF+e8W8TdUsxPwvdOgE= -github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= -github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= -github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= -github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= -github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5 h1:Ii+DKncOVM8Cu1Hc+ETb5K+23HdAMvESYE3ZJ5b5cMI= -github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0/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/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= -github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= -github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= -github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5 h1:EaDatTxkdHG+U3Bk4EUr+DZ7fOGwTfezUiUJMaIcaho= -github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5/go.mod h1:fyalQWdtzDBECAQFBJuQe5bzQ02jGd5Qcbgb97Flm7U= -github.com/redis/go-redis/extra/redisotel/v9 v9.0.5 h1:EfpWLLCyXw8PSM2/XNJLjI3Pb27yVE+gIAfeqp8LUCc= -github.com/redis/go-redis/extra/redisotel/v9 v9.0.5/go.mod h1:WZjPDy7VNzn77AAfnAfVjZNvfJTYfPetfZk5yoSTLaQ= -github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= -github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/rubenv/sql-migrate v1.8.1 h1:EPNwCvjAowHI3TnZ+4fQu3a915OpnQoPAjTXCGOy2U0= -github.com/rubenv/sql-migrate v1.8.1/go.mod h1:BTIKBORjzyxZDS6dzoiw6eAFYJ1iNlGAtjn4LGeVjS8= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ= -github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= -github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= -github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= -github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= -github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= -github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= -github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= -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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= -github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= -github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= -go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/bridges/prometheus v0.57.0 h1:UW0+QyeyBVhn+COBec3nGhfnFe5lwB0ic1JBVjzhk0w= -go.opentelemetry.io/contrib/bridges/prometheus v0.57.0/go.mod h1:ppciCHRLsyCio54qbzQv0E4Jyth/fLWDTJYfvWpcSVk= -go.opentelemetry.io/contrib/exporters/autoexport v0.57.0 h1:jmTVJ86dP60C01K3slFQa2NQ/Aoi7zA+wy7vMOKD9H4= -go.opentelemetry.io/contrib/exporters/autoexport v0.57.0/go.mod h1:EJBheUMttD/lABFyLXhce47Wr6DPWYReCzaZiXadH7g= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.8.0 h1:WzNab7hOOLzdDF/EoWCt4glhrbMPVMOO5JYTmpz36Ls= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.8.0/go.mod h1:hKvJwTzJdp90Vh7p6q/9PAOd55dI6WA6sWj62a/JvSs= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.8.0 h1:S+LdBGiQXtJdowoJoQPEtI52syEP/JYBUpjO49EQhV8= -go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.8.0/go.mod h1:5KXybFvPGds3QinJWQT7pmXf+TN5YIa7CNYObWRkj50= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.32.0 h1:j7ZSD+5yn+lo3sGV69nW04rRR0jhYnBwjuX3r0HvnK0= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.32.0/go.mod h1:WXbYJTUaZXAbYd8lbgGuvih0yuCfOFC5RJoYnoLcGz8= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.32.0 h1:t/Qur3vKSkUCcDVaSumWF2PKHt85pc7fRvFuoVT8qFU= -go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.32.0/go.mod h1:Rl61tySSdcOJWoEgYZVtmnKdA0GeKrSqkHC1t+91CH8= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0 h1:cMyu9O88joYEaI47CnQkxO1XZdpoTF9fEnW2duIddhw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0/go.mod h1:6Am3rn7P9TVVeXYG+wtcGE7IE1tsQ+bP3AuWcKt/gOI= -go.opentelemetry.io/otel/exporters/prometheus v0.54.0 h1:rFwzp68QMgtzu9PgP3jm9XaMICI6TsofWWPcBDKwlsU= -go.opentelemetry.io/otel/exporters/prometheus v0.54.0/go.mod h1:QyjcV9qDP6VeK5qPyKETvNjmaaEc7+gqjh4SS0ZYzDU= -go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.8.0 h1:CHXNXwfKWfzS65yrlB2PVds1IBZcdsX8Vepy9of0iRU= -go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.8.0/go.mod h1:zKU4zUgKiaRxrdovSS2amdM5gOc59slmo/zJwGX+YBg= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.32.0 h1:SZmDnHcgp3zwlPBS2JX2urGYe/jBKEIT6ZedHRUyCz8= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.32.0/go.mod h1:fdWW0HtZJ7+jNpTKUR0GpMEDP69nR8YBJQxNiVCE3jk= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.32.0 h1:cC2yDI3IQd0Udsux7Qmq8ToKAx1XCilTQECZ0KDZyTw= -go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.32.0/go.mod h1:2PD5Ex6z8CFzDbTdOlwyNIUywRr1DN0ospafJM1wJ+s= -go.opentelemetry.io/otel/log v0.8.0 h1:egZ8vV5atrUWUbnSsHn6vB8R21G2wrKqNiDt3iWertk= -go.opentelemetry.io/otel/log v0.8.0/go.mod h1:M9qvDdUTRCopJcGRKg57+JSQ9LgLBrwwfC32epk5NX8= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/log v0.8.0 h1:zg7GUYXqxk1jnGF/dTdLPrK06xJdrXgqgFLnI4Crxvs= -go.opentelemetry.io/otel/sdk/log v0.8.0/go.mod h1:50iXr0UVwQrYS45KbruFrEt4LvAdCaWWgIrsN3ZQggo= -go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= -go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.3.1-0.20251210191316-2b7fd8a0d244 h1:OdZ8e4E9yDUGiis9x2ta/Ec5yhMAKT6ZivRvakyxC7E= -go.uber.org/goleak v1.3.1-0.20251210191316-2b7fd8a0d244/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= -go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= -go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -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/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -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/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -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/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= -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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= -google.golang.org/genproto v0.0.0-20231211222908-989df2bf70f3 h1:1hfbdAfFbkmpg41000wDVqr7jUpK/Yo+LPnIxxGzmkg= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= -google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= -gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= -gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= -gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= -helm.sh/helm/v3 v3.20.2 h1:binM4rvPx5DcNsa1sIt7UZi55lRbu3pZUFmQkSoRh48= -helm.sh/helm/v3 v3.20.2/go.mod h1:Fl1kBaWCpkUrM6IYXPjQ3bdZQfFrogKArqptvueZ6Ww= -k8s.io/api v0.36.0 h1:SgqDhZzHdOtMk40xVSvCXkP9ME0H05hPM3p9AB1kL80= -k8s.io/api v0.36.0/go.mod h1:m1LVrGPNYax5NBHdO+QuAedXyuzTt4RryI/qnmNvs34= -k8s.io/apiextensions-apiserver v0.36.0 h1:Wt7E8J+VBCbj4FjiBfDTK/neXDDjyJVJc7xfuOHImZ0= -k8s.io/apiextensions-apiserver v0.36.0/go.mod h1:kGDjH0msuiIB3tgsYRV0kS9GqpMYMUsQ3GHv7TApyug= -k8s.io/apimachinery v0.36.0 h1:jZyPzhd5Z+3h9vJLt0z9XdzW9VzNzWAUw+P1xZ9PXtQ= -k8s.io/apimachinery v0.36.0/go.mod h1:FklypaRJt6n5wUIwWXIP6GJlIpUizTgfo1T/As+Tyxc= -k8s.io/apiserver v0.36.0 h1:Jg5OFAENUACByUCg15CmhZAYrr5ZyJ+jodyA1mHl3YE= -k8s.io/apiserver v0.36.0/go.mod h1:mHvwdHf+qKEm+1/hYm756SV+oREOKSPnsjagOpx6Vho= -k8s.io/cli-runtime v0.36.0 h1:HNxciQpQMMOKS0/GiUXcKDyA6J2FDILJj9NmP2BZrTg= -k8s.io/cli-runtime v0.36.0/go.mod h1:KObkknK9Ro5LYX+1RdiKc7C8CvGg4aX+V/Zv+E8WPHA= -k8s.io/client-go v0.36.0 h1:pOYi7C4RHChYjMiHpZSpSbIM6ZxVbRXBy7CuiIwqA3c= -k8s.io/client-go v0.36.0/go.mod h1:ZKKcpwF0aLYfkHFCjillCKaTK/yBkEDHTDXCFY6AS9Y= -k8s.io/component-base v0.36.0 h1:hFjEktssxiJhrK1zfybkH4kJOi8iZuF+mIDCqS5+jRo= -k8s.io/component-base v0.36.0/go.mod h1:JZvIfcNHk+uck+8LhJzhSBtydWXaZNQwX2OdL+Mnwsk= -k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= -k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f h1:4Qiq0YAoQATdgmHALJWz9rJ4fj20pB3xebpB4CFNhYM= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/kubectl v0.36.0 h1:hEGr8NvIm2Wjqs2Xy48Uzmvo6lpHdGKlLyMvau2gTms= -k8s.io/kubectl v0.36.0/go.mod h1:iDe8aV5BEi45W8k+5n71I2pJ/nwE0PHDu+/2cejzYoo= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -oras.land/oras-go/v2 v2.6.2 h1:N04RXngAp1LJKTG6ifz3xHPipasEkWr+hFmInja5YKo= -oras.land/oras-go/v2 v2.6.2/go.mod h1:PlTtg4JTDJkDe8yVHpM2wz7/YDc00GVas+i4jAW2TZ4= -pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= -pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/controller-runtime v0.23.3 h1:VjB/vhoPoA9l1kEKZHBMnQF33tdCLQKJtydy4iqwZ80= -sigs.k8s.io/controller-runtime v0.23.3/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kind v0.31.0 h1:UcT4nzm+YM7YEbqiAKECk+b6dsvc/HRZZu9U0FolL1g= -sigs.k8s.io/kind v0.31.0/go.mod h1:FSqriGaoTPruiXWfRnUXNykF8r2t+fHtK0P0m1AbGF8= -sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= -sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= -sigs.k8s.io/kustomize/kyaml v0.21.1 h1:IVlbmhC076nf6foyL6Taw4BkrLuEsXUXNpsE+ScX7fI= -sigs.k8s.io/kustomize/kyaml v0.21.1/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= -sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= -sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0 h1:qmp2e3ZfFi1/jJbDGpD4mt3wyp6PE1NfKHCYLqgNQJo= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= -sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= -sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/docs/generators/cli-doc/main.go b/docs/generators/cli-doc/main.go index 2f7eaf24a..bb88a5963 100644 --- a/docs/generators/cli-doc/main.go +++ b/docs/generators/cli-doc/main.go @@ -1,5 +1,5 @@ /* -Copyright 2024 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,45 +17,57 @@ limitations under the License. package main import ( - "flag" "fmt" - "log" - "os" + "html" + "strings" - "github.com/kcp-dev/kcp/hack/third_party/github.com/spf13/cobra/doc" "github.com/spf13/cobra" - bindcmd "github.com/kube-bind/kube-bind/cli/cmd/kubectl-bind/cmd" - "github.com/kube-bind/kube-bind/cli/pkg/help" + bindcmd "github.com/kbind/kbind/cli/cmd" ) func main() { - output := flag.String("output", "", "Path to output directory") - flag.Parse() + root := bindcmd.New() + root.InitDefaultHelpFlag() + root.InitDefaultVersionFlag() + fmt.Println("# CLI Reference") + fmt.Println("\nGenerated from this checkout's CLI commands. Examples use the `kubectl bind` plugin. See [plugin installation](../../setup/kubectl-plugin.md).") + fmt.Println("\nBundle output contains provider credentials: encrypt it or use a secret manager, never commit plaintext to git. Override `--konnector-image` with an explicit v2 image, the compiled `latest` default is not a v2 guarantee.") + render(root) +} - if output == nil || *output == "" { - fmt.Fprintln(os.Stderr, "output is required") - os.Exit(1) +func render(command *cobra.Command) { + fmt.Printf("\n## kubectl %s\n\n", command.CommandPath()) + description := command.Long + if description == "" { + description = command.Short } - - if err := os.MkdirAll(*output, 0755); err != nil { - log.Fatalf("Failed to re-create docs directory: %v", err) + fmt.Println(formatDescription(description)) + if command.Example != "" { + fmt.Printf("\n```bash\n%s\n```\n", strings.TrimSpace(command.Example)) } - - rootCmd := bindcmd.KubectlBindCommand() - - // remove the indentation for examples, as they look weird in the rendered markdown - unindentExamples(rootCmd) - - if err := doc.GenMarkdownTree(rootCmd, *output); err != nil { - log.Fatalf("Failed to generate docs: %v", err) + command.InitDefaultHelpFlag() + fmt.Printf("\n```text\n%s```\n", command.UsageString()) + for _, child := range command.Commands() { + if !child.Hidden { + render(child) + } } } -func unindentExamples(cmd *cobra.Command) { - cmd.Example = help.RemoveIndentation(cmd.Example) - - for _, child := range cmd.Commands() { - unindentExamples(child) +func formatDescription(description string) string { + var paragraphs []string + for _, paragraph := range strings.Split(strings.Trim(description, "\n"), "\n\n") { + indent := paragraph[:len(paragraph)-len(strings.TrimLeft(paragraph, " \t"))] + if len(indent) >= 2 || strings.Contains(indent, "\t") { + lines := strings.Split(paragraph, "\n") + for i := range lines { + lines[i] = strings.TrimPrefix(lines[i], indent) + } + paragraphs = append(paragraphs, "```bash\n"+strings.Join(lines, "\n")+"\n```") + } else { + paragraphs = append(paragraphs, html.EscapeString(strings.Join(strings.Fields(paragraph), " "))) + } } + return strings.Join(paragraphs, "\n\n") } diff --git a/docs/generators/cli-doc/main_test.go b/docs/generators/cli-doc/main_test.go new file mode 100644 index 000000000..9ecbf24c3 --- /dev/null +++ b/docs/generators/cli-doc/main_test.go @@ -0,0 +1,65 @@ +/* +Copyright 2026 The kbind 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 main + +import "testing" + +func TestFormatDescription(t *testing.T) { + tests := []struct { + name string + description string + want string + }{ + { + name: "wrapped prose", + description: "Connect to a provider\nand bind its APIs.", + want: "Connect to a provider and bind its APIs.", + }, + { + name: "paragraph spacing", + description: "\nFirst paragraph.\n\nSecond\nparagraph.\n", + want: "First paragraph.\n\nSecond paragraph.", + }, + { + name: "literal placeholders", + description: "Run kubectl bind export .", + want: "Run kubectl bind export <name>.", + }, + { + name: "indented commands", + description: "Examples:\n\n kubectl bind catalog\n kubectl bind export widgets # keep spacing", + want: "Examples:\n\n```bash\nkubectl bind catalog\nkubectl bind export widgets # keep spacing\n```", + }, + { + name: "tab indented command", + description: "\tkubectl bind catalog", + want: "```bash\nkubectl bind catalog\n```", + }, + { + name: "empty", + description: "", + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := formatDescription(tt.description); got != tt.want { + t.Errorf("formatDescription() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/docs/generators/crd-ref/config.yaml b/docs/generators/crd-ref/config.yaml index 1fde36617..c4801a197 100644 --- a/docs/generators/crd-ref/config.yaml +++ b/docs/generators/crd-ref/config.yaml @@ -1,76 +1,7 @@ -# Copyright 2021 The Kube Bind 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. - -template_path: ./crd.template.md - -source_repositories: - - url: https://github.com/kube-bind/kube-bind - organization: kube-bind - short_name: kube-bind - commit_reference: main - crd_paths: - - deploy/crd - cr_paths: - - docs/cr - metadata: - apiservicebindings.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - apiserviceexportrequests.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - apiserviceexports.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - apiservicenamespaces.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - clusterbindings.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - apiconversions.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - apiserviceexporttemplates.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - bindableresourcesrequests.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - boundschemas.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis - collections.kube-bind.io: - owner: - - https://github.com/kube-bind/kube-bind - topics: - - apis +processor: + ignoreTypes: + - "List$" + ignoreFields: + - "TypeMeta$" +render: + kubernetesVersion: "1.33" diff --git a/docs/generators/crd-ref/crd.template.md b/docs/generators/crd-ref/crd.template.md deleted file mode 100644 index 7ac1aa503..000000000 --- a/docs/generators/crd-ref/crd.template.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: {{ .Title }} -description: | -{{- if .Description }} -{{ .Description | indent 2 }} -{{- else }} - Custom resource definition (CRD) schema reference page for the {{ .Title }} - resource ({{ .NamePlural }}.{{ .Group }}), as part of the Giant Swarm - Management API documentation. -{{- end }} -weight: {{ .Weight }} ---- - -{{- with .Metadata.Deprecation }} -{{ "{{" }}% pageinfo color="warning" %{{ "}}"}} -{{- with .Info }} -{{ . }} -{{- end }} -{{- with .ReplacedBy }} -This CRD is being replaced by {{ .ShortName }}. -{{- end }} -{{"{{% /pageinfo %}}"}} -{{- end }} - -## {{ .Title }} CRD schema reference (group {{ .Group }}) -
{{`{{`}} page.meta.description {{`}}`}}
- -
-
Full name:
-
{{ .NamePlural }}.{{ .Group }}
-
Group:
-
{{ .Group }}
-
Singular name:
-
{{ .NameSingular }}
-
Plural name:
-
{{ .NamePlural }}
-
Scope:
-
{{ .Scope }}
-
Versions:
-
-{{- range .Versions -}} -{{.}} -{{- end -}} -
-
- -{{ if .VersionSchemas }} -{{ $versionSchemas := .VersionSchemas }} -{{ range .Versions -}} -{{ $versionName := . -}} -{{ $versionSchema := (index $versionSchemas $versionName) -}} -
-

Version {{$versionName}}

- -{{ with $versionSchema.ExampleCR }} -

Example CR

- -```yaml -{{ .|raw -}} -``` - -{{end}} - -

Properties

- -{{ range $versionSchema.Properties }} -
-
-

{{.Path}}

-
-
-
-{{with .Type}}{{.}}{{end}} -{{ if not .Required }} -{{ else -}} -Required -{{ end -}} -
-{{with .Description}} -
-{{.|markdown}} -
-{{end}} -
-
-{{ end }} - -{{ if $versionSchema.Annotations }} -

Annotations

- -{{ range $versionSchema.Annotations }} -
-
-

{{.Annotation}}

-
-
-
-{{with .Release}}{{.}}{{end}} -
-{{with .Documentation}} -
-{{.|markdown}} -
-{{end}} -
-
-{{ end }} -{{ end }} - -
-{{end}} - -{{ else }} -
-

We currently cannot show any schema information on this CRD. Sorry for the inconvenience!

-

Please refer to the Godoc or source for details.

-
-{{ end }} diff --git a/docs/generators/crd-ref/run-crd-ref-gen.sh b/docs/generators/crd-ref/run-crd-ref-gen.sh deleted file mode 100755 index 7137c5af4..000000000 --- a/docs/generators/crd-ref/run-crd-ref-gen.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2024 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail -set -o xtrace - -REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd) - -CONTAINER_ENGINE=${CONTAINER_ENGINE:-docker} -CRD_DOCS_GENERATOR_VERSION=0.10.0 - -#TODO(ncdc): i18n -DESTINATION="${REPO_ROOT}/docs/content/reference/crd" -mkdir -p "${DESTINATION}" - -BIND_MOUNT_OPTS=":z" -if [[ $(uname -s) == "Darwin" ]]; then - BIND_MOUNT_OPTS="" -fi - -# Generate new content -$CONTAINER_ENGINE run --rm \ - -v "${DESTINATION}":/opt/crd-docs-generator/output"${BIND_MOUNT_OPTS}" \ - -v "${REPO_ROOT}"/docs/generators/crd-ref:/opt/crd-docs-generator/config"${BIND_MOUNT_OPTS}" \ - quay.io/giantswarm/crd-docs-generator:${CRD_DOCS_GENERATOR_VERSION} \ - --config /opt/crd-docs-generator/config/config.yaml - -# Organise CRDs by API group -for file in ${DESTINATION}/*.md; do - filename=$(basename $file) - apigroup=$(basename $filename .md | cut -d. -f2-) - crdname=$(basename $filename .md | cut -d. -f1) - echo "${filename} | ${apigroup}" - - mkdir -p "${DESTINATION}/${apigroup}" - mv "${file}" "${DESTINATION}/${apigroup}/${crdname}.md" -done - -# Generate a .pages config file to override title case being applied to -# folder names by default (https://github.com/mkdocs/mkdocs/issues/2086) -echo "nav:" > ${DESTINATION}/.pages -for dir in ${DESTINATION}/*/; do - if [ -d "${dir}" ]; then - echo ${dir} - fi - apigroup=$(basename $dir) - echo " - ${apigroup}: ${apigroup}" >> ${DESTINATION}/.pages -done diff --git a/docs/images/manifesto.png b/docs/images/manifesto.png deleted file mode 100644 index ddb26b688..000000000 Binary files a/docs/images/manifesto.png and /dev/null differ diff --git a/docs/images/overview.png b/docs/images/overview.png deleted file mode 100644 index 12217eb29..000000000 Binary files a/docs/images/overview.png and /dev/null differ diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 0c49ca305..1247eed70 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,4 +1,5 @@ site_name: kbind +site_description: "kbind v2: bind provider APIs into consumer Kubernetes clusters." repo_url: https://github.com/kbind-dev/kbind repo_name: kbind-dev/kbind site_url: https://docs.kbind.dev/ @@ -7,6 +8,7 @@ site_url: https://docs.kbind.dev/ docs_dir: "content" # Where to generate site_dir: "generated" +strict: true theme: name: material @@ -72,6 +74,7 @@ plugins: - social: cards_layout: default/variant cards_layout_options: + logo: overrides/logo.png background_color: "#1a1a1a" color: "#ffffff" font_family: Roboto @@ -134,3 +137,8 @@ watch: - mkdocs.yml - content - overrides + +validation: + links: + not_found: warn + anchors: warn diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 000000000..85a98c41a --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1,6 @@ +{% extends "base.html" %} + +{% block announce %} + This is the v2 development preview, not the default release. + Read the stable 0.x documentation. +{% endblock %} diff --git a/docs/proposals/backend-only-bindings.md b/docs/proposals/backend-only-bindings.md deleted file mode 100644 index 2a5fee69c..000000000 --- a/docs/proposals/backend-only-bindings.md +++ /dev/null @@ -1,114 +0,0 @@ -# Backend-Only Bindings - -**Status**: Implemented -**Date**: January 2025 - -## Problem - -Traditional kube-bind requires OIDC authentication and manual web UI interaction to bind services. This doesn't work for: -- CI/CD pipelines and automation -- Headless servers -- GitOps workflows - -## Solution - -**APIServiceBindingBundle**: A single resource that automatically discovers and binds ALL services from a provider cluster using only a kubeconfig. - -**One command instead of a multi-step handshake:** - -```bash -kubectl create secret generic provider-kubeconfig \ - --from-file=kubeconfig=provider.kubeconfig - -kubectl apply -f - < **2026-07-29 update.** The slim core shipped under a new identity: the project is +> **kbind** (`github.com/kbind/kbind`, API group `core.kbind.io`), the `v2/` prefix is +> gone (the konnector module IS the repo root, v1 was deleted). Everything below is +> normalized to that reality: groups are `catalog.kbind.io` / `iam.kbind.io`, the CLI is +> `kbind`, the backend binary is `kbind-backend`, and the Packaging section describes the +> root layout. Additional implementation decisions are logged in **Decided**. ## Summary The v2 core contract is up for discussion: a binding is one `kubectl apply` of a Secret + -`Connection` + bindings, consumed by the konnector, with zero kbind components on -the provider. This proposal designs everything *around* that contract — the optional +`Connection` + bindings, consumed by the konnector, with zero kube-bind components on +the provider. This proposal designs everything *around* that contract, the optional service layer that answers the questions the core deliberately doesn't: * **Who are you?** (auth: OIDC, sessions) @@ -20,7 +27,7 @@ service layer that answers the questions the core deliberately doesn't: * **Make it pleasant.** (CLI, UI) The defining rule, inherited from the core: **every path through this layer terminates -in the same one-apply bundle.** The service layer negotiates; it never syncs. If the +in the same one-apply bundle.** The service layer negotiates, it never syncs. If the backend is deleted the day after binding, sync is unaffected. ``` @@ -39,20 +46,20 @@ backend is deleted the day after binding, sync is unaffected. ## Goals -* Every component independently deployable and optional; any subset works. The core +* Every component independently deployable and optional, any subset works. The core (GitOps-only, no extended layer at all) remains a first-class path forever. -* The backend's terminal output is **exactly** the core's one-apply bundle — no +* The backend's terminal output is **exactly** the core's one-apply bundle, no intermediate request/response CRDs on the consumer, no phase-gated handshake. * Tenancy lives here: per-consumer provider namespaces / kcp workspaces are an issuer concern, invisible to the core (which just sees a kubeconfig whose RBAC fences it in). -* Pluggable auth from day one — OIDC is the reference implementation, not the contract. +* Pluggable auth from day one, OIDC is the reference implementation, not the contract. * HA-capable by construction (the v1 in-memory-session/single-replica limitation, roadmap #424/#488, must not survive into v2). ## Non-Goals -* Anything that changes core sync semantics — the core contract is immutable, this layer must adapt around it. -* Marketplace/billing/quotas (a future layer above this one; the catalog leaves room). +* Anything that changes core sync semantics, the core contract is immutable, this layer must adapt around it. +* Marketplace/billing/quotas (a future layer above this one, the catalog leaves room). * Re-implementing v1's wire protocol (`BindingProvider`, `BindingResourceResponse`, `APIServiceExportRequest` flow). v2 extended is a clean protocol. @@ -64,11 +71,11 @@ Raw discovery already exists in core (`Connection.status.exportedAPIs` from labe CRDs / the workspace boundary). The catalog adds **curation**: human-facing metadata and sensible defaults that turn "a list of CRD names" into "a service you'd choose". -Group: `catalog.kbind.dev`. Two kinds, successors of v1's +Group: `catalog.kbind.io`. Two kinds, successors of v1's `APIServiceExportTemplate` and `Collection`: ```yaml -apiVersion: catalog.kbind.dev/v1alpha1 +apiVersion: catalog.kbind.io/v1alpha1 kind: Export # one offering metadata: name: mangodb @@ -93,7 +100,7 @@ spec: ``` ```yaml -apiVersion: catalog.kbind.dev/v1alpha1 +apiVersion: catalog.kbind.io/v1alpha1 kind: Collection # grouping for UI/CLI browsing metadata: name: databases @@ -106,7 +113,7 @@ spec: Notes: * The catalog is **derived-from-core-truth**: an `Export` listing an API that isn't - actually exported (label/boundary) gets a condition; the gateway hides it. The label + actually exported (label/boundary) gets a condition, the gateway hides it. The label remains the source of truth, the catalog is presentation + defaults. * These CRDs live on the provider and are read only by the gateway/UI/CLI. The konnector never sees them. @@ -114,28 +121,28 @@ Notes: ### 2. Issuer (provider-side controller) Everything v1's `backend/kubernetes` did, made a named component. The issuer is a Go -interface (provision boundary, mint credentials, revoke); **the in-tree implementation -is plain Kubernetes only** — the kcp issuer lives in the separate `contrib/kcp` +interface (provision boundary, mint credentials, revoke), **the in-tree implementation +is plain Kubernetes only**, the kcp issuer lives in the separate `contrib/kcp` distribution, which wires its own implementation against the same interface. -* Per consumer identity: provision the tenancy boundary — a namespace set on plain +* Per consumer identity: provision the tenancy boundary, a namespace set on plain Kubernetes (workspaces, in the contrib/kcp issuer). * Mint credentials: ServiceAccount + RBAC scoped to exactly the exported APIs (+ declared related resources) within that boundary + kubeconfig. This fixes v1's cluster-admin-ish `kube-binder` ClusterRole (roadmap #303: reduced footprint). On a plain-Kubernetes provider "scoped to the exported APIs" is an explicit Role enumerating - those resources; on the kcp/CRD-less flavor the tenancy boundary *is* the workspace, so + those resources, on the kcp/CRD-less flavor the tenancy boundary *is* the workspace, so scoping is the workspace grant itself (everything in it is exported by construction) - rather than a per-resource enumeration — same `Issuer` interface, two scoping mechanisms + rather than a per-resource enumeration, same `Issuer` interface, two scoping mechanisms matching the core's two schema sources. * **Credential mechanism: long-lived SA token** (v1 behavior, secret-based ServiceAccount token). Trade-off accepted deliberately: zero rotation friction and no - konnector-side refresh machinery, at the cost of security posture — and noting + konnector-side refresh machinery, at the cost of security posture, and noting upstream Kubernetes is steering away from secret-based SA tokens, so this is - revisitable without API change (the bundle's Secret is replaceable; a bounded-token + + revisitable without API change (the bundle's Secret is replaceable, a bounded-token + reissue mode can be added later behind the same interface). Revocation = delete the `Grant` → issuer deletes the SA/token. -* Records issuance in **`Grant`** (`iam.kbind.dev` — an issuance/identity record, not +* Records issuance in **`Grant`** (`iam.kbind.io`, an issuance/identity record, not catalog presentation): "identity X was issued credentials Y for export Z". The anchor for revocation, audit, and the reaper. @@ -143,7 +150,7 @@ distribution, which wires its own implementation against the same interface. Stateless HTTP server (sessions externalized), serving: -One gateway fronts exactly **one provider** — catalog aggregation across providers is a +One gateway fronts exactly **one provider**, catalog aggregation across providers is a future layer above this one, already possible externally because the protocol's output is just a bundle. @@ -152,15 +159,15 @@ is just a bundle. | `GET /api/provider` | provider metadata + supported auth methods (successor of v1 `/api/exports`) | | `GET /api/catalog` | `Export`s + `Collection`s visible to the caller | | `POST /api/bind` | input: export name + consumer identity → drives issuer → returns a **one-time pickup URL** for the bundle | -| `GET /api/bundle/` | single-use, short-TTL (5 min) bundle pickup — **returns the bundle**, then the token is dead | -| `POST /api/apply` | optional, flag-gated: browser-apply path — gateway applies the bundle (+ konnector install) into a consumer cluster using a caller-supplied consumer kubeconfig | +| `GET /api/bundle/` | single-use, short-TTL (5 min) bundle pickup, **returns the bundle**, then the token is dead | +| `POST /api/apply` | optional, flag-gated: browser-apply path, gateway applies the bundle (+ konnector install) into a consumer cluster using a caller-supplied consumer kubeconfig | | `GET /api/authorize`, `/api/callback` | auth flow (delegated to authenticator plugin) | | `GET /api/healthz` | health | **The bundle is the one-apply file**, delivered through a one-time pickup URL so live credentials are fetched exactly once and never stored at rest in the gateway. Content negotiation on pickup: `application/yaml` returns the literal multi-doc bundle (Secret + -`Connection` + `ClusterBinding`); `application/json` wraps the same objects in a thin +`Connection` + `ClusterBinding`), `application/json` wraps the same objects in a thin envelope (`{ bundle: [...] }`). There is no other handshake state: no request objects to poll, no phases to wait on. `curl` bind + pickup piped to `kubectl apply -f -` is a complete client. @@ -168,56 +175,64 @@ complete client. The single-use, short-TTL property applies to the **pickup URL**, not to the credential inside it: the bundle's Secret carries the long-lived SA token minted by the issuer (§2), so a bundle that has been picked up once stays valid and re-appliable. That is what -makes `-o yaml > binding.yaml` committed to git a real GitOps artifact — the pickup is +makes `-o yaml > binding.yaml` committed to git a real GitOps artifact, the pickup is consumed once, the token it delivered keeps working until its `Grant` is revoked. -Re-running `bind` mints a fresh `Grant`/token and a new pickup; it does not invalidate a +Re-running `bind` mints a fresh `Grant`/token and a new pickup, it does not invalidate a previously committed bundle unless that `Grant` is explicitly revoked. ### 4. Auth (pluggable) * `Authenticator` interface: `Routes()` (mounted under `/api/auth/…`) + `Authenticate(r) (Identity, error)`. Reference implementations: OIDC (code grant + - PKCE, as v1) and `kubernetes` (SubjectAccessReview against the provider — for - in-platform UIs that already hold a cluster identity). -* The embedded mock-OIDC server survives **only** as a dev-mode flag. -* Session store stays an interface (memory, Redis as today) but the gateway must be - fully functional with ≥2 replicas out of the box — Redis (or any external store) is - the documented production default, memory is dev-only. + PKCE, as v1) and `kubernetes` (TokenReview against the provider, for in-platform + UIs that already hold a cluster identity). +* The embedded mock-OIDC server survives **only** as a dev-mode flag (`--oidc-mock`). +* OIDC is configured with kube-apiserver/kcp-style flags: `--oidc-issuer-url`, + `--oidc-client-id`, `--oidc-client-secret`, `--oidc-ca-file`, + `--oidc-username-claim`, `--oidc-groups-claim`, `--oidc-scopes`, + `--oidc-redirect-url`. +* Sessions are **stateless encrypted cookies/tokens** (keys via + `--cookie-signing-key`/`--cookie-encryption-key`), no session store at all. With + shared keys, any number of gateway replicas works out of the box, the same encrypted + blob doubles as the CLI's bearer token. (Supersedes the earlier memory/Redis + session-store idea: the only server-side state the flow ever needed, one-time bundle + pickup, lives on the `Grant` via annotations with optimistic concurrency, so the + gateway keeps zero state.) * Identity → tenancy key: `issuer + "/" + subject` hash, as v1, so the same human gets the same boundary on re-bind. ### 5. Reaper (provider-side, optional) The core leaves dead-consumer GC explicitly to this layer, keyed off the per-Connection -`Lease` the konnector maintains. **This component is blocked on that core primitive:** the -konnector's provider-side `Lease` is specified in the core proposal but is new (no v1 -equivalent), so the reaper ships only once the konnector actually maintains the Lease; -until then dead-consumer GC is manual. +`Lease` the konnector maintains. That core primitive is implemented (the konnector +renews a `coordination.k8s.io/Lease` per Connection on the provider), so the reaper is +unblocked. * Lease expired beyond TTL → mark the issuance stale → (configurably) revoke - credentials, then delete kbind-created namespaces and synced objects. + credentials, then delete kube-bind-created namespaces and synced objects. * TTLs and the destructive step are opt-in and conservative by default (revoke ≠ - delete; deletion requires explicit enablement). + delete, deletion requires explicit enablement). -### 6. CLI (`kubectl bind`) +### 6. CLI (`kbind`) -Thin client over the gateway; everything it does is reproducible by hand: +Thin client over the gateway, everything it does is reproducible by hand. Named `kbind` +(a copy/symlink as `kubectl-bind` makes it a kubectl plugin). The **krew plugin name +stays `bind`** (kept from v1, `kubectl krew install bind` keeps working): release +archives ship the binary as `kubectl-bind`, and krew-release-bot renders `.krew.yaml` +against each GitHub release to PR krew-index (`.github/workflows/cli.yaml`). ```sh -kubectl bind login https://mangodb.example.com # auth, cache token -kubectl bind catalog # list Exports/Collections -kubectl bind export mangodb # bind an Export: +kubectl bind login https://mangodb.example.com # auth, cache token +kubectl bind catalog # list Exports/Collections +kubectl bind export mangodb # bind an Export: # POST /api/bind → bundle - # → kubectl apply (or -o yaml) -kubectl bind export mangodb -o yaml > binding.yaml # GitOps mode: print, don't apply + # → apply (or -o yaml) +kubectl bind export mangodb -o yaml > binding.yaml # GitOps mode: print, don't apply ``` -* Every CLI action is an explicit subcommand (`login`, `catalog`, `export`); export - names never occupy the subcommand slot — `kubectl bind export mangodb`, not - `kubectl bind mangodb` — so command names and export names cannot collide. * `--install-konnector` (default on for interactive use) installs/upgrades the v2 konnector, as v1 did. -* The CLI never creates bespoke objects — it applies the gateway's bundle verbatim. +* The CLI never creates bespoke objects, it applies the gateway's bundle verbatim. `-o yaml` output committed to git is byte-for-byte the GitOps path. * v1 subcommands that existed to ferry the old handshake (`apiservice`, `deploy`, per-resource polling) disappear. @@ -226,25 +241,45 @@ kubectl bind export mangodb -o yaml > binding.yaml # GitOps mode: print, don' Browse catalog → authenticate → bind → then either: -* **download the bundle** (via the one-time pickup URL) / copy a - `kubectl bind export` one-liner, or +* **download the bundle** (via the one-time pickup URL) / copy a `kubectl bind` + one-liner, or * **browser-apply** (v1's UI-only flow, roadmap #406, kept): the user supplies a consumer-cluster kubeconfig (or the UI runs in-platform where one is already held), and the gateway's `/api/apply` applies the bundle and installs the konnector into the consumer cluster. -The UI is a pure gateway client; it holds no flow state the gateway doesn't have. -Browser-apply is flag-gated on the gateway and off by default — it means consumer +The UI is a pure gateway client, it holds no flow state the gateway doesn't have. +Browser-apply is flag-gated on the gateway and off by default, it means consumer credentials transit the gateway, which deployments must consciously accept. ## Packaging & repo -Per the frozen core layout: `v2/backend` (gateway + issuer + reaper + auth), `v2/cli`, -`v2/web`. The backend ships as **one binary with module flags** (`--enable-gateway`, -`--enable-issuer`, `--enable-reaper`, `--enable-apply`) — operational simplicity over -purity; the boundaries stay as Go packages so a future split costs a `main.go`, not a -refactor. All of it depends on `v2/sdk` only. The kcp distribution (`contrib/kcp`) -remains separate, providing its own issuer implementation behind the same interface. +Post-restructure layout (the repo root is the kbind module, `sdk/` is the standalone +type module): + +``` +kbind/ +├── sdk/apis/core/v1alpha1/ # core (implemented) +├── sdk/apis/catalog/v1alpha1/ # Export, Collection +├── sdk/apis/iam/v1alpha1/ # Grant +├── backend/ # this proposal's server-side packages +│ ├── auth/ # Authenticator iface, OIDC (+dev mock), sessions +│ ├── issuer/ # Issuer iface + kube impl + Grant controller +│ ├── gateway/ # HTTP API + embedded UI +│ └── reaper/ # Lease-keyed GC +├── cli/ # kbind CLI packages +├── web/ # SPA sources (embedded into the gateway) +├── cmd/konnector/ # core (implemented) +├── cmd/backend/ # kbind-backend binary +└── cmd/kbind/ # CLI binary +``` + +The backend ships as **one binary with module flags** (`--enable-gateway`, +`--enable-issuer`, `--enable-reaper`, `--enable-apply`), operational simplicity over +purity, the boundaries stay as Go packages so a future split costs a `main.go`, not a +refactor. Types the backend serves live in `sdk` (separate module) so integrations can +depend on the APIs without the server. A future kcp distribution provides its own issuer +implementation behind the same interface (it no longer lives in this repo). ## Migration notes @@ -252,35 +287,69 @@ remains separate, providing its own issuer implementation behind the same interf can run side by side on one provider during transition (different endpoints, disjoint CRD groups). * v1 catalog objects (`APIServiceExportTemplate`/`Collection`) translate mechanically - to `Export`/`Collection`; a converter script ships with the backend. + to `Export`/`Collection`, a converter script ships with the backend. ## Decided -* **Packaging**: one `kbind-backend` binary; gateway/issuer/reaper/apply are module +* **Packaging**: one `kube-bind-backend` binary, gateway/issuer/reaper/apply are module flags, boundaries kept as Go packages. -* **Issuance anchor**: `Grant` in `iam.kbind.dev` — the typed record of - "identity X was issued credentials Y for export Z"; anchor for revocation, audit, - reaper. Kept out of `catalog.kbind.dev` so that group stays purely presentation+defaults. -* **Credentials**: long-lived secret-based SA token (v1 behavior) — zero rotation - friction accepted over security posture; revocation via `Grant` deletion; bounded +* **Issuance anchor**: `Grant` in `iam.kbind.io`, the typed record of + "identity X was issued credentials Y for export Z", anchor for revocation, audit, + reaper. Kept out of `catalog.kbind.io` so that group stays purely presentation+defaults. +* **Credentials**: long-lived secret-based SA token (v1 behavior), zero rotation + friction accepted over security posture, revocation via `Grant` deletion, bounded tokens addable later behind the same issuer interface without API change. * **Catalog vocabulary**: `Export` + `Collection`. -* **Bundle delivery**: one-time pickup URL, 5-minute TTL, single use — the TTL/single-use +* **Bundle delivery**: one-time pickup URL, 5-minute TTL, single use, the TTL/single-use applies to the *pickup URL*, not the long-lived SA token inside, so a picked-up bundle stays re-appliable (GitOps-safe). The bundle is never stored at rest in the gateway. * **kcp**: stays a separate distribution (`contrib/kcp`) providing its own issuer - implementation; the in-tree backend issuer is plain Kubernetes only. -* **UI reach**: browser-apply path **kept** (roadmap #406) — gateway `/api/apply` + implementation, the in-tree backend issuer is plain Kubernetes only. +* **UI reach**: browser-apply path **kept** (roadmap #406), gateway `/api/apply` applies bundle + installs konnector into the consumer cluster with a caller-supplied - kubeconfig; flag-gated, off by default, consumer credentials transiting the gateway + kubeconfig, flag-gated, off by default, consumer credentials transiting the gateway is an explicitly accepted trade-off when enabled. -* **Federation**: one gateway = one provider; cross-provider aggregation is a future +* **Federation**: one gateway = one provider, cross-provider aggregation is a future layer above the bundle protocol. -* **CLI verb structure**: every action is an explicit subcommand; binding an export is - `kubectl bind export `, never a bare `kubectl bind ` — export names and - command names must not share a namespace (review feedback, @sttts). + +Added 2026-07-29 (implementation round): + +* **Naming**: project is **kbind**. Groups `catalog.kbind.io` (Export, Collection) and + `iam.kbind.io` (Grant), binaries `kbind-backend` and `kbind` (CLI, kubectl-plugin + compatible), packages `backend/`, `cli/`, `web/` in the root module. +* **Sessions**: stateless encrypted cookie/bearer tokens, no session store (see §4). + HA needs only shared cookie keys across replicas. +* **One-time pickup without gateway state**: the pickup token is + `.`, the gateway stamps `sha256(random)` + expiry as annotations + on the `Grant` at bind time and removes them (optimistic concurrency) on pickup. The + bundle itself is (re)constructed on demand from the issuer's token Secret, never + stored at rest, single-use enforced by the API server, HA-safe. +* **Grant is spec-resolved at bind time**: the gateway copies the `Export`'s API list + + defaults into `Grant.spec`, so issuance is a stable record even if the catalog entry + changes later. The issuer controller provisions namespace/SA/RBAC from `Grant.spec` + and reports the artifacts in `Grant.status`, deletion (revocation) unwinds via an + `iam.kbind.io/cleanup` finalizer. +* **Lease ↔ Grant link (per-grant)**: the issued kubeconfig pins its context namespace + to the per-consumer boundary namespace, and the konnector's heartbeat writes its + Lease into the kubeconfig's context namespace when set (falling back to the `kbind` + namespace). The Lease is named `-` and annotated + with its Connection name, since the bundle names the Connection after the Grant, the + reaper judges staleness **per grant** by that annotation. Fallback for hand-renamed + Connections is conservative: any fresh Lease in the boundary keeps its Grants alive, + only a fully silent boundary goes stale. RBAC for Leases stays scoped to the + tenant's own namespace. +* **kubernetes authenticator**: implemented as **TokenReview** (not SAR, SAR is + authorization, identity comes from TokenReview) against the provider, behind + `--kubernetes-auth`. Tenancy key `kubernetes#`. No interactive routes, + in-platform callers just send their own bearer token. +* **Packaging (charts)**: `deploy/charts/backend` ships the service layer (module + flags as values, catalog+iam CRDs, Service, RBAC incl. `escalate`/`bind` so the + issuer may create Roles enumerating APIs the backend itself does not hold, OIDC + client secret and cookie keys via existing Secrets). +* **UI**: dependency-free static SPA (embedded via `go:embed` into the gateway), no + build toolchain in the repo, pure gateway client. ## Open questions -None — initial design questions resolved (see **Decided**). New questions raised during +None, initial design questions resolved (see **Decided**). New questions raised during review go here. diff --git a/docs/proposals/v2-slim-core.md b/docs/proposals/v2-slim-core.md index fbc99c723..10d4da411 100644 --- a/docs/proposals/v2-slim-core.md +++ b/docs/proposals/v2-slim-core.md @@ -1,26 +1,26 @@ -# kbind v2: Slim Core, Pluggable Everything Else +# kube-bind v2: Slim Core, Pluggable Everything Else * Status: **Proposed** * Authors: @mjudeikis * Date: 2026-06-10 * Supersedes parts of: [backend-only-bindings.md](backend-only-bindings.md) -* Follow-up: [v2-extended.md](v2-extended.md) — the optional service layer (backend API, +* Follow-up: [v2-extended.md](v2-extended.md), the optional service layer (backend API, CLI, UI) built on this contract -Changes to this document now require re-opening the decision log in **Decided**; the +Changes to this document now require re-opening the decision log in **Decided**, the remaining **Open questions** (OpenAPI fidelity spike, built-ins filter) are tracked for implementation, not re-design. ## Summary -kbind v2 (kbind is the project formerly known as kube-bind) splits the project into a -**slim sync core** and an **optional service layer**. The core does exactly one thing: given a Secret containing a kubeconfig, a +kube-bind v2 splits the project into a **slim sync core** and an **optional service +layer**. The core does exactly one thing: given a Secret containing a kubeconfig, a connection object, and a binding per API, it syncs CRDs and resource instances between a -consumer and a provider cluster — same scope, same names, no transformation — and reports +consumer and a provider cluster, same scope, same names, no transformation, and reports conflicts instead of papering over them. -Everything else — OIDC, the auth handshake, the web UI, the CLI, templates, collections, -service-account provisioning — moves out of the core into optional, pluggable components +Everything else, OIDC, the auth handshake, the web UI, the CLI, templates, collections, +service-account provisioning, moves out of the core into optional, pluggable components whose only job is to *produce the core inputs* (the kubeconfig Secret, the `Connection`, and the `Binding`/`ClusterBinding` objects). @@ -38,7 +38,7 @@ and the `Binding`/`ClusterBinding` objects). │ consumed by ▼ ┌────────────────────────────────────────────────────────┐ - │ core: konnector — CRD sync, spec ⇩up / status ⇩down, │ + │ core: konnector, CRD sync, spec ⇩up / status ⇩down, │ │ related resources, conflict detection │ └────────────────────────────────────────────────────────┘ ``` @@ -81,7 +81,7 @@ and the `Binding`/`ClusterBinding` objects). a monolith, not an architecture. 4. **Sync engine inefficiencies.** Per-export dynamic controller spawning duplicates - informers per GVR; the konnector watches *all* secrets cluster-wide; heartbeat interval + informers per GVR, the konnector watches *all* secrets cluster-wide, heartbeat interval and many behaviors are hardcoded. ## Goals @@ -89,7 +89,7 @@ and the `Binding`/`ClusterBinding` objects). * **One apply.** A full end-to-end binding to a provider is a single `kubectl apply -f` of one file containing all objects (Secret + `Connection` + bindings). Nothing else, nothing more: no handshake, no waiting on phases, no ordering - requirements — the konnector converges from whatever has been applied. + requirements, the konnector converges from whatever has been applied. * Scope-preserving, name-preserving sync ("plain sync"): namespaced ↔ namespaced in the same namespace name, cluster-scoped ↔ cluster-scoped under the same name. * First-class conflict handling: never silently fight over or adopt objects another actor @@ -97,7 +97,7 @@ and the `Binding`/`ClusterBinding` objects). * CRD/schema delivery in core: applying the core objects yields working APIs on the consumer. * Related-resource sync (Secrets/ConfigMaps referenced by synced objects) in core. -* Zero kbind components required on the provider cluster for the core path. +* Zero kube-bind components required on the provider cluster for the core path. * Portability and extension points so v1-style behaviors (tenancy mapping, handshakes, UIs) can be rebuilt *on top*. @@ -118,36 +118,36 @@ and the `Binding`/`ClusterBinding` objects). provider, the operator marks which CRDs are exported by labeling them: ```sh -kubectl label crd mangodbs.mangodb.io "core.kbind.dev/exported=true" +kubectl label crd mangodbs.mangodb.io "core.kube-bind.io/exported=true" ``` Whatever carries the label *and* is readable by the consumer's credentials is exported. -On **CRD-less providers** (kcp and kcp-like systems — APIs served from APIBindings / +On **CRD-less providers** (kcp and kcp-like systems, APIs served from APIBindings / logical clusters, no CRD objects to label), the export boundary is the **logical cluster itself**: the kubeconfig points at a workspace that was deliberately populated with exactly the APIs to offer, so everything discoverable there (minus built-ins) is -exported. No label needed — curation happened when the workspace was assembled. +exported. No label needed, curation happened when the workspace was assembled. Either way this is the entire provider-side footprint of the core: a label (or a -workspace boundary) plus RBAC. The credentials' RBAC *is* the authorization model; there +workspace boundary) plus RBAC. The credentials' RBAC *is* the authorization model, there is no separate permission/claim grant object in core. **1. A Secret with a kubeconfig** pointing at the provider cluster, living in the -konnector's designated namespace (default `kbind`). +konnector's designated namespace (default `kube-bind`). -**2. `Connection`** (cluster-scoped) — the link to one provider. Owns credentials and +**2. `Connection`** (cluster-scoped), the link to one provider. Owns credentials and schema delivery, and surfaces what the provider offers: ```yaml -apiVersion: core.kbind.dev/v1alpha1 +apiVersion: core.kube-bind.io/v1alpha1 kind: Connection metadata: name: mangodb-provider spec: # Immutable. The only credential reference in the core. kubeconfigSecretRef: - namespace: kbind + namespace: kube-bind name: mangodb-provider key: kubeconfig @@ -173,13 +173,13 @@ status: conditions: [] # SecretValid, Connected, SchemaInSync ``` -**3. `ClusterBinding`** (cluster-scoped) and **`Binding`** (namespaced) — activate +**3. `ClusterBinding`** (cluster-scoped) and **`Binding`** (namespaced), activate instance sync for one or more APIs, following the `ClusterRole`/`Role` convention. APIs -are referenced by their **CRD name** on the provider (`.`) — no +are referenced by their **CRD name** on the provider (`.`), no group/version/resource triples to get out of sync with the schema: ```yaml -apiVersion: core.kbind.dev/v1alpha1 +apiVersion: core.kube-bind.io/v1alpha1 kind: ClusterBinding # syncs objects of these APIs cluster-wide metadata: name: mangodb @@ -210,12 +210,12 @@ status: boundAPIs: # per-API observed state - name: mangodbs.mangodb.io crdHash: sha256:… # applied schema version - conflictCount: 0 # objects skipped due to foreign ownership; + conflictCount: 0 # objects skipped due to foreign ownership, # per-object detail lives on each object's own condition ``` ```yaml -apiVersion: core.kbind.dev/v1alpha1 +apiVersion: core.kube-bind.io/v1alpha1 kind: Binding # same spec, but syncs only objects in its own namespace metadata: name: mangodb @@ -232,11 +232,11 @@ plain namespace RBAC, and is the v2 answer to v1's `informerScope: Namespaced`. `Binding` listing a cluster-scoped CRD is invalid for that entry (per-API condition, no sync). Where a `ClusterBinding` and a `Binding` cover the same API on the same connection, the `ClusterBinding` wins and the `Binding` gets a per-API condition. -"Bind everything" is `Connection.spec.autoBind: true` — the konnector then maintains a +"Bind everything" is `Connection.spec.autoBind: true`, the konnector then maintains a managed `ClusterBinding` mirroring `status.exportedAPIs`. -That is the **entire core API**: three kinds plus the Secret. No kbind CRDs are -required on the provider; the konnector reads provider CRDs through the ordinary +That is the **entire core API**: three kinds plus the Secret. No kube-bind CRDs are +required on the provider, the konnector reads provider CRDs through the ordinary apiextensions API and reads/writes instances through the dynamic client. ### The whole UX: one apply @@ -250,22 +250,22 @@ apiVersion: v1 kind: Secret metadata: name: mangodb-provider - namespace: kbind + namespace: kube-bind stringData: kubeconfig: | --- -apiVersion: core.kbind.dev/v1alpha1 +apiVersion: core.kube-bind.io/v1alpha1 kind: Connection metadata: name: mangodb-provider spec: kubeconfigSecretRef: - namespace: kbind + namespace: kube-bind name: mangodb-provider key: kubeconfig --- -apiVersion: core.kbind.dev/v1alpha1 +apiVersion: core.kube-bind.io/v1alpha1 kind: ClusterBinding metadata: name: mangodb @@ -283,7 +283,7 @@ kubectl apply -f mangodb-binding.yaml …and the APIs are live on the consumer. Design rule this imposes: **all core objects are order-independent and level-triggered**. A binding referencing a not-yet-existing `Connection`, a `Connection` referencing a not-yet-existing Secret, a binding listing a -not-yet-exported CRD — none of these are errors, all are `Pending` conditions that +not-yet-exported CRD, none of these are errors, all are `Pending` conditions that resolve when the missing piece arrives. No phase gating, no request/response objects, no controller that must answer before the user may apply the next thing. @@ -294,7 +294,7 @@ whose release requires the konnector to reach the provider through the *very* `C being deleted. The konnector therefore drains object finalizers before a referenced `Connection`/binding is allowed to finalize: one that still has synced objects bound to it stays in `Terminating` with a `DrainingObjects` condition until those objects' provider -copies are gone, then releases. "Delete the whole file" converges — it does not deadlock — +copies are gone, then releases. "Delete the whole file" converges, it does not deadlock, but the `Connection` is the *last* object to disappear, not the first. ### Schema sources: CRD and OpenAPI @@ -303,41 +303,30 @@ The konnector must install a working CRD on the consumer for every bound API. Tw to obtain it, selected by `Connection.spec.schema.source` (`Auto` probes CRD first, falls back to OpenAPI): -* **`CRD`** — read the CRD from the provider's apiextensions API and apply it on the +* **`CRD`**, read the CRD from the provider's apiextensions API and apply it on the consumer with mechanical adjustments: never copy provider-side `conversion.strategy: - Webhook` or its caBundle (such CRDs are refused — per-API condition + skip, see the + Webhook` or its caBundle (such CRDs are refused, per-API condition + skip, see the sync table), add an owner-ref to the `Connection`, and inject UX-only printer columns/categories. To keep a multi-version CRD installable on the consumer *without* a conversion webhook, install only the provider's **storage/served version** rather than - every historical version. Highest fidelity; requires the provider to *have* CRDs and + every historical version. Highest fidelity, requires the provider to *have* CRDs and the credentials to read them. -* **`OpenAPI`** — for CRD-less providers (kcp and kcp-like systems, aggregated APIs): +* **`OpenAPI`**, for CRD-less providers (kcp and kcp-like systems, aggregated APIs): synthesize a CRD from what every Kubernetes-shaped API server already serves: * **discovery** (`/apis//`) → plural/singular/kind/shortNames, - categories, `namespaced`, verbs, and the served versions of the group; + categories, `namespaced`, verbs, and the served versions of the group, * **`/openapi/v3/apis//`** → the structural schema per version, - including `x-kubernetes-*` extensions and defaults; + including `x-kubernetes-*` extensions and defaults, * subresource detection (status/scale) from the OpenAPI paths. Known fidelity limits, stated honestly: CEL validation rules and other - server-side-only constraints may not round-trip through OpenAPI — the consumer-side + server-side-only constraints may not round-trip through OpenAPI, the consumer-side CRD can be *looser* than the provider's real validation, and the provider remains the - enforcing side (a consumer object that passes locally can still be rejected upstream; + enforcing side (a consumer object that passes locally can still be rejected upstream, that surfaces as a per-object sync condition, not silent loss). - Considered and rejected: closing this gap with a consumer-side **validation webhook** - that proxies validation to the provider (e.g. a dry-run apply against the provider at - admission time). Admission webhooks require a serving-certificate pair — a - cert-manager (or equivalent) dependency — and demand ongoing operational care across - the wide range of cluster configurations the konnector must run in; they would break - the lightweight, ship-anywhere property of the core. CEL-based - `ValidatingAdmissionPolicy` avoids the certificate problem but cannot reach the - provider, so it cannot close the gap either (it may later cover the subset of rules - that *do* round-trip). The trade-off stands as stated: the provider enforces, the - consumer surfaces rejections as conditions. - -Binding by CRD name (`.`) works identically under both sources — it's -just resource + group; with the OpenAPI source there simply is no CRD object behind the +Binding by CRD name (`.`) works identically under both sources, it's +just resource + group, with the OpenAPI source there simply is no CRD object behind the name on the provider. `status.exportedAPIs` is computed per source: labeled CRDs for `CRD`, discovery (minus built-in groups) for `OpenAPI`. @@ -346,16 +335,16 @@ name on the provider. `status.exportedAPIs` is computed per source: labeled CRDs | Aspect | v2 behavior | |---|---| | Identity | `ns/name` on consumer == `ns/name` on provider. Cluster-scoped stays cluster-scoped. No prefixes, no remapping, no `APIServiceNamespace`. | -| Selection | `ClusterBinding` syncs all instances of its listed APIs cluster-wide; namespaced `Binding` syncs only instances in its own namespace. `Connection.spec.autoBind` binds everything exported. | +| Selection | `ClusterBinding` syncs all instances of its listed APIs cluster-wide, namespaced `Binding` syncs only instances in its own namespace. `Connection.spec.autoBind` binds everything exported. | | Spec | consumer → provider, server-side apply with a dedicated field manager. | | Status | provider → consumer, status subresource update. | -| Namespaces | If the consumer namespace doesn't exist on the provider, the konnector creates it (annotated as kbind-created; only kbind-created namespaces are cleaned up on unbind). | -| Deletion | Finalizer on consumer object (as today); consumer deletion propagates to provider, finalizer released only when the provider copy is fully gone (a provider-side finalizer holds the consumer object in `Terminating` until it clears). `kbind.dev/deletion-policy: Orphan` on a consumer object releases the finalizer without deleting the provider copy. Provider-side deletion of a synced object is treated as drift and re-created **unless** the provider copy has a non-zero deletionTimestamp — then the konnector waits for it to finalize rather than racing a re-create. Consumer is source of truth for spec. | -| Schema | Per `Connection.spec.schema`: konnector obtains schemas via `source: CRD` (read apiextensions) or `OpenAPI` (synthesize from discovery + `/openapi/v3` — CRD-less providers like kcp), pulls per `pullPolicy: All` or `Bound`, applies on the consumer (owner-ref to the `Connection`). `updatePolicy: Always` keeps following provider schema changes; `Once` pins. CRDs with `strategy: Webhook` are refused (per-API condition + skip). | -| Discovery | `Connection.status.exportedAPIs`: labeled CRDs (`source: CRD`) or discovery minus built-ins (`source: OpenAPI`, where the logical-cluster boundary is the export boundary) — core-level discovery with zero provider CRDs. | -| Related resources | Selected Secrets/ConfigMaps sync in the declared direction, same identity rules, scoped like their binding. They are owned by the **binding** (not by individual instances): an object is synced while it matches the selector and is garbage-collected when it stops matching or the binding is removed. The same ownership markers and `conflictPolicy` apply — a related object already owned by another binding/consumer is a conflict, never silently overwritten. | -| RBAC | The supplied credentials' RBAC *is* the authorization model; partial RBAC is an expected steady state, not a failure. Each forbidden operation surfaces as a typed `PermissionDenied` condition naming the verb+resource refused (per-API on the binding, per-object on the instance); the konnector keeps syncing everything it *is* allowed to and never fails a whole binding because one resource or namespace is out of reach. | -| Informers | One shared dynamic informer per GVR per connection. Cluster-wide informers for `ClusterBinding`; namespace-scoped informers where only namespaced `Binding`s exist. | +| Namespaces | If the consumer namespace doesn't exist on the provider, the konnector creates it (annotated as kube-bind-created, only kube-bind-created namespaces are cleaned up on unbind). | +| Deletion | Finalizer on consumer object (as today), consumer deletion propagates to provider, finalizer released only when the provider copy is fully gone (a provider-side finalizer holds the consumer object in `Terminating` until it clears). `kube-bind.io/deletion-policy: Orphan` on a consumer object releases the finalizer without deleting the provider copy. Provider-side deletion of a synced object is treated as drift and re-created **unless** the provider copy has a non-zero deletionTimestamp, then the konnector waits for it to finalize rather than racing a re-create. Consumer is source of truth for spec. | +| Schema | Per `Connection.spec.schema`: konnector obtains schemas via `source: CRD` (read apiextensions) or `OpenAPI` (synthesize from discovery + `/openapi/v3`, CRD-less providers like kcp), pulls per `pullPolicy: All` or `Bound`, applies on the consumer (owner-ref to the `Connection`). `updatePolicy: Always` keeps following provider schema changes, `Once` pins. CRDs with `strategy: Webhook` are refused (per-API condition + skip). | +| Discovery | `Connection.status.exportedAPIs`: labeled CRDs (`source: CRD`) or discovery minus built-ins (`source: OpenAPI`, where the logical-cluster boundary is the export boundary), core-level discovery with zero provider CRDs. | +| Related resources | Selected Secrets/ConfigMaps sync in the declared direction, same identity rules, scoped like their binding. They are owned by the **binding** (not by individual instances): an object is synced while it matches the selector and is garbage-collected when it stops matching or the binding is removed. The same ownership markers and `conflictPolicy` apply, a related object already owned by another binding/consumer is a conflict, never silently overwritten. | +| RBAC | The supplied credentials' RBAC *is* the authorization model, partial RBAC is an expected steady state, not a failure. Each forbidden operation surfaces as a typed `PermissionDenied` condition naming the verb+resource refused (per-API on the binding, per-object on the instance), the konnector keeps syncing everything it *is* allowed to and never fails a whole binding because one resource or namespace is out of reach. | +| Informers | One shared dynamic informer per GVR per connection. Cluster-wide informers for `ClusterBinding`, namespace-scoped informers where only namespaced `Binding`s exist. | ### Conflict handling (the new hard part) @@ -363,34 +352,38 @@ Identity mapping means two writers can legitimately collide. Core rules: 1. Every object the konnector writes carries ownership markers: the **binding UID** plus the **source cluster UID**. The source cluster UID is the identity the `Connection` - pins in its status the first time it resolves its credentials — *not* something read + pins in its status the first time it resolves its credentials, *not* something read from a fixed object like the `kube-system` namespace, which does not exist on CRD-less/logical-cluster providers (kcp). This keeps the marker well-defined under both - schema sources. (Same idea as v1's `kube-bind.io/consumer-uid` / `provider-uid` - annotations, carried forward under the new `kbind.dev/*` prefix.) + schema sources. (Same idea as today's `kube-bind.io/consumer-uid` / `provider-uid` + annotations, kept.) 2. Before first write, the konnector classifies the existing target object three ways: * **No markers** (a foreign, un-owned object): `conflictPolicy: Fail` (default) does - not touch it; `conflictPolicy: Adopt` stamps markers and SSA force-applies. - * **Our markers, our current binding + object UID**: ours — normal SSA update. + not touch it, `conflictPolicy: Adopt` stamps markers and SSA force-applies. + * **Our markers, our current binding + object UID**: ours, normal SSA update. * **Our cluster's markers but a stale/foreign binding-or-object UID**, *or* **another cluster's markers**: always a conflict, regardless of `conflictPolicy`. `Adopt` - never steals an object another binding/consumer owns; first-writer-wins, + never steals an object another binding/consumer owns, first-writer-wins, deterministically. -3. Conflicts are recorded **on the conflicting object itself** as a typed condition that - distinguishes the two cases an operator remediates differently — `ForeignObjectExists` - (no markers; rename or switch to `Adopt`) vs. `OwnedByAnother` (claimed by a different - binding/consumer; pick another name). The binding does **not** inline an unbounded list - of object names: its status carries only a `Conflicts` condition and a count - (`boundAPIs[].conflictCount`), plus an Event. The konnector keeps syncing everything - else. +3. Conflicts are surfaced by **two authoritative signals**: a Kubernetes **Event** on the + consumer object, and a **count + `Conflicts` condition on the binding** + (`boundAPIs[].conflictCount`), never an unbounded list of object names. Both carry the + reason that tells an operator how to remediate: `ForeignObjectExists` (no markers, + rename or switch to `Adopt`) vs. `OwnedByAnother` (claimed by a different + binding/consumer, pick another name). The konnector *also* writes that reason as a + condition on the conflicting object itself, but only **best-effort**: a structural CRD + whose `status` schema has no `conditions` field will have it pruned by the API server + (confirmed in the POC against a status-only CRD). So the Event and the binding count are + the contract, the per-object condition is a convenience present only when the synced + type defines `status.conditions`. The konnector keeps syncing everything else. 4. Field-level conflicts within an owned object are resolved by SSA with `force=true` for our field manager on our sync direction only (spec fields upstream, - status fields downstream) — same as today, but now stated as the contract. + status fields downstream), same as today, but now stated as the contract. ### Topology: the konnector is the only running component -Consumer-side pull, as today — and **the core has no backend**. The konnector is the -single process in the entire core path; everything v1's backend did for sync either +Consumer-side pull, as today, and **the core has no backend**. The konnector is the +single process in the entire core path, everything v1's backend did for sync either moved into the konnector or out of core: | v1 backend job | v2 home | @@ -399,28 +392,28 @@ moved into the konnector or out of core: | materialize exports/schemas (`BoundSchema`) | konnector reads provider CRDs via apiextensions API directly | | create provider namespaces (`APIServiceNamespace` controller) | konnector creates them (iff RBAC allows) | | track consumer liveness (`ClusterBinding` heartbeat) | konnector maintains a `Lease` on the provider | -| mint kubeconfigs / service accounts, rotate credentials | **out of core** — service layer or manual | -| GC artifacts of dead/vanished consumers | **out of core** — service layer can reap based on expired Leases | +| mint kubeconfigs / service accounts, rotate credentials | **out of core**, service layer or manual | +| GC artifacts of dead/vanished consumers | **out of core**, service layer can reap based on expired Leases | * The konnector runs in the consumer cluster (or out-of-cluster with a consumer - kubeconfig — it must not assume in-cluster). One konnector may serve many consumer - logical clusters (kcp workspaces, a cluster fleet) — see + kubeconfig, it must not assume in-cluster). One konnector may serve many consumer + logical clusters (kcp workspaces, a cluster fleet), see [Engine](#engine-built-on-multicluster-runtime). * It watches `Connection`, `ClusterBinding`, and `Binding` objects, and only the Secrets that `Connection`s reference (fixes the v1 watch-all-secrets issue). A `Connection`'s `kubeconfigSecretRef` must resolve to the konnector's own designated namespace (default - `kbind`): `Connection` is cluster-scoped, so letting it name a Secret in any + `kube-bind`): `Connection` is cluster-scoped, so letting it name a Secret in any namespace would let anyone who can create a `Connection` read any Secret the konnector's ServiceAccount can. Cross-namespace refs are rejected with `SecretValid=False`. -* One `Connection` = one provider client/informer context; all bindings referencing it +* One `Connection` = one provider client/informer context, all bindings referencing it share that context. * The provider cluster needs: reachable API server + RBAC for the supplied credentials. No backend, no controllers, no CRDs. The honest cost of zero provider-side runtime: credential issuance/rotation and cleanup after consumers that disappear forever are nobody's job in core. The Lease per -`Connection` is the hook — an optional provider-side reaper (service layer) can GC -kbind-created namespaces and synced objects whose Lease has expired. +`Connection` is the hook, an optional provider-side reaper (service layer) can GC +kube-bind-created namespaces and synced objects whose Lease has expired. Heartbeat keeps the zero-CRD property: the konnector maintains a plain `coordination.k8s.io/Lease` per `Connection` in a designated provider namespace. @@ -431,7 +424,7 @@ component in the service layer. The v2 konnector is built on [multicluster-runtime](https://github.com/kubernetes-sigs/multicluster-runtime) -(roadmap #299), not hand-rolled informer plumbing — and structured as a **bridge between +(roadmap #299), not hand-rolled informer plumbing, and structured as a **bridge between two cluster sets**, each fronted by an mcr provider: * **Provider side**: a custom mcr provider discovers "clusters" from `Connection` @@ -439,25 +432,25 @@ two cluster sets**, each fronted by an mcr provider: resolves, disengaged on deletion). * **Consumer side**: also behind an mcr provider abstraction. The default is the trivial single-cluster provider (today's shape: one konnector in one consumer cluster). But - nothing in the engine assumes one consumer cluster — swapping the consumer-side + nothing in the engine assumes one consumer cluster, swapping the consumer-side provider scales the same binary out: - * **kcp provider** → one konnector per kcp instance, serving *every* workspace; each + * **kcp provider** → one konnector per kcp instance, serving *every* workspace, each workspace carries its own `Connection`/`Binding` objects and is its own sync domain. * **fleet provider** (kubeconfig/cluster-inventory) → one konnector serving many physical consumer clusters, connecting a *set* of consumer clusters to a *set* of providers. * The sync domain is always the pair *(consumer logical cluster, `Connection` within - it)* — the core API is unchanged regardless of how many consumer clusters one + it)*, the core API is unchanged regardless of how many consumer clusters one konnector serves. Multi-consumer is purely an engine/deployment dimension, never an API dimension. -* Sync controllers are written once as multi-cluster-aware reconcilers; per-connection +* Sync controllers are written once as multi-cluster-aware reconcilers, per-connection client/cache lifecycle, informer dedup per GVR, and teardown come from the framework instead of v1's contextstore + dynamic controller spawning. * The backend already uses multicluster-runtime (`mcmanager` + the kcp apiexport - provider) — v2 aligns consumer and provider sides on one runtime model, and the kcp + provider), v2 aligns consumer and provider sides on one runtime model, and the kcp flavor falls out of swapping the mcr provider rather than special-casing the engine. -Alpha ships the single-cluster consumer provider only; the kcp and fleet consumer +Alpha ships the single-cluster consumer provider only, the kcp and fleet consumer providers are the explicit scale-out path, unlocked by the architecture rather than designed later. @@ -473,7 +466,7 @@ forking the engine: type Mapper interface { // ToProvider maps a consumer object key to its provider key. ToProvider(gvr schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) - // ToConsumer is the inverse; must round-trip. + // ToConsumer is the inverse, must round-trip. ToConsumer(gvr schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) } ``` @@ -483,10 +476,10 @@ Notes: * This is a *compile-time* extension (custom konnector build), not a CRD-configurable one. Keeping it out of the API keeps the API honest: the core CRD never promises renaming. -* The v1 `Prefixed` behavior is implementable as a Mapper; `Namespaced` (scope - conversion) is intentionally **not** implementable — the interface maps keys, it cannot +* The v1 `Prefixed` behavior is implementable as a Mapper, `Namespaced` (scope + conversion) is intentionally **not** implementable, the interface maps keys, it cannot change scope. That's the hard line v2 draws. -* Possible second interface later: `Transformer` (mutate object payload before write — +* Possible second interface later: `Transformer` (mutate object payload before write, label injection, field stripping). Deliberately deferred. ### Extension point 2: the handshake @@ -496,60 +489,40 @@ becomes "anything that can create a Secret, a `Connection`, and bindings": | v1 component | v2 home | |---|---| -| backend HTTP API, OIDC, sessions, SPA/UI | optional `kbind-backend` component (own module/repo dir, own release cycle). Its output is exactly the core objects. | +| backend HTTP API, OIDC, sessions, SPA/UI | optional `kube-bind-backend` component (own module/repo dir, own release cycle). Its output is exactly the core objects. | | `kubectl bind` CLI + browser dance | optional `cli/` plugin, talks to the backend, ends by applying the core objects + (optionally) installing the konnector. | -| `APIServiceExportTemplate`, `Collection` | backend-layer CRDs (rich catalog: descriptions, grouping, permission review). Raw discovery is core (`Connection.status.exportedAPIs`); curation is service layer. | +| `APIServiceExportTemplate`, `Collection` | backend-layer CRDs (rich catalog: descriptions, grouping, permission review). Raw discovery is core (`Connection.status.exportedAPIs`), curation is service layer. | | `APIServiceExportRequest`, `BindableResourcesRequest`, `BindingResourceResponse` | backend-layer wire/handshake types. | | `APIServiceBindingBundle` ("bind everything") | absorbed into core as `Connection.spec.autoBind: true` (managed `ClusterBinding` mirroring `exportedAPIs`). | | service-account + kubeconfig minting ([backend/kubernetes/resources/](../../backend/kubernetes/resources/)) | backend layer (it's credential issuance, i.e. auth). | -| kcp integration ([contrib/kcp/](../../contrib/kcp/)) | a backend *flavor*: kcp workspaces give per-consumer isolation for free, which is exactly what identity-mapping core wants. The core already speaks to kcp-like providers natively via `schema.source: OpenAPI` (no CRDs needed); the backend flavor only adds workspace provisioning/handshake. Likely the best-fit v2 deployment. | -| heartbeat / `ClusterBinding` | core keeps a plain `Lease` on the provider; anything richer is an optional provider-side visibility component. | +| kcp integration ([contrib/kcp/](../../contrib/kcp/)) | a backend *flavor*: kcp workspaces give per-consumer isolation for free, which is exactly what identity-mapping core wants. The core already speaks to kcp-like providers natively via `schema.source: OpenAPI` (no CRDs needed), the backend flavor only adds workspace provisioning/handshake. Likely the best-fit v2 deployment. | +| heartbeat / `ClusterBinding` | core keeps a plain `Lease` on the provider, anything richer is an optional provider-side visibility component. | GitOps is the degenerate case: a human or pipeline commits the one-apply file (Secret + `Connection` + bindings), no optional layer at all. -### Every v1 API, dispositioned - -Where each `kube-bind.io/v1alpha2` kind lands in v2, in one table: - -| v1 API (v1alpha2) | v2 disposition | -|---|---| -| `APIServiceBinding` | **Replaced in core** by `Binding` / `ClusterBinding` (`core.kbind.dev`). | -| `APIServiceBindingBundle` | **Absorbed into core** as `Connection.spec.autoBind: true`. | -| `ClusterBinding` (provider-side consumer record + heartbeat) | **Dropped.** Heartbeat becomes a plain `coordination.k8s.io/Lease`; richer provider-side visibility may return in the service layer. Note the name reuse: v2's `ClusterBinding` is a different, consumer-side object. | -| `APIServiceExport` | **Dropped.** Export opt-in is the `core.kbind.dev/exported=true` CRD label (or the logical-cluster boundary on CRD-less providers). | -| `BoundSchema` | **Dropped.** The konnector reads provider CRDs / OpenAPI directly; no provider-side copy-of-a-CRD object. | -| `APIServiceNamespace` | **Dropped.** Identity mapping means no namespace re-mapping, ever. | -| `APIServiceExportRequest` | **Dropped from core.** The handshake becomes the service layer's HTTP protocol ([v2-extended](v2-extended.md)), which terminates in the one-apply bundle — no request/response CRDs on the consumer. | -| `BindableResourcesRequest` / `BindingResourceResponse` | **Dropped.** Same reason — wire/handshake types become gateway endpoints. | -| `APIServiceExportTemplate` | **Moves to the service layer** as `catalog.kbind.dev/Export` ([v2-extended](v2-extended.md)). | -| `Collection` | **Moves to the service layer** as `catalog.kbind.dev/Collection`. | - -New in v2 core: `Connection` — no v1 equivalent; the provider link was previously -implicit in the kubeconfig Secret plus the provider-side `ClusterBinding`. New in the -service layer: `Grant` (`iam.kbind.dev`), the issuance record. - ### What gets deleted outright -Beyond the dropped kinds above, the machinery around them goes too: - * `Isolation` / `ClusterScopedIsolation` / `informerScope` fields and the isolation strategy implementations (`prefixed.go`, `namespaced.go`, `none.go`). -* The namespace-lifecycle controller (served `APIServiceNamespace`). +* `APIServiceNamespace` and the namespace-lifecycle controller. +* `BoundSchema` (core reads provider CRDs directly, the provider-side copy-of-a-CRD + object disappears). +* `ClusterBinding` from core (possibly resurrected in the backend layer). * Embedded OIDC, sessions, cookies, SPA from anything called "core". -* The hardcoded claimable-APIs list (`claimable_apis.go`) — replaced by +* The hardcoded claimable-APIs list (`claimable_apis.go`), replaced by `relatedResources` limited to `secrets`/`configmaps`, label + named selectors only. ### Repo & module layout (new group, same repo, `v2/` prefix) -One rule: **the path tells you the version**. Everything v2 lives under `v2/`; every -path outside it is v1 by definition — frozen on main, maintained on a release branch, +One rule: **the path tells you the version**. Everything v2 lives under `v2/`, every +path outside it is v1 by definition, frozen on main, maintained on a release branch, deleted from main at v2 GA. ``` -kbind/ +kube-bind/ ├── v2/ # ── ALL v2 code lives here ── -│ ├── sdk/ # Go module: type-only API (core.kbind.dev) +│ ├── sdk/ # Go module: type-only API (core.kube-bind.io) │ │ └── apis/core/v1alpha1/ # Connection, ClusterBinding, Binding │ ├── konnector/ # Go module: the slim core engine + binary │ │ ├── cmd/konnector/ @@ -558,8 +531,8 @@ kbind/ │ ├── backend/ # future optional layer (follow-up proposal) │ └── cli/ # future optional layer (follow-up proposal) │ -├── sdk/apis/kubebind/v1alpha2/ # v1 — frozen; types kept on main for consumers -├── pkg/ cmd/ backend/ cli/ web/ # v1 — frozen on main, fixes on release-1.x, +├── sdk/apis/kubebind/v1alpha2/ # v1, frozen, types kept on main for consumers +├── pkg/ cmd/ backend/ cli/ web/ # v1, frozen on main, fixes on release-1.x, └── contrib/kcp/ # deleted from main at v2 GA ``` @@ -567,18 +540,18 @@ Rules: * **No imports across the boundary, in either direction**: nothing under `v2/` imports v1 packages, nothing outside `v2/` imports v2 packages. Enforced in CI. Shared code is - copied, not linked — the freedom to diverge is the point of the split. + copied, not linked, the freedom to diverge is the point of the split. * `v2/sdk` is a type-only module so consumers (backends, integrations) can depend on the - API without pulling the engine; `v2/konnector` depends on `v2/sdk`, never vice versa. + API without pulling the engine, `v2/konnector` depends on `v2/sdk`, never vice versa. * Within v2, optional layers (`v2/backend`, `v2/cli`) depend on `v2/sdk` (and at most the konnector's library surface), never the other way. -* The v2 konnector binary serves **only** `core.kbind.dev`. v1alpha2 konnector is - maintained on the release branch until deprecation; no dual-stack binary. +* The v2 konnector binary serves **only** `core.kube-bind.io`. v1alpha2 konnector is + maintained on the release branch until deprecation, no dual-stack binary. * Engine implementation: built on multicluster-runtime (see - [Engine](#engine-built-on-multicluster-runtime)); one shared informer set per provider + [Engine](#engine-built-on-multicluster-runtime)), one shared informer set per provider connection, no hand-rolled informer plumbing. -* Images follow the same rule: `ghcr.io/kbind-dev/konnector:v2.*` is built from - `v2/konnector`; `v1.*` / `v0.*` tags only ever come from the release branch. +* Images follow the same rule: `ghcr.io/kube-bind/konnector:v2.*` is built from + `v2/konnector`, `v1.*` / `v0.*` tags only ever come from the release branch. ## Migration @@ -588,78 +561,77 @@ Rules: that, for bindings using `None` isolation + identity-compatible layouts, generates the equivalent v2 objects. Anything using `Prefixed`/`Namespaced` isolation cannot migrate to core semantics and stays on v1 / moves to a per-consumer provider deployment first. -* v1alpha2 enters maintenance on the day v2 core reaches alpha; removal horizon TBD. +* v1alpha2 enters maintenance on the day v2 core reaches alpha, removal horizon TBD. ## Decided * **One apply**: a complete e2e binding is a single `kubectl apply -f` of one file - (Secret + `Connection` + bindings); all core objects are order-independent and - level-triggered — missing references are `Pending` conditions, never errors. -* **Naming**: the project is **kbind** (formerly kube-bind; org `kbind-dev`, domain - `kbind.dev`). All new v2 API groups live under the new domain: group `core.kbind.dev`, - kinds `Connection`, `ClusterBinding`, `Binding` (service layer: `catalog.kbind.dev`, - `iam.kbind.dev`). v1 groups (`kube-bind.io/v1alpha2`) are untouched on the frozen side. + (Secret + `Connection` + bindings), all core objects are order-independent and + level-triggered, missing references are `Pending` conditions, never errors. +* **Naming**: group `core.kube-bind.io`, kinds `Connection`, `ClusterBinding`, `Binding`. The agent stays **konnector**. * **Binding shape & scope**: a binding lists one or more CRD names (`spec.apis`) plus - its related resources; cluster-wide vs per-namespace is expressed by kind + its related resources, cluster-wide vs per-namespace is expressed by kind (`ClusterBinding`/`Binding`), not by fields. -* **Bind everything**: `Connection.spec.autoBind: true` — konnector maintains a managed +* **Bind everything**: `Connection.spec.autoBind: true`, konnector maintains a managed `ClusterBinding` mirroring `status.exportedAPIs`. Replaces `APIServiceBindingBundle`. -* **Discovery**: provider opt-in via `core.kbind.dev/exported=true` CRD label on - plain Kubernetes; on CRD-less providers (kcp, kcp-like) the logical-cluster boundary +* **Discovery**: provider opt-in via `core.kube-bind.io/exported=true` CRD label on + plain Kubernetes, on CRD-less providers (kcp, kcp-like) the logical-cluster boundary is the export boundary (discovery minus built-ins). Exported APIs surfaced on `Connection.status.exportedAPIs`. No catalog CRDs in core. * **Schema delivery**: owned by `Connection` (`source`, `pullPolicy`, `updatePolicy`). `source: Auto` (default) reads provider CRDs when present, else synthesizes CRDs from - discovery + `/openapi/v3` — so kcp-like, CRD-less providers work in core. - `pullPolicy` defaults to `Bound` — CRDs are installed only when a binding references - them; `All` is the eager opt-in. + discovery + `/openapi/v3`, so kcp-like, CRD-less providers work in core. + `pullPolicy` defaults to `Bound`, CRDs are installed only when a binding references + them, `All` is the eager opt-in. * **Conversion webhooks**: CRDs with `strategy: Webhook` are refused in core alpha - (per-API condition + skip); revisit on demand. -* **Sync direction**: fixed — spec consumer→provider, status provider→consumer. A + (per-API condition + skip), revisit on demand. +* **Sync direction**: fixed, spec consumer→provider, status provider→consumer. A `syncMode` field name is reserved per-API but not implemented in alpha. -* **Related resources**: `secrets` + `configmaps` only; `labelSelector` + named +* **Related resources**: `secrets` + `configmaps` only, `labelSelector` + named selectors only. JSONPath reference-following selectors do not enter core. * **Conflicts**: `conflictPolicy: Fail | Adopt` with three-way classification (no markers / ours / foreign-or-stale). `Adopt` only takes *un-owned* objects and never steals one - carrying another binding's/consumer's markers — cross-binding collisions are always - conflicts, first-writer-wins. Per-object detail lives on the conflicting object's own - condition (`ForeignObjectExists` vs `OwnedByAnother`); the binding holds only a - `Conflicts` condition + count. The marker's source cluster UID is the + carrying another binding's/consumer's markers, cross-binding collisions are always + conflicts, first-writer-wins. Conflicts are surfaced authoritatively by a Kubernetes + **Event** on the consumer object plus a **`Conflicts` condition + `conflictCount`** on + the binding (reasons `ForeignObjectExists` vs `OwnedByAnother`), a per-object condition + is written best-effort only (the API server prunes it on CRDs whose `status` schema has + no `conditions` field, confirmed in the POC). The marker's source cluster UID is the `Connection`-pinned identity, so conflicts stay well-defined on CRD-less providers too. * **Cluster identity**: each `Connection` pins the resolved provider (and local) cluster - UID in its status on first connect and is immutable thereafter; a Secret later pointing + UID in its status on first connect and is immutable thereafter, a Secret later pointing at a *different* cluster is rejected (`Connected=False`) rather than silently re-homing synced objects. * **Deletion**: consumer deletion propagates to the provider and the binding/`Connection` - drains object finalizers before finalizing (`DrainingObjects`); `deletion-policy: + drains object finalizers before finalizing (`DrainingObjects`), `deletion-policy: Orphan` opts an object out of provider-side deletion. * **Provider namespaces**: konnector creates missing namespaces iff RBAC allows - (annotated kbind-created, cleaned up on unbind); otherwise condition + wait. + (annotated kube-bind-created, cleaned up on unbind), otherwise condition + wait. * **Heartbeat**: a plain `coordination.k8s.io/Lease` per Connection, maintained by the - konnector in a designated provider namespace. Still zero kbind CRDs on the + konnector in a designated provider namespace. Still zero kube-bind CRDs on the provider. -* **Mapper**: identity only in-tree; compile-time interface for out-of-tree key mapping; +* **Mapper**: identity only in-tree, compile-time interface for out-of-tree key mapping, scope conversion impossible by construction. -* **Topology**: consumer-side pull; the konnector is the **only running component** in - the core — no backend required. Provider needs zero kbind CRDs, controllers, or +* **Topology**: consumer-side pull, the konnector is the **only running component** in + the core, no backend required. Provider needs zero kube-bind CRDs, controllers, or processes. Provider-side credential lifecycle and dead-consumer GC are service-layer jobs (keyed off the Lease). -* **Engine**: built on multicluster-runtime as a bridge between two cluster sets — a +* **Engine**: built on multicluster-runtime as a bridge between two cluster sets, a custom mcr provider turns each `Connection` into a logical provider cluster, and the - consumer side sits behind an mcr provider too (single-cluster in alpha; kcp provider = - one konnector per kcp instance serving all workspaces; fleet provider = sets of + consumer side sits behind an mcr provider too (single-cluster in alpha, kcp provider = + one konnector per kcp instance serving all workspaces, fleet provider = sets of consumer clusters to sets of providers). The sync domain is always *(consumer logical - cluster, Connection)*; multi-consumer is an engine/deployment dimension, never an API + cluster, Connection)*, multi-consumer is an engine/deployment dimension, never an API dimension. Sync controllers are multi-cluster-aware reconcilers, no hand-rolled informer/contextstore machinery. -* **Repo**: new API group, same repo, `v2/` prefix directory — the path tells you the - version. `v2/sdk` (types) + `v2/konnector` (engine) as separate Go modules; no imports - across the v1/v2 boundary in either direction (CI-enforced); v1 paths frozen on main +* **Repo**: new API group, same repo, `v2/` prefix directory, the path tells you the + version. `v2/sdk` (types) + `v2/konnector` (engine) as separate Go modules, no imports + across the v1/v2 boundary in either direction (CI-enforced), v1 paths frozen on main and deleted at v2 GA. -* **Dual-stack**: none. v2 konnector serves only `core.kbind.dev`; the v1alpha2 +* **Dual-stack**: none. v2 konnector serves only `core.kube-bind.io`, the v1alpha2 konnector is maintained on a release branch until deprecation. -* **Backend/UI/CLI redesign**: separate follow-up proposal; this doc only fixes the +* **Backend/UI/CLI redesign**: separate follow-up proposal, this doc only fixes the contract boundary. ## Open questions @@ -667,11 +639,11 @@ Rules: 1. **OpenAPI synthesis fidelity.** How lossy is discovery + `/openapi/v3` → CRD in practice (CEL rules, defaulting edge cases, multi-version with conversion)? Needs a spike against kcp and a kcp-like system (e.g. kplane) before the `Auto` default is - locked. Mitigation already in the contract: the provider is the enforcing side; + locked. Mitigation already in the contract: the provider is the enforcing side, upstream rejections surface as per-object sync conditions. Do we need different way to deliver schema as we do now in v1? 2. **Built-ins filter for `source: OpenAPI`.** Exact exclusion list/heuristic for "minus - built-ins" in `exportedAPIs` (core groups, `*.k8s.io`, kcp's own groups?) — and + built-ins" in `exportedAPIs` (core groups, `*.k8s.io`, kcp's own groups?), and whether it should be overridable on the `Connection`. diff --git a/docs/requirements.txt b/docs/requirements.txt index 251db2a87..d1ad46659 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,12 +1,7 @@ mike==2.1.3 mkdocs==1.6.1 +mkdocs-material[imaging]==9.7.1 mkdocs-awesome-pages-plugin==2.9.2 mkdocs-macros-plugin==1.0.5 -mkdocs-material[imaging]>=9.7.1 -mkdocs-material-extensions==1.3.1 -mkdocs-static-i18n==1.3.0 -pymdown-extensions==11.0.1 -Pygments<2.18 - -# https://github.com/mkdocs/mkdocs/issues/4032 -click<=8.2.1 +pymdown-extensions==10.21.3 +click==8.1.8 diff --git a/docs/scripts/deploy-docs.sh b/docs/scripts/deploy-docs.sh old mode 100755 new mode 100644 index d4ed5bf86..2633e1eeb --- a/docs/scripts/deploy-docs.sh +++ b/docs/scripts/deploy-docs.sh @@ -1,83 +1,23 @@ #!/usr/bin/env bash -# Copyright 2024 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail -set -o xtrace +set -euo pipefail REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) cd "$REPO_ROOT/docs" if [[ "${GITHUB_EVENT_NAME:-}" == "pull_request" ]]; then - # For PRs, we don't want to use GITHUB_REF_NAME, which will be something like merge/1234; instead, we want to use - # the branch the PR is targeting, such as main or release-0.11 - VERSION=$GITHUB_BASE_REF -else - if [[ -n "${GITHUB_REF_NAME:-}" ]]; then - VERSION="${VERSION:-$GITHUB_REF_NAME}" - else - VERSION=${VERSION:-$(git rev-parse --abbrev-ref HEAD)} - fi - - if echo "$VERSION" | grep '^release-[0-9]'; then - VERSION=v$(echo "$VERSION" | cut -d - -f 2) - elif echo "$VERSION" | grep '^v[0-9]\+\.[0-9]\+'; then - VERSION=$(echo "$VERSION" | grep -o '^v[0-9]\+\.[0-9]\+') - fi -fi - -MIKE_OPTIONS=() -MIKE_DEPLOY_OPTIONS=() -MIKE_ALIASES=() - -if [[ -n "${REMOTE:-}" ]]; then - MIKE_OPTIONS+=(--remote "$REMOTE") + echo "Pull requests must build documentation without deploying." >&2 + exit 1 fi -if [[ -n "${BRANCH:-}" ]]; then - MIKE_OPTIONS+=(--branch "$BRANCH") -fi +remote=${REMOTE:-origin} +branch=${BRANCH:-gh-pages} +options=(--remote "$remote" --branch "$branch") -LATEST=$(git describe --tags --match="v[0-9]*" `git rev-list --tags --max-count=1` | grep -o '^v[0-9]\+\.[0-9]\+') -if [[ "${LATEST:-}" == "${VERSION:-}" ]]; then - MIKE_DEPLOY_OPTIONS+=(--update-aliases) - MIKE_ALIASES+=(latest) +if [[ "${PUSH:-0}" == "1" ]]; then + options+=(--push) fi -if [[ -n "${CI:-}" ]]; then - if [[ "${GITHUB_EVENT_NAME:-}" == "push" ]] || [[ "${GITHUB_EVENT_NAME:-}" == "workflow_dispatch" ]]; then - # Only push to gh-pages if we're in GitHub Actions (CI is set) and we have a non-PR event. - MIKE_OPTIONS+=(--push) - fi - - # Always set git user info in CI because even if we're not pushing, we need it - git config user.name kube-bind-ci-bot - git config user.email no-reply@kube-bind.io -else - MIKE_OPTIONS+=(--ignore-remote-status) -fi - -mike deploy "${MIKE_OPTIONS[@]}" "${MIKE_DEPLOY_OPTIONS[@]}" "$VERSION" "${MIKE_ALIASES[@]}" - -if [[ -n "${CI:-}" ]]; then - if [[ "${GITHUB_EVENT_NAME:-}" == "push" ]] || [[ "${GITHUB_EVENT_NAME:-}" == "workflow_dispatch" ]]; then - if [[ "${LATEST:-}" == "${VERSION:-}" ]]; then - # only set the default if we pushed before, otherwise the "latest" alias might not yet exist. - mike set-default "${MIKE_OPTIONS[@]}" latest - fi - fi -fi +git fetch "$remote" "$branch" +message=${DOCS_COMMIT_MESSAGE:-Publish v2 documentation preview} +mike deploy "${options[@]}" --message "$message" --title "v2 (preview)" v2 diff --git a/docs/scripts/serve-docs.sh b/docs/scripts/serve-docs.sh deleted file mode 100755 index d556a5b41..000000000 --- a/docs/scripts/serve-docs.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2024 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) -cd "$REPO_ROOT/docs" - -MIKE_OPTIONS=() - -if [[ -n "${REMOTE:-}" ]]; then - MIKE_OPTIONS+=(--remote "$REMOTE") -fi - -if [[ -n "${BRANCH:-}" ]]; then - MIKE_OPTIONS+=(--branch "$BRANCH") -fi - -# for local docs testing, we don't care what the remote branch looks like. -MIKE_OPTIONS+=(--ignore-remote-status) - -mike set-default "${MIKE_OPTIONS[@]}" main --allow-undefined - -if [[ -n "${DEV_MODE:-}" ]]; then - mkdocs serve --dev-addr=127.0.0.1:8000 --livereload -else - mike serve "${MIKE_OPTIONS[@]}" -fi \ No newline at end of file diff --git a/engine/binding/cleanup.go b/engine/binding/cleanup.go new file mode 100644 index 000000000..b8f156bcc --- /dev/null +++ b/engine/binding/cleanup.go @@ -0,0 +1,246 @@ +/* +Copyright 2026 The kbind 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 binding + +import ( + "context" + "fmt" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// cleanup unwinds what a binding created when it is deleted. For each API the +// binding bound that no *other* binding still covers, it deletes the provider +// copies of synced instances (best effort), releases the syncer finalizer on +// the consumer instances, and — for a cluster-wide unbind — removes the pulled +// CRD (which cascade-deletes the now finalizer-free instances). +// +// - namespace: "" for a cluster-wide unbind; otherwise the Binding's namespace. +// - removeCRD: true for ClusterBinding (owns the CRD), false for Binding. +func (b *base) cleanup(ctx context.Context, obj corev1alpha1.BindingAccessor, namespace string, removeCRD bool) error { + log := ctrl.LoggerFrom(ctx) + spec := obj.BindingSpecP() + + // Best-effort provider client: the Secret/Connection may already be gone + // during a `delete -f`. If unavailable, we still release finalizers so the + // consumer never wedges; orphaned provider copies are the reaper's job. + var providerClient client.Client + conn := &corev1alpha1.Connection{} + if err := b.client.Get(ctx, client.ObjectKey{Name: spec.ConnectionRef.Name}, conn); err == nil { + if pc, perr := b.providerClient(ctx, conn); perr == nil { + providerClient = pc + } else { + log.V(2).Info("provider client unavailable during cleanup; releasing finalizers only", "err", perr.Error()) + } + } + localUID := conn.Status.LocalClusterUID + + for _, api := range spec.APIs { + if b.otherBindingCovers(ctx, api.Name, obj) { + continue + } + gvr, ok, err := b.gvrFor(ctx, api.Name) + if err != nil { + return err + } + if !ok { + continue // CRD already gone + } + + if err := b.drainInstances(ctx, gvr, namespace, providerClient, localUID); err != nil { + return err + } + + if removeCRD { + crd := &apiextensionsv1.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: api.Name}} + if err := b.client.Delete(ctx, crd); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("deleting pulled CRD %s: %w", api.Name, err) + } + } + } + + // Delete related Secret/ConfigMap copies this binding created. + return b.cleanupRelated(ctx, obj, namespace, providerClient) +} + +// countConflicts counts consumer instances of gvr in scope that the syncer +// marked as conflicting (the conflict annotation). +func (b *base) countConflicts(ctx context.Context, gvr schema.GroupVersionResource, namespace string) int32 { + ri := b.dyn.Resource(gvr) + var lister dynamicLister = ri + if namespace != "" { + lister = ri.Namespace(namespace) + } + list, err := lister.List(ctx, metav1.ListOptions{}) + if err != nil { + return 0 + } + var n int32 + for i := range list.Items { + if list.Items[i].GetAnnotations()[corev1alpha1.AnnotationConflict] != "" { + n++ + } + } + return n +} + +// drainInstances deletes provider copies and releases the syncer finalizer on +// every consumer instance of gvr in scope. +func (b *base) drainInstances(ctx context.Context, gvr schema.GroupVersionResource, namespace string, providerClient client.Client, localUID string) error { + ri := b.dyn.Resource(gvr) + var lister dynamicLister = ri + if namespace != "" { + lister = ri.Namespace(namespace) + } + list, err := lister.List(ctx, metav1.ListOptions{}) + if err != nil { + if apierrors.IsNotFound(err) { + return nil + } + return fmt.Errorf("listing instances of %s: %w", gvr.Resource, err) + } + + for i := range list.Items { + inst := &list.Items[i] + if !controllerutil.ContainsFinalizer(inst, corev1alpha1.FinalizerSyncer) { + continue + } + // Delete the provider copy if it is ours (best effort), unless the + // instance opted out with deletion-policy: Orphan. + if providerClient != nil && inst.GetAnnotations()[corev1alpha1.AnnotationDeletionPolicy] != corev1alpha1.DeletionPolicyOrphan { + if err := deleteProviderCopy(ctx, providerClient, gvr, inst, localUID); err != nil { + return err + } + } + // Release the syncer finalizer so the consumer instance can be deleted. + controllerutil.RemoveFinalizer(inst, corev1alpha1.FinalizerSyncer) + var updErr error + if inst.GetNamespace() == "" { + _, updErr = ri.Update(ctx, inst, metav1.UpdateOptions{}) + } else { + _, updErr = ri.Namespace(inst.GetNamespace()).Update(ctx, inst, metav1.UpdateOptions{}) + } + if client.IgnoreNotFound(updErr) != nil { + return fmt.Errorf("releasing finalizer on %s/%s: %w", inst.GetNamespace(), inst.GetName(), updErr) + } + } + return nil +} + +func deleteProviderCopy(ctx context.Context, providerClient client.Client, gvr schema.GroupVersionResource, inst *unstructured.Unstructured, localUID string) error { + existing := &unstructured.Unstructured{} + existing.SetGroupVersionKind(gvkFromGVR(gvr, inst)) + err := providerClient.Get(ctx, client.ObjectKey{Namespace: inst.GetNamespace(), Name: inst.GetName()}, existing) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + // Best effort: if we can't read the provider object during teardown we + // can't confirm ownership, so skip rather than fail the whole unbind. + return nil //nolint:nilerr // intentional best-effort skip + } + // Only delete if it carries our markers. + ann := existing.GetAnnotations() + if ann[corev1alpha1.AnnotationConsumerClusterUID] != localUID || ann[corev1alpha1.AnnotationConsumerObjectUID] != string(inst.GetUID()) { + return nil + } + return client.IgnoreNotFound(providerClient.Delete(ctx, existing)) +} + +func gvkFromGVR(gvr schema.GroupVersionResource, inst *unstructured.Unstructured) schema.GroupVersionKind { + if gvk := inst.GroupVersionKind(); gvk.Kind != "" { + return gvk + } + return schema.GroupVersionKind{Group: gvr.Group, Version: gvr.Version} +} + +// otherBindingCovers reports whether a binding other than self lists crdName. +func (b *base) otherBindingCovers(ctx context.Context, crdName string, self corev1alpha1.BindingAccessor) bool { + var cbs corev1alpha1.ClusterBindingList + if err := b.client.List(ctx, &cbs); err == nil { + for i := range cbs.Items { + if cbs.Items[i].DeletionTimestamp != nil || cbs.Items[i].UID == self.GetUID() { + continue + } + if listsAPI(cbs.Items[i].Spec.APIs, crdName) { + return true + } + } + } + var bs corev1alpha1.BindingList + if err := b.client.List(ctx, &bs); err == nil { + for i := range bs.Items { + if bs.Items[i].DeletionTimestamp != nil || bs.Items[i].UID == self.GetUID() { + continue + } + if listsAPI(bs.Items[i].Spec.APIs, crdName) { + return true + } + } + } + return false +} + +// gvrFor resolves the GVR for an exported API CRD name from the pulled consumer +// CRD (storage/served version). Returns ok=false if the CRD is already gone. +func (b *base) gvrFor(ctx context.Context, crdName string) (schema.GroupVersionResource, bool, error) { + crd := &apiextensionsv1.CustomResourceDefinition{} + if err := b.client.Get(ctx, client.ObjectKey{Name: crdName}, crd); err != nil { + if apierrors.IsNotFound(err) { + return schema.GroupVersionResource{}, false, nil + } + return schema.GroupVersionResource{}, false, err + } + version := "" + for _, v := range crd.Spec.Versions { + if v.Storage { + version = v.Name + break + } + if version == "" && v.Served { + version = v.Name + } + } + if version == "" { + return schema.GroupVersionResource{}, false, nil + } + return schema.GroupVersionResource{Group: crd.Spec.Group, Version: version, Resource: crd.Spec.Names.Plural}, true, nil +} + +func listsAPI(apis []corev1alpha1.APIRef, crdName string) bool { + for _, a := range apis { + if a.Name == crdName { + return true + } + } + return false +} + +// dynamicLister is the common List surface of a (namespaced or not) dynamic +// resource interface. +type dynamicLister interface { + List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) +} diff --git a/engine/binding/reconciler.go b/engine/binding/reconciler.go new file mode 100644 index 000000000..975e0c5e7 --- /dev/null +++ b/engine/binding/reconciler.go @@ -0,0 +1,384 @@ +/* +Copyright 2026 The kbind 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 binding reconciles ClusterBinding and Binding objects: it validates +// the referenced Connection, pulls the CRDs for the listed APIs onto the +// consumer (schema.source: CRD), and reports per-API state. +package binding + +import ( + "context" + "fmt" + "sort" + "strings" + "time" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + "github.com/kbind/kbind/engine/crdpull" + "github.com/kbind/kbind/engine/openapi" + "github.com/kbind/kbind/engine/remote" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// base holds the shared dependencies and logic for both binding kinds. +type base struct { + client client.Client + dyn dynamic.Interface + scheme *runtime.Scheme + resync time.Duration + newClient func(ctx context.Context, conn *corev1alpha1.Connection) (client.Client, error) +} + +// resyncInterval is how often a Ready binding re-reconciles to refresh +// conflictCount (conflicts are detected by the syncer, not via binding events). +func (b *base) resyncInterval() time.Duration { + if b.resync > 0 { + return b.resync + } + return 30 * time.Second +} + +func (b *base) providerClient(ctx context.Context, conn *corev1alpha1.Connection) (client.Client, error) { + if b.newClient != nil { + return b.newClient(ctx, conn) + } + return remote.ProviderClient(ctx, b.client, conn, b.scheme) +} + +// reconcileAccessor drives a binding (cluster or namespaced) toward Ready. +// namespace scopes conflict counting: "" for a ClusterBinding (cluster-wide), +// the Binding's namespace otherwise. +func (b *base) reconcileAccessor(ctx context.Context, obj corev1alpha1.BindingAccessor, namespace string) error { + spec := obj.BindingSpecP() + status := obj.BindingStatusP() + + // Resolve the Connection. + conn := &corev1alpha1.Connection{} + if err := b.client.Get(ctx, client.ObjectKey{Name: spec.ConnectionRef.Name}, conn); err != nil { + if apierrors.IsNotFound(err) { + setReady(status, obj, metav1.ConditionFalse, corev1alpha1.ReasonPending, + fmt.Sprintf("Connection %q not found yet", spec.ConnectionRef.Name)) + return nil + } + return fmt.Errorf("getting Connection %q: %w", spec.ConnectionRef.Name, err) + } + if !apimeta.IsStatusConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) { + setReady(status, obj, metav1.ConditionFalse, corev1alpha1.ReasonPending, + fmt.Sprintf("Connection %q not ready yet", spec.ConnectionRef.Name)) + return nil + } + + providerClient, err := b.providerClient(ctx, conn) + if err != nil { + return fmt.Errorf("building provider client: %w", err) + } + + var ( + boundAPIs []corev1alpha1.BoundAPI + notExported []string + pendingSchema []string + ) + for _, api := range spec.APIs { + exported, ok := conn.Status.ExportsAPI(api.Name) + if !ok { + notExported = append(notExported, api.Name) + continue + } + var hash string + if conn.Status.ActiveSchemaSource == corev1alpha1.SchemaSourceOpenAPI { + // CRD-less provider (kcp): install the CRD for THIS bound API only + // (unless pullPolicy: None, where the user manages CRDs). The Connection + // no longer installs the whole discovery set, so the provider's built-in + // groups (e.g. *.kcp.io) never reach the consumer — only what a binding + // references does. + crd := &apiextensionsv1.CustomResourceDefinition{} + err := b.client.Get(ctx, client.ObjectKey{Name: api.Name}, crd) + if apierrors.IsNotFound(err) && conn.Spec.Schema.PullPolicy != corev1alpha1.PullPolicyNone { + cfg, cerr := remote.RestConfigFromConnection(ctx, b.client, conn) + if cerr != nil { + return fmt.Errorf("provider rest config: %w", cerr) + } + synth, serr := openapi.SynthesizeCRD(ctx, cfg, api.Name) + if serr != nil { + return fmt.Errorf("synthesizing CRD %q: %w", api.Name, serr) + } + if _, ierr := crdpull.Install(ctx, b.client, synth, conn.Name, conn.Spec.Schema.UpdatePolicy != corev1alpha1.UpdatePolicyOnce); ierr != nil { + return fmt.Errorf("installing synthesized CRD %q: %w", api.Name, ierr) + } + err = b.client.Get(ctx, client.ObjectKey{Name: api.Name}, crd) + } + if err != nil { + if apierrors.IsNotFound(err) { + // Exported but the CRD is not present yet (pullPolicy: None until + // the user applies it) — a transient wait, not "not exported". + pendingSchema = append(pendingSchema, api.Name) + continue + } + return fmt.Errorf("getting synthesized CRD %q: %w", api.Name, err) + } + hash = crd.Annotations[crdpull.AnnotationSchemaHash] + } else { + h, _, err := crdpull.Pull(ctx, b.client, providerClient, api.Name, conn.Name, crdpull.Options{ + Create: conn.Spec.Schema.PullPolicy != corev1alpha1.PullPolicyNone, + Update: conn.Spec.Schema.UpdatePolicy != corev1alpha1.UpdatePolicyOnce, + }) + if err != nil { + if apierrors.IsForbidden(err) { + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionPermissionDenied, metav1.ConditionTrue, corev1alpha1.ReasonForbidden, + fmt.Sprintf("pulling CRD %q is forbidden by provider RBAC", api.Name))) + setReady(status, obj, metav1.ConditionFalse, corev1alpha1.ReasonForbidden, "provider RBAC denies reading the CRD") + return nil + } + return fmt.Errorf("pulling CRD %q: %w", api.Name, err) + } + hash = h + } + // Count instances we refused to sync due to a foreign provider target. + var conflicts int32 + if gvr, ok, gerr := b.gvrFor(ctx, api.Name); gerr == nil && ok { + conflicts = b.countConflicts(ctx, gvr, namespace) + } + boundAPIs = append(boundAPIs, corev1alpha1.BoundAPI{Name: exported.Name, CRDHash: hash, ConflictCount: conflicts}) + } + sort.Slice(boundAPIs, func(i, j int) bool { return boundAPIs[i].Name < boundAPIs[j].Name }) + status.BoundAPIs = boundAPIs + + if len(notExported) > 0 { + setReady(status, obj, metav1.ConditionFalse, corev1alpha1.ReasonAPINotExported, + fmt.Sprintf("APIs not exported by the provider yet: %s", strings.Join(notExported, ", "))) + return nil + } + if len(pendingSchema) > 0 { + setReady(status, obj, metav1.ConditionFalse, corev1alpha1.ReasonPending, + fmt.Sprintf("waiting for the Connection to install the synthesized CRD(s): %s", strings.Join(pendingSchema, ", "))) + return nil + } + + // Sync related Secrets/ConfigMaps in the declared direction, scoped like the + // binding. + if err := b.reconcileRelated(ctx, obj, namespace, providerClient, conn.Status.LocalClusterUID); err != nil { + return fmt.Errorf("syncing related resources: %w", err) + } + + var totalConflicts int32 + for _, ba := range boundAPIs { + totalConflicts += ba.ConflictCount + } + if totalConflicts > 0 { + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionConflicts, metav1.ConditionTrue, corev1alpha1.ReasonForeignObjectExists, + fmt.Sprintf("%d object(s) skipped due to foreign ownership; see object Events", totalConflicts))) + } else { + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionConflicts, metav1.ConditionFalse, corev1alpha1.ReasonAsExpected, "no conflicts")) + } + + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionPermissionDenied, metav1.ConditionFalse, corev1alpha1.ReasonAsExpected, "no RBAC denials")) + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionSynced, metav1.ConditionTrue, corev1alpha1.ReasonAsExpected, "all APIs installed")) + setReady(status, obj, metav1.ConditionTrue, corev1alpha1.ReasonAsExpected, "binding ready") + return nil +} + +func condition(obj client.Object, t string, s metav1.ConditionStatus, reason, msg string) metav1.Condition { + return metav1.Condition{ + Type: t, + Status: s, + Reason: reason, + Message: msg, + ObservedGeneration: obj.GetGeneration(), + } +} + +func setReady(status *corev1alpha1.BindingStatus, obj client.Object, s metav1.ConditionStatus, reason, msg string) { + apimeta.SetStatusCondition(&status.Conditions, condition(obj, corev1alpha1.ConditionReady, s, reason, msg)) +} + +// ----- ClusterBinding ----- + +// ClusterReconciler reconciles ClusterBinding objects. +type ClusterReconciler struct { + base + // Resync is how often a Ready binding re-reconciles to refresh conflictCount + // (0 = default 30s). + Resync time.Duration +} + +// SetupWithManager registers the ClusterBinding reconciler. It also watches +// Connection so bindings re-reconcile when their connection becomes Ready or +// its exported APIs change (level-triggered). +func (r *ClusterReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.base.client = mgr.GetClient() + r.base.scheme = mgr.GetScheme() + r.base.resync = r.Resync + dyn, err := dynamic.NewForConfig(mgr.GetConfig()) + if err != nil { + return err + } + r.base.dyn = dyn + return ctrl.NewControllerManagedBy(mgr). + For(&corev1alpha1.ClusterBinding{}). + Watches(&corev1alpha1.Connection{}, handler.EnqueueRequestsFromMapFunc(r.bindingsForConnection)). + Named("clusterbinding"). + Complete(r) +} + +func (r *ClusterReconciler) bindingsForConnection(ctx context.Context, conn client.Object) []reconcile.Request { + var list corev1alpha1.ClusterBindingList + if err := r.base.client.List(ctx, &list); err != nil { + return nil + } + var reqs []reconcile.Request + for i := range list.Items { + if list.Items[i].Spec.ConnectionRef.Name == conn.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Name: list.Items[i].Name}}) + } + } + return reqs +} + +// Reconcile reconciles a ClusterBinding. +func (r *ClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + cb := &corev1alpha1.ClusterBinding{} + if err := r.base.client.Get(ctx, req.NamespacedName, cb); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if cb.DeletionTimestamp != nil { + if !controllerutil.ContainsFinalizer(cb, corev1alpha1.FinalizerCleanup) { + return ctrl.Result{}, nil + } + // Cluster-wide unbind: clean up cluster-wide and remove the pulled CRDs. + if err := r.base.cleanup(ctx, cb, "", true); err != nil { + return ctrl.Result{}, err + } + controllerutil.RemoveFinalizer(cb, corev1alpha1.FinalizerCleanup) + return ctrl.Result{}, client.IgnoreNotFound(r.base.client.Update(ctx, cb)) + } + if controllerutil.AddFinalizer(cb, corev1alpha1.FinalizerCleanup) { + return ctrl.Result{}, r.base.client.Update(ctx, cb) + } + orig := cb.DeepCopy() + rerr := r.base.reconcileAccessor(ctx, cb, "") + if !equalBindingStatus(&orig.Status, &cb.Status) { + if err := r.base.client.Status().Update(ctx, cb); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: r.base.resyncInterval()}, rerr +} + +// ----- Binding (namespaced) ----- + +// NamespacedReconciler reconciles Binding objects. +type NamespacedReconciler struct { + base + // Resync is how often a Ready binding re-reconciles to refresh conflictCount + // (0 = default 30s). + Resync time.Duration +} + +// SetupWithManager registers the Binding reconciler. It also watches Connection +// so bindings re-reconcile when their connection becomes Ready (level-triggered). +func (r *NamespacedReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.base.client = mgr.GetClient() + r.base.scheme = mgr.GetScheme() + r.base.resync = r.Resync + dyn, err := dynamic.NewForConfig(mgr.GetConfig()) + if err != nil { + return err + } + r.base.dyn = dyn + return ctrl.NewControllerManagedBy(mgr). + For(&corev1alpha1.Binding{}). + Watches(&corev1alpha1.Connection{}, handler.EnqueueRequestsFromMapFunc(r.bindingsForConnection)). + Named("binding"). + Complete(r) +} + +func (r *NamespacedReconciler) bindingsForConnection(ctx context.Context, conn client.Object) []reconcile.Request { + var list corev1alpha1.BindingList + if err := r.base.client.List(ctx, &list); err != nil { + return nil + } + var reqs []reconcile.Request + for i := range list.Items { + if list.Items[i].Spec.ConnectionRef.Name == conn.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: list.Items[i].Namespace, Name: list.Items[i].Name}}) + } + } + return reqs +} + +// Reconcile reconciles a Binding. +func (r *NamespacedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + b := &corev1alpha1.Binding{} + if err := r.base.client.Get(ctx, req.NamespacedName, b); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if b.DeletionTimestamp != nil { + if !controllerutil.ContainsFinalizer(b, corev1alpha1.FinalizerCleanup) { + return ctrl.Result{}, nil + } + // Namespaced unbind: clean up only instances in this namespace; the CRD + // is shared and stays. + if err := r.base.cleanup(ctx, b, b.Namespace, false); err != nil { + return ctrl.Result{}, err + } + controllerutil.RemoveFinalizer(b, corev1alpha1.FinalizerCleanup) + return ctrl.Result{}, client.IgnoreNotFound(r.base.client.Update(ctx, b)) + } + if controllerutil.AddFinalizer(b, corev1alpha1.FinalizerCleanup) { + return ctrl.Result{}, r.base.client.Update(ctx, b) + } + orig := b.DeepCopy() + rerr := r.base.reconcileAccessor(ctx, b, b.Namespace) + if !equalBindingStatus(&orig.Status, &b.Status) { + if err := r.base.client.Status().Update(ctx, b); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: r.base.resyncInterval()}, rerr +} + +func equalBindingStatus(a, b *corev1alpha1.BindingStatus) bool { + if len(a.BoundAPIs) != len(b.BoundAPIs) { + return false + } + for i := range a.BoundAPIs { + if a.BoundAPIs[i] != b.BoundAPIs[i] { + return false + } + } + if len(a.Conditions) != len(b.Conditions) { + return false + } + for i := range a.Conditions { + ac, bc := a.Conditions[i], b.Conditions[i] + if ac.Type != bc.Type || ac.Status != bc.Status || ac.Reason != bc.Reason || ac.Message != bc.Message { + return false + } + } + return true +} diff --git a/engine/binding/related.go b/engine/binding/related.go new file mode 100644 index 000000000..c59657ce8 --- /dev/null +++ b/engine/binding/related.go @@ -0,0 +1,219 @@ +/* +Copyright 2026 The kbind 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 binding + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// relatedFieldOwner is the SSA field manager for related-resource writes. +const relatedFieldOwner = "kbind-konnector-related" + +// relatedGVK maps a related-resource kind to its GVK. Only secrets/configmaps. +func relatedGVK(resource string) (schema.GroupVersionKind, bool) { + switch resource { + case "secrets": + return schema.GroupVersionKind{Version: "v1", Kind: "Secret"}, true + case "configmaps": + return schema.GroupVersionKind{Version: "v1", Kind: "ConfigMap"}, true + default: + return schema.GroupVersionKind{}, false + } +} + +// reconcileRelated syncs the binding's related Secrets/ConfigMaps in the +// declared direction, scoped like the binding, and garbage-collects copies that +// no longer match. Identity-preserving, marked with the binding UID. +func (b *base) reconcileRelated(ctx context.Context, obj corev1alpha1.BindingAccessor, namespace string, providerClient client.Client, localUID string) error { + spec := obj.BindingSpecP() + bindingUID := string(obj.GetUID()) + for i := range spec.RelatedResources { + rr := &spec.RelatedResources[i] + gvk, ok := relatedGVK(rr.Resource) + if !ok { + continue + } + source, target := b.client, providerClient // FromConsumer + if rr.Direction == corev1alpha1.FromProvider { + source, target = providerClient, b.client + } + + sel := labels.Everything() + if rr.Selector != nil && rr.Selector.LabelSelector != nil { + s, err := metav1.LabelSelectorAsSelector(rr.Selector.LabelSelector) + if err != nil { + return fmt.Errorf("invalid related selector: %w", err) + } + sel = s + } + names := nameSet(rr.Selector) + + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + opts := []client.ListOption{client.MatchingLabelsSelector{Selector: sel}} + if namespace != "" { + opts = append(opts, client.InNamespace(namespace)) + } + if err := source.List(ctx, list, opts...); err != nil { + return fmt.Errorf("listing related %s: %w", rr.Resource, err) + } + + matched := map[client.ObjectKey]bool{} + for j := range list.Items { + src := &list.Items[j] + if names != nil && !names[src.GetName()] { + continue + } + key := client.ObjectKey{Namespace: src.GetNamespace(), Name: src.GetName()} + matched[key] = true + if err := applyRelated(ctx, target, gvk, src, localUID, bindingUID); err != nil { + return err + } + } + if err := b.gcRelated(ctx, target, gvk, namespace, bindingUID, matched); err != nil { + return err + } + } + return nil +} + +// applyRelated copies a related object to the target side (identity-preserving) +// with our markers, refusing to overwrite a foreign object of the same name. +func applyRelated(ctx context.Context, target client.Client, gvk schema.GroupVersionKind, src *unstructured.Unstructured, localUID, bindingUID string) error { + key := client.ObjectKey{Namespace: src.GetNamespace(), Name: src.GetName()} + + existing := &unstructured.Unstructured{} + existing.SetGroupVersionKind(gvk) + switch err := target.Get(ctx, key, existing); { + case err == nil: + if existing.GetAnnotations()[corev1alpha1.AnnotationRelatedBinding] != bindingUID { + return nil // foreign object — never overwrite + } + case apierrors.IsNotFound(err): + if src.GetNamespace() != "" { + if err := ensureNamespace(ctx, target, src.GetNamespace(), localUID); err != nil { + return err + } + } + default: + return fmt.Errorf("getting related target: %w", err) + } + + out := &unstructured.Unstructured{} + out.SetGroupVersionKind(gvk) + out.SetNamespace(src.GetNamespace()) + out.SetName(src.GetName()) + out.SetLabels(map[string]string{corev1alpha1.LabelManaged: "true"}) + out.SetAnnotations(map[string]string{ + corev1alpha1.AnnotationConsumerClusterUID: localUID, + corev1alpha1.AnnotationRelatedBinding: bindingUID, + }) + for _, f := range []string{"data", "stringData", "binaryData", "type", "immutable"} { + if v, ok, _ := unstructured.NestedFieldCopy(src.Object, f); ok { + _ = unstructured.SetNestedField(out.Object, v, f) + } + } + if err := target.Patch(ctx, out, client.Apply, client.FieldOwner(relatedFieldOwner), client.ForceOwnership); err != nil { + return fmt.Errorf("applying related %s/%s: %w", src.GetNamespace(), src.GetName(), err) + } + return nil +} + +// gcRelated deletes target copies we own (this binding) that are no longer in +// the matched set. +func (b *base) gcRelated(ctx context.Context, target client.Client, gvk schema.GroupVersionKind, namespace, bindingUID string, matched map[client.ObjectKey]bool) error { + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + opts := []client.ListOption{client.MatchingLabels{corev1alpha1.LabelManaged: "true"}} + if namespace != "" { + opts = append(opts, client.InNamespace(namespace)) + } + if err := target.List(ctx, list, opts...); err != nil { + return fmt.Errorf("listing managed related %s: %w", gvk.Kind, err) + } + for i := range list.Items { + o := &list.Items[i] + if o.GetAnnotations()[corev1alpha1.AnnotationRelatedBinding] != bindingUID { + continue + } + if matched[client.ObjectKey{Namespace: o.GetNamespace(), Name: o.GetName()}] { + continue + } + if err := target.Delete(ctx, o); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("gc related %s/%s: %w", o.GetNamespace(), o.GetName(), err) + } + } + return nil +} + +// cleanupRelated deletes all related copies this binding created, on unbind. +func (b *base) cleanupRelated(ctx context.Context, obj corev1alpha1.BindingAccessor, namespace string, providerClient client.Client) error { + spec := obj.BindingSpecP() + bindingUID := string(obj.GetUID()) + for i := range spec.RelatedResources { + rr := &spec.RelatedResources[i] + gvk, ok := relatedGVK(rr.Resource) + if !ok { + continue + } + target := providerClient // FromConsumer copies live on the provider + if rr.Direction == corev1alpha1.FromProvider { + target = b.client + } + if target == nil { + continue + } + if err := b.gcRelated(ctx, target, gvk, namespace, bindingUID, nil); err != nil { + return err + } + } + return nil +} + +func nameSet(sel *corev1alpha1.RelatedResourceSelector) map[string]bool { + if sel == nil || len(sel.Names) == 0 { + return nil + } + m := make(map[string]bool, len(sel.Names)) + for _, n := range sel.Names { + m[n] = true + } + return m +} + +// ensureNamespace creates the target namespace if absent (best-effort markers). +func ensureNamespace(ctx context.Context, c client.Client, name, localUID string) error { + ns := &unstructured.Unstructured{} + ns.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: "Namespace"}) + ns.SetName(name) + ns.SetLabels(map[string]string{corev1alpha1.LabelManaged: "true"}) + ns.SetAnnotations(map[string]string{corev1alpha1.AnnotationConsumerClusterUID: localUID}) + if err := c.Create(ctx, ns); err != nil && !apierrors.IsAlreadyExists(err) { + return err + } + return nil +} diff --git a/engine/connection/reconciler.go b/engine/connection/reconciler.go new file mode 100644 index 000000000..f1c302a32 --- /dev/null +++ b/engine/connection/reconciler.go @@ -0,0 +1,614 @@ +/* +Copyright 2026 The kbind 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 connection reconciles Connection objects: it resolves the provider +// credentials, pins the provider/consumer cluster identity, and discovers the +// APIs the provider exports to those credentials. +package connection + +import ( + "context" + "fmt" + "sort" + "time" + + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + "github.com/kbind/kbind/engine/crdpull" + "github.com/kbind/kbind/engine/openapi" + "github.com/kbind/kbind/engine/remote" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// Reconciler reconciles Connection objects on the consumer cluster. +type Reconciler struct { + // Client is the consumer-cluster client. + Client client.Client + // Scheme is used to build the provider-cluster client. + Scheme *runtime.Scheme + // NewProviderClient builds a direct client for the provider cluster from a + // Connection. Overridable in tests; defaults to a fresh client from the + // resolved kubeconfig. + NewProviderClient func(ctx context.Context, conn *corev1alpha1.Connection) (client.Client, error) + // DiscoveryResync is how often a Ready Connection re-discovers exported APIs + // (so a CRD labeled exported after connect is picked up). 0 = default 30s. + DiscoveryResync time.Duration + // LeaseNamespace is the provider namespace where the konnector maintains its + // heartbeat Lease. Empty = the kubeconfig context's namespace if set (a + // service-layer issuer pins it to the per-consumer tenancy boundary), + // falling back to "kbind". + LeaseNamespace string +} + +const ( + leaseNamespaceDefault = "kbind" + leaseDurationSeconds = 60 +) + +// leaseNamespace resolves where the heartbeat Lease lives: the explicit +// override, else the kubeconfig context's namespace (the issuer pins it to the +// per-consumer boundary, where tenant RBAC allows Leases), else "kbind". +func (r *Reconciler) leaseNamespace(ctx context.Context, conn *corev1alpha1.Connection) string { + if r.LeaseNamespace != "" { + return r.LeaseNamespace + } + if ns, err := remote.DefaultNamespaceFromConnection(ctx, r.Client, conn); err == nil && ns != "" { + return ns + } + return leaseNamespaceDefault +} + +func (r *Reconciler) discoveryResync() time.Duration { + if r.DiscoveryResync > 0 { + return r.DiscoveryResync + } + return 30 * time.Second +} + +// SetupWithManager registers the reconciler with the consumer manager. It also +// watches Secrets so a Connection created before its kubeconfig Secret resolves +// as soon as the Secret arrives (order-independent "one apply"). +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { + r.Client = mgr.GetClient() + r.Scheme = mgr.GetScheme() + if r.NewProviderClient == nil { + r.NewProviderClient = r.defaultProviderClient + } + return ctrl.NewControllerManagedBy(mgr). + For(&corev1alpha1.Connection{}). + Watches(&corev1.Secret{}, handler.EnqueueRequestsFromMapFunc(r.connectionsForSecret)). + Named("connection"). + Complete(r) +} + +// connectionsForSecret enqueues every Connection whose kubeconfigSecretRef +// points at the given Secret. +func (r *Reconciler) connectionsForSecret(ctx context.Context, secret client.Object) []reconcile.Request { + var list corev1alpha1.ConnectionList + if err := r.Client.List(ctx, &list); err != nil { + return nil + } + var reqs []reconcile.Request + for i := range list.Items { + ref := list.Items[i].Spec.KubeconfigSecretRef + if ref.Namespace == secret.GetNamespace() && ref.Name == secret.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Name: list.Items[i].Name}}) + } + } + return reqs +} + +func (r *Reconciler) defaultProviderClient(ctx context.Context, conn *corev1alpha1.Connection) (client.Client, error) { + cfg, err := remote.RestConfigFromConnection(ctx, r.Client, conn) + if err != nil { + return nil, err + } + return client.New(cfg, client.Options{Scheme: r.Scheme}) +} + +// Reconcile drives a Connection toward Ready: SecretValid, Connected (identity +// pinned), and exportedAPIs discovered. +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := ctrl.LoggerFrom(ctx) + + conn := &corev1alpha1.Connection{} + if err := r.Client.Get(ctx, req.NamespacedName, conn); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + + if conn.DeletionTimestamp != nil { + return r.reconcileDelete(ctx, conn) + } + + // Ensure cleanup finalizers on the Connection and (best effort) its Secret + // before doing any work, so teardown can always unwind. + if added, err := r.ensureFinalizers(ctx, conn); err != nil { + return ctrl.Result{}, err + } else if added { + return ctrl.Result{}, nil + } + + orig := conn.DeepCopy() + reconcileErr := r.reconcile(ctx, conn) + + if !apiequalStatus(orig, conn) { + if err := r.Client.Status().Update(ctx, conn); err != nil { + log.Error(err, "updating Connection status") + return ctrl.Result{}, err + } + } + // Periodically re-discover so a CRD labeled exported after connect is picked + // up (the binding watches the Connection and reacts to exportedAPIs changes). + result := ctrl.Result{} + if reconcileErr == nil { + result.RequeueAfter = r.discoveryResync() + } + return result, reconcileErr +} + +func (r *Reconciler) reconcile(ctx context.Context, conn *corev1alpha1.Connection) error { + // 1. Build the provider client (validates the secret + kubeconfig). + providerClient, err := r.NewProviderClient(ctx, conn) + if err != nil { + setCondition(conn, corev1alpha1.ConditionSecretValid, metav1.ConditionFalse, corev1alpha1.ReasonSecretNotFound, err.Error()) + setNotReady(conn, corev1alpha1.ReasonSecretNotFound, "kubeconfig secret not usable yet") + return nil // level-triggered: resolves when the secret arrives + } + setCondition(conn, corev1alpha1.ConditionSecretValid, metav1.ConditionTrue, corev1alpha1.ReasonAsExpected, "kubeconfig secret resolved") + + // 2. Pin and verify cluster identity. + remoteUID, err := remote.ClusterUID(ctx, providerClient) + if err != nil { + if apierrors.IsForbidden(err) { + return r.denyPermission(conn, "reading provider cluster identity is forbidden by RBAC: "+err.Error()) + } + setCondition(conn, corev1alpha1.ConditionConnected, metav1.ConditionFalse, corev1alpha1.ReasonPending, err.Error()) + setNotReady(conn, corev1alpha1.ReasonPending, "cannot reach provider cluster") + return nil + } + localUID, err := remote.ClusterUID(ctx, r.Client) + if err != nil { + return fmt.Errorf("determining local cluster identity: %w", err) + } + if conn.Status.RemoteClusterUID != "" && conn.Status.RemoteClusterUID != remoteUID { + setCondition(conn, corev1alpha1.ConditionConnected, metav1.ConditionFalse, corev1alpha1.ReasonClusterIdentityChanged, + fmt.Sprintf("kubeconfig now points at cluster %s, but %s was pinned", remoteUID, conn.Status.RemoteClusterUID)) + setNotReady(conn, corev1alpha1.ReasonClusterIdentityChanged, "provider cluster identity changed") + return nil + } + conn.Status.RemoteClusterUID = remoteUID + if conn.Status.LocalClusterUID == "" { + conn.Status.LocalClusterUID = localUID + } + setCondition(conn, corev1alpha1.ConditionConnected, metav1.ConditionTrue, corev1alpha1.ReasonAsExpected, "connected to provider") + + // 3. Discover exported APIs and install schemas, per schema.source. + source, exported, err := r.discoverAndInstall(ctx, conn, providerClient) + if err != nil { + if apierrors.IsForbidden(err) { + return r.denyPermission(conn, "discovery is forbidden by provider RBAC: "+err.Error()) + } + return fmt.Errorf("discovering exported APIs: %w", err) + } + conn.Status.ActiveSchemaSource = source + conn.Status.ExportedAPIs = exported + setCondition(conn, corev1alpha1.ConditionPermissionDenied, metav1.ConditionFalse, corev1alpha1.ReasonAsExpected, "no RBAC denials") + + // pullPolicy: All — eagerly install every exported CRD on the consumer, + // without waiting for a binding. (Bound/None defer to the binding.) The CRD + // source pulls the provider CRD object; the OpenAPI source has no CRD object + // to pull, so it synthesizes and installs. + if conn.Spec.Schema.PullPolicy == corev1alpha1.PullPolicyAll { + if source == corev1alpha1.SchemaSourceOpenAPI { + cfg, err := remote.RestConfigFromConnection(ctx, r.Client, conn) + if err != nil { + return fmt.Errorf("provider rest config: %w", err) + } + crds, err := openapi.SynthesizeCRDs(ctx, cfg) + if err != nil { + return fmt.Errorf("synthesizing CRDs: %w", err) + } + for _, crd := range crds { + if _, err := crdpull.Install(ctx, r.Client, crd, conn.Name, conn.Spec.Schema.UpdatePolicy != corev1alpha1.UpdatePolicyOnce); err != nil { + return fmt.Errorf("eager-installing CRD %q: %w", crd.Name, err) + } + } + } else { + for i := range exported { + if _, _, err := crdpull.Pull(ctx, r.Client, providerClient, exported[i].Name, conn.Name, crdpull.Options{ + Create: true, + Update: conn.Spec.Schema.UpdatePolicy != corev1alpha1.UpdatePolicyOnce, + }); err != nil { + return fmt.Errorf("eager-pulling CRD %q: %w", exported[i].Name, err) + } + } + } + } + + // autoBind: maintain a managed ClusterBinding (named after the Connection) + // mirroring the exported APIs. + if conn.Spec.AutoBind { + if err := r.reconcileAutoBind(ctx, conn, exported); err != nil { + return fmt.Errorf("reconciling autoBind: %w", err) + } + } + + // Heartbeat: maintain a Lease on the provider so a service-layer reaper can + // detect a consumer that stopped checking in. Best-effort — a missing Lease + // never blocks sync. + if err := r.heartbeat(ctx, providerClient, conn); err != nil { + ctrl.LoggerFrom(ctx).V(2).Info("heartbeat lease update failed (continuing)", "err", err.Error()) + } + + setCondition(conn, corev1alpha1.ConditionReady, metav1.ConditionTrue, corev1alpha1.ReasonAsExpected, "connection ready") + return nil +} + +// heartbeat creates or renews a coordination.k8s.io/Lease on the provider in the +// designated namespace, keyed by the consumer cluster identity. Zero kbind +// CRDs on the provider — just a plain Lease. +func (r *Reconciler) heartbeat(ctx context.Context, providerClient client.Client, conn *corev1alpha1.Connection) error { + if conn.Status.LocalClusterUID == "" { + return nil + } + ns := r.leaseNamespace(ctx, conn) + if err := providerClient.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}); err != nil && + !apierrors.IsAlreadyExists(err) && !apierrors.IsForbidden(err) { + return fmt.Errorf("ensuring lease namespace: %w", err) + } + + now := metav1.NowMicro() + lease := &coordinationv1.Lease{ObjectMeta: metav1.ObjectMeta{Name: leaseName(conn), Namespace: ns}} + _, err := controllerutil.CreateOrUpdate(ctx, providerClient, lease, func() error { + if lease.Labels == nil { + lease.Labels = map[string]string{} + } + lease.Labels[corev1alpha1.LabelManaged] = "true" + if lease.Annotations == nil { + lease.Annotations = map[string]string{} + } + lease.Annotations[corev1alpha1.AnnotationConsumerClusterUID] = conn.Status.LocalClusterUID + lease.Annotations[corev1alpha1.AnnotationConnection] = conn.Name + lease.Spec.HolderIdentity = ptr.To(conn.Status.LocalClusterUID) + lease.Spec.LeaseDurationSeconds = ptr.To(int32(leaseDurationSeconds)) + if lease.Spec.AcquireTime == nil { + lease.Spec.AcquireTime = &now + } + lease.Spec.RenewTime = &now + return nil + }) + return err +} + +// leaseName keys the heartbeat Lease by (Connection, consumer cluster): the +// Connection name for per-connection liveness (a service-layer bundle names +// the Connection after its Grant, so a reaper gets per-grant staleness via +// the connection annotation), plus a consumer-cluster-UID suffix so two +// consumer clusters using the same Connection name in a shared namespace do +// not fight over one Lease. +func leaseName(conn *corev1alpha1.Connection) string { + uid := conn.Status.LocalClusterUID + if len(uid) > 10 { + uid = uid[:10] + } + return conn.Name + "-" + uid +} + +// reconcileAutoBind keeps a managed ClusterBinding named after the Connection in +// sync with the exported APIs. With no exports it removes the managed binding. +func (r *Reconciler) reconcileAutoBind(ctx context.Context, conn *corev1alpha1.Connection, exported []corev1alpha1.ExportedAPI) error { + cb := &corev1alpha1.ClusterBinding{ObjectMeta: metav1.ObjectMeta{Name: conn.Name}} + if len(exported) == 0 { + return client.IgnoreNotFound(r.Client.Delete(ctx, cb)) + } + apis := make([]corev1alpha1.APIRef, 0, len(exported)) + for i := range exported { + apis = append(apis, corev1alpha1.APIRef{Name: exported[i].Name}) + } + _, err := controllerutil.CreateOrUpdate(ctx, r.Client, cb, func() error { + if err := controllerutil.SetControllerReference(conn, cb, r.Scheme); err != nil { + return err + } + if cb.Labels == nil { + cb.Labels = map[string]string{} + } + cb.Labels[corev1alpha1.LabelManaged] = "true" + cb.Spec.ConnectionRef = corev1alpha1.ConnectionRef{Name: conn.Name} + cb.Spec.APIs = apis + return nil + }) + return err +} + +// ensureFinalizers adds the cleanup finalizer to the Connection and to its +// referenced Secret (so the credential outlives the Connection during a +// `delete -f` teardown). Returns true if it changed the Connection. +func (r *Reconciler) ensureFinalizers(ctx context.Context, conn *corev1alpha1.Connection) (bool, error) { + // Secret finalizer (best effort: the Secret may not exist yet). + ref := conn.Spec.KubeconfigSecretRef + var secret corev1.Secret + if err := r.Client.Get(ctx, types.NamespacedName{Namespace: ref.Namespace, Name: ref.Name}, &secret); err == nil { + if controllerutil.AddFinalizer(&secret, corev1alpha1.FinalizerCleanup) { + if err := r.Client.Update(ctx, &secret); err != nil { + return false, fmt.Errorf("adding finalizer to secret: %w", err) + } + } + } else if !apierrors.IsNotFound(err) { + return false, err + } + + if controllerutil.AddFinalizer(conn, corev1alpha1.FinalizerCleanup) { + if err := r.Client.Update(ctx, conn); err != nil { + return false, fmt.Errorf("adding finalizer to connection: %w", err) + } + return true, nil + } + return false, nil +} + +// reconcileDelete blocks the Connection from finalizing until no Binding +// references it (so binding cleanup can still reach the provider through it), +// then releases the Secret's finalizer and its own. +func (r *Reconciler) reconcileDelete(ctx context.Context, conn *corev1alpha1.Connection) (ctrl.Result, error) { + if !controllerutil.ContainsFinalizer(conn, corev1alpha1.FinalizerCleanup) { + return ctrl.Result{}, nil + } + + // Explicitly delete the managed autoBind ClusterBinding so it drains; relying + // on owner-ref GC would deadlock (this Connection won't finalize until its + // bindings are gone, but GC won't remove the owned binding until the + // Connection is gone). + if conn.Spec.AutoBind { + managed := &corev1alpha1.ClusterBinding{ObjectMeta: metav1.ObjectMeta{Name: conn.Name}} + if err := r.Client.Delete(ctx, managed); client.IgnoreNotFound(err) != nil { + return ctrl.Result{}, err + } + } + + refs, err := r.bindingsReferencing(ctx, conn.Name) + if err != nil { + return ctrl.Result{}, err + } + if refs > 0 { + setCondition(conn, corev1alpha1.ConditionReady, metav1.ConditionFalse, "DrainingBindings", + fmt.Sprintf("waiting for %d binding(s) to finish unbinding", refs)) + if err := r.Client.Status().Update(ctx, conn); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + return ctrl.Result{RequeueAfter: 2 * time.Second}, nil + } + + // Release the Secret finalizer — but only if no other Connection still + // references the same Secret. + ref := conn.Spec.KubeconfigSecretRef + if others, err := r.otherConnectionsUsingSecret(ctx, ref, conn.Name); err != nil { + return ctrl.Result{}, err + } else if others == 0 { + var secret corev1.Secret + if err := r.Client.Get(ctx, types.NamespacedName{Namespace: ref.Namespace, Name: ref.Name}, &secret); err == nil { + if controllerutil.RemoveFinalizer(&secret, corev1alpha1.FinalizerCleanup) { + if err := r.Client.Update(ctx, &secret); err != nil { + return ctrl.Result{}, fmt.Errorf("releasing secret finalizer: %w", err) + } + } + } else if !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + } + + controllerutil.RemoveFinalizer(conn, corev1alpha1.FinalizerCleanup) + if err := r.Client.Update(ctx, conn); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + return ctrl.Result{}, nil +} + +// otherConnectionsUsingSecret counts Connections other than self whose +// kubeconfigSecretRef points at the same Secret, so we don't release the +// Secret finalizer while another Connection still depends on it. +func (r *Reconciler) otherConnectionsUsingSecret(ctx context.Context, ref corev1alpha1.SecretKeyRef, selfName string) (int, error) { + var list corev1alpha1.ConnectionList + if err := r.Client.List(ctx, &list); err != nil { + return 0, err + } + var n int + for i := range list.Items { + c := &list.Items[i] + if c.Name == selfName || c.DeletionTimestamp != nil { + continue + } + if c.Spec.KubeconfigSecretRef.Namespace == ref.Namespace && c.Spec.KubeconfigSecretRef.Name == ref.Name { + n++ + } + } + return n, nil +} + +// bindingsReferencing counts ClusterBindings and Bindings whose connectionRef +// names this Connection. +func (r *Reconciler) bindingsReferencing(ctx context.Context, name string) (int, error) { + var n int + var cbs corev1alpha1.ClusterBindingList + if err := r.Client.List(ctx, &cbs); err != nil { + return 0, err + } + for i := range cbs.Items { + if cbs.Items[i].Spec.ConnectionRef.Name == name { + n++ + } + } + var bs corev1alpha1.BindingList + if err := r.Client.List(ctx, &bs); err != nil { + return 0, err + } + for i := range bs.Items { + if bs.Items[i].Spec.ConnectionRef.Name == name { + n++ + } + } + return n, nil +} + +// discoverExportedCRDs lists provider CRDs carrying the exported label and maps +// them to ExportedAPI entries. +// discoverAndInstall resolves the schema source and returns the active source + +// exported APIs. It NEVER installs here: installation is gated by pullPolicy +// (All: eager in Reconcile; Bound: the binding installs only referenced APIs; +// None: never), identically for both sources. For CRD it lists label-gated +// provider CRDs; for OpenAPI it synthesizes candidate CRDs from discovery + +// /openapi/v3 (CRD-less providers like kcp) purely to populate exportedAPIs. +// Auto probes CRD first and falls back to OpenAPI. +func (r *Reconciler) discoverAndInstall(ctx context.Context, conn *corev1alpha1.Connection, providerClient client.Client) (corev1alpha1.SchemaSource, []corev1alpha1.ExportedAPI, error) { + src := conn.Spec.Schema.Source + if src == "" { + src = corev1alpha1.SchemaSourceAuto + } + + if src == corev1alpha1.SchemaSourceCRD || src == corev1alpha1.SchemaSourceAuto { + exported, err := discoverExportedCRDs(ctx, providerClient) + if err != nil { + return "", nil, err + } + if len(exported) > 0 || src == corev1alpha1.SchemaSourceCRD { + return corev1alpha1.SchemaSourceCRD, exported, nil + } + // Auto with no labeled CRDs → fall through to OpenAPI. + } + + // OpenAPI: synthesize candidate CRDs from discovery + /openapi/v3 to populate + // exportedAPIs. Do NOT install here — installation is pullPolicy-gated (see + // Reconcile for All, the binding for Bound). This keeps the provider's + // built-in groups (e.g. kcp's *.kcp.io) off the consumer unless a binding + // references them, while still letting the binding go Ready (the API is in + // exportedAPIs) so status + related-resource sync work. + cfg, err := remote.RestConfigFromConnection(ctx, r.Client, conn) + if err != nil { + return "", nil, err + } + crds, err := openapi.SynthesizeCRDs(ctx, cfg) + if err != nil { + return "", nil, err + } + exported := make([]corev1alpha1.ExportedAPI, 0, len(crds)) + for _, crd := range crds { + versions := make([]string, len(crd.Spec.Versions)) + for i, v := range crd.Spec.Versions { + versions[i] = v.Name + } + exported = append(exported, corev1alpha1.ExportedAPI{ + Name: crd.Name, + Group: crd.Spec.Group, + Resource: crd.Spec.Names.Plural, + Scope: crd.Spec.Scope, + Versions: versions, + }) + } + sort.Slice(exported, func(i, j int) bool { return exported[i].Name < exported[j].Name }) + return corev1alpha1.SchemaSourceOpenAPI, exported, nil +} + +func discoverExportedCRDs(ctx context.Context, providerClient client.Client) ([]corev1alpha1.ExportedAPI, error) { + var crds apiextensionsv1.CustomResourceDefinitionList + if err := providerClient.List(ctx, &crds, client.MatchingLabels{corev1alpha1.LabelExported: "true"}); err != nil { + return nil, err + } + + out := make([]corev1alpha1.ExportedAPI, 0, len(crds.Items)) + for i := range crds.Items { + crd := &crds.Items[i] + versions := make([]string, 0, len(crd.Spec.Versions)) + for _, v := range crd.Spec.Versions { + if v.Served { + versions = append(versions, v.Name) + } + } + if len(versions) == 0 { + continue + } + out = append(out, corev1alpha1.ExportedAPI{ + Name: crd.Name, + Group: crd.Spec.Group, + Resource: crd.Spec.Names.Plural, + Scope: crd.Spec.Scope, + Versions: versions, + }) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +func setCondition(conn *corev1alpha1.Connection, condType string, status metav1.ConditionStatus, reason, msg string) { + apimeta.SetStatusCondition(&conn.Status.Conditions, metav1.Condition{ + Type: condType, + Status: status, + Reason: reason, + Message: msg, + ObservedGeneration: conn.Generation, + }) +} + +func setNotReady(conn *corev1alpha1.Connection, reason, msg string) { + setCondition(conn, corev1alpha1.ConditionReady, metav1.ConditionFalse, reason, msg) +} + +// denyPermission marks the Connection as blocked by provider RBAC. +func (r *Reconciler) denyPermission(conn *corev1alpha1.Connection, msg string) error { + setCondition(conn, corev1alpha1.ConditionPermissionDenied, metav1.ConditionTrue, corev1alpha1.ReasonForbidden, msg) + setNotReady(conn, corev1alpha1.ReasonForbidden, msg) + return nil // level-triggered: resolves when RBAC is granted (re-discovery requeue) +} + +func apiequalStatus(a, b *corev1alpha1.Connection) bool { + return apiequal(a.Status, b.Status) +} + +// apiequal compares two ConnectionStatus values ignoring condition timestamps. +func apiequal(a, b corev1alpha1.ConnectionStatus) bool { + if a.RemoteClusterUID != b.RemoteClusterUID || a.LocalClusterUID != b.LocalClusterUID { + return false + } + if len(a.ExportedAPIs) != len(b.ExportedAPIs) { + return false + } + for i := range a.ExportedAPIs { + if a.ExportedAPIs[i].Name != b.ExportedAPIs[i].Name { + return false + } + } + if len(a.Conditions) != len(b.Conditions) { + return false + } + for i := range a.Conditions { + ac, bc := a.Conditions[i], b.Conditions[i] + if ac.Type != bc.Type || ac.Status != bc.Status || ac.Reason != bc.Reason || ac.Message != bc.Message { + return false + } + } + return true +} diff --git a/engine/crdpull/crdpull.go b/engine/crdpull/crdpull.go new file mode 100644 index 000000000..070d62ce5 --- /dev/null +++ b/engine/crdpull/crdpull.go @@ -0,0 +1,200 @@ +/* +Copyright 2026 The kbind 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 crdpull centralizes how a provider CRD is installed on the consumer: +// stripping it to a consumer-installable form, creating it, and (per +// updatePolicy) updating it when the provider schema changes. Shared by the +// Connection (pullPolicy: All) and the binding (pullPolicy: Bound). +package crdpull + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// AnnotationSchemaHash records the hash of the installed schema so updatePolicy +// can detect provider changes without re-deriving. +const AnnotationSchemaHash = "core.kbind.io/schema-hash" + +// Options control how the CRD is reconciled on the consumer. +type Options struct { + // Create installs the CRD if absent (pullPolicy Bound/All). When false + // (pullPolicy None) an absent CRD is left to the user; an existing one is + // only stamped with the managed/connection markers so sync can find it. + Create bool + // Update re-applies the CRD spec when the provider schema changes + // (updatePolicy Always). When false (updatePolicy Once) the schema is pinned. + Update bool +} + +// Pull reconciles the consumer CRD for crdName from the provider. It returns the +// schema hash and whether the CRD is installed on the consumer. +func Pull(ctx context.Context, consumer client.Client, provider client.Reader, crdName, connName string, opts Options) (hash string, installed bool, err error) { + var remoteCRD apiextensionsv1.CustomResourceDefinition + if err := provider.Get(ctx, client.ObjectKey{Name: crdName}, &remoteCRD); err != nil { + return "", false, fmt.Errorf("reading provider CRD: %w", err) + } + desired := ForConsumer(&remoteCRD, connName) + return install(ctx, consumer, desired, connName, opts) +} + +// Install installs an already-built (e.g. OpenAPI-synthesized) consumer CRD, +// stamping the managed/connection/schema-hash markers. updatePolicy: Always +// follows changes; Once pins. +func Install(ctx context.Context, consumer client.Client, crd *apiextensionsv1.CustomResourceDefinition, connName string, update bool) (hash string, err error) { + desired := crd.DeepCopy() + if desired.Labels == nil { + desired.Labels = map[string]string{} + } + desired.Labels[corev1alpha1.LabelManaged] = "true" + if desired.Annotations == nil { + desired.Annotations = map[string]string{} + } + desired.Annotations[corev1alpha1.AnnotationConnection] = connName + h, _, err := install(ctx, consumer, desired, connName, Options{Create: true, Update: update}) + return h, err +} + +// install reconciles a fully-built consumer CRD (create-if-absent, update on +// schema change per opts.Update, stamp-only when opts.Create is false). +func install(ctx context.Context, consumer client.Client, desired *apiextensionsv1.CustomResourceDefinition, connName string, opts Options) (string, bool, error) { + hash := Hash(desired) + desired.Annotations[AnnotationSchemaHash] = hash + + var existing apiextensionsv1.CustomResourceDefinition + getErr := consumer.Get(ctx, client.ObjectKey{Name: desired.Name}, &existing) + switch { + case apierrors.IsNotFound(getErr): + if !opts.Create { + return hash, false, nil // None + absent: user manages it + } + if err := consumer.Create(ctx, desired); err != nil { + return "", false, fmt.Errorf("creating consumer CRD: %w", err) + } + return hash, true, nil + + case getErr != nil: + return "", false, getErr + + default: + if !opts.Create { + // None + present: only stamp the markers so the syncer can find it. + if stampMarkers(&existing, connName) { + if err := consumer.Update(ctx, &existing); err != nil { + return "", false, fmt.Errorf("stamping consumer CRD: %w", err) + } + } + return hash, true, nil + } + if opts.Update && existing.Annotations[AnnotationSchemaHash] != hash { + existing.Spec = desired.Spec + if existing.Annotations == nil { + existing.Annotations = map[string]string{} + } + existing.Annotations[AnnotationSchemaHash] = hash + existing.Annotations[corev1alpha1.AnnotationConnection] = connName + if existing.Labels == nil { + existing.Labels = map[string]string{} + } + existing.Labels[corev1alpha1.LabelManaged] = "true" + if err := consumer.Update(ctx, &existing); err != nil { + return "", false, fmt.Errorf("updating consumer CRD: %w", err) + } + } + return hash, true, nil + } +} + +// ForConsumer strips a provider CRD to something installable on the consumer +// without a conversion webhook: single storage/served version, conversion +// forced to None, no webhook/caBundle, no ownerRefs/status. It is marked managed +// and annotated with the source Connection. +func ForConsumer(in *apiextensionsv1.CustomResourceDefinition, connName string) *apiextensionsv1.CustomResourceDefinition { + out := in.DeepCopy() + out.ResourceVersion = "" + out.UID = "" + out.ManagedFields = nil + out.OwnerReferences = nil + out.Status = apiextensionsv1.CustomResourceDefinitionStatus{} + + var keep *apiextensionsv1.CustomResourceDefinitionVersion + for i := range out.Spec.Versions { + v := &out.Spec.Versions[i] + if v.Storage { + keep = v + break + } + if keep == nil && v.Served { + keep = v + } + } + if keep != nil { + k := *keep + k.Storage = true + k.Served = true + out.Spec.Versions = []apiextensionsv1.CustomResourceDefinitionVersion{k} + } + out.Spec.Conversion = &apiextensionsv1.CustomResourceConversion{Strategy: apiextensionsv1.NoneConverter} + + if out.Labels == nil { + out.Labels = map[string]string{} + } + out.Labels[corev1alpha1.LabelManaged] = "true" + if out.Annotations == nil { + out.Annotations = map[string]string{} + } + out.Annotations[corev1alpha1.AnnotationConnection] = connName + return out +} + +// Hash is a content hash over the consumer CRD spec, so updatePolicy: Always can +// detect provider schema changes. +func Hash(crd *apiextensionsv1.CustomResourceDefinition) string { + b, err := json.Marshal(crd.Spec) + if err != nil { + return "" + } + sum := sha256.Sum256(b) + return "sha256:" + hex.EncodeToString(sum[:])[:16] +} + +func stampMarkers(crd *apiextensionsv1.CustomResourceDefinition, connName string) bool { + changed := false + if crd.Labels[corev1alpha1.LabelManaged] != "true" { + if crd.Labels == nil { + crd.Labels = map[string]string{} + } + crd.Labels[corev1alpha1.LabelManaged] = "true" + changed = true + } + if crd.Annotations[corev1alpha1.AnnotationConnection] != connName { + if crd.Annotations == nil { + crd.Annotations = map[string]string{} + } + crd.Annotations[corev1alpha1.AnnotationConnection] = connName + changed = true + } + return changed +} diff --git a/engine/crdpull/crdpull_test.go b/engine/crdpull/crdpull_test.go new file mode 100644 index 000000000..b0f4527eb --- /dev/null +++ b/engine/crdpull/crdpull_test.go @@ -0,0 +1,148 @@ +/* +Copyright 2026 The kbind 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 crdpull + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +func scheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + require.NoError(t, apiextensionsv1.AddToScheme(s)) + return s +} + +func providerCRD(printerCol string) *apiextensionsv1.CustomResourceDefinition { + return &apiextensionsv1.CustomResourceDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets.example.org"}, + Spec: apiextensionsv1.CustomResourceDefinitionSpec{ + Group: "example.org", + Names: apiextensionsv1.CustomResourceDefinitionNames{Plural: "widgets", Kind: "Widget"}, + Scope: apiextensionsv1.NamespaceScoped, + Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{ + Name: "v1", + Served: true, + Storage: true, + AdditionalPrinterColumns: []apiextensionsv1.CustomResourceColumnDefinition{ + {Name: printerCol, Type: "string", JSONPath: ".spec." + printerCol}, + }, + }}, + }, + } +} + +func TestPull_BoundCreatesCRD(t *testing.T) { + s := scheme(t) + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("size")).Build() + consumer := fake.NewClientBuilder().WithScheme(s).Build() + + hash, installed, err := Pull(context.Background(), consumer, provider, "widgets.example.org", "conn", Options{Create: true}) + require.NoError(t, err) + require.True(t, installed) + require.NotEmpty(t, hash) + + got := &apiextensionsv1.CustomResourceDefinition{} + require.NoError(t, consumer.Get(context.Background(), client.ObjectKey{Name: "widgets.example.org"}, got)) + require.Equal(t, "true", got.Labels[corev1alpha1.LabelManaged]) + require.Equal(t, "conn", got.Annotations[corev1alpha1.AnnotationConnection]) +} + +func TestPull_UpdatePolicyOnce_DoesNotUpdate(t *testing.T) { + s := scheme(t) + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("size")).Build() + consumer := fake.NewClientBuilder().WithScheme(s).Build() + + // First pull installs it. + _, _, err := Pull(context.Background(), consumer, provider, "widgets.example.org", "conn", Options{Create: true, Update: true}) + require.NoError(t, err) + + // Provider schema changes, but updatePolicy: Once (Update=false) pins it. + provider2 := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("colour")).Build() + _, _, err = Pull(context.Background(), consumer, provider2, "widgets.example.org", "conn", Options{Create: true, Update: false}) + require.NoError(t, err) + + got := &apiextensionsv1.CustomResourceDefinition{} + require.NoError(t, consumer.Get(context.Background(), client.ObjectKey{Name: "widgets.example.org"}, got)) + require.Equal(t, "size", got.Spec.Versions[0].AdditionalPrinterColumns[0].Name, "Once must not follow provider changes") +} + +func TestPull_UpdatePolicyAlways_FollowsProviderChanges(t *testing.T) { + s := scheme(t) + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("size")).Build() + consumer := fake.NewClientBuilder().WithScheme(s).Build() + + _, hash1, err := pull3(t, consumer, provider, Options{Create: true, Update: true}) + require.NoError(t, err) + + provider2 := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("colour")).Build() + _, hash2, err := pull3(t, consumer, provider2, Options{Create: true, Update: true}) + require.NoError(t, err) + require.NotEqual(t, hash1, hash2, "schema hash must change when provider schema changes") + + got := &apiextensionsv1.CustomResourceDefinition{} + require.NoError(t, consumer.Get(context.Background(), client.ObjectKey{Name: "widgets.example.org"}, got)) + require.Equal(t, "colour", got.Spec.Versions[0].AdditionalPrinterColumns[0].Name, "Always must follow provider changes") +} + +func TestPull_NoneAbsent_NotInstalled(t *testing.T) { + s := scheme(t) + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("size")).Build() + consumer := fake.NewClientBuilder().WithScheme(s).Build() + + _, installed, err := Pull(context.Background(), consumer, provider, "widgets.example.org", "conn", Options{Create: false}) + require.NoError(t, err) + require.False(t, installed, "pullPolicy None must not create the CRD") + + got := &apiextensionsv1.CustomResourceDefinition{} + require.True(t, client.IgnoreNotFound(consumer.Get(context.Background(), client.ObjectKey{Name: "widgets.example.org"}, got)) == nil) + require.Empty(t, got.Name) +} + +func TestPull_NonePresent_StampsMarkers(t *testing.T) { + s := scheme(t) + // A user-installed CRD already on the consumer, without our markers. + existing := providerCRD("size") + provider := fake.NewClientBuilder().WithScheme(s).WithObjects(providerCRD("size")).Build() + consumer := fake.NewClientBuilder().WithScheme(s).WithObjects(existing.DeepCopy()).Build() + + _, installed, err := Pull(context.Background(), consumer, provider, "widgets.example.org", "conn", Options{Create: false}) + require.NoError(t, err) + require.True(t, installed) + + got := &apiextensionsv1.CustomResourceDefinition{} + require.NoError(t, consumer.Get(context.Background(), client.ObjectKey{Name: "widgets.example.org"}, got)) + require.Equal(t, "true", got.Labels[corev1alpha1.LabelManaged], "None must stamp an existing CRD so the syncer finds it") + require.Equal(t, "conn", got.Annotations[corev1alpha1.AnnotationConnection]) +} + +// pull3 returns (installed, hash, err) reordered for convenience. +func pull3(t *testing.T, consumer client.Client, provider client.Reader, opts Options) (bool, string, error) { + t.Helper() + hash, installed, err := Pull(context.Background(), consumer, provider, "widgets.example.org", "conn", opts) + return installed, hash, err +} diff --git a/engine/mapper/mapper.go b/engine/mapper/mapper.go new file mode 100644 index 000000000..52b6010dd --- /dev/null +++ b/engine/mapper/mapper.go @@ -0,0 +1,67 @@ +/* +Copyright 2026 The kbind 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 mapper defines the Mapper extension point: how the konnector +// translates object identity (namespace/name) between the consumer and the +// provider when syncing instances. +// +// Core ships exactly one implementation — Identity — and the interface is a +// compile-time seam so out-of-tree konnector builds can restore tenancy +// key-mapping (e.g. v1's "Prefixed" isolation) without forking the engine. It +// is deliberately kept out of the CRD API: the core API never promises +// renaming. +// +// The interface maps KEYS only; it cannot change an object's scope +// (cluster-scoped stays cluster-scoped). That is the hard line v2 draws — v1's +// "Namespaced" scope-conversion isolation is intentionally not expressible here. +// A later, separate Transformer interface (mutating the object payload — label +// injection, field stripping) is possible but deliberately deferred. +package mapper + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// ObjectKey is a namespace/name identity. It aliases controller-runtime's +// client.ObjectKey for drop-in interop with the syncer. +type ObjectKey = client.ObjectKey + +// Mapper translates object identity between consumer and provider. Core +// registers exactly one implementation: Identity. +type Mapper interface { + // ToProvider maps a consumer object key to its provider key. + ToProvider(gvr schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) + // ToConsumer is the inverse of ToProvider; it must round-trip, i.e. + // ToConsumer(gvr, ToProvider(gvr, k)) == k. + ToConsumer(gvr schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) +} + +// Identity is the core Mapper: the consumer ns/name equals the provider ns/name +// with no transformation. It is the only mapping core ships. +type Identity struct{} + +// ToProvider returns key unchanged. +func (Identity) ToProvider(_ schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) { + return key, nil +} + +// ToConsumer returns key unchanged. +func (Identity) ToConsumer(_ schema.GroupVersionResource, key ObjectKey) (ObjectKey, error) { + return key, nil +} + +var _ Mapper = Identity{} diff --git a/engine/mapper/mapper_test.go b/engine/mapper/mapper_test.go new file mode 100644 index 000000000..42733dee5 --- /dev/null +++ b/engine/mapper/mapper_test.go @@ -0,0 +1,70 @@ +/* +Copyright 2026 The kbind 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 mapper_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/kbind/kbind/engine/mapper" +) + +var widgetGVR = schema.GroupVersionResource{Group: "example.org", Version: "v1", Resource: "widgets"} + +func TestIdentity_RoundTrips(t *testing.T) { + m := mapper.Identity{} + in := mapper.ObjectKey{Namespace: "team-a", Name: "w1"} + + prov, err := m.ToProvider(widgetGVR, in) + require.NoError(t, err) + require.Equal(t, in, prov, "Identity must not change the key on the way to the provider") + + back, err := m.ToConsumer(widgetGVR, prov) + require.NoError(t, err) + require.Equal(t, in, back, "Identity must round-trip") +} + +// prefixMapper is an out-of-tree-style Mapper that prefixes the provider +// namespace, exercising the interface the way a custom build would (v1's +// "Prefixed" isolation). It lives in the test to prove the seam is usable and +// that the round-trip contract is satisfiable by a non-identity mapping. +type prefixMapper struct{ prefix string } + +func (p prefixMapper) ToProvider(_ schema.GroupVersionResource, key mapper.ObjectKey) (mapper.ObjectKey, error) { + return mapper.ObjectKey{Namespace: p.prefix + key.Namespace, Name: key.Name}, nil +} + +func (p prefixMapper) ToConsumer(_ schema.GroupVersionResource, key mapper.ObjectKey) (mapper.ObjectKey, error) { + return mapper.ObjectKey{Namespace: strings.TrimPrefix(key.Namespace, p.prefix), Name: key.Name}, nil +} + +func TestMapper_NonIdentityRoundTrips(t *testing.T) { + var m mapper.Mapper = prefixMapper{prefix: "consumer-7-"} + in := mapper.ObjectKey{Namespace: "team-a", Name: "w1"} + + prov, err := m.ToProvider(widgetGVR, in) + require.NoError(t, err) + require.Equal(t, "consumer-7-team-a", prov.Namespace) + require.Equal(t, "w1", prov.Name) + + back, err := m.ToConsumer(widgetGVR, prov) + require.NoError(t, err) + require.Equal(t, in, back, "a Mapper must round-trip: ToConsumer(ToProvider(k)) == k") +} diff --git a/engine/openapi/openapi.go b/engine/openapi/openapi.go new file mode 100644 index 000000000..bd8c427c9 --- /dev/null +++ b/engine/openapi/openapi.go @@ -0,0 +1,304 @@ +/* +Copyright 2026 The kbind 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 openapi synthesizes CRDs for a CRD-less provider (kcp, aggregated +// APIs) from server discovery + the published /openapi/v3 schemas. This is the +// schema.source: OpenAPI path. Known fidelity limits (CEL, defaulting, +// multi-version conversion) are accepted — the provider remains the enforcing +// side. +package openapi + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "strings" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + k8sversion "k8s.io/apimachinery/pkg/version" + "k8s.io/client-go/discovery" + "k8s.io/client-go/rest" +) + +// builtinGroups are never exported via the OpenAPI boundary. +var builtinGroups = map[string]bool{ + "": true, // core + "apps": true, + "batch": true, + "extensions": true, + "policy": true, + "autoscaling": true, + "networking.k8s.io": true, +} + +// isBuiltinGroup reports whether a group is a Kubernetes built-in (excluded from +// the OpenAPI export boundary). +func isBuiltinGroup(group string) bool { + return builtinGroups[group] || strings.HasSuffix(group, ".k8s.io") || group == "apiregistration.k8s.io" +} + +// crdVersionInfo holds the per-version data collected during discovery. +type crdVersionInfo struct { + gv schema.GroupVersion + resource metav1.APIResource + hasStatus bool + props *apiextensionsv1.JSONSchemaProps +} + +// SynthesizeCRDs discovers every served, non-built-in API on the provider and +// synthesizes a consumer-installable CRD for each from its /openapi/v3 schema. +// All discovered versions of a group-resource are merged into a single CRD; +// the preferred version (per discovery) is marked as the storage version. +func SynthesizeCRDs(ctx context.Context, cfg *rest.Config) ([]*apiextensionsv1.CustomResourceDefinition, error) { + dc, err := discovery.NewDiscoveryClientForConfig(cfg) + if err != nil { + return nil, err + } + apiGroups, resourceLists, err := dc.ServerGroupsAndResources() + if err != nil { + // Partial discovery (an aggregated API may be down) is tolerable. + if len(resourceLists) == 0 { + return nil, fmt.Errorf("discovery: %w", err) + } + } + + // Build preferred-version map (group → preferred version name) from discovery. + preferredVersion := make(map[string]string, len(apiGroups)) + for _, g := range apiGroups { + preferredVersion[g.Name] = g.PreferredVersion.Version + } + + root := dc.OpenAPIV3() + paths, err := root.Paths() + if err != nil { + return nil, fmt.Errorf("openapi v3 paths: %w", err) + } + + // Collect all versions per group-resource before building CRDs. + versionsForGR := map[schema.GroupResource][]crdVersionInfo{} + for _, rl := range resourceLists { + gv, err := schema.ParseGroupVersion(rl.GroupVersion) + if err != nil || isBuiltinGroup(gv.Group) { + continue + } + + hasStatus := map[string]bool{} + for _, r := range rl.APIResources { + if base, sub, ok := strings.Cut(r.Name, "/"); ok && sub == "status" { + hasStatus[base] = true + } + } + + gvObj, ok := paths["apis/"+gv.Group+"/"+gv.Version] + if !ok { + continue + } + doc, err := gvObj.Schema("application/json") + if err != nil { + continue + } + + for _, r := range rl.APIResources { + if strings.Contains(r.Name, "/") { // skip subresources + continue + } + gvk := schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: r.Kind} + props, err := schemaForGVK(doc, gvk) + if err != nil { + continue // no usable schema; skip this resource + } + gr := schema.GroupResource{Group: gv.Group, Resource: r.Name} + versionsForGR[gr] = append(versionsForGR[gr], crdVersionInfo{ + gv: gv, + resource: r, + hasStatus: hasStatus[r.Name], + props: props, + }) + } + } + + out := make([]*apiextensionsv1.CustomResourceDefinition, 0, len(versionsForGR)) + for gr, versions := range versionsForGR { + out = append(out, buildCRD(gr, versions, preferredVersion[gr.Group])) + } + return out, nil +} + +// SynthesizeCRD synthesizes the single CRD named ".", for +// on-demand install of one bound API (schema.source: OpenAPI, pullPolicy: Bound). +// Returns an error if the provider does not export that resource. +func SynthesizeCRD(ctx context.Context, cfg *rest.Config, name string) (*apiextensionsv1.CustomResourceDefinition, error) { + crds, err := SynthesizeCRDs(ctx, cfg) + if err != nil { + return nil, err + } + for _, crd := range crds { + if crd.Name == name { + return crd, nil + } + } + return nil, fmt.Errorf("provider does not export %q", name) +} + +func buildCRD(gr schema.GroupResource, versions []crdVersionInfo, preferredVer string) *apiextensionsv1.CustomResourceDefinition { + // Keep deterministic order so that we don't trigger updates without actually changing the schema. + sort.SliceStable(versions, func(i, j int) bool { + return k8sversion.CompareKubeAwareVersionStrings(versions[i].gv.Version, versions[j].gv.Version) > 0 + }) + + // Determine the storage version: use the preferred version if it was + // discovered, otherwise fall back to the highest-priority version. + storageVer := preferredVer + storageFound := false + for _, v := range versions { + if v.gv.Version == storageVer { + storageFound = true + break + } + } + if !storageFound { + storageVer = versions[0].gv.Version + } + + // Canonical resource metadata (names, scope) comes from the storage version. + canonical := versions[0] + for _, v := range versions { + if v.gv.Version == storageVer { + canonical = v + break + } + } + + scope := apiextensionsv1.ClusterScoped + if canonical.resource.Namespaced { + scope = apiextensionsv1.NamespaceScoped + } + singular := canonical.resource.SingularName + if singular == "" { + singular = strings.ToLower(canonical.resource.Kind) + } + + crdVersions := make([]apiextensionsv1.CustomResourceDefinitionVersion, 0, len(versions)) + for _, v := range versions { + crdv := apiextensionsv1.CustomResourceDefinitionVersion{ + Name: v.gv.Version, + Served: true, + Storage: v.gv.Version == storageVer, + Schema: &apiextensionsv1.CustomResourceValidation{OpenAPIV3Schema: v.props}, + } + if v.hasStatus { + crdv.Subresources = &apiextensionsv1.CustomResourceSubresources{ + Status: &apiextensionsv1.CustomResourceSubresourceStatus{}, + } + } + crdVersions = append(crdVersions, crdv) + } + + return &apiextensionsv1.CustomResourceDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: gr.Resource + "." + gr.Group}, + Spec: apiextensionsv1.CustomResourceDefinitionSpec{ + Group: gr.Group, + Names: apiextensionsv1.CustomResourceDefinitionNames{ + Plural: canonical.resource.Name, + Singular: singular, + Kind: canonical.resource.Kind, + ListKind: canonical.resource.Kind + "List", + }, + Scope: scope, + Versions: crdVersions, + }, + } +} + +// schemaForGVK finds the component schema for gvk in an OpenAPI v3 document and +// converts it to a structural CRD schema (JSON round-trip + cleanup). +func schemaForGVK(doc []byte, gvk schema.GroupVersionKind) (*apiextensionsv1.JSONSchemaProps, error) { + var parsed struct { + Components struct { + Schemas map[string]json.RawMessage `json:"schemas"` + } `json:"components"` + } + if err := json.Unmarshal(doc, &parsed); err != nil { + return nil, err + } + for _, raw := range parsed.Components.Schemas { + var meta struct { + GVK []struct { + Group string `json:"group"` + Version string `json:"version"` + Kind string `json:"kind"` + } `json:"x-kubernetes-group-version-kind"` + } + if err := json.Unmarshal(raw, &meta); err != nil { + continue + } + for _, g := range meta.GVK { + if g.Group == gvk.Group && g.Version == gvk.Version && g.Kind == gvk.Kind { + var props apiextensionsv1.JSONSchemaProps + if err := json.Unmarshal(raw, &props); err != nil { + return nil, err + } + return cleanSchema(&props), nil + } + } + } + return nil, fmt.Errorf("no openapi schema for %s", gvk) +} + +// cleanSchema turns a top-level object schema into a structural CRD schema: drop +// the apiserver-managed apiVersion/kind/metadata (metadata is a $ref that won't +// resolve in a CRD), and guarantee an object type with unknown fields preserved +// where a sub-schema is otherwise empty. +func cleanSchema(p *apiextensionsv1.JSONSchemaProps) *apiextensionsv1.JSONSchemaProps { + p.Type = "object" + p.Ref = nil + if p.Properties != nil { + delete(p.Properties, "apiVersion") + delete(p.Properties, "kind") + delete(p.Properties, "metadata") + for k, v := range p.Properties { + p.Properties[k] = *normalize(&v) + } + } else { + preserve := true + p.XPreserveUnknownFields = &preserve + } + return p +} + +// normalize makes a sub-schema structural: drop $ref (unresolvable in a CRD) and +// preserve unknown fields where the type is unknown. +func normalize(p *apiextensionsv1.JSONSchemaProps) *apiextensionsv1.JSONSchemaProps { + if p.Ref != nil { + preserve := true + return &apiextensionsv1.JSONSchemaProps{Type: "object", XPreserveUnknownFields: &preserve} + } + if p.Type == "" && p.XPreserveUnknownFields == nil { + preserve := true + p.Type = "object" + p.XPreserveUnknownFields = &preserve + } + for k, v := range p.Properties { + p.Properties[k] = *normalize(&v) + } + if p.Items != nil && p.Items.Schema != nil { + p.Items.Schema = normalize(p.Items.Schema) + } + return p +} diff --git a/engine/provider/connection_provider.go b/engine/provider/connection_provider.go new file mode 100644 index 000000000..5b46a9294 --- /dev/null +++ b/engine/provider/connection_provider.go @@ -0,0 +1,235 @@ +/* +Copyright 2026 The kbind 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 provider implements the multicluster-runtime provider that turns each +// ready Connection into an engaged provider cluster. This is the consumer<->provider +// bridge from the v2 proposal: one Connection == one logical provider cluster. +package provider + +import ( + "context" + "fmt" + "sync" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" + + "github.com/kbind/kbind/engine/remote" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +var _ multicluster.Provider = &ConnectionProvider{} + +// Options configures the ConnectionProvider. +type Options struct { + // ClusterOptions are passed to the cluster constructor. + ClusterOptions []cluster.Option + // NewCluster builds (but does not start) a cluster from a rest.Config. + NewCluster func(ctx context.Context, cfg *rest.Config, opts ...cluster.Option) (cluster.Cluster, error) +} + +func setDefaults(o *Options) { + if o.NewCluster == nil { + o.NewCluster = func(_ context.Context, cfg *rest.Config, opts ...cluster.Option) (cluster.Cluster, error) { + return cluster.New(cfg, opts...) + } + } +} + +type index struct { + object client.Object + field string + extractValue client.IndexerFunc +} + +// ConnectionProvider discovers provider clusters from Connection objects and +// engages them with the multicluster manager. The cluster key is the +// Connection name. +type ConnectionProvider struct { + opts Options + hcClient client.Client + + mcMgr mcmanager.Manager + + lock sync.Mutex + clusters map[string]cluster.Cluster + cancelFns map[string]context.CancelFunc + indexers []index +} + +// New registers the provider as a controller on the local (consumer) manager, +// watching Connection objects. +func New(localMgr manager.Manager, opts Options) (*ConnectionProvider, error) { + p := &ConnectionProvider{ + opts: opts, + hcClient: localMgr.GetClient(), + clusters: map[string]cluster.Cluster{}, + cancelFns: map[string]context.CancelFunc{}, + } + setDefaults(&p.opts) + + if err := builder.ControllerManagedBy(localMgr). + For(&corev1alpha1.Connection{}). + WithOptions(controller.Options{MaxConcurrentReconciles: 1}). + Named("connection-provider"). + Complete(p); err != nil { + return nil, fmt.Errorf("creating connection-provider controller: %w", err) + } + return p, nil +} + +// Reconcile engages a provider cluster once its Connection is Ready, and +// disengages it on deletion. +func (p *ConnectionProvider) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { + log := ctrl.LoggerFrom(ctx).WithValues("connection", req.Name) + key := req.Name + + conn := &corev1alpha1.Connection{} + if err := p.hcClient.Get(ctx, req.NamespacedName, conn); err != nil { + if apierrors.IsNotFound(err) { + p.disengage(key) + return reconcile.Result{}, nil + } + return reconcile.Result{}, fmt.Errorf("getting Connection: %w", err) + } + + p.lock.Lock() + mcMgr := p.mcMgr + _, engaged := p.clusters[key] + p.lock.Unlock() + + if mcMgr == nil { + return reconcile.Result{RequeueAfter: 2 * time.Second}, nil + } + // A Connection that is no longer Ready (e.g. its credential was revoked, the + // provider became unreachable, or RBAC was withdrawn) must be disengaged, not + // just left running against a dead cluster. This also covers a Connection + // mid-deletion that has already flipped not-Ready. + if !isReady(conn) { + if engaged { + p.disengage(key) + log.Info("Disengaged provider cluster (Connection no longer ready)") + } else { + log.V(4).Info("Connection not ready yet, not engaging") + } + return reconcile.Result{}, nil + } + if engaged { + return reconcile.Result{}, nil + } + + p.lock.Lock() + defer p.lock.Unlock() + // Re-check under the lock in case a concurrent reconcile engaged it. + if _, ok := p.clusters[key]; ok { + return reconcile.Result{}, nil + } + + cfg, err := remote.RestConfigFromConnection(ctx, p.hcClient, conn) + if err != nil { + return reconcile.Result{}, fmt.Errorf("building provider rest config: %w", err) + } + + cl, err := p.opts.NewCluster(ctx, cfg, p.opts.ClusterOptions...) + if err != nil { + return reconcile.Result{}, fmt.Errorf("creating provider cluster: %w", err) + } + for _, idx := range p.indexers { + if err := cl.GetCache().IndexField(ctx, idx.object, idx.field, idx.extractValue); err != nil { + return reconcile.Result{}, fmt.Errorf("indexing field %q: %w", idx.field, err) + } + } + + clusterCtx, cancel := context.WithCancel(ctx) + go func() { + if err := cl.Start(clusterCtx); err != nil { + log.Error(err, "provider cluster stopped") + } + }() + if !cl.GetCache().WaitForCacheSync(clusterCtx) { + cancel() + return reconcile.Result{}, fmt.Errorf("provider cluster cache failed to sync") + } + + p.clusters[key] = cl + p.cancelFns[key] = cancel + + if err := p.mcMgr.Engage(clusterCtx, key, cl); err != nil { + cancel() + delete(p.clusters, key) + delete(p.cancelFns, key) + return reconcile.Result{}, fmt.Errorf("engaging provider cluster: %w", err) + } + log.Info("Engaged provider cluster") + return reconcile.Result{}, nil +} + +func (p *ConnectionProvider) disengage(key string) { + p.lock.Lock() + defer p.lock.Unlock() + if cancel, ok := p.cancelFns[key]; ok { + cancel() + delete(p.cancelFns, key) + } + delete(p.clusters, key) +} + +// Get returns the engaged cluster for the given Connection name. +func (p *ConnectionProvider) Get(_ context.Context, clusterName string) (cluster.Cluster, error) { + p.lock.Lock() + defer p.lock.Unlock() + if cl, ok := p.clusters[clusterName]; ok { + return cl, nil + } + return nil, multicluster.ErrClusterNotFound +} + +// Run records the multicluster manager and blocks until the context is done. +func (p *ConnectionProvider) Run(ctx context.Context, mgr mcmanager.Manager) error { + p.lock.Lock() + p.mcMgr = mgr + p.lock.Unlock() + <-ctx.Done() + return ctx.Err() +} + +// IndexField indexes a field on all engaged and future provider clusters. +func (p *ConnectionProvider) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error { + p.lock.Lock() + defer p.lock.Unlock() + p.indexers = append(p.indexers, index{object: obj, field: field, extractValue: extractValue}) + for name, cl := range p.clusters { + if err := cl.GetCache().IndexField(ctx, obj, field, extractValue); err != nil { + return fmt.Errorf("indexing field %q on cluster %q: %w", field, name, err) + } + } + return nil +} + +func isReady(conn *corev1alpha1.Connection) bool { + return apimeta.IsStatusConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) +} diff --git a/engine/remote/remote.go b/engine/remote/remote.go new file mode 100644 index 000000000..e90378733 --- /dev/null +++ b/engine/remote/remote.go @@ -0,0 +1,136 @@ +/* +Copyright 2026 The kbind 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 remote resolves provider credentials and cluster identity for a +// Connection. +package remote + +import ( + "context" + "fmt" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// ProviderClient builds a direct (uncached) client for the provider cluster a +// Connection points at. Used for one-shot reads/writes (discovery, CRD pull) +// that do not warrant a cache. +func ProviderClient(ctx context.Context, local client.Client, conn *corev1alpha1.Connection, scheme *runtime.Scheme) (client.Client, error) { + cfg, err := RestConfigFromConnection(ctx, local, conn) + if err != nil { + return nil, err + } + return client.New(cfg, client.Options{Scheme: scheme}) +} + +// RestConfigFromConnection reads the Connection's kubeconfig Secret and returns +// a rest.Config for the provider cluster. +func RestConfigFromConnection(ctx context.Context, c client.Client, conn *corev1alpha1.Connection) (*rest.Config, error) { + ref := conn.Spec.KubeconfigSecretRef + key := ref.Key + if key == "" { + key = "kubeconfig" + } + + var secret corev1.Secret + if err := c.Get(ctx, types.NamespacedName{Namespace: ref.Namespace, Name: ref.Name}, &secret); err != nil { + return nil, fmt.Errorf("getting kubeconfig secret %s/%s: %w", ref.Namespace, ref.Name, err) + } + + data, ok := secret.Data[key] + if !ok { + return nil, fmt.Errorf("kubeconfig secret %s/%s has no key %q", ref.Namespace, ref.Name, key) + } + if len(data) == 0 { + return nil, fmt.Errorf("kubeconfig secret %s/%s key %q is empty", ref.Namespace, ref.Name, key) + } + + cfg, err := clientcmd.RESTConfigFromKubeConfig(data) + if err != nil { + return nil, fmt.Errorf("parsing kubeconfig: %w", err) + } + return cfg, nil +} + +// DefaultNamespaceFromConnection returns the namespace of the current context +// in the Connection's kubeconfig, or "" if none is set. A provider service +// layer (issuer) pins this to the per-consumer tenancy boundary so tenant RBAC +// can be namespace-scoped; the konnector uses it as the home for its heartbeat +// Lease. +func DefaultNamespaceFromConnection(ctx context.Context, c client.Client, conn *corev1alpha1.Connection) (string, error) { + ref := conn.Spec.KubeconfigSecretRef + key := ref.Key + if key == "" { + key = "kubeconfig" + } + var secret corev1.Secret + if err := c.Get(ctx, types.NamespacedName{Namespace: ref.Namespace, Name: ref.Name}, &secret); err != nil { + return "", err + } + kubeconfig, err := clientcmd.Load(secret.Data[key]) + if err != nil { + return "", fmt.Errorf("parsing kubeconfig: %w", err) + } + if kctx, ok := kubeconfig.Contexts[kubeconfig.CurrentContext]; ok { + return kctx.Namespace, nil + } + return "", nil +} + +// logicalClusterGVK is kcp's per-workspace singleton identity object. +var logicalClusterGVK = schema.GroupVersionKind{Group: "core.kcp.io", Version: "v1alpha1", Kind: "LogicalCluster"} + +// ClusterUID returns a stable identity for the cluster behind c. It tries, in +// order: +// - the kcp LogicalCluster "cluster" object's UID (kcp / logical clusters, +// which have no kube-system namespace) — preferred when present, since only +// a kcp-shaped cluster serves core.kcp.io; then +// - the kube-system namespace UID (plain Kubernetes). +// +// A Forbidden error from a source is surfaced (so the caller can report +// PermissionDenied) rather than silently falling through. +func ClusterUID(ctx context.Context, c client.Client) (string, error) { + lc := &unstructured.Unstructured{} + lc.SetGroupVersionKind(logicalClusterGVK) + lcErr := c.Get(ctx, types.NamespacedName{Name: "cluster"}, lc) + if lcErr == nil && lc.GetUID() != "" { + return string(lc.GetUID()), nil + } + if apierrors.IsForbidden(lcErr) { + return "", lcErr + } + + var ns corev1.Namespace + nsErr := c.Get(ctx, types.NamespacedName{Name: "kube-system"}, &ns) + if nsErr == nil && ns.UID != "" { + return string(ns.UID), nil + } + if apierrors.IsForbidden(nsErr) { + return "", nsErr + } + + return "", fmt.Errorf("cannot determine cluster identity (no LogicalCluster: %v; no kube-system namespace: %v)", lcErr, nsErr) +} diff --git a/engine/remote/remote_test.go b/engine/remote/remote_test.go new file mode 100644 index 000000000..64779f7c3 --- /dev/null +++ b/engine/remote/remote_test.go @@ -0,0 +1,91 @@ +/* +Copyright 2026 The kbind 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 remote + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func identityScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + require.NoError(t, clientgoscheme.AddToScheme(s)) + // Register the kcp LogicalCluster GVK as unstructured so the fake client can + // serve it. + s.AddKnownTypeWithName(logicalClusterGVK, &unstructured.Unstructured{}) + s.AddKnownTypeWithName(logicalClusterGVK.GroupVersion().WithKind("LogicalClusterList"), &unstructured.UnstructuredList{}) + return s +} + +func logicalCluster(uid string) *unstructured.Unstructured { + lc := &unstructured.Unstructured{} + lc.SetGroupVersionKind(logicalClusterGVK) + lc.SetName("cluster") + lc.SetUID(types.UID(uid)) + return lc +} + +func TestClusterUID_KubeSystem(t *testing.T) { + s := identityScheme(t) + c := fake.NewClientBuilder().WithScheme(s).WithObjects( + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "kube-system", UID: "ks-uid"}}, + ).Build() + + uid, err := ClusterUID(context.Background(), c) + require.NoError(t, err) + require.Equal(t, "ks-uid", uid, "plain Kubernetes should use the kube-system namespace UID") +} + +func TestClusterUID_KCPLogicalClusterFallback(t *testing.T) { + s := identityScheme(t) + // No kube-system namespace (a kcp logical cluster) — only a LogicalCluster. + c := fake.NewClientBuilder().WithScheme(s).WithObjects(logicalCluster("lc-uid")).Build() + + uid, err := ClusterUID(context.Background(), c) + require.NoError(t, err) + require.Equal(t, "lc-uid", uid, "a kcp logical cluster should fall back to the LogicalCluster UID") +} + +func TestClusterUID_LogicalClusterWinsWhenBothPresent(t *testing.T) { + s := identityScheme(t) + c := fake.NewClientBuilder().WithScheme(s).WithObjects( + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "kube-system", UID: "ks-uid"}}, + logicalCluster("lc-uid"), + ).Build() + + uid, err := ClusterUID(context.Background(), c) + require.NoError(t, err) + require.Equal(t, "lc-uid", uid, "a kcp-shaped cluster (LogicalCluster present) should prefer the LogicalCluster UID") +} + +func TestClusterUID_NoSource(t *testing.T) { + s := identityScheme(t) + c := fake.NewClientBuilder().WithScheme(s).Build() + + _, err := ClusterUID(context.Background(), c) + require.Error(t, err, "with neither source the identity is undeterminable") +} diff --git a/engine/sync/crd_controller.go b/engine/sync/crd_controller.go new file mode 100644 index 000000000..6d74c0b1c --- /dev/null +++ b/engine/sync/crd_controller.go @@ -0,0 +1,428 @@ +/* +Copyright 2026 The kbind 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 sync implements the dynamic per-GVR instance sync. A CRD controller +// watches the CRDs installed by bindings and starts/stops a spec/status syncer +// for each. +package sync + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-logr/logr" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "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/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/runtime" + dynamicclient "k8s.io/client-go/dynamic" + "k8s.io/client-go/dynamic/dynamicinformer" + "k8s.io/client-go/dynamic/dynamiclister" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/tools/record" + "k8s.io/client-go/util/workqueue" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/cluster" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + "github.com/kbind/kbind/engine/mapper" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +const cleanupTimeout = 10 * time.Second + +// ClusterGetter resolves a Connection name to its engaged provider cluster. +// The multicluster-runtime ConnectionProvider satisfies it. +type ClusterGetter interface { + Get(ctx context.Context, name string) (cluster.Cluster, error) +} + +// CRDController watches managed CRDs and runs a per-GVR syncer for each, wired +// to the provider's multicluster-runtime engaged cluster. +type CRDController struct { + mgr ctrl.Manager + consumerConfig *rest.Config + consumerClient client.Client + clusters ClusterGetter + recorder record.EventRecorder + resync time.Duration + // mapper translates consumer<->provider object keys. Defaults to + // mapper.Identity; an out-of-tree build swaps it via WithMapper. + mapper mapper.Mapper + + lock sync.Mutex + contexts map[string]*syncContext // by CRD name +} + +// Option configures the CRDController at setup. It is the compile-time seam for +// out-of-tree konnector builds (e.g. a custom Mapper). +type Option func(*CRDController) + +// WithMapper overrides the consumer<->provider key Mapper (default: Identity). +func WithMapper(m mapper.Mapper) Option { + return func(c *CRDController) { c.mapper = m } +} + +type syncContext struct { + generation int64 + // cluster is the engaged provider cluster this syncer was built against. A + // different instance means the Connection re-engaged and the syncer must be + // rebuilt (the old one holds a dead client/cache). + cluster cluster.Cluster + cancel context.CancelFunc + wg *sync.WaitGroup +} + +// SetupWithManager registers the CRD controller. The consumer side uses a +// direct (uncached) client built from the manager's rest config; the provider +// side comes from the multicluster-runtime engaged cluster resolved via clusters. +func SetupWithManager(mgr ctrl.Manager, clusters ClusterGetter, opts ...Option) error { + consumerClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: mgr.GetScheme()}) + if err != nil { + return fmt.Errorf("building direct consumer client: %w", err) + } + r := &CRDController{ + mgr: mgr, + consumerConfig: mgr.GetConfig(), + consumerClient: consumerClient, + clusters: clusters, + recorder: mgr.GetEventRecorderFor("kbind-konnector"), + resync: time.Minute, + mapper: mapper.Identity{}, + contexts: map[string]*syncContext{}, + } + for _, o := range opts { + o(r) + } + return ctrl.NewControllerManagedBy(mgr). + For(&apiextensionsv1.CustomResourceDefinition{}, builder.WithPredicates(predicate.NewPredicateFuncs(managedCRD))). + // Watch Connections so an engage/disengage (Ready flip) re-evaluates the + // syncers of every CRD that Connection pulled — stopping them on disengage + // and rebuilding them against the freshly-engaged cluster on re-engage. + Watches(&corev1alpha1.Connection{}, handler.EnqueueRequestsFromMapFunc(r.crdsForConnection)). + Named("managed-crds"). + Complete(r) +} + +func managedCRD(o client.Object) bool { + return o.GetLabels()[corev1alpha1.LabelManaged] == "true" +} + +// crdsForConnection enqueues every managed CRD pulled through the given +// Connection, so its readiness transitions re-evaluate the per-GVR syncers. +func (r *CRDController) crdsForConnection(ctx context.Context, conn client.Object) []reconcile.Request { + var crds apiextensionsv1.CustomResourceDefinitionList + if err := r.consumerClient.List(ctx, &crds, client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + return nil + } + var reqs []reconcile.Request + for i := range crds.Items { + if crds.Items[i].Annotations[corev1alpha1.AnnotationConnection] == conn.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Name: crds.Items[i].Name}}) + } + } + return reqs +} + +// Reconcile starts or stops the syncer for a managed CRD. +func (r *CRDController) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { + crd := &apiextensionsv1.CustomResourceDefinition{} + if err := r.consumerClient.Get(ctx, req.NamespacedName, crd); err != nil { + if apierrors.IsNotFound(err) { + crd = nil + } else { + return reconcile.Result{}, err + } + } + return r.reconcile(ctx, req.Name, crd) +} + +func (r *CRDController) reconcile(ctx context.Context, name string, crd *apiextensionsv1.CustomResourceDefinition) (reconcile.Result, error) { + log := ctrl.LoggerFrom(ctx).WithValues("crd", name) + + // The CRD is gone (unbind removed it) — stop the syncer. + if crd == nil || crd.DeletionTimestamp != nil { + r.stopSyncer(name, log) + return reconcile.Result{}, nil + } + generation := crd.Generation + + // The provider is pinned by the binding that pulled this CRD. + connName := crd.Annotations[corev1alpha1.AnnotationConnection] + if connName == "" { + return reconcile.Result{}, fmt.Errorf("managed CRD %s has no %s annotation", name, corev1alpha1.AnnotationConnection) + } + + // The syncer must only run while the Connection is Ready (engaged). If the + // Connection is gone or no longer Ready, stop the syncer; the Connection watch + // re-triggers this reconcile when it becomes Ready again. + conn := &corev1alpha1.Connection{} + if err := r.consumerClient.Get(ctx, client.ObjectKey{Name: connName}, conn); err != nil { + if apierrors.IsNotFound(err) { + r.stopSyncer(name, log) + return reconcile.Result{}, nil + } + return reconcile.Result{}, fmt.Errorf("getting Connection %s: %w", connName, err) + } + if !connectionReady(conn) || conn.Status.LocalClusterUID == "" { + r.stopSyncer(name, log) + log.V(4).Info("provider not ready; syncer stopped", "connection", connName) + return reconcile.Result{}, nil + } + + // Resolve the multicluster-runtime engaged provider cluster. A Ready + // Connection engages asynchronously, so it may be briefly absent — stop any + // stale syncer and requeue. + providerCluster, err := r.clusters.Get(ctx, connName) + if err != nil { + r.stopSyncer(name, log) + log.V(4).Info("provider cluster not engaged yet, requeueing", "connection", connName, "reason", err.Error()) + return reconcile.Result{RequeueAfter: 2 * time.Second}, nil + } + + // Already syncing this generation against this exact engaged cluster? Done. + // A different cluster instance means the Connection re-engaged (after a + // disengage) — fall through to rebuild so the syncer tracks the live cluster. + r.lock.Lock() + if c, found := r.contexts[name]; found && c.generation >= generation && c.cluster == providerCluster { + r.lock.Unlock() + return reconcile.Result{}, nil + } + r.lock.Unlock() + + // (Re)build the syncer. Stop any prior one (older generation or dead cluster). + r.stopSyncer(name, log) + + version := storageOrServedVersion(crd) + if version == "" { + return reconcile.Result{}, fmt.Errorf("CRD %s has no served version", name) + } + gvr := schema.GroupVersionResource{Group: crd.Spec.Group, Version: version, Resource: crd.Spec.Names.Plural} + gvk := schema.GroupVersionKind{Group: crd.Spec.Group, Version: version, Kind: crd.Spec.Names.Kind} + + dyn, err := dynamicclient.NewForConfig(r.consumerConfig) + if err != nil { + return reconcile.Result{}, err + } + inf := dynamicinformer.NewFilteredDynamicInformer(dyn, gvr, metav1.NamespaceAll, r.resync, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, nil) + lister := dynamiclister.New(inf.Informer().GetIndexer(), gvr) + + rec := &specReconciler{ + gvr: gvr, + gvk: gvk, + scope: crd.Spec.Scope, + consumerLister: lister, + consumerClient: r.consumerClient, + providerClient: providerCluster.GetClient(), + providerReader: providerCluster.GetAPIReader(), + localUID: conn.Status.LocalClusterUID, + mapper: r.mapper, + recorder: r.recorder, + } + + syncLog := ctrl.Log.WithName("sync").WithValues("gvr", gvr.String()) + ctrlr, err := controller.NewTypedUnmanaged(fmt.Sprintf("sync-%s", gvr.GroupResource().String()), controller.TypedOptions[reconcile.Request]{ + Reconciler: rec, + LogConstructor: func(*reconcile.Request) logr.Logger { return syncLog }, + // A CRD can be removed and re-added (same GVR), recreating this + // controller with the same name — skip the global uniqueness check. + SkipNameValidation: ptr.To(true), + }) + if err != nil { + return reconcile.Result{}, fmt.Errorf("creating sync controller: %w", err) + } + + src := newInformerSource(inf) + if err := ctrlr.Watch(src); err != nil { + return reconcile.Result{}, fmt.Errorf("watching consumer informer: %w", err) + } + // Provider-side watch via the engaged cluster's cache: status/drift events + // arrive here instead of being polled. + if err := ctrlr.Watch(providerSource(providerCluster.GetCache(), gvr, gvk, conn.Status.LocalClusterUID, r.mapper)); err != nil { + return reconcile.Result{}, fmt.Errorf("watching provider cluster: %w", err) + } + if err := ctrlr.Watch(r.bindingSource(gvr.GroupResource(), lister)); err != nil { + return reconcile.Result{}, fmt.Errorf("watching cluster bindings: %w", err) + } + if err := ctrlr.Watch(r.namespacedBindingSource(gvr.GroupResource(), lister)); err != nil { + return reconcile.Result{}, fmt.Errorf("watching bindings: %w", err) + } + + syncCtx, cancel := context.WithCancel(ctx) + wg := &sync.WaitGroup{} + wg.Add(2) + go func() { defer wg.Done(); inf.Informer().Run(syncCtx.Done()) }() + go func() { + defer wg.Done() + if err := ctrlr.Start(syncCtx); err != nil { + runtime.HandleErrorWithContext(syncCtx, err, "sync controller stopped") + } + }() + if !cache.WaitForCacheSync(syncCtx.Done(), inf.Informer().HasSynced) { + cancel() + return reconcile.Result{}, fmt.Errorf("consumer informer for %s failed to sync", gvr) + } + + r.lock.Lock() + r.contexts[name] = &syncContext{generation: generation, cluster: providerCluster, cancel: cancel, wg: wg} + r.lock.Unlock() + log.Info("started syncer", "gvr", gvr.String()) + return reconcile.Result{}, nil +} + +func (r *CRDController) bindingSource(gr schema.GroupResource, lister dynamiclister.Lister) source.TypedSource[reconcile.Request] { + return source.Kind(r.mgr.GetCache(), &corev1alpha1.ClusterBinding{}, handler.TypedEnqueueRequestsFromMapFunc( + func(_ context.Context, cb *corev1alpha1.ClusterBinding) []reconcile.Request { + if !listsAPI(cb.Spec.APIs, gr.String()) { + return nil + } + return requestsForAll(lister, "") + })) +} + +func (r *CRDController) namespacedBindingSource(gr schema.GroupResource, lister dynamiclister.Lister) source.TypedSource[reconcile.Request] { + return source.Kind(r.mgr.GetCache(), &corev1alpha1.Binding{}, handler.TypedEnqueueRequestsFromMapFunc( + func(_ context.Context, b *corev1alpha1.Binding) []reconcile.Request { + if !listsAPI(b.Spec.APIs, gr.String()) { + return nil + } + return requestsForAll(lister, b.GetNamespace()) + })) +} + +func requestsForAll(lister dynamiclister.Lister, namespace string) []reconcile.Request { + var list []any + if namespace != "" { + l, err := lister.Namespace(namespace).List(labels.Everything()) + if err != nil { + return nil + } + for _, o := range l { + list = append(list, o) + } + } else { + l, err := lister.List(labels.Everything()) + if err != nil { + return nil + } + for _, o := range l { + list = append(list, o) + } + } + out := make([]reconcile.Request, 0, len(list)) + for _, o := range list { + acc, ok := o.(interface { + GetName() string + GetNamespace() string + }) + if !ok { + continue + } + out = append(out, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: acc.GetNamespace(), Name: acc.GetName()}}) + } + return out +} + +func storageOrServedVersion(crd *apiextensionsv1.CustomResourceDefinition) string { + var served string + for _, v := range crd.Spec.Versions { + if v.Storage { + return v.Name + } + if served == "" && v.Served { + served = v.Name + } + } + return served +} + +// stopSyncer tears down the running syncer for a CRD, if any, and blocks (up to +// cleanupTimeout) for its goroutines to exit. A no-op when nothing is running. +func (r *CRDController) stopSyncer(name string, log logr.Logger) { + r.lock.Lock() + c, found := r.contexts[name] + if found { + delete(r.contexts, name) + } + r.lock.Unlock() + if !found { + return + } + log.Info("stopping syncer") + c.cancel() + waitWithTimeout(c.wg, cleanupTimeout) +} + +func connectionReady(conn *corev1alpha1.Connection) bool { + return apimeta.IsStatusConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) +} + +func waitWithTimeout(wg *sync.WaitGroup, timeout time.Duration) { + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(timeout): + } +} + +// newInformerSource adapts a dynamic informer to a controller-runtime source. +func newInformerSource(gi interface { + Informer() cache.SharedIndexInformer +}) source.TypedSource[reconcile.Request] { + return &informerSourceImpl{informer: gi.Informer()} +} + +type informerSourceImpl struct { + informer cache.SharedIndexInformer +} + +func (s *informerSourceImpl) Start(ctx context.Context, q workqueue.TypedRateLimitingInterface[reconcile.Request]) error { + _, err := s.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: func(o any) { enqueue(o, q) }, + UpdateFunc: func(_, o any) { enqueue(o, q) }, + DeleteFunc: func(o any) { enqueue(o, q) }, + }) + return err +} + +func enqueue(o any, q workqueue.TypedRateLimitingInterface[reconcile.Request]) { + key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(o) + if err != nil { + return + } + ns, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return + } + q.Add(reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ns, Name: name}}) +} + +var _ source.TypedSource[reconcile.Request] = &informerSourceImpl{} diff --git a/engine/sync/resolve.go b/engine/sync/resolve.go new file mode 100644 index 000000000..ee5165645 --- /dev/null +++ b/engine/sync/resolve.go @@ -0,0 +1,102 @@ +/* +Copyright 2026 The kbind 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 sync + +import ( + "context" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// CRDNameForGVR returns the "." CRD name for a GVR. +func CRDNameForGVR(gvr schema.GroupVersionResource) string { + return gvr.Resource + "." + gvr.Group +} + +// Resolution is the result of resolving which binding covers an API. +type Resolution struct { + // Found is true if a binding lists the API. + Found bool + // Ready is true if that binding is Ready. + Ready bool + // ConnectionName is the Connection the binding references. + ConnectionName string + // ConflictPolicy is the binding's conflict policy (Fail if unset). + ConflictPolicy corev1alpha1.ConflictPolicy +} + +// ResolveConnection finds the binding that covers crdName for the given +// namespace. A ClusterBinding wins over a namespaced Binding (proposal rule). +func ResolveConnection(ctx context.Context, c client.Client, crdName, namespace string) (Resolution, error) { + var cbs corev1alpha1.ClusterBindingList + if err := c.List(ctx, &cbs); err != nil { + return Resolution{}, err + } + for i := range cbs.Items { + cb := &cbs.Items[i] + // A binding being deleted is no longer a valid sync source — this gates + // the syncer off during unbind so it doesn't re-add finalizers or + // re-create provider copies while cleanup runs. + if cb.DeletionTimestamp != nil { + continue + } + if listsAPI(cb.Spec.APIs, crdName) { + return Resolution{ + Found: true, + Ready: apimeta.IsStatusConditionTrue(cb.Status.Conditions, corev1alpha1.ConditionReady), + ConnectionName: cb.Spec.ConnectionRef.Name, + ConflictPolicy: cb.Spec.ConflictPolicy, + }, nil + } + } + + if namespace != "" { + var bs corev1alpha1.BindingList + if err := c.List(ctx, &bs, client.InNamespace(namespace)); err != nil { + return Resolution{}, err + } + for i := range bs.Items { + b := &bs.Items[i] + if b.DeletionTimestamp != nil { + continue + } + if listsAPI(b.Spec.APIs, crdName) { + return Resolution{ + Found: true, + Ready: apimeta.IsStatusConditionTrue(b.Status.Conditions, corev1alpha1.ConditionReady), + ConnectionName: b.Spec.ConnectionRef.Name, + ConflictPolicy: b.Spec.ConflictPolicy, + }, nil + } + } + } + + return Resolution{Found: false}, nil +} + +func listsAPI(apis []corev1alpha1.APIRef, crdName string) bool { + for _, a := range apis { + if a.Name == crdName { + return true + } + } + return false +} diff --git a/engine/sync/syncer.go b/engine/sync/syncer.go new file mode 100644 index 000000000..feaff9902 --- /dev/null +++ b/engine/sync/syncer.go @@ -0,0 +1,395 @@ +/* +Copyright 2026 The kbind 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 sync + +import ( + "context" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic/dynamiclister" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + "github.com/kbind/kbind/engine/mapper" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +const ( + // fieldOwner is the server-side-apply field manager for spec writes. + fieldOwner = "kbind-konnector" + // statusResyncBackstop is a low-frequency safety net. Provider-originated + // changes (status, drift) are primarily delivered by the engaged-cluster + // watch; this just heals any missed watch event. + statusResyncBackstop = 10 * time.Minute +) + +// specReconciler syncs instances of one GVR: spec consumer->provider (SSA), +// status provider->consumer, with a finalizer and ownership markers. The +// provider side is the multicluster-runtime engaged cluster for one Connection: +// writes go through its client, reads through its API reader (no cache +// staleness), and provider events arrive via a watch on its cache. +type specReconciler struct { + gvr schema.GroupVersionResource + gvk schema.GroupVersionKind + scope apiextensionsv1.ResourceScope + + consumerLister dynamiclister.Lister + consumerClient client.Client // direct, uncached + + providerClient client.Client // engaged-cluster client: SSA + delete + providerReader client.Reader // engaged-cluster API reader: fresh reads + localUID string // consumer cluster identity for ownership markers + + // mapper translates the consumer object key to its provider key. Core uses + // mapper.Identity (ns/name unchanged); an out-of-tree build can swap it. + mapper mapper.Mapper + + recorder record.EventRecorder +} + +// providerSource turns the engaged provider cluster's cache into an event +// source: a provider object owned by us (matching localUID) enqueues its mapped +// consumer object. This is what makes status/drift sync event-driven instead of +// polled. The provider key is mapped back to the consumer key via the Mapper so +// the request targets the right consumer object under non-identity mappings. +func providerSource(c cache.Cache, gvr schema.GroupVersionResource, gvk schema.GroupVersionKind, localUID string, m mapper.Mapper) source.TypedSource[reconcile.Request] { + obj := &unstructured.Unstructured{} + obj.SetGroupVersionKind(gvk) + return source.Kind(c, client.Object(obj), handler.TypedEnqueueRequestsFromMapFunc( + func(_ context.Context, o client.Object) []reconcile.Request { + if o.GetAnnotations()[corev1alpha1.AnnotationConsumerClusterUID] != localUID { + return nil // not ours (another consumer on a shared provider) + } + consumerKey, err := m.ToConsumer(gvr, client.ObjectKey{Namespace: o.GetNamespace(), Name: o.GetName()}) + if err != nil { + return nil + } + return []reconcile.Request{{NamespacedName: consumerKey}} + })) +} + +func (r *specReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { + log := ctrl.LoggerFrom(ctx).WithValues("gvr", r.gvr.String(), "key", req.String()) + + obj, err := r.getConsumerObject(req) + if apierrors.IsNotFound(err) { + return reconcile.Result{}, nil + } + if err != nil { + return reconcile.Result{}, err + } + obj = obj.DeepCopy() + + // Gate: is there a ready binding covering this object? (Namespaced Bindings + // scope which namespaces sync; ClusterBindings cover everything.) + res, err := ResolveConnection(ctx, r.consumerClient, CRDNameForGVR(r.gvr), req.Namespace) + if err != nil { + return reconcile.Result{}, fmt.Errorf("resolving connection: %w", err) + } + bound := res.Found && res.Ready + + // Deletion: always release our copy, even if the binding is already gone. + if obj.GetDeletionTimestamp() != nil { + return r.reconcileDelete(ctx, obj) + } + if !bound { + // Not bound yet; binding changes re-trigger this reconcile. + return reconcile.Result{}, nil + } + + // Map the consumer key to the provider key. Core maps identity; an out-of-tree + // Mapper can rename/re-namespace. Every provider-side operation below uses + // providerKey, never the consumer object's own key. + providerKey, err := r.mapper.ToProvider(r.gvr, client.ObjectKeyFromObject(obj)) + if err != nil { + return reconcile.Result{}, fmt.Errorf("mapping %s to provider: %w", client.ObjectKeyFromObject(obj), err) + } + + // Ensure finalizer before first write. + if controllerutil.AddFinalizer(obj, corev1alpha1.FinalizerSyncer) { + if err := r.consumerClient.Update(ctx, obj); err != nil { + return reconcile.Result{}, fmt.Errorf("adding finalizer: %w", err) + } + return reconcile.Result{Requeue: true}, nil + } + + // Conflict check before first write (fresh read via the API reader). + existing := newUnstructured(r.gvk) + getErr := r.providerReader.Get(ctx, providerKey, existing) + switch { + case getErr == nil: + if owner, ours := ownershipOf(existing, r.localUID, string(obj.GetUID())); !ours { + // Adopt only takes an un-owned (markerless) object; it never steals + // one already owned by another binding/consumer. + if owner != ownerForeignUnmanaged || res.ConflictPolicy != corev1alpha1.ConflictPolicyAdopt { + reason := conflictReason(owner) + msg := fmt.Sprintf("provider object %s already exists and is %s; not overwriting (conflictPolicy: %s)", providerKey, owner, policyOrFail(res.ConflictPolicy)) + log.Info("conflict: refusing to overwrite provider object", "owner", owner) + if err := r.markConflict(ctx, obj, reason, msg); err != nil { + return reconcile.Result{}, err + } + return reconcile.Result{}, nil + } + log.Info("adopting un-owned provider object", "key", providerKey) + } + case apierrors.IsNotFound(getErr): + if r.scope == apiextensionsv1.NamespaceScoped { + if err := ensureNamespace(ctx, r.providerClient, providerKey.Namespace, r.localUID); err != nil { + if apierrors.IsForbidden(err) { + return r.permissionDenied(obj, "creating provider namespace", err), nil + } + return reconcile.Result{}, err + } + } + default: + return reconcile.Result{}, fmt.Errorf("provider get: %w", getErr) + } + + // We are syncing — clear any stale conflict marker from a previous round. + if err := r.clearConflict(ctx, obj); err != nil { + return reconcile.Result{}, err + } + + // Spec consumer -> provider (SSA). + patch := r.providerPatch(obj, providerKey, r.localUID) + if err := r.providerClient.Patch(ctx, patch, client.Apply, client.FieldOwner(fieldOwner), client.ForceOwnership); err != nil { + if apierrors.IsForbidden(err) { + return r.permissionDenied(obj, "applying spec to provider", err), nil + } + return reconcile.Result{}, fmt.Errorf("applying spec to provider: %w", err) + } + + // Status provider -> consumer. + got := newUnstructured(r.gvk) + if err := r.providerReader.Get(ctx, providerKey, got); err != nil { + return reconcile.Result{}, fmt.Errorf("reading provider status: %w", err) + } + if err := r.copyStatus(ctx, got, obj); err != nil { + return reconcile.Result{}, err + } + + return reconcile.Result{RequeueAfter: statusResyncBackstop}, nil +} + +// markConflict records a conflict durably (an annotation that survives status +// pruning, used by bindings to count conflicts), best-effort on the object's +// own condition, and as an Event. +func (r *specReconciler) markConflict(ctx context.Context, obj *unstructured.Unstructured, reason, msg string) error { + if obj.GetAnnotations()[corev1alpha1.AnnotationConflict] != reason { + p := fmt.Appendf(nil, `{"metadata":{"annotations":{%q:%q}}}`, corev1alpha1.AnnotationConflict, reason) + if err := r.consumerClient.Patch(ctx, obj, client.RawPatch(types.MergePatchType, p)); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("marking conflict: %w", err) + } + } + setObjCondition(obj, metav1.ConditionFalse, reason, msg) + _ = r.consumerClient.Status().Update(ctx, obj) + if r.recorder != nil { + r.recorder.Event(obj, corev1.EventTypeWarning, reason, msg) + } + return nil +} + +// permissionDenied surfaces a provider RBAC denial as an Event and requeues — +// it never fails the whole controller, so other objects keep syncing. The denial +// resolves on its own once RBAC is granted. +func (r *specReconciler) permissionDenied(obj *unstructured.Unstructured, op string, err error) reconcile.Result { + if r.recorder != nil { + r.recorder.Event(obj, corev1.EventTypeWarning, corev1alpha1.ReasonForbidden, + fmt.Sprintf("%s is forbidden by provider RBAC: %v", op, err)) + } + return reconcile.Result{RequeueAfter: 30 * time.Second} +} + +// clearConflict removes the conflict marker once the object syncs cleanly. +func (r *specReconciler) clearConflict(ctx context.Context, obj *unstructured.Unstructured) error { + if obj.GetAnnotations()[corev1alpha1.AnnotationConflict] == "" { + return nil + } + p := fmt.Appendf(nil, `{"metadata":{"annotations":{%q:null}}}`, corev1alpha1.AnnotationConflict) + if err := r.consumerClient.Patch(ctx, obj, client.RawPatch(types.MergePatchType, p)); client.IgnoreNotFound(err) != nil { + return fmt.Errorf("clearing conflict: %w", err) + } + return nil +} + +func (r *specReconciler) reconcileDelete(ctx context.Context, obj *unstructured.Unstructured) (reconcile.Result, error) { + if !controllerutil.ContainsFinalizer(obj, corev1alpha1.FinalizerSyncer) { + return reconcile.Result{}, nil + } + // deletion-policy: Orphan keeps the provider copy — just release the finalizer. + if obj.GetAnnotations()[corev1alpha1.AnnotationDeletionPolicy] != corev1alpha1.DeletionPolicyOrphan { + providerKey, err := r.mapper.ToProvider(r.gvr, client.ObjectKeyFromObject(obj)) + if err != nil { + return reconcile.Result{}, fmt.Errorf("mapping %s to provider: %w", client.ObjectKeyFromObject(obj), err) + } + existing := newUnstructured(r.gvk) + err = r.providerReader.Get(ctx, providerKey, existing) + switch { + case err == nil: + // Only delete the provider copy if it is ours. A foreign object that + // merely shares the name (a conflict) must never be deleted by us. + if _, ours := ownershipOf(existing, r.localUID, string(obj.GetUID())); ours { + if err := r.providerClient.Delete(ctx, existing); client.IgnoreNotFound(err) != nil { + return reconcile.Result{}, fmt.Errorf("deleting provider object: %w", err) + } + // Wait for the provider copy to be fully gone before releasing. + return reconcile.Result{RequeueAfter: 2 * time.Second}, nil + } + case !apierrors.IsNotFound(err): + return reconcile.Result{}, fmt.Errorf("provider get during delete: %w", err) + } + } + controllerutil.RemoveFinalizer(obj, corev1alpha1.FinalizerSyncer) + if err := r.consumerClient.Update(ctx, obj); err != nil { + return reconcile.Result{}, fmt.Errorf("removing finalizer: %w", err) + } + return reconcile.Result{}, nil +} + +func (r *specReconciler) getConsumerObject(req reconcile.Request) (*unstructured.Unstructured, error) { + if r.scope == apiextensionsv1.NamespaceScoped { + return r.consumerLister.Namespace(req.Namespace).Get(req.Name) + } + return r.consumerLister.Get(req.Name) +} + +// providerPatch builds the SSA patch: spec + identity, ownership markers, no +// status, no consumer-only metadata. The provider key (from the Mapper) sets the +// name/namespace, so a non-identity mapping writes to the mapped location while +// the ownership markers still record the consumer object's identity. +func (r *specReconciler) providerPatch(obj *unstructured.Unstructured, providerKey mapper.ObjectKey, localUID string) *unstructured.Unstructured { + patch := newUnstructured(r.gvk) + patch.SetName(providerKey.Name) + patch.SetNamespace(providerKey.Namespace) + patch.SetLabels(map[string]string{corev1alpha1.LabelManaged: "true"}) + patch.SetAnnotations(map[string]string{ + corev1alpha1.AnnotationConsumerClusterUID: localUID, + corev1alpha1.AnnotationConsumerObjectUID: string(obj.GetUID()), + }) + if spec, ok, _ := unstructured.NestedFieldCopy(obj.Object, "spec"); ok { + _ = unstructured.SetNestedField(patch.Object, spec, "spec") + } + return patch +} + +func (r *specReconciler) copyStatus(ctx context.Context, from, to *unstructured.Unstructured) error { + status, ok, err := unstructured.NestedFieldCopy(from.Object, "status") + if err != nil { + return err + } + if !ok { + return nil + } + if err := unstructured.SetNestedField(to.Object, status, "status"); err != nil { + return err + } + return r.consumerClient.Status().Update(ctx, to) +} + +func newUnstructured(gvk schema.GroupVersionKind) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(gvk) + return u +} + +// Ownership classifications returned by ownershipOf. +const ( + ownerForeignUnmanaged = "foreign-unmanaged" + ownerOurs = "ours" + ownerByAnother = "owned-by-another" +) + +// ownershipOf reports the marker owner of a provider object and whether it is +// ours (our consumer cluster + our consumer object UID). +func ownershipOf(obj *unstructured.Unstructured, localUID, consumerObjUID string) (string, bool) { + ann := obj.GetAnnotations() + cluster := ann[corev1alpha1.AnnotationConsumerClusterUID] + objUID := ann[corev1alpha1.AnnotationConsumerObjectUID] + if cluster == "" && objUID == "" { + return ownerForeignUnmanaged, false + } + if cluster == localUID && objUID == consumerObjUID { + return ownerOurs, true + } + return ownerByAnother, false +} + +func conflictReason(owner string) string { + if owner == ownerForeignUnmanaged { + return corev1alpha1.ReasonForeignObjectExists + } + return corev1alpha1.ReasonOwnedByAnother +} + +func policyOrFail(p corev1alpha1.ConflictPolicy) corev1alpha1.ConflictPolicy { + if p == "" { + return corev1alpha1.ConflictPolicyFail + } + return p +} + +func setObjCondition(obj *unstructured.Unstructured, status metav1.ConditionStatus, reason, msg string) { + cond := map[string]any{ + "type": corev1alpha1.ConditionSynced, + "status": string(status), + "reason": reason, + "message": msg, + } + conds, _, _ := unstructured.NestedSlice(obj.Object, "status", "conditions") + // Replace any existing Synced condition. + out := make([]any, 0, len(conds)+1) + for _, c := range conds { + if m, ok := c.(map[string]any); ok && m["type"] == corev1alpha1.ConditionSynced { + continue + } + out = append(out, c) + } + out = append(out, cond) + _ = unstructured.SetNestedSlice(obj.Object, out, "status", "conditions") +} + +func ensureNamespace(ctx context.Context, c client.Client, name, localUID string) error { + if name == "" { + return nil + } + ns := &unstructured.Unstructured{} + ns.SetGroupVersionKind(schema.GroupVersionKind{Version: "v1", Kind: "Namespace"}) + ns.SetName(name) + ns.SetLabels(map[string]string{ + corev1alpha1.LabelManaged: "true", + corev1alpha1.AnnotationConsumerClusterUID: localUID, + }) + err := c.Create(ctx, ns) + if apierrors.IsAlreadyExists(err) { + return nil + } + return err +} diff --git a/examples/crossplane/consumer-db.yaml b/examples/crossplane/consumer-db.yaml deleted file mode 100644 index c8b55ffba..000000000 --- a/examples/crossplane/consumer-db.yaml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: mangodb.com/v1 -kind: MySQLDatabase -metadata: - name: consumer-database - namespace: default -spec: - name: consumer-database diff --git a/examples/crossplane/db-apiserviceexporttemplate.yaml b/examples/crossplane/db-apiserviceexporttemplate.yaml deleted file mode 100644 index 0aa1df90c..000000000 --- a/examples/crossplane/db-apiserviceexporttemplate.yaml +++ /dev/null @@ -1,18 +0,0 @@ -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceExportTemplate -metadata: - name: mysqldatabase -spec: - resources: - - group: mangodb.com - resource: mysqldatabases - versions: - - v1 - permissionClaims: - - group: "" - resource: secrets - selector: - labelSelector: - matchLabels: - kube-bind.io/selector: consumer-database - scope: Namespaced diff --git a/examples/crossplane/db-provider/config.yaml b/examples/crossplane/db-provider/config.yaml deleted file mode 100644 index 50df3948c..000000000 --- a/examples/crossplane/db-provider/config.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: mysql.sql.m.crossplane.io/v1alpha1 -kind: ProviderConfig -metadata: - name: mysql-cfg - namespace: default -spec: - credentials: - source: MySQLConnectionSecret - connectionSecretRef: - name: db-conn - tls: preferred diff --git a/examples/crossplane/db-provider/provider.yaml b/examples/crossplane/db-provider/provider.yaml deleted file mode 100644 index 97f54f460..000000000 --- a/examples/crossplane/db-provider/provider.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: pkg.crossplane.io/v1 -kind: Provider -metadata: - name: provider-sql -spec: - package: xpkg.upbound.io/crossplane-contrib/provider-sql:v0.13.0 diff --git a/examples/crossplane/mysql.yaml b/examples/crossplane/mysql.yaml deleted file mode 100644 index 86290fdab..000000000 --- a/examples/crossplane/mysql.yaml +++ /dev/null @@ -1,70 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: mysql -spec: - selector: - matchLabels: - app: mysql - strategy: - type: Recreate - template: - metadata: - labels: - app: mysql - spec: - containers: - - image: mysql:9 - name: mysql - env: - # Use secret in real usage - - name: MYSQL_ROOT_PASSWORD - value: password - ports: - - containerPort: 3306 - name: mysql - volumeMounts: - - name: mysql-persistent-storage - mountPath: /var/lib/mysql - volumes: - - name: mysql-persistent-storage - persistentVolumeClaim: - claimName: mysql-pv-claim ---- -apiVersion: v1 -kind: PersistentVolume -metadata: - name: mysql-pv-volume - labels: - type: local -spec: - storageClassName: manual - capacity: - storage: 1Gi - accessModes: - - ReadWriteOnce - hostPath: - path: "/mnt/data" ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: mysql-pv-claim -spec: - storageClassName: manual - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 1Gi ---- -apiVersion: v1 -kind: Service -metadata: - name: mysql -spec: - ports: - - port: 3306 - selector: - app: mysql - clusterIP: None diff --git a/examples/crossplane/xrd/composition.yaml b/examples/crossplane/xrd/composition.yaml deleted file mode 100644 index c072c51a3..000000000 --- a/examples/crossplane/xrd/composition.yaml +++ /dev/null @@ -1,132 +0,0 @@ -apiVersion: apiextensions.crossplane.io/v1 -kind: Composition -metadata: - name: mysql-database-simple -spec: - compositeTypeRef: - apiVersion: mangodb.com/v1 - kind: MySQLDatabase - mode: Pipeline - pipeline: - - step: create-mysql-resources - functionRef: - name: function-go-templating - input: - apiVersion: gotemplating.fn.crossplane.io/v1beta1 - kind: GoTemplate - source: Inline - inline: - template: | - {{ $objName := .observed.composite.resource.metadata.name }} - {{ $dbName := .observed.composite.resource.spec.name }} - {{ $objNamespace := .observed.composite.resource.metadata.namespace }} - {{ $userName := printf "%s-user" $dbName }} - {{ $secretName := printf "%s-secret" $dbName }} - {{ $credentials := printf "%s-credentials" $objName }} - --- - apiVersion: mysql.sql.m.crossplane.io/v1alpha1 - kind: Database - metadata: - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: database - {{ if eq (.observed.resources.database | getResourceCondition "Synced").Status "True" }} - gotemplating.fn.crossplane.io/ready: "True" - {{ end }} - name: {{ $dbName }} - namespace: default - spec: - forProvider: {} - providerConfigRef: - kind: ProviderConfig - name: mysql-cfg - --- - apiVersion: v1 - kind: Secret - metadata: - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: secret-exposed - gotemplating.fn.crossplane.io/ready: "True" - labels: - kube-bind.io/selector: consumer-database - namespace: default - name: {{ $credentials }} - {{ if eq $.observed.resources nil }} - stringData: {} - {{ else }} - stringData: - username: {{ ( index $.observed.resources "user" ).connectionDetails.username }} - password: {{ ( index $.observed.resources "user" ).connectionDetails.password }} - port: {{ ( index $.observed.resources "user" ).connectionDetails.port }} - endpoint: {{ ( index $.observed.resources "user" ).connectionDetails.endpoint }} - {{ end }} - --- - apiVersion: v1 - kind: Secret - metadata: - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: secret - gotemplating.fn.crossplane.io/ready: "True" - namespace: default - name: {{ $secretName }} - data: - password: {{ randAlphaNum 16 | b64enc }} - --- - # Hardcoded demo Secret used by ProviderConfig (in default namespace) - apiVersion: v1 - kind: Secret - metadata: - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: provider-db-conn - gotemplating.fn.crossplane.io/ready: "True" - namespace: default - name: db-conn - type: Opaque - stringData: - endpoint: mysql.default.svc.cluster.local - port: "3306" - username: root - password: password - --- - apiVersion: mysql.sql.m.crossplane.io/v1alpha1 - kind: User - metadata: - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: user - {{ if eq (.observed.resources.user | getResourceCondition "Synced").Status "True" }} - gotemplating.fn.crossplane.io/ready: "True" - {{ end }} - name: {{ $userName }} - namespace: default - spec: - forProvider: - passwordSecretRef: - name: {{ $secretName }} - key: password - writeConnectionSecretToRef: - name: {{ printf "%s-connection-secret" $dbName }} - providerConfigRef: - kind: ProviderConfig - name: mysql-cfg - --- - apiVersion: mangodb.com/v1 - kind: MySQLDatabase - metadata: - name: {{ $objName }} - namespace: default - status: - ready: {{ and (eq (.observed.resources.database | getResourceCondition "Synced").Status "True") (eq (.observed.resources.user | getResourceCondition "Synced").Status "True") }} - connectionSecret: {{ printf "%s-connection-secret" $dbName }} - --- - apiVersion: mysql.sql.m.crossplane.io/v1alpha1 - kind: ProviderConfig - metadata: - name: mysql-cfg - annotations: - gotemplating.fn.crossplane.io/composition-resource-name: provider-cfg - gotemplating.fn.crossplane.io/ready: "True" - spec: - credentials: - source: MySQLConnectionSecret - connectionSecretRef: - name: db-conn - tls: preferred diff --git a/examples/crossplane/xrd/function-go-templating.yaml b/examples/crossplane/xrd/function-go-templating.yaml deleted file mode 100644 index 9f3e78b11..000000000 --- a/examples/crossplane/xrd/function-go-templating.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: pkg.crossplane.io/v1 -kind: Function -metadata: - name: function-go-templating -spec: - package: xpkg.crossplane.io/crossplane-contrib/function-go-templating:v0.9.2 diff --git a/examples/crossplane/xrd/xrd-db.yaml b/examples/crossplane/xrd/xrd-db.yaml deleted file mode 100644 index 31fa86d5c..000000000 --- a/examples/crossplane/xrd/xrd-db.yaml +++ /dev/null @@ -1,37 +0,0 @@ -apiVersion: apiextensions.crossplane.io/v2 -kind: CompositeResourceDefinition -metadata: - name: mysqldatabases.mangodb.com - labels: - kube-bind.io/exported: "true" -spec: - scope: Namespaced - group: mangodb.com - names: - kind: MySQLDatabase - plural: mysqldatabases - versions: - - name: v1 - served: true - referenceable: true - schema: - openAPIV3Schema: - type: object - properties: - spec: - type: object - properties: - name: - description: The name of the database to create - type: string - required: - - name - status: - type: object - properties: - ready: - description: Whether the database setup is ready - type: boolean - connectionSecret: - description: Name of the connection secret - type: string diff --git a/go.mod b/go.mod index 11cafece4..6c50f80d6 100644 --- a/go.mod +++ b/go.mod @@ -1,186 +1,81 @@ -module github.com/kube-bind/kube-bind +module github.com/kbind/kbind -// Two Go versions are maintained - the minimum supported Go version as -// noted in the go directive and the build version used in PROW and GHA -// jobs and Docker builds as noted in the comment. -// The script hack/verify-go-versions.sh checks that all version -// references across the codebase are consistent with the versions -// maintained here. -// go-build-version 1.26.9 -go 1.26.9 - -replace ( - github.com/kube-bind/kube-bind => ./ - github.com/kube-bind/kube-bind/cli => ./cli - github.com/kube-bind/kube-bind/sdk => ./sdk - github.com/kube-bind/kube-bind/web => ./web - k8s.io/api => k8s.io/api v0.35.1 - k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.35.1 - k8s.io/apimachinery => k8s.io/apimachinery v0.35.1 - k8s.io/apiserver => k8s.io/apiserver v0.35.1 - k8s.io/cli-runtime => k8s.io/cli-runtime v0.35.1 - k8s.io/client-go => k8s.io/client-go v0.35.1 - k8s.io/code-generator => k8s.io/code-generator v0.35.1 - k8s.io/component-base => k8s.io/component-base v0.35.1 -) +go 1.26.2 require ( - github.com/alicebob/miniredis/v2 v2.37.0 - github.com/coreos/go-oidc/v3 v3.18.0 - github.com/dexidp/dex/api/v2 v2.4.0 - github.com/evanphx/json-patch/v5 v5.9.11 - github.com/golang-jwt/jwt/v5 v5.3.1 - github.com/google/go-cmp v0.7.0 - github.com/google/uuid v1.6.0 - github.com/gorilla/mux v1.8.1 + github.com/coreos/go-oidc/v3 v3.20.0 + github.com/go-logr/logr v1.4.2 github.com/gorilla/securecookie v1.1.2 - github.com/headzoo/surf v1.0.1 - github.com/kcp-dev/multicluster-provider v0.6.0 - github.com/kcp-dev/sdk v0.31.0 - github.com/kube-bind/kube-bind/cli v0.7.1 - github.com/kube-bind/kube-bind/sdk v0.7.1 - github.com/kube-bind/kube-bind/web v0.0.0-20260424090035-f3f89e73d6ee - github.com/martinlindhe/base36 v1.1.1 - github.com/redis/go-redis/v9 v9.18.0 + github.com/kbind/kbind/sdk v0.0.0-00010101000000-000000000000 + github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 github.com/spf13/cobra v1.10.2 - github.com/spf13/pflag v1.0.10 - github.com/stretchr/testify v1.11.1 - github.com/tidwall/gjson v1.18.0 - github.com/vmihailenco/msgpack/v4 v4.3.13 - github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a + github.com/stretchr/testify v1.10.0 golang.org/x/oauth2 v0.36.0 - google.golang.org/grpc v1.83.1 - gopkg.in/yaml.v3 v3.0.1 - k8s.io/api v0.36.0 - k8s.io/apiextensions-apiserver v0.35.1 - k8s.io/apimachinery v0.36.0 - k8s.io/apiserver v0.36.0 - k8s.io/cli-runtime v0.36.0 - k8s.io/client-go v0.36.0 - k8s.io/code-generator v0.35.1 - k8s.io/component-base v0.36.0 - k8s.io/klog/v2 v2.140.0 - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 - sigs.k8s.io/controller-runtime v0.23.3 - sigs.k8s.io/multicluster-runtime v0.23.3 - sigs.k8s.io/yaml v1.6.0 + golang.org/x/sync v0.12.0 + k8s.io/api v0.33.4 + k8s.io/apiextensions-apiserver v0.33.4 + k8s.io/apimachinery v0.33.4 + k8s.io/client-go v0.33.4 + k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 + sigs.k8s.io/controller-runtime v0.21.0 + sigs.k8s.io/multicluster-runtime v0.21.0-alpha.9 + sigs.k8s.io/yaml v1.4.0 ) require ( - cel.dev/expr v0.25.2 // indirect - github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect - github.com/NYTimes/gziphandler v1.1.1 // indirect - github.com/PuerkitoBio/goquery v1.12.0 // indirect - github.com/andybalholm/cascadia v1.3.3 // indirect - github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect - github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/coreos/go-semver v0.3.1 // indirect - github.com/coreos/go-systemd/v22 v22.7.0 // indirect - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fsnotify/fsnotify v1.9.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-errors/errors v1.5.1 // indirect - github.com/go-jose/go-jose/v3 v3.0.5 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/evanphx/json-patch/v5 v5.9.11 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect + github.com/go-jose/go-jose/v3 v3.0.1 // indirect github.com/go-jose/go-jose/v4 v4.1.4 // indirect - github.com/go-logr/logr v1.4.4 // indirect - github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/zapr v1.3.0 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.5 // indirect - github.com/go-openapi/swag v0.26.0 // indirect - github.com/go-openapi/swag/cmdutils v0.26.0 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.26.0 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.23.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/protobuf v1.5.4 // indirect + github.com/golang-jwt/jwt/v5 v5.2.0 // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/cel-go v0.28.0 // indirect - github.com/google/gnostic-models v0.7.1 // indirect - github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect - github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect - github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect - github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect - github.com/headzoo/ut v0.0.0-20181013193318-a13b5a7a02ca // indirect + github.com/google/gnostic-models v0.6.9 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/kcp-dev/apimachinery/v2 v2.31.0 // indirect - github.com/kcp-dev/logicalcluster/v3 v3.0.5 // indirect - github.com/kylelemons/godebug v1.1.0 // indirect - github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/moby/term v0.5.2 // indirect + github.com/mailru/easyjson v0.7.7 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect - github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/onsi/gomega v1.39.1 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.20.1 // indirect - github.com/tidwall/match v1.2.0 // indirect - github.com/tidwall/pretty v1.2.1 // indirect - github.com/vmihailenco/tagparser v0.1.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_golang v1.22.0 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.62.0 // indirect + github.com/prometheus/procfs v0.15.1 // indirect + github.com/spf13/pflag v1.0.9 // indirect github.com/x448/float16 v0.8.4 // indirect - github.com/xlab/treeprint v1.2.0 // indirect - github.com/yuin/gopher-lua v1.1.1 // indirect - go.etcd.io/etcd/api/v3 v3.6.10 // indirect - go.etcd.io/etcd/client/pkg/v3 v3.6.10 // indirect - go.etcd.io/etcd/client/v3 v3.6.10 // indirect - go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 // indirect - go.opentelemetry.io/otel/metric v1.45.0 // indirect - go.opentelemetry.io/otel/sdk v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect - go.opentelemetry.io/proto/otlp v1.11.0 // indirect - go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.27.1 // indirect - go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.57.0 // indirect - golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect - golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.60.0 // indirect - golang.org/x/sync v0.23.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/time v0.15.0 // indirect - golang.org/x/tools v0.49.0 // indirect - gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect - google.golang.org/appengine v1.6.8 // 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 - google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect - gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect + go.uber.org/zap v1.27.0 // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.38.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/term v0.30.0 // indirect + golang.org/x/text v0.23.0 // indirect + golang.org/x/time v0.9.0 // indirect + gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect + google.golang.org/protobuf v1.36.5 // indirect + gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b // indirect - k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f // indirect - sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 // indirect - sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect - sigs.k8s.io/kustomize/api v0.21.1 // indirect - sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff // indirect + sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.0 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect ) + +replace github.com/kbind/kbind/sdk => ./sdk diff --git a/go.sum b/go.sum index 1fd452018..343963623 100644 --- a/go.sum +++ b/go.sum @@ -1,180 +1,76 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= -github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= -github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= -github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= -github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo= -github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ= -github.com/alicebob/miniredis/v2 v2.37.0 h1:RheObYW32G1aiJIj81XVt78ZHJpHonHLHW7OLIshq68= -github.com/alicebob/miniredis/v2 v2.37.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= -github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= -github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= -github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= -github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= -github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= -github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/coreos/go-oidc/v3 v3.18.0 h1:V9orjXynvu5wiC9SemFTWnG4F45v403aIcjWo0d41+A= -github.com/coreos/go-oidc/v3 v3.18.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= -github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= -github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= -github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= -github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= +github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE= +github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dexidp/dex/api/v2 v2.4.0 h1:gNba7n6BKVp8X4Jp24cxYn5rIIGhM6kDOXcZoL6tr9A= -github.com/dexidp/dex/api/v2 v2.4.0/go.mod h1:/p550ADvFFh7K95VmhUD+jgm15VdaNnab9td8DHOpyI= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= -github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g= +github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k= +github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= -github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= -github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ= -github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= +github.com/go-jose/go-jose/v3 v3.0.1 h1:pWmKFVtt+Jl0vBZTIpz/eAKwsm6LkIxDVVbFHKkchhA= +github.com/go-jose/go-jose/v3 v3.0.1/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8= github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= -github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= -github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= -github.com/go-openapi/swag v0.26.0 h1:GVDXCmfvhfu1BxiHo8/FA+BbKmhecHnG3varjON5/RI= -github.com/go-openapi/swag v0.26.0/go.mod h1:82g3193sZJRbocs7bNCqGfIgq8pkuwVwCfhKIRlEQF0= -github.com/go-openapi/swag/cmdutils v0.26.0 h1:iowihOcvq7y4egO8cOq0dmfohz6wfeQ63U1EnuhO2TU= -github.com/go-openapi/swag/cmdutils v0.26.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.26.0 h1:CmZp+ZT7HrmFwrC3GdGsXBq2+42T1bjKBapcqVpIs3c= -github.com/go-openapi/swag/netutils v0.26.0/go.mod h1:5iK+Ok3ZohWWex1C50BFTPexi03UaPwjW4Oj8kgrpwo= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= -github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE= +github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= -github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw= +github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= -github.com/google/cel-go v0.28.0 h1:KjSWstCpz/MN5t4a8gnGJNIYUsJRpdi/r97xWDphIQc= -github.com/google/cel-go v0.28.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= -github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= -github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gnostic-models v0.6.9 h1:MU/8wDLif2qCXZmzncUQ/BOfxWfthHi63KqpoNbWqVw= +github.com/google/gnostic-models v0.6.9/go.mod h1:CiWsm0s6BSQd1hRn8/QmxqB6BesYcbSZxsz9b0KuDBw= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= -github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= -github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= -github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 h1:QGLs/O40yoNK9vmy4rhUGBVyMf1lISBGtXRpsu/Qu/o= -github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.mod h1:hM2alZsMUni80N33RBe6J0e423LB+odMj7d3EMP9l20= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns= -github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= -github.com/headzoo/surf v1.0.1 h1:wk3+LT8gjnCxEwfBJl6MhaNg154En5KjgmgzAG9uMS0= -github.com/headzoo/surf v1.0.1/go.mod h1:/bct0m/iMNEqpn520y01yoaWxsAEigGFPnvyR1ewR5M= -github.com/headzoo/ut v0.0.0-20181013193318-a13b5a7a02ca h1:utFgFwgxaqx5OthzE3DSGrtOq7rox5r2sxZ2wbfTuK0= -github.com/headzoo/ut v0.0.0-20181013193318-a13b5a7a02ca/go.mod h1:8926sG02TCOX4RFRzIMFIzRw4xuc/TwO2gtN7teMJZ4= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= -github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kcp-dev/apimachinery/v2 v2.31.0 h1:N/ALc/v8ZXMxC9a8ovXeQaiFwx8COrqG+FOqD1zl2fY= -github.com/kcp-dev/apimachinery/v2 v2.31.0/go.mod h1:ta+d3xQkLYWBEEg8ICed+PekW3MckEYqXG4amq6Uk9Y= -github.com/kcp-dev/logicalcluster/v3 v3.0.5 h1:JbYakokb+5Uinz09oTXomSUJVQsqfxEvU4RyHUYxHOU= -github.com/kcp-dev/logicalcluster/v3 v3.0.5/go.mod h1:EWBUBxdr49fUB1cLMO4nOdBWmYifLbP1LfoL20KkXYY= -github.com/kcp-dev/multicluster-provider v0.6.0 h1:t7Wac92T4dde9DMMVqA/VPhNhrqkgZ4/Cyij0yh0M5s= -github.com/kcp-dev/multicluster-provider v0.6.0/go.mod h1:pJvWD+5dP+aMsntlu7sBG7oOmYrWfuWKqDQ8WBHur34= -github.com/kcp-dev/sdk v0.31.0 h1:fLqgY6MHVmmBcttqR/V3h2Dnv7xmab84FTKTwV08+Bo= -github.com/kcp-dev/sdk v0.31.0/go.mod h1:GpNW9wPULY9+UuLVAaB5z/sJ8r0Jo/l0Jgy4BKnIJTE= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= -github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= -github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= -github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -183,321 +79,145 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= -github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/martinlindhe/base36 v1.1.1 h1:1F1MZ5MGghBXDZ2KJ3QfxmiydlWOGB8HCEtkap5NkVg= -github.com/martinlindhe/base36 v1.1.1/go.mod h1:vMS8PaZ5e/jV9LwFKlm0YLnXl/hpOihiBxKkIoc3g08= -github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= -github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= -github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/onsi/ginkgo/v2 v2.28.0 h1:Rrf+lVLmtlBIKv6KrIGJCjyY8N36vDVcutbGJkyqjJc= -github.com/onsi/ginkgo/v2 v2.28.0/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= -github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25 h1:9bCMuD3TcnjeqjPT2gSlha4asp8NvgcFRYExCaikCxk= +github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25/go.mod h1:eDjgYHYDJbPLBLsyZ6qRaugP0mX8vePOhZ5id1fdzJw= +github.com/onsi/ginkgo/v2 v2.22.0 h1:Yed107/8DjTr0lKCNt7Dn8yQ6ybuDRQoMGrNFKzMfHg= +github.com/onsi/ginkgo/v2 v2.22.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= +github.com/onsi/gomega v1.36.1 h1:bJDPBO7ibjxcbHMgSCoo4Yj18UWbKDlLwX1x9sybDcw= +github.com/onsi/gomega v1.36.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/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.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= -github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= -github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= -github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= +github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= +github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= -github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= -github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= -github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= 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 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= 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/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= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= -github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM= -github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= -github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= -github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7otjonDflCTK0BCfls4SPy3NcCVb5dqqmbRknE= -github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= -github.com/vmihailenco/msgpack/v4 v4.3.13 h1:A2wsiTbvp63ilDaWmsk2wjx6xZdxQOvpiNlKBGKKXKI= -github.com/vmihailenco/msgpack/v4 v4.3.13/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= -github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbd1qPqc= -github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= -github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= -github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= -github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a h1:rPK2vAgG4T5k6ay5v+DVU7j2xjW/S3LWbzKpOGukdeE= -github.com/xrstf/mockoidc v0.0.0-20251217111820-5b7a850f338a/go.mod h1:1S3+yz/sau3wSTpmFOwg+JmOudpq6KA6vTuvmP5VReM= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= -github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= -github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= -github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= -go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo= -go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E= -go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY= -go.etcd.io/etcd/api/v3 v3.6.10/go.mod h1:pdV4VeFmvhdNjB4LWRkC8ReLyRBAxUOze3GarMhE2sk= -go.etcd.io/etcd/client/pkg/v3 v3.6.10 h1:tBT7podcPhuVbCVkAEzx8bC5I+aqxfLwBN8/As1arrA= -go.etcd.io/etcd/client/pkg/v3 v3.6.10/go.mod h1:WEy3PpwbbEBVRdh1NVJYsuUe/8eyI21PNJRazeD8z/Y= -go.etcd.io/etcd/client/v3 v3.6.10 h1:J598zJ+C/ZPvImypmq5waj84+bovePrlZERHklf34y0= -go.etcd.io/etcd/client/v3 v3.6.10/go.mod h1:iHhUDUcEwaKs1YFq3MgmI9U4zhTVasp/vgdVbFf1RS8= -go.etcd.io/etcd/pkg/v3 v3.6.5 h1:byxWB4AqIKI4SBmquZUG1WGtvMfMaorXFoCcFbVeoxM= -go.etcd.io/etcd/pkg/v3 v3.6.5/go.mod h1:uqrXrzmMIJDEy5j00bCqhVLzR5jEJIwDp5wTlLwPGOU= -go.etcd.io/etcd/server/v3 v3.6.5 h1:4RbUb1Bd4y1WkBHmuF+cZII83JNQMuNXzyjwigQ06y0= -go.etcd.io/etcd/server/v3 v3.6.5/go.mod h1:PLuhyVXz8WWRhzXDsl3A3zv/+aK9e4A9lpQkqawIaH0= -go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ= -go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo= -go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= -go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= -go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= -go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/goleak v1.3.1-0.20241121203838-4ff5fa6529ee h1:uOMbcH1Dmxv45VkkpZQYoerZFeDncWpjbN7ATiQOO7c= -go.uber.org/goleak v1.3.1-0.20241121203838-4ff5fa6529ee/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= -go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= -golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= -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/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= -golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -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.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= -golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= -golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= 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/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/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.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= -golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -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.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/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.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.28.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/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= -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.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= -golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= -golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= -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/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y= +golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -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.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= 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.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -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.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= -golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= -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/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= -golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= -golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= -golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/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= -gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= -gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.1 h1:HIO0+BEtBP6soyqvqC8sNUjZ7bTs+0hFQuFF+RAy++Y= -google.golang.org/grpc v1.83.1/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw= +gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= -gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4= +gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= -gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.35.1 h1:0PO/1FhlK/EQNVK5+txc4FuhQibV25VLSdLMmGpDE/Q= -k8s.io/api v0.35.1/go.mod h1:28uR9xlXWml9eT0uaGo6y71xK86JBELShLy4wR1XtxM= -k8s.io/apiextensions-apiserver v0.35.1 h1:p5vvALkknlOcAqARwjS20kJffgzHqwyQRM8vHLwgU7w= -k8s.io/apiextensions-apiserver v0.35.1/go.mod h1:2CN4fe1GZ3HMe4wBr25qXyJnJyZaquy4nNlNmb3R7AQ= -k8s.io/apimachinery v0.35.1 h1:yxO6gV555P1YV0SANtnTjXYfiivaTPvCTKX6w6qdDsU= -k8s.io/apimachinery v0.35.1/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= -k8s.io/apiserver v0.35.1 h1:potxdhhTL4i6AYAa2QCwtlhtB1eCdWQFvJV6fXgJzxs= -k8s.io/apiserver v0.35.1/go.mod h1:BiL6Dd3A2I/0lBnteXfWmCFobHM39vt5+hJQd7Lbpi4= -k8s.io/cli-runtime v0.35.1 h1:uKcXFe8J7AMAM4Gm2JDK4mp198dBEq2nyeYtO+JfGJE= -k8s.io/cli-runtime v0.35.1/go.mod h1:55/hiXIq1C8qIJ3WBrWxEwDLdHQYhBNRdZOz9f7yvTw= -k8s.io/client-go v0.35.1 h1:+eSfZHwuo/I19PaSxqumjqZ9l5XiTEKbIaJ+j1wLcLM= -k8s.io/client-go v0.35.1/go.mod h1:1p1KxDt3a0ruRfc/pG4qT/3oHmUj1AhSHEcxNSGg+OA= -k8s.io/code-generator v0.35.1 h1:yLKR2la7Z9cWT5qmk67ayx8xXLM4RRKQMnC8YPvTWRI= -k8s.io/code-generator v0.35.1/go.mod h1:F2Fhm7aA69tC/VkMXLDokdovltXEF026Tb9yfQXQWKg= -k8s.io/component-base v0.35.1 h1:XgvpRf4srp037QWfGBLFsYMUQJkE5yMa94UsJU7pmcE= -k8s.io/component-base v0.35.1/go.mod h1:HI/6jXlwkiOL5zL9bqA3en1Ygv60F03oEpnuU1G56Bs= -k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b h1:gMplByicHV/TJBizHd9aVEsTYoJBnnUAT5MHlTkbjhQ= -k8s.io/gengo/v2 v2.0.0-20250922181213-ec3ebc5fd46b/go.mod h1:CgujABENc3KuTrcsdpGmrrASjtQsWCT7R99mEV4U/fM= -k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= -k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kms v0.35.1 h1:kjv2r9g1mY7uL+l1RhyAZvWVZIA/4qIfBHXyjFGLRhU= -k8s.io/kms v0.35.1/go.mod h1:VT+4ekZAdrZDMgShK37vvlyHUVhwI9t/9tvh0AyCWmQ= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f h1:4Qiq0YAoQATdgmHALJWz9rJ4fj20pB3xebpB4CFNhYM= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0 h1:hSfpvjjTQXQY2Fol2CS0QHMNs/WI1MOSGzCm1KhM5ec= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.34.0/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw= -sigs.k8s.io/controller-runtime v0.23.3 h1:VjB/vhoPoA9l1kEKZHBMnQF33tdCLQKJtydy4iqwZ80= -sigs.k8s.io/controller-runtime v0.23.3/go.mod h1:B6COOxKptp+YaUT5q4l6LqUJTRpizbgf9KSRNdQGns0= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= -sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= -sigs.k8s.io/kustomize/kyaml v0.21.1 h1:IVlbmhC076nf6foyL6Taw4BkrLuEsXUXNpsE+ScX7fI= -sigs.k8s.io/kustomize/kyaml v0.21.1/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= -sigs.k8s.io/multicluster-runtime v0.23.3 h1:vrzlXRzHTDsjspUAfoW2rCtr0agoI4q20p9x4Fz4png= -sigs.k8s.io/multicluster-runtime v0.23.3/go.mod h1:r/UA4GHgFoXCcR4tcvlZz7SiLx3l1kJKDuBAhILNIHs= +k8s.io/api v0.33.4 h1:oTzrFVNPXBjMu0IlpA2eDDIU49jsuEorGHB4cvKupkk= +k8s.io/api v0.33.4/go.mod h1:VHQZ4cuxQ9sCUMESJV5+Fe8bGnqAARZ08tSTdHWfeAc= +k8s.io/apiextensions-apiserver v0.33.4 h1:rtq5SeXiDbXmSwxsF0MLe2Mtv3SwprA6wp+5qh/CrOU= +k8s.io/apiextensions-apiserver v0.33.4/go.mod h1:mWXcZQkQV1GQyxeIjYApuqsn/081hhXPZwZ2URuJeSs= +k8s.io/apimachinery v0.33.4 h1:SOf/JW33TP0eppJMkIgQ+L6atlDiP/090oaX0y9pd9s= +k8s.io/apimachinery v0.33.4/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/client-go v0.33.4 h1:TNH+CSu8EmXfitntjUPwaKVPN0AYMbc9F1bBS8/ABpw= +k8s.io/client-go v0.33.4/go.mod h1:LsA0+hBG2DPwovjd931L/AoaezMPX9CmBgyVyBZmbCY= +k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= +k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff h1:/usPimJzUKKu+m+TE36gUyGcf03XZEP0ZIKgKj35LS4= +k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff/go.mod h1:5jIi+8yX4RIb8wk3XwBo5Pq2ccx4FP10ohkbSKCZoK8= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/controller-runtime v0.21.0 h1:CYfjpEuicjUecRk+KAeyYh+ouUBn4llGyDYytIGcJS8= +sigs.k8s.io/controller-runtime v0.21.0/go.mod h1:OSg14+F65eWqIu4DceX7k/+QRAbTTvxeQSNSOQpukWM= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= +sigs.k8s.io/multicluster-runtime v0.21.0-alpha.9 h1:baonM4f081WWct3U7O4EfqrxcUGtmCrFDbsT1FQ8xlo= +sigs.k8s.io/multicluster-runtime v0.21.0-alpha.9/go.mod h1:CpBzLMLQKdm+UCchd2FiGPiDdCxM5dgCCPKuaQ6Fsv0= +sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0 h1:qmp2e3ZfFi1/jJbDGpD4mt3wyp6PE1NfKHCYLqgNQJo= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= -sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= -sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/hack/boilerplate/boilerplate.Dockerfile.txt b/hack/boilerplate/boilerplate.Dockerfile.txt index 3b4ee55a7..b1b685e88 100644 --- a/hack/boilerplate/boilerplate.Dockerfile.txt +++ b/hack/boilerplate/boilerplate.Dockerfile.txt @@ -1,4 +1,4 @@ -# Copyright YEAR The Kube Bind Authors. +# Copyright YEAR The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,4 +11,3 @@ # 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. - diff --git a/hack/boilerplate/boilerplate.Makefile.txt b/hack/boilerplate/boilerplate.Makefile.txt index 3b4ee55a7..b1b685e88 100644 --- a/hack/boilerplate/boilerplate.Makefile.txt +++ b/hack/boilerplate/boilerplate.Makefile.txt @@ -1,4 +1,4 @@ -# Copyright YEAR The Kube Bind Authors. +# Copyright YEAR The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,4 +11,3 @@ # 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. - diff --git a/hack/boilerplate/boilerplate.generatego.txt b/hack/boilerplate/boilerplate.generatego.txt index 4f8a6acbd..571123155 100644 --- a/hack/boilerplate/boilerplate.generatego.txt +++ b/hack/boilerplate/boilerplate.generatego.txt @@ -1,5 +1,5 @@ /* -Copyright The Kube Bind Authors. +Copyright The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -13,4 +13,3 @@ 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. */ - diff --git a/hack/boilerplate/boilerplate.go.txt b/hack/boilerplate/boilerplate.go.txt index 462a02bb5..d86a4a7bd 100644 --- a/hack/boilerplate/boilerplate.go.txt +++ b/hack/boilerplate/boilerplate.go.txt @@ -1,5 +1,5 @@ /* -Copyright YEAR The Kube Bind Authors. +Copyright YEAR The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -13,4 +13,3 @@ 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. */ - diff --git a/hack/boilerplate/boilerplate.py.txt b/hack/boilerplate/boilerplate.py.txt index 3b4ee55a7..b1b685e88 100644 --- a/hack/boilerplate/boilerplate.py.txt +++ b/hack/boilerplate/boilerplate.py.txt @@ -1,4 +1,4 @@ -# Copyright YEAR The Kube Bind Authors. +# Copyright YEAR The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,4 +11,3 @@ # 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. - diff --git a/hack/boilerplate/boilerplate.sh.txt b/hack/boilerplate/boilerplate.sh.txt index 3b4ee55a7..b1b685e88 100644 --- a/hack/boilerplate/boilerplate.sh.txt +++ b/hack/boilerplate/boilerplate.sh.txt @@ -1,4 +1,4 @@ -# Copyright YEAR The Kube Bind Authors. +# Copyright YEAR The kbind Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -11,4 +11,3 @@ # 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. - diff --git a/hack/build-image.sh b/hack/build-image.sh deleted file mode 100755 index 46525df69..000000000 --- a/hack/build-image.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -eu - -# Inputs (env vars): -# IMAGE_REPO registry+namespace, e.g. ghcr.io/kbind-dev or kube-bind (required) -# PLATFORMS buildx platform list, default: linux/ -# IMAGE_TAGS space-separated tag suffixes, default: $REV -# PUSH true|false; default: true if PLATFORMS is multi-arch, else false (--load) -# LDFLAGS go ldflags passed as build-arg -# OUTPUT_DIR if set, write .metadata.json files (used by image-sign.sh) -# BUILDX_CACHE_FROM passed to --cache-from (e.g. type=gha) -# BUILDX_CACHE_TO passed to --cache-to (e.g. type=gha,mode=max) -# IMAGE_LABELS newline- or space-separated key=value labels (applied to both images) - -: "${IMAGE_REPO:?IMAGE_REPO must be set}" -: "${PLATFORMS:=linux/$(go env GOARCH)}" -: "${IMAGE_TAGS:=${REV:?REV must be set when IMAGE_TAGS is unset}}" - -if [[ -z "${PUSH:-}" ]]; then - if [[ "$PLATFORMS" == *","* ]]; then - PUSH=true - else - PUSH=false - fi -fi - -if [[ "$PUSH" == "true" ]]; then - OUTPUT_FLAG="--push" -else - OUTPUT_FLAG="--load" - if [[ "$PLATFORMS" == *","* ]]; then - echo "PUSH=false with multi-platform PLATFORMS=$PLATFORMS will fail (--load only supports a single platform)." >&2 - exit 1 - fi -fi - -command -v docker >/dev/null 2>&1 || { echo "docker not found. Please install Docker"; exit 1; } -docker buildx version >/dev/null 2>&1 || { echo "docker buildx not found. Please enable buildx in Docker"; exit 1; } - -# Reuse an existing active builder (e.g. one set up by docker/setup-buildx-action in CI). -# Only create our own if none is active — otherwise we'd lose the GHA cache wiring. -if ! docker buildx inspect >/dev/null 2>&1; then - docker buildx create --name kube-bind-builder --use >/dev/null -fi -docker buildx inspect --bootstrap >/dev/null 2>&1 - -cache_args=() -if [[ -n "${BUILDX_CACHE_FROM:-}" ]]; then - cache_args+=("--cache-from" "$BUILDX_CACHE_FROM") -fi -if [[ -n "${BUILDX_CACHE_TO:-}" ]]; then - cache_args+=("--cache-to" "$BUILDX_CACHE_TO") -fi - -label_args=() -if [[ -n "${IMAGE_LABELS:-}" ]]; then - while IFS= read -r label; do - [[ -z "$label" ]] && continue - label_args+=("--label" "$label") - done <<< "$(echo "$IMAGE_LABELS" | tr ' ' '\n')" -fi - -build_image() { - local component="$1" - local dockerfile="$2" - - local tag_args=() - for t in $IMAGE_TAGS; do - tag_args+=("-t" "${IMAGE_REPO}/${component}:${t}") - done - - local metadata_args=() - if [[ -n "${OUTPUT_DIR:-}" ]]; then - mkdir -p "$OUTPUT_DIR" - metadata_args+=("--metadata-file" "${OUTPUT_DIR}/${component}.metadata.json") - fi - - echo "Building ${component} image (platforms: $PLATFORMS, push: $PUSH)..." - docker buildx build \ - --platform "$PLATFORMS" \ - --build-arg LDFLAGS="${LDFLAGS:-}" \ - "${tag_args[@]}" \ - "${cache_args[@]}" \ - "${label_args[@]}" \ - "${metadata_args[@]}" \ - -f "$dockerfile" \ - $OUTPUT_FLAG . -} - -build_image konnector Dockerfile.konnector -build_image backend Dockerfile - -echo "Successfully built images on platforms ${PLATFORMS}" -echo "Tags:" -for t in $IMAGE_TAGS; do - echo " ${IMAGE_REPO}/konnector:${t}" - echo " ${IMAGE_REPO}/backend:${t}" -done diff --git a/hack/demo.sh b/hack/demo.sh new file mode 100755 index 000000000..5acfa336e --- /dev/null +++ b/hack/demo.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash + +# Copyright 2026 The kbind 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. + +# Stands up two kind clusters (provider + consumer) and wires the v2 slim-core +# demo: a provider exports the Widget CRD, the consumer binds it, and the +# konnector syncs instances. Run the konnector separately (printed at the end). +set -euo pipefail + +PROVIDER=kbind-provider +CONSUMER=kbind-consumer +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +V2="$(cd "${HERE}/.." && pwd)" +SAMPLES="${V2}/config/samples" +PROVIDER_KC=/tmp/${PROVIDER}.kubeconfig +CONSUMER_KC=/tmp/${CONSUMER}.kubeconfig + +echo "==> Creating kind clusters" +kind create cluster --name "${PROVIDER}" || true +kind create cluster --name "${CONSUMER}" || true + +# Internal kubeconfig so the konnector (running on the host) can reach the +# provider API server via its host-mapped port. +kind get kubeconfig --name "${PROVIDER}" > "${PROVIDER_KC}" +kind get kubeconfig --name "${CONSUMER}" > "${CONSUMER_KC}" + +kp() { kubectl --kubeconfig "${PROVIDER_KC}" "$@"; } +kc() { kubectl --kubeconfig "${CONSUMER_KC}" "$@"; } + +echo "==> Provider: install + export the Widget CRD" +kp apply -f "${SAMPLES}/provider-widget-crd.yaml" + +echo "==> Consumer: install core CRDs and the kbind namespace" +kc apply -f "${V2}/sdk/config/crd" +kc create namespace kbind --dry-run=client -o yaml | kc apply -f - + +echo "==> Consumer: store the provider kubeconfig as a Secret" +kc -n kbind delete secret demo-provider-kubeconfig --ignore-not-found +kc -n kbind create secret generic demo-provider-kubeconfig \ + --from-file=kubeconfig="${PROVIDER_KC}" + +echo "==> Consumer: the one-apply bundle (Connection + ClusterBinding)" +kc apply -f "${SAMPLES}/binding.yaml" + +cat <${RESET} $*"; } +pass() { echo "${GREEN} ✓${RESET} $*"; } +fail() { echo "${RED} ✗ $*${RESET}" >&2; exit 1; } + +# retry — succeeds as soon as does. +retry() { + local attempts=$1 delay=$2; shift 2 + local i + for ((i = 1; i <= attempts; i++)); do + if "$@"; then return 0; fi + sleep "${delay}" + done + return 1 +} + +cleanup() { + rm -f "${PROVIDER_KC}" "${CONSUMER_KC}" "${PROVIDER_INTERNAL_KC}" + if [[ "${KEEP}" == "1" ]]; then + cat </dev/null 2>&1 || true + kind delete cluster --name "${CONSUMER}" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +# ---------------------------------------------------------------------------- +info "Creating kind clusters (${PROVIDER}, ${CONSUMER})" +kind create cluster --name "${PROVIDER}" >/dev/null 2>&1 || true +kind create cluster --name "${CONSUMER}" >/dev/null 2>&1 || true +kind get kubeconfig --name "${PROVIDER}" > "${PROVIDER_KC}" +kind get kubeconfig --name "${CONSUMER}" > "${CONSUMER_KC}" + +# A kind cluster can report "created" before its API server is reachable, and a +# memory-starved docker host can leave a node NotReady. Gate on real readiness +# so later steps fail loudly here instead of with a cryptic "connection refused". +info "Waiting for both clusters' API servers and nodes to be Ready" +retry "${TIMEOUT}" 2 kp get --raw=/readyz >/dev/null 2>&1 \ + || fail "provider API server never became ready (check 'docker ps' — the kind node may have been OOM-killed)" +retry "${TIMEOUT}" 2 kc get --raw=/readyz >/dev/null 2>&1 \ + || fail "consumer API server never became ready (check 'docker ps' — the kind node may have been OOM-killed)" +kp wait --for=condition=Ready nodes --all --timeout="${TIMEOUT}s" >/dev/null +kc wait --for=condition=Ready nodes --all --timeout="${TIMEOUT}s" >/dev/null +pass "both clusters are reachable and Ready" + +# The konnector runs as a pod in the consumer cluster, so it cannot reach the +# provider via the host-mapped 127.0.0.1 port. Rewrite the server to the +# provider node's IP on the shared docker "kind" network; the kind API server +# cert includes that internal IP as a SAN, so TLS still verifies. +PROVIDER_IP="$(docker inspect -f '{{(index .NetworkSettings.Networks "kind").IPAddress}}' "${PROVIDER}-control-plane")" +[[ -n "${PROVIDER_IP}" ]] || fail "could not determine provider node IP on the kind network" +sed -E "s#server: https://127\.0\.0\.1:[0-9]+#server: https://${PROVIDER_IP}:6443#" \ + "${PROVIDER_KC}" > "${PROVIDER_INTERNAL_KC}" + +# ---------------------------------------------------------------------------- +if [[ "${NO_BUILD}" == "1" ]]; then + info "Skipping image build (NO_BUILD=1); loading ${IMAGE} into ${CONSUMER}" +else + info "Building konnector image ${IMAGE}" + docker build -t "${IMAGE}" "${ROOT}" +fi +info "Loading ${IMAGE} into the consumer cluster" +kind load docker-image "${IMAGE}" --name "${CONSUMER}" + +# ---------------------------------------------------------------------------- +info "Provider: installing the exported Widget CRD" +kp apply -f "${SAMPLES}/provider-widget-crd.yaml" + +# ---------------------------------------------------------------------------- +info "Consumer: helm install the konnector (chart bundles the core CRDs)" +kc create namespace "${NAMESPACE}" --dry-run=client -o yaml | kc apply -f - +helm --kubeconfig "${CONSUMER_KC}" upgrade --install "${RELEASE}" "${CHART}" \ + --namespace "${NAMESPACE}" \ + --set image.repository="${IMAGE_REPO}" \ + --set image.tag="${IMAGE_TAG}" \ + --set image.pullPolicy=IfNotPresent \ + --wait --timeout "${TIMEOUT}s" + +DEPLOY="$(kc -n "${NAMESPACE}" get deploy -l app.kubernetes.io/instance="${RELEASE}" -o name | head -n1)" +[[ -n "${DEPLOY}" ]] || fail "konnector deployment not found" +kc -n "${NAMESPACE}" rollout status "${DEPLOY}" --timeout="${TIMEOUT}s" +pass "konnector deployment is available" + +# ---------------------------------------------------------------------------- +info "Consumer: store the provider kubeconfig and apply the bundle" +kc -n "${NAMESPACE}" delete secret demo-provider-kubeconfig --ignore-not-found >/dev/null +kc -n "${NAMESPACE}" create secret generic demo-provider-kubeconfig \ + --from-file=kubeconfig="${PROVIDER_INTERNAL_KC}" +kc apply -f "${SAMPLES}/binding.yaml" + +# ---------------------------------------------------------------------------- +info "Asserting the bind flow" +kc wait --for=condition=Ready connection/demo-provider --timeout="${TIMEOUT}s" \ + || fail "Connection did not become Ready" +pass "Connection demo-provider is Ready" + +retry "${TIMEOUT}" 1 kc get crd widgets.example.org >/dev/null 2>&1 \ + || fail "Widget CRD was not pulled onto the consumer" +kc wait --for=condition=Established crd/widgets.example.org --timeout="${TIMEOUT}s" >/dev/null +pass "Widget CRD pulled onto the consumer and Established" + +kc wait --for=condition=Synced clusterbinding/widgets --timeout="${TIMEOUT}s" \ + || fail "ClusterBinding did not become Synced" +pass "ClusterBinding widgets is Synced" + +# ---------------------------------------------------------------------------- +info "Asserting spec sync UP (consumer -> provider)" +kc apply -f "${SAMPLES}/widget.yaml" +retry "${TIMEOUT}" 1 kp -n default get widget my-widget >/dev/null 2>&1 \ + || fail "Widget did not sync up to the provider" +SIZE="$(kp -n default get widget my-widget -o jsonpath='{.spec.size}')" +[[ "${SIZE}" == "large" ]] || fail "Widget synced up but spec.size=${SIZE:-} (want large)" +pass "Widget synced up to the provider (spec.size=large)" + +# ---------------------------------------------------------------------------- +info "Asserting status sync DOWN (provider -> consumer)" +kp -n default patch widget my-widget --subresource=status --type=merge \ + -p '{"status":{"phase":"Running"}}' +phase_is_running() { + [[ "$(kc -n default get widget my-widget -o jsonpath='{.status.phase}' 2>/dev/null)" == "Running" ]] +} +retry "${TIMEOUT}" 1 phase_is_running \ + || fail "provider status did not flow down to the consumer" +pass "status flowed down to the consumer (status.phase=Running)" + +echo +echo "${GREEN}${BOLD}E2E PASSED${RESET}" diff --git a/hack/generate_boilerplate.py b/hack/generate_boilerplate.py new file mode 100644 index 000000000..7bde5ff85 --- /dev/null +++ b/hack/generate_boilerplate.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 + +# Copyright 2026 The kbind 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. + +"""Generate or update source-file boilerplate headers from templates.""" + +import argparse +import datetime +import glob +import os +import re +import sys + + +YEAR_RE = re.compile(r"\b\d{4}(?:-\d{4})?\b") +COPYRIGHT_RE = re.compile( + r"Copyright\s+(\d{4})(?:-(\d{4}))?\s+The kbind Authors\." +) + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "filenames", + help="list of files to update, all files if unspecified", + nargs='*') + + rootdir = os.path.abspath('.') + parser.add_argument("--rootdir", + default=rootdir, + help="root directory to examine") + + default_boilerplate_dir = os.path.join(rootdir, "hack/boilerplate") + parser.add_argument("--boilerplate-dir", default=default_boilerplate_dir) + + parser.add_argument( + '--skip', + default=[ + 'external/bazel_tools', + '.git', + 'node_modules', + '_output', + 'third_party', + 'vendor', + 'verify/boilerplate/test', + 'verify_boilerplate.py', + 'generate_boilerplate.py', + ], + action='append', + help='Customize paths to avoid', + ) + parser.add_argument( + '--check', + action='store_true', + help='Report files that would be changed without writing them', + ) + return parser.parse_args() + + +def get_refs(): + refs = {} + + template_dir = ARGS.boilerplate_dir + if not os.path.isdir(template_dir): + template_dir = os.path.dirname(template_dir) + for path in glob.glob(os.path.join(template_dir, "boilerplate.*.txt")): + extension = os.path.basename(path).split(".")[1] + + with open(path, 'r', encoding='utf-8') as ref_file: + refs[extension] = ref_file.read().splitlines() + + return refs + + +def file_extension(filename): + return os.path.splitext(filename)[1].split(".")[-1].lower() + + +def has_ignored_header(pathname): + with open(pathname, 'r', encoding='utf-8') as myfile: + data = myfile.read() + return data.startswith('// Code generated by go-bindata.') + + +def normalize_files(files): + newfiles = [] + for pathname in files: + if any(x in pathname for x in ARGS.skip): + continue + newfiles.append(pathname) + for idx, pathname in enumerate(newfiles): + if not os.path.isabs(pathname): + newfiles[idx] = os.path.join(ARGS.rootdir, pathname) + return newfiles + + +def get_files(extensions): + files = [] + if ARGS.filenames: + files = ARGS.filenames + else: + for root, dirs, walkfiles in os.walk(ARGS.rootdir): + for dpath in ARGS.skip: + if dpath in dirs: + dirs.remove(dpath) + + for name in walkfiles: + files.append(os.path.join(root, name)) + + files = normalize_files(files) + outfiles = [] + for pathname in files: + basename = os.path.basename(pathname) + extension = file_extension(pathname) + if extension in extensions or basename in extensions: + if not has_ignored_header(pathname): + outfiles.append(pathname) + return outfiles + + +def get_year(): + return datetime.datetime.now().year + + +def get_year_text(header_lines, current_year): + for line in header_lines: + match = COPYRIGHT_RE.search(line) + if match is None: + continue + + start_year = match.group(1) + end_year = match.group(2) + if end_year is None: + if int(start_year) == current_year: + return start_year + return f"{start_year}-{current_year}" + + if int(end_year) == current_year: + return f"{start_year}-{end_year}" + return f"{start_year}-{current_year}" + + return str(current_year) + + +def replace_years(lines, year_text): + return [YEAR_RE.sub(year_text, line) for line in lines] + + +def render_template(lines, year_text): + return [line.replace("YEAR", year_text) for line in lines] + + +def extract_prefix(lines, extension): + prefix = [] + idx = 0 + + if extension == "go": + while idx < len(lines) and (lines[idx].startswith("//go:build") or + lines[idx].startswith("// +build")): + prefix.append(lines[idx]) + idx += 1 + if idx < len(lines) and lines[idx] == "": + prefix.append(lines[idx]) + idx += 1 + return prefix, lines[idx:] + + if extension in ("sh", "py") and lines and lines[0].startswith("#!"): + prefix.append(lines[0]) + idx = 1 + if idx < len(lines) and lines[idx] == "": + prefix.append(lines[idx]) + idx += 1 + return prefix, lines[idx:] + + return prefix, lines + + +def update_file(pathname, refs, current_year): + with open(pathname, 'r', encoding='utf-8') as fp: + original = fp.read() + + if not original: + return False + + lines = original.splitlines() + trailing_newline = original.endswith("\n") + + basename = os.path.basename(pathname) + extension = file_extension(pathname) + if extension != "": + template = refs[extension] + else: + template = refs[basename] + + prefix, body = extract_prefix(lines, extension) + existing = body[:len(template)] + normalized_existing = replace_years(existing, "YEAR") + has_header = normalized_existing == template + + if has_header: + year_text = get_year_text(existing, current_year) + rest = body[len(template):] + else: + year_text = str(current_year) + rest = body + + updated = prefix + render_template(template, year_text) + rest + new_text = "\n".join(updated) + if trailing_newline: + new_text += "\n" + + if new_text == original: + return False + + if ARGS.check: + return True + + with open(pathname, 'w', encoding='utf-8') as fp: + fp.write(new_text) + return True + + +def main(): + refs = get_refs() + filenames = get_files(refs.keys()) + current_year = get_year() + + changed = [] + for filename in sorted(filenames): + if update_file(filename, refs, current_year): + changed.append(filename) + + if changed and ARGS.check: + print('%d files would be updated:' % len(changed)) + for fp in changed: + print(os.path.relpath(fp, ARGS.rootdir)) + sys.exit(1) + + +if __name__ == "__main__": + ARGS = get_args() + main() diff --git a/hack/go-install.sh b/hack/go-install.sh deleted file mode 100755 index f93f2a473..000000000 --- a/hack/go-install.sh +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2021 The Kube Bind 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. - -# Originally copied from -# https://github.com/kubernetes-sigs/cluster-api-provider-gcp/blob/c26a68b23e9317323d5d37660fe9d29b3d2ff40c/scripts/go_install.sh -# -# Installs a Go binary either via "go install" or by cloning and building -# from source (for modules with replace directives that block go install). - -set -o errexit -set -o nounset -set -o pipefail - -if [[ -z "${1:-}" ]]; then - echo "must provide module as first parameter" - exit 1 -fi - -if [[ -z "${2:-}" ]]; then - echo "must provide binary name as second parameter" - exit 1 -fi - -if [[ -z "${3:-}" ]]; then - echo "must provide version as third parameter" - exit 1 -fi - -if [[ -z "${GOBIN:-}" ]]; then - echo "GOBIN is not set. Must set GOBIN to install the bin in a specified directory." - exit 1 -fi - -MODULE="${1}" -BINARY="${2}" -VERSION="${3}" - -# Extract the repo URL from the module path (everything before /cmd/...) -# e.g. github.com/kcp-dev/kcp/cmd/kcp -> github.com/kcp-dev/kcp -REPO_URL="${MODULE}" -if [[ "${REPO_URL}" == *"/cmd/"* ]]; then - REPO_URL="${REPO_URL%%/cmd/*}" -fi -# Relative path within the repo to the binary (e.g. ./cmd/kcp) -CMD_PATH="./${MODULE#"${REPO_URL}"/}" -if [[ "${CMD_PATH}" == "./${MODULE}" ]]; then - CMD_PATH="." -fi - -mkdir -p "${GOBIN}" - -# If the versioned binary already exists, just ensure the symlink and exit. -if [[ -f "${GOBIN}/${BINARY}-${VERSION}" ]]; then - ln -sf "${GOBIN}/${BINARY}-${VERSION}" "${GOBIN}/${BINARY}" - exit 0 -fi - -tmp_dir=$(mktemp -d -t goinstall_XXXXXXXXXX) -function clean { - rm -rf "${tmp_dir}" -} -trap clean EXIT - -rm "${GOBIN}/${BINARY}"* > /dev/null 2>&1 || true - -cd "${tmp_dir}" - -# Try go install first (works when the module has no replace directives). -# The || true prevents errexit from killing the script on failure. -go mod init fake/mod -if go install -tags tools "${MODULE}@${VERSION}" 2>/dev/null; then - mv "${GOBIN}/${BINARY}" "${GOBIN}/${BINARY}-${VERSION}" - ln -sf "${GOBIN}/${BINARY}-${VERSION}" "${GOBIN}/${BINARY}" - exit 0 -fi - -# Fallback: clone the repo and build from source. -# This handles modules with replace directives in go.mod. -echo "go install failed (module likely has replace directives), cloning and building from source..." -git clone --quiet "https://${REPO_URL}.git" repo -cd repo -git checkout --quiet "${VERSION}" -go build -trimpath -o "${GOBIN}/${BINARY}-${VERSION}" "${CMD_PATH}" -ln -sf "${GOBIN}/${BINARY}-${VERSION}" "${GOBIN}/${BINARY}" diff --git a/hack/helm-build.sh b/hack/helm-build.sh deleted file mode 100755 index cb9285f12..000000000 --- a/hack/helm-build.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -eu - -APP_VERSION="${APP_VERSION:-0.0.0-${REV:-}}" -if [[ -z "$APP_VERSION" || "$APP_VERSION" == "0.0.0-" ]]; then - echo "ERROR: APP_VERSION or REV must be set" >&2; exit 1 -fi -CHART_VERSION="${APP_VERSION#v}" - -echo "Building Helm charts (appVersion: $APP_VERSION, chartVersion: $CHART_VERSION)..." - -HELM="$(UGET_PRINT_PATH=absolute make --no-print-directory install-helm)" - -for chart_dir in deploy/charts/*/; do - if [ -f "${chart_dir}Chart.yaml" ]; then - chart_name=$(basename "$chart_dir") - echo "Processing chart: $chart_name" - - cp "${chart_dir}Chart.yaml" "${chart_dir}Chart.yaml.bak" - sed -i.tmp "s/^version:.*/version: $CHART_VERSION/" "${chart_dir}Chart.yaml" - sed -i.tmp "s/^appVersion:.*/appVersion: \"$APP_VERSION\"/" "${chart_dir}Chart.yaml" - rm -f "${chart_dir}Chart.yaml.tmp" - - "$HELM" package "$chart_dir" --version "$CHART_VERSION" --destination ./bin/ - echo "Packaged: ./bin/$chart_name-$CHART_VERSION.tgz" - - mv "${chart_dir}Chart.yaml.bak" "${chart_dir}Chart.yaml" - fi -done - -echo "Helm charts built successfully in ./bin/" diff --git a/hack/helm-push.sh b/hack/helm-push.sh deleted file mode 100755 index 1291239ef..000000000 --- a/hack/helm-push.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -eu - -# Inputs (env vars): -# IMAGE_REPO registry+namespace, e.g. ghcr.io/kbind-dev (required) -# REV short git sha (required if CHART_VERSION is unset) -# CHART_VERSION chart version string; default: 0.0.0-$REV -# (must match a previously-packaged chart in ./bin/) - -: "${IMAGE_REPO:?IMAGE_REPO must be set}" -: "${CHART_VERSION:=0.0.0-${REV:?REV must be set when CHART_VERSION is unset}}" - -echo "Pushing Helm charts to registry: $IMAGE_REPO (version: $CHART_VERSION)" - -HELM="$(UGET_PRINT_PATH=absolute make --no-print-directory install-helm)" - -export HELM_EXPERIMENTAL_OCI=1 - -for chart_file in ./bin/*-$CHART_VERSION.tgz; do - if [ -f "$chart_file" ]; then - chart_filename=$(basename "$chart_file") - chart_name=${chart_filename%-$CHART_VERSION.tgz} - - if [[ "$chart_name" =~ [[:space:]] ]]; then - echo "Skipping chart with invalid name: '$chart_name' (contains spaces)" - continue - fi - - echo "Pushing $chart_name to $IMAGE_REPO" - "$HELM" push "$chart_file" "oci://$IMAGE_REPO/charts" - echo "Chart available at: oci://$IMAGE_REPO/charts/$chart_name:$CHART_VERSION" - fi -done diff --git a/hack/helm-test.sh b/hack/helm-test.sh deleted file mode 100755 index 0b6af9fd5..000000000 --- a/hack/helm-test.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -eu - -echo "Testing Helm chart installation..." - -HELM="$(UGET_PRINT_PATH=absolute make --no-print-directory install-helm)" -CHART_VERSION="0.0.0-$REV" - -for chart_dir in deploy/charts/*/; do - if [ -f "${chart_dir}Chart.yaml" ]; then - chart_name=$(basename "$chart_dir") - echo "Testing chart: $chart_name" - "$HELM" install test-$chart_name "./bin/$chart_name-$CHART_VERSION.tgz" --dry-run --debug - echo "✓ Chart $chart_name passes dry-run test" - fi -done diff --git a/hack/image-sign.sh b/hack/image-sign.sh deleted file mode 100755 index 699396e1a..000000000 --- a/hack/image-sign.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -eu - -# Inputs (env vars): -# IMAGE_REPO registry+namespace, e.g. ghcr.io/kbind-dev (required) -# OUTPUT_DIR directory containing .metadata.json files (required) -# COMPONENTS space-separated component names; default: "konnector backend" -# COSIGN_ARGS extra args for `cosign sign` (e.g. -a sha=... -a ref=...) - -: "${IMAGE_REPO:?IMAGE_REPO must be set}" -: "${OUTPUT_DIR:?OUTPUT_DIR must be set (directory with image build metadata files)}" -: "${COMPONENTS:=konnector backend}" - -if ! command -v cosign >/dev/null 2>&1; then - echo "cosign not found in PATH; skipping image signing." - echo " install: https://docs.sigstore.dev/cosign/installation/" - exit 0 -fi - -if ! command -v jq >/dev/null 2>&1; then - echo "jq not found in PATH; required to parse buildx metadata." >&2 - exit 1 -fi - -export COSIGN_EXPERIMENTAL=true - -for component in $COMPONENTS; do - metadata_file="${OUTPUT_DIR}/${component}.metadata.json" - if [[ ! -f "$metadata_file" ]]; then - echo "metadata file not found: $metadata_file (run image build with OUTPUT_DIR set)" >&2 - exit 1 - fi - digest=$(jq -r '."containerimage.digest"' "$metadata_file") - if [[ -z "$digest" || "$digest" == "null" ]]; then - echo "could not extract containerimage.digest from $metadata_file" >&2 - exit 1 - fi - img="${IMAGE_REPO}/${component}@${digest}" - echo "signing ${img}" - # shellcheck disable=SC2086 - cosign sign "$img" --yes ${COSIGN_ARGS:-} -done diff --git a/hack/kind-example-setup/app-cluster.sh b/hack/kind-example-setup/app-cluster.sh deleted file mode 100755 index 74eb1a441..000000000 --- a/hack/kind-example-setup/app-cluster.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -o nounset -set -o pipefail - -DEFAULT_KONNECTOR_IMAGE="ghcr.io/kbind-dev/konnector:v0.4.6" - -if [[ -z "${HOST_IP:-}" ]]; then - source "$(dirname "$0")/host-ip.sh" - get_host_ip -fi - -cat << EOF_AppClusterDefinition | kind create cluster --config=- -apiVersion: kind.x-k8s.io/v1alpha4 -kind: Cluster -name: app -networking: - apiServerAddress: ${HOST_IP} -EOF_AppClusterDefinition - -kubectl config use-context kind-app - -if [[ -n "${KONNECTOR_IMAGE:-}" ]]; then - pushd "$(dirname "$0")/../.." - KIND_CLUSTER=app make kind-load - popd - - if [[ -z "${TAG:-}" ]]; then - REV=$(git rev-parse --short HEAD) - TAG=${REV} - fi - konnector_image="${KONNECTOR_IMAGE}:${TAG}" - echo "Using override konnector image: ${konnector_image}" - $(dirname "$0")/../../bin/kubectl-bind --konnector-image=${konnector_image} http://${HOST_IP}:8080/export -else - konnector_image=${DEFAULT_KONNECTOR_IMAGE} - echo "Using default konnector image: ${konnector_image}" - kubectl bind --konnector-image=${konnector_image} http://${HOST_IP}:8080/export -fi diff --git a/hack/kind-example-setup/backend-cluster.sh b/hack/kind-example-setup/backend-cluster.sh deleted file mode 100755 index d57b80681..000000000 --- a/hack/kind-example-setup/backend-cluster.sh +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -DEFAULT_EXAMPLE_BACKEND_IMAGE="ghcr.io/kbind-dev/backend:v0.5.0" - -if [[ -z "${HOST_IP:-}" ]]; then - source "$(dirname "$0")/host-ip.sh" - get_host_ip -fi - -cat << EOF_BackendClusterDefinition | kind create cluster --config=- -apiVersion: kind.x-k8s.io/v1alpha4 -kind: Cluster -name: backend -networking: - apiServerAddress: ${HOST_IP} -nodes: -- role: control-plane - extraPortMappings: - # MangoDB export endpoint - - containerPort: 30080 - hostPort: 8080 - protocol: TCP - # dex endpoint - - containerPort: 30556 - hostPort: 5556 - protocol: TCP -EOF_BackendClusterDefinition - -if [[ -n "${EXAMPLE_BACKEND_IMAGE:-}" ]]; then - pushd "$(dirname "$0")/../.." - KIND_CLUSTER=backend make kind-load - popd - - if [[ -z "${TAG:-}" ]]; then - REV=$(git rev-parse --short HEAD) - TAG=${REV} - fi - example_backend_image="${EXAMPLE_BACKEND_IMAGE}:${TAG}" - echo "Using override example backend image: ${example_backend_image}" -else - example_backend_image=${DEFAULT_EXAMPLE_BACKEND_IMAGE} - echo "Using default example backend image: ${example_backend_image}" -fi - -helm repo add jetstack https://charts.jetstack.io -helm install \ - --create-namespace \ - --namespace pki \ - --version v1.16.2 \ - --set crds.enabled=true \ - cert-manager jetstack/cert-manager - - -helm repo add dex https://charts.dexidp.io - -cat << EOF_DEXDeploymentConfig | -config: - staticClients: - - id: kube-bind - redirectURIs: - - 'http://${HOST_IP}:8080/callback' - name: 'Kube Bind' - secret: ZXhhbXBsZS1hcHAtc2VjcmV0 - - issuer: http://${HOST_IP}:5556/dex - - storage: - type: kubernetes - config: - inCluster: true - - web: - http: 127.0.0.1:5556 - - telemetry: - http: 127.0.0.1:5558 - - grpc: - addr: 127.0.0.1:5557 - - connectors: - - type: mockCallback - id: mock - name: Example - - enablePasswordDB: true - staticPasswords: - - email: "admin@example.com" - hash: "\$2a\$10\$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W" - username: "admin" - userID: "08a8684b-db88-4b73-90a9-3cd1661f5466" -EOF_DEXDeploymentConfig - -helm install \ - --create-namespace \ - --namespace idp \ - --set service.type=NodePort \ - --set service.ports.http.nodePort=30556 \ - dex dex/dex \ - -f - - -kubectl apply -f $(dirname "$0")/../../deploy/crd -kubectl apply -f $(dirname "$0")/../../test/e2e/bind/fixtures/provider/crd-mangodb.yaml -kubectl create namespace backend -# This is the address that will be used when generating kubeconfigs the App cluster, -# and so we need to be able to reach it from outside. -BACKEND_KUBE_API_EXTERNAL_ADDRESS="$(kubectl config view --minify -o json | jq '.clusters[0].cluster.server' -r)" -# For demo example let's just bind "cluster-admin" ClusterRole to backend's "default" ServiceAccount. -kubectl create clusterrolebinding backend-admin --clusterrole cluster-admin --serviceaccount backend:default -# Create a new Deployment for the MangoDB backend. -kubectl --namespace backend \ - create deployment mangodb \ - --image ${example_backend_image} \ - --port 8080 \ - -- /ko-app/backend \ - --listen-address 0.0.0.0:8080 \ - --external-address "${BACKEND_KUBE_API_EXTERNAL_ADDRESS}" \ - --oidc-issuer-client-secret=ZXhhbXBsZS1hcHAtc2VjcmV0 \ - --oidc-issuer-client-id=kube-bind \ - --oidc-issuer-url=http://${HOST_IP}:5556/dex \ - --oidc-callback-url=http://${HOST_IP}:8080/callback \ - --pretty-name="BigCorp.com" \ - --namespace-prefix="kube-bind-" \ - --cookie-signing-key=bGMHz7SR9XcI9JdDB68VmjQErrjbrAR9JdVqjAOKHzE= \ - --cookie-encryption-key=wadqi4u+w0bqnSrVFtM38Pz2ykYVIeeadhzT34XlC1Y= - -# Expose mangodb's container port 8080 as a NodePort at 30080. We've already configured -# Kind to expose 30800 at host's 8080. -kubectl --namespace backend \ - create service nodeport mangodb \ - --tcp 8080 \ - --node-port 30080 diff --git a/hack/kind-example-setup/cleanup.sh b/hack/kind-example-setup/cleanup.sh deleted file mode 100755 index 76837c30b..000000000 --- a/hack/kind-example-setup/cleanup.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -kind delete cluster --name backend -kind delete cluster --name app diff --git a/hack/kind-example-setup/host-ip.sh b/hack/kind-example-setup/host-ip.sh deleted file mode 100644 index 9a461f645..000000000 --- a/hack/kind-example-setup/host-ip.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -get_host_ip() { - local os - os="$(uname -s | tr '[:upper:]' '[:lower:]')" - if [[ "$os" == linux ]]; then - export HOST_IP="$(hostname -i | cut -d' ' -f1)" - elif [[ "$os" == darwin ]]; then - export HOST_IP="$(ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\ -f2)" - fi -} diff --git a/hack/release.sh b/hack/release.sh deleted file mode 100755 index 14377af40..000000000 --- a/hack/release.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2024 The Kube Bind 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. - -# This script ensures that the generated client code checked into git is up-to-date -# with the generator. If it is not, re-generate the configuration to update it. - -set -o errexit -set -o nounset -set -o pipefail - -# Usage helper function -usage() { - echo "Usage: $0 \"comment\" [remote_name]" - exit 1 -} - -# Check if at least the version tag and comment are provided -if [ $# -lt 2 ]; then - usage -fi - -VERSION_TAG=$1 -RELEASE_COMMENT=$2 -REMOTE_NAME=${3:-origin} # Set default remote name to 'origin' if not provided - -# Validate the version tag format -if ! [[ $VERSION_TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "Error: Version tag must be in 'vX.Y.Z' format." - usage -fi - -# Create the tag -git tag -a $VERSION_TAG -s -m "$RELEASE_COMMENT" -git tag -a sdk/apis/$VERSION_TAG -s -m "$RELEASE_COMMENT" -git tag -a sdk/client/$VERSION_TAG -s -m "$RELEASE_COMMENT" - -# Check if the tag was created successfully -if [ $? -ne 0 ]; then - echo "Error: Failed to create tag." - exit 1 -fi - -# Push the tag to remote repository -git push $REMOTE_NAME $VERSION_TAG -git push $REMOTE_NAME sdk/apis/$VERSION_TAG -git push $REMOTE_NAME sdk/client/$VERSION_TAG - -# Check if the push was successful -if [ $? -ne 0 ]; then - echo "Error: Failed to push the tag to the remote repository." - exit 1 -fi - -echo "Version $VERSION_TAG has been successfully tagged and pushed to $REMOTE_NAME with comment: '$RELEASE_COMMENT'" diff --git a/hack/run-frontend.sh b/hack/run-frontend.sh deleted file mode 100755 index 4b49535dc..000000000 --- a/hack/run-frontend.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2025 The Kube Bind 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. - -set -e - -echo "Building frontend..." - -# Navigate to web directory -cd web - -# Install dependencies if node_modules doesn't exist -if [ ! -d "node_modules" ]; then - echo "Installing frontend dependencies..." - npm install -fi - -# Build the frontend -echo "Running dev application..." -npm run dev diff --git a/hack/tilt/Tiltfile b/hack/tilt/Tiltfile new file mode 100644 index 000000000..c6b0c8895 --- /dev/null +++ b/hack/tilt/Tiltfile @@ -0,0 +1,103 @@ +# -*- mode: Python -*- +# kbind dev loop across two kind clusters (run hack/tilt/kind.sh first). +# +# Tilt drives exactly one kube-context, so: +# - the PROVIDER cluster (kind-kbind-provider, the current context) is +# managed natively: backend image (auto kind-load), backend chart, +# port-forwards, rebuild-on-change; +# - the CONSUMER cluster (kind-kbind-consumer) is driven via +# local_resources: konnector image -> kind load -> helm upgrade. +# +# After `tilt up`: +# open http://localhost:8080 # gateway UI (mock OIDC, auto-approves) +# kbind login http://localhost:8080 +# kbind bind widgets --kubeconfig ~/.kube/config \ +# --server http://localhost:8080 # consumer context: kind-kbind-consumer + +allow_k8s_contexts('kind-kbind-provider') +if k8s_context() != 'kind-kbind-provider': + fail('current kube-context is %s; run hack/tilt/kind.sh (it switches to kind-kbind-provider)' % k8s_context()) + +# ---------------------------------------------------------------- provider -- + +docker_build( + 'ghcr.io/kbind-dev/backend', + '../..', + dockerfile='../../Dockerfile', + target='backend', + only=['cmd', 'engine', 'backend', 'cli', 'pkg', 'web', 'sdk', 'go.mod', 'go.sum'], +) + +k8s_yaml(blob(""" +apiVersion: v1 +kind: Namespace +metadata: + name: kbind-system +""")) + +k8s_yaml(helm( + '../../deploy/charts/backend', + name='backend', + namespace='kbind-system', + set=[ + 'oidc.mock=true', + 'externalURL=http://localhost:8080', + # Issued kubeconfigs must point at an address the CONSUMER cluster + # can reach: the provider control-plane container on the shared + # "kind" docker network. + 'externalAddress=https://kbind-provider-control-plane:6443', + 'modules.apply=true', + ], +)) + +k8s_resource( + 'backend', + # 8080 = gateway (UI/API), 5556 = the in-pod mock OIDC issuer so the host + # browser can complete the login redirect. + port_forwards=['8080:8080', '5556:5556'], + labels=['provider'], +) + +# Demo catalog content (waits for the backend so the catalog CRDs exist). +local_resource( + 'seed-catalog', + cmd=' && '.join([ + 'kubectl --context kind-kbind-provider wait --for condition=established crd/exports.catalog.kbind.io --timeout=120s', + 'kubectl --context kind-kbind-provider apply -f seed/', + ]), + deps=['seed'], + resource_deps=['backend'], + labels=['provider'], +) + +# ---------------------------------------------------------------- consumer -- + +local_resource( + 'konnector-image', + cmd=' && '.join([ + 'docker build --target konnector -t ghcr.io/kbind-dev/konnector:tilt ../..', + 'kind load docker-image ghcr.io/kbind-dev/konnector:tilt --name kbind-consumer', + ]), + deps=['../../cmd/konnector', '../../engine', '../../sdk/apis', '../../go.mod'], + labels=['consumer'], +) + +local_resource( + 'konnector', + cmd=' && '.join([ + 'helm upgrade --install konnector ../../deploy/charts/konnector' + + ' --kube-context kind-kbind-consumer --namespace kbind --create-namespace' + + ' --set image.repository=ghcr.io/kbind-dev/konnector --set image.tag=tilt', + 'kubectl --context kind-kbind-consumer -n kbind rollout restart deployment/konnector', + 'kubectl --context kind-kbind-consumer -n kbind rollout status deployment/konnector --timeout=120s', + ]), + resource_deps=['konnector-image'], + labels=['consumer'], +) + +local_resource( + 'konnector-logs', + serve_cmd='kubectl --context kind-kbind-consumer -n kbind logs -f deployment/konnector', + resource_deps=['konnector'], + labels=['consumer'], +) diff --git a/hack/tilt/kind.sh b/hack/tilt/kind.sh new file mode 100755 index 000000000..6ef179748 --- /dev/null +++ b/hack/tilt/kind.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +# Copyright 2026 The kbind 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. + +# Create the two kind clusters for the Tilt dev loop (idempotent): +# kbind-provider — runs the backend (gateway + issuer) +# kbind-consumer — runs the konnector +# Both live on the shared "kind" docker network, so consumer pods reach the +# provider API server at https://kbind-provider-control-plane:6443. + +set -euo pipefail + +for cluster in kbind-provider kbind-consumer; do + if ! kind get clusters 2>/dev/null | grep -qx "${cluster}"; then + kind create cluster --name "${cluster}" + else + echo "kind cluster ${cluster} already exists" + fi +done + +kubectl config use-context kind-kbind-provider +echo +echo "Ready. Start the dev loop with:" +echo " cd $(dirname "${BASH_SOURCE[0]}") && tilt up" diff --git a/hack/tilt/seed/widgets.yaml b/hack/tilt/seed/widgets.yaml new file mode 100644 index 000000000..4dab49805 --- /dev/null +++ b/hack/tilt/seed/widgets.yaml @@ -0,0 +1,101 @@ +# Demo provider content for the Tilt dev loop: one exported CRD, its related +# resources, and the catalog entry — same canonical Widget as config/samples. +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: widgets.example.org + labels: + core.kbind.io/exported: "true" +spec: + group: example.org + names: + plural: widgets + singular: widget + kind: Widget + listKind: WidgetList + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + subresources: + status: {} + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + size: + type: string + status: + type: object + properties: + phase: + type: string + additionalPrinterColumns: + - name: Size + type: string + jsonPath: .spec.size + - name: Phase + type: string + jsonPath: .status.phase +--- +# Related resources the widgets service ships alongside its API: connection +# details as a Secret and tuning as a ConfigMap, synced provider -> consumer. +apiVersion: v1 +kind: Secret +metadata: + name: widgets-connection + namespace: default + labels: + widgets.example.org/related: "true" +stringData: + endpoint: https://widgets.internal.example.org + api-key: demo-not-a-real-key +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: widgets-tuning + namespace: default + labels: + widgets.example.org/related: "true" +data: + pointiness: "11" +--- +apiVersion: catalog.kbind.io/v1alpha1 +kind: Export +metadata: + name: widgets +spec: + title: Widgets + description: Managed widgets with automated pointiness. + apis: + - name: widgets.example.org + defaults: + relatedResources: + - group: "" + resource: secrets + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/related: "true" + - group: "" + resource: configmaps + direction: FromProvider + selector: + labelSelector: + matchLabels: + widgets.example.org/related: "true" +--- +apiVersion: catalog.kbind.io/v1alpha1 +kind: Collection +metadata: + name: hardware +spec: + title: Hardware + exports: + - name: widgets diff --git a/hack/tools.checksums b/hack/tools.checksums deleted file mode 100644 index e41736f76..000000000 --- a/hack/tools.checksums +++ /dev/null @@ -1,12 +0,0 @@ -golangci-lint|GOARCH=amd64;GOOS=linux|657d27b11b6b92169ceef89d39a12da5670caa4ef27376ac49a26433050e2356 -golangci-lint|GOARCH=arm64;GOOS=darwin|324c8926c741695bfca4a2333391c04a442a386d39ee921bd2fa3b648fdaadb6 -golangci-lint|GOARCH=arm64;GOOS=linux|5ef8816f90dcdb532924586601d2a0e5ace9f975c9d104519bc92721dffd75ed -goreleaser|ARCH=x86_64;OS=Linux|8de4a7d97d9b2b62e8186bcd28f7a203ba55ecfaaa4329e14264d3235095faed -gotestsum|GOARCH=amd64;GOOS=linux|ee25248e6f5073cad0b7a712c97ed473adb7420f7eefad534177de0113a8a505 -gotestsum|GOARCH=arm64;GOOS=linux|7a5e7f8cb5e2126be563b7c7182cc4522fbc65408a99df82d156d30e997b8705 -helm-docs|ARCH=arm64;OS=Darwin|911f2763de0201b4870b3468247ef794d9401aa8d4aa285089bbee040d4ae9c4 -helm|GOARCH=amd64;GOOS=linux|c153fd9c1173f39aefe8e9aa9f00fd3daf6b40c8ea01e94a0d2f2c1787fc60e0 -kcp|GOARCH=amd64;GOOS=linux|367525b4334e30f598054a62c8f10f04c21afa480c1700d0a9dbb8c905c931a5 -kcp|GOARCH=arm64;GOOS=darwin|463dd70f665baac198f2c6b979bd9dc5e4349636711509dd83fd96b05d1d0bb5 -kcp|GOARCH=arm64;GOOS=linux|44e5ac1c58642b7cffa88796adf9478a9b4110e61876e83237e419fb244216c7 -verify_boilerplate.py||6928a807e2ffc2e6902de705ce7a7cddbbbf5ef61a43901432c4f4551b4e9a7b diff --git a/hack/tools.go b/hack/tools.go deleted file mode 100644 index e996264ca..000000000 --- a/hack/tools.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build tools - -/* -Copyright 2022 The Kube Bind 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 tools - -import ( - _ "k8s.io/code-generator" -) diff --git a/hack/uget.sh b/hack/uget.sh deleted file mode 100755 index 4f13fefcc..000000000 --- a/hack/uget.sh +++ /dev/null @@ -1,702 +0,0 @@ -#!/bin/sh - -# SPDX-FileCopyrightText: 2025 Christoph Mewes, https://codeberg.org/xrstf/uget -# SPDX-License-Identifier: MIT -# -# µget 0.5.0 – your friendly downloader -# ------------------------------------- -# -# µget can download software as binaries, archives or Go modules. -# -# Usage: ./uget.sh URL_PATTERN BINARY_NAME VERSION [EXTRACT_PATTERN=**/$BINARY_NAME] - -set -eu - -############################################################################### -# Configuration - -# µget supports a large range of environment variables to customize its -# behaviour. Global configuration settings are prefixed with UGET_, settings -# usually meant for a single tool only have no prefix (like GO_MODULE). - -# GO_MODULE can be set to true to create a dummy Go module, add the given -# URL and version as a dependency and then go build the desired binary. Note -# that Go modules do not use checksums by default, see $UGET_GO_CHECKSUMS. -GO_MODULE=${GO_MODULE:-false} - -# GO_EXTRA_DEPS is an optional, space-separated list of additional dependencies -# that should be added to the temporary Go module before the actual dependency -# is added and built. This can be used to override/upgrade individual dependencies -# when needed. -GO_EXTRA_DEPS="${GO_EXTRA_DEPS:-}" - -# UNCOMPRESSED can be set to true if the downloaded file is not an archive, -# but the binary itself and doesn't need decompressing. -UNCOMPRESSED=${UNCOMPRESSED:-false} - -# UGET_UPDATE can be set to true when the VERSION parameter of a program has -# been updated and you want µget to update all known variants (based on the -# checksums file) before installing the correct variant for the current system. -# When UGET_CHECKSUMS is not in use, this variable has no effect. -# Use UGET_UPDATE_ONLY if you want to just update the checksums without also -# installing the binary. -UGET_UPDATE=${UGET_UPDATE:-false} - -# UGET_UPDATE_ONLY is like UGET_UPDATE, but does not install the binary on -# the current system (i.e. it only touches the checksum file). -UGET_UPDATE_ONLY=${UGET_UPDATE_ONLY:-false} - -# UGET_DIRECTORY is where downloaded binaries will be placed. -UGET_DIRECTORY="${UGET_DIRECTORY:-_tools}" - -# UGET_CHECKSUMS is an optional path to a checksum file that µget should use to -# ensure subsequent downloads match previously known checksums to prevent -# tampering on the server side. -UGET_CHECKSUMS="${UGET_CHECKSUMS:-}" - -# UGET_VERSIONED_BINARIES can be set to true to append the binary's version to -# its filename, leading to final paths like "_tools/mytool-v1.2.3". This can -# help when µget is being used in Makefiles to improve staleness detection. -# Note that µget never deletes any installed binaries, so enabling this can -# lead to leftover binaries that you can cleanup at your own convenience. -UGET_VERSIONED_BINARIES=${UGET_VERSIONED_BINARIES:-false} - -# UGET_TEMPDIR is the root directory to use when creating new temporary dirs. -UGET_TEMPDIR="${UGET_TEMPDIR:-/tmp}" - -# UGET_CACHE is an optional path to a directory where binaries are stored/read -# from instead of being downloaded from the internet. This can be useful if you -# have many projects using µget and do not want to re-download the same binary -# for all of them. This does not apply for Go modules since those are already -# effectively cached by Go itself. -UGET_CACHE="${UGET_CACHE:-}" - -# UGET_CACHE_SYMLINK can be set to true to create a symlink between the cached -# file and the local copy in $UGET_DIRECTORY. If left on false, µget will instead -# copy the file from the cache. -UGET_CACHE_SYMLINK=${UGET_CACHE_SYMLINK:-false} - -# UGET_PRINT_PATH can be set to "relative" to make µget only omit log output -# and only print the relative path to the binary, and set to "absolute" to -# output the absolute path. -UGET_PRINT_PATH="${UGET_PRINT_PATH:-no}" - -# UGET_HASHFUNC is the hashing function used to calculate file checksums. The -# output of this program is processed with awk to only print the first column. -UGET_HASHFUNC="${UGET_HASHFUNC:-sha256sum}" - -# UGET_GO_BUILD_CMD overwrites the default call to "go build" when installing -# a Go module. Use this to inject custom Go flags or toolchains. -# The given command is called with "-o BINARY_NAME MODULE_URL" with the pwd -# being inside a fake module that depends on the given module. -UGET_GO_BUILD_CMD="${UGET_GO_BUILD_CMD:-go build}" - -# UGET_GO_CHECKSUMS can be set to true to force checksums even for Go modules. -# This is disabled by default because the exact binaries being built depend on -# a lot of factors and usually it's a hassle to ensure everyone in a project -# has the *exact* same build environment. Go modules already make use of Google's -# GOSUMDB and should be "safe enough" by default with µget checksums. -UGET_GO_CHECKSUMS=${UGET_GO_CHECKSUMS:-false} - -############################################################################### -# Function library - -uget_mktemp() { - set -e - # --tmpdir does not work on MacOS - mktemp -d -p "$ABS_UGET_TEMPDIR" -} - -uget_log() { - if [ "$UGET_PRINT_PATH" = "no" ]; then - echo "$@" >&2 - fi -} - -uget_error() { - echo "$@" >&2 -} - -uget_lowercase() { - set -e - cat | tr '[:upper:]' '[:lower:]' -} - -uget_checksum_enabled() { - set -e - [ -n "$UGET_CHECKSUMS" ] -} - -uget_cache_enabled() { - set -e - [ -n "$UGET_CACHE" ] -} - -uget_checksum_check() { - set -e - - local kvString="$1" - local downloadedBinary="$2" - - if ! uget_checksum_enabled; then return; fi - - local newChecksum - newChecksum="$(uget_checksum_calculate "$downloadedBinary")" - - local oldChecksum - oldChecksum="$(uget_checksum_read "$kvString")" - - if [ -n "$oldChecksum" ] && [ "$oldChecksum" != "$newChecksum" ]; then - uget_error - uget_error " *************************************************************************" - uget_error " SECURITY ERROR" - uget_error - uget_error " The downloaded file $downloadedBinary does not have the expected checksum." - uget_error - uget_error " Expected: $oldChecksum" - uget_error " Actual : $newChecksum" - uget_error - uget_error " If you are updating $IDENTIFIER, this error is expected." - uget_error " Re-run this command with the environment variable UGET_UPDATE=true to make" - uget_error " µget update the checksums for all known variants of $IDENTIFIER." - uget_error " Use UGET_UPDATE_ONLY=true if you want to just update the checksums and not" - uget_error " install the given binary on this machine." - uget_error " *************************************************************************" - uget_error - - return 1 - fi - - if [ -z "$oldChecksum" ]; then - uget_checksum_write "$kvString" "$newChecksum" - fi -} - -uget_checksum_read() { - set -e - - local kvString="$1" - - if [ -f "$UGET_CHECKSUMS" ]; then - awk -F'|' -v "binary=$IDENTIFIER" -v "kv=$kvString" '{ if ($1 == binary && $2 == kv) print $3 }' "$UGET_CHECKSUMS" - fi -} - -uget_checksum_calculate() { - set -e - "$UGET_HASHFUNC" "$1" | awk '{ print $1 }' -} - -# hash_string includes a trailing newline in the hashed data -# (because of echo), but since *all* hashes contain it, it -# doesn't matter. -uget_hash_string() { - set -e - echo "$1" | "$UGET_HASHFUNC" | awk '{ print $1 }' -} - -uget_checksum_write() { - set -e - - local kvString="$1" - local checksum="$2" - - if [ -f "$UGET_CHECKSUMS" ]; then - local tempDir - tempDir="$(uget_mktemp)" - - # use awk to drop any existing hash for this binary/keyvalue combo - # (for better readability, do not invert the condition here); - # checking for NF (number of fields) to drop empty lines - awk \ - -F'|' -v "binary=$IDENTIFIER" -v "kv=$kvString" \ - '{ if (NF == 0 || ($1 == binary && $2 == kv)) {} else print }' \ - "$UGET_CHECKSUMS" > "$tempDir/checksums.txt" - - # add our new checksum - echo "$IDENTIFIER|$kvString|$checksum" >> "$tempDir/checksums.txt" - - # sort the file because it looks nicer and prevents ugly git diffs - sort "$tempDir/checksums.txt" > "$UGET_CHECKSUMS" - - rm -rf -- "$tempDir" - else - # start a new file - echo "$IDENTIFIER|$kvString|$checksum" > "$UGET_CHECKSUMS" - fi -} - -uget_begins_with() { - case $2 in - "$1"*) true ;; - *) false ;; - esac -} - -uget_trim_env_prefix() { - set -e - - echo "${1#ENV:}" -} - -uget_url_placeholder() { - set -e - - # trim potential "ENV:" prefix - local envName - envName="$(uget_trim_env_prefix "$1")" - - if [ "$envName" != "$1" ]; then - if ! printenv "$envName"; then - uget_error "Unexpected placeholder, environment variable $envName is not set." - return 1 - fi - else - # built-in, default placeholders - case "$1" in - GOARCH) go env GOARCH ;; - GOOS) go env GOOS ;; - UARCH) uname -m | uget_lowercase ;; - UOS) uname -s | uget_lowercase ;; - *) uget_error "Unexpected placeholder $1."; return 1 ;; - esac - fi -} - -# valueFromPair returns "foo" for "myvalue=foo;myothervalue=bar" when called with -# "myvalue" as the key. -uget_url_valueFromPair() { - set -e - - local kvString="$1" - local key="$2" - - # adding semicolons makes matching full keys easier - echo ";$kvString;" | sed -E "s/.*;$key=([^;]+).*/\\1/" -} - -uget_url_setKeyInPairs() { - set -e - - local kvString="$1" - local key="$2" - local value="$3" - - # first take the existing pairs and turn it into a multiline string; then - # awk out the existing pair for $key, - # then add a new pair and sort it all together, strip empty lines in case - # kvstring as empty, then join the multiple lines back into a single line - # and drop the trailing ';' - ( - echo "$kvString" | tr ';' "\n" | awk -F'=' -v "key=$key" '{ if ($1 != key) print }' - echo "$key=$value" - ) | sort | sed '/^[[:space:]]*$/d' | tr "\n" ';' | sed 's/;$//' -} - -uget_url_findPlaceholders() { - set -e - - # match all {...}, - # then sort and return only unique values (no need to replace the - # same placeholder multiple times) (this is important to allow for consistent - # matches when awk'ing through the checksum file), - # then remove braces and - # finally turn into a singleline string - echo "$1" | - grep -oE '\{(ENV:)?[A-Z0-9_]+\}' | - sort -u | - tr -d '{}' | - awk '{printf("%s ", $0)}' -} - -# replaceLive() use live system-data to replace placeholders in the given pattern. -# It returns a string of form "KVSTRING|URL". -uget_url_replaceLive() { - set -e - - local urlPattern="$1" - local usedPlaceholders="" - - for placeholder in $(uget_url_findPlaceholders "$urlPattern"); do - # version is treated specially - [ "$placeholder" = "VERSION" ] && continue - - local replacement - replacement="$(uget_url_placeholder "$placeholder")" - urlPattern="$(echo "$urlPattern" | sed "s|{$placeholder}|$replacement|g")" - - # remember this placeholder and its value - placeholder="$(uget_trim_env_prefix "$placeholder")" - usedPlaceholders="$usedPlaceholders;$placeholder=$replacement" - done - - # trim leading ";" - usedPlaceholders="$(echo "$usedPlaceholders" | sed 's/^;//')" - - echo "$usedPlaceholders|$urlPattern" -} - -# replaceWithArgs() does not ask the current system for the values when replacing -# a placeholder, but uses a given key-value pair string as the source. It also -# only returns the resulting string, since the used placeholders are known to -# the caller already. -uget_url_replaceWithArgs() { - set -e - - local urlPattern="$1" - local kvString="$2" - - for placeholder in $(uget_url_findPlaceholders "$urlPattern"); do - # version is treated specially - [ "$placeholder" = "VERSION" ] && continue - - placeholder="$(uget_trim_env_prefix "$placeholder")" - - local replacement - replacement="$(uget_url_valueFromPair "$kvString" "$placeholder")" - if [ -z "$replacement" ]; then - uget_error "Found no replacement string for placeholder $placeholder." - exit 1 - fi - - urlPattern="$(echo "$urlPattern" | sed "s|{$placeholder}|$replacement|g")" - done - - echo "$urlPattern" -} - -# returns "KVSTRING URL" -uget_url_build() { - set -e - - local kvString="${1:-}" - local pattern - - if [ -z "$kvString" ]; then - local result - result="$(uget_url_replaceLive "$URL_PATTERN")" - kvString="$(echo "$result" | cut -d'|' -f1)" - pattern="$(echo "$result" | cut -d'|' -f2)" - else - pattern="$(uget_url_replaceWithArgs "$URL_PATTERN" "$kvString")" - fi - - pattern="$(echo "$pattern" | sed "s|{VERSION}|$VERSION|g")" - - echo "$kvString|$pattern" -} - -# uget_http_download() uses either curl or wget to download the given URL into -# the current directory. -uget_http_download() { - set -e - - local url="$1" - - if command -v curl >/dev/null 2>&1; then - curl --fail -LO "$url" - elif command -v wget >/dev/null 2>&1; then - wget "$url" - else - uget_error "Neither curl nor wget are available." - return 1 - fi -} - -# uget_go_install creates a temporary Go module, adds the given URL as a -# dependency and then builds $BINARY. -uget_go_install() { - set -e - - local destinationDir="$1" - local kvString="$2" - local url="$3" - - # make sure GOARCH and GOOS will be set correctly - local os - local arch - os="$(uget_url_valueFromPair "$kvString" "GOOS")" - arch="$(uget_url_valueFromPair "$kvString" "GOARCH")" - - # since we crosscompile, we cannot do "GOBIN=(somewhere) go install url@version", - # because Go considers this to be dangerous behaviour: - # https://github.com/golang/go/issues/57485 - # Instead we create a dummy module and use the desired program as a dependency, - # *then* we're allowed to crosscompile it anywhere using "go build". Go figure. - - go mod init temp 2>/dev/null - - if [ -n "$GO_EXTRA_DEPS" ]; then - for dependency in $GO_EXTRA_DEPS; do - go get "$dependency" - done - fi - - go get "$url@$VERSION" - - local tmpFilename="__tmp.bin" - - # go build command is meant to be expanded - # shellcheck disable=SC2086 - GOFLAGS=-trimpath GOARCH="$arch" GOOS="$os" $UGET_GO_BUILD_CMD -o "$tmpFilename" "$url" - - mv "$tmpFilename" "$destinationDir/$BINARY" -} - -# uget_extract_archive extracts a downloaded archive and moves the one interesting -# file out of it. -uget_extract_archive() { - set -e - - local destinationDir="$1" - local archive="$2" - - if ! $UNCOMPRESSED; then - case "$archive" in - *.tar.gz | *.tgz) - tar xzf "$archive" - ;; - *.tar.bz2 | *.tbz2) - tar xjf "$archive" - ;; - *.tar.xz | *.txz) - tar xJf "$archive" - ;; - *.zip) - unzip "$archive" - ;; - *) - uget_error "Unknown file type: $archive" - return 1 - esac - fi - - # pattern is explicitly meant to be interpreted by the shell - # shellcheck disable=SC2086 - mv $BINARY_PATTERN "$destinationDir/$BINARY" - chmod +x "$destinationDir/$BINARY" -} - -# uget_download performs the actual download or reads a binary -# from the configured cache (if any), and finally places it -# in a given directory. -uget_download() { - set -e - - local destinationDir="$1" - local kvString="$2" - local url="$3" - - local startDir - startDir="$(pwd)" - - local tempDir - tempDir="$(uget_mktemp)" - - cd "$tempDir" - - if $GO_MODULE; then - uget_go_install "$destinationDir" "$kvString" "$url" - else - local urlHash - urlHash="$(uget_hash_string "$url")" - - cacheFile="$UGET_CACHE/$IDENTIFIER-$VERSION-$urlHash" - - if uget_cache_enabled && [ -f "$cacheFile" ]; then - if $UGET_CACHE_SYMLINK; then - ln -s "$cacheFile" "$destinationDir/$BINARY" - uget_log "Symlinked $BINARY from µget cache." - else - cp "$cacheFile" "$destinationDir/$BINARY" - uget_log "Copied $BINARY from µget cache." - fi - else - uget_http_download "$url" - - local archive - archive="$(ls)" - - uget_extract_archive "$destinationDir" "$archive" - - if uget_cache_enabled; then - cp "$destinationDir/$BINARY" "$cacheFile" - fi - fi - fi - - cd "$startDir" - rm -rf -- "$tempDir" -} - -# ready() checks if the desired binary already exists in the desired version. -uget_ready() { - local fullFinalPath="$ABS_UGET_DIRECTORY/$BINARY" - if ! [ -f "$fullFinalPath" ]; then - return 1 - fi - - # skip further checks if we're using versioned binaries - if $UGET_VERSIONED_BINARIES; then - return 0 - fi - - local versionFile="$fullFinalPath.version" - [ -f "$versionFile" ] && [ "$VERSION" = "$(cat "$versionFile")" ] -} - -# install() downloads the binary, checks the checksum and places it in UGET_DIRECTORY. -uget_install() { - set -e - - local kvString="$1" - local url="$2" - local fullFinalPath="$ABS_UGET_DIRECTORY/$BINARY" - local versionFile="$fullFinalPath.version" - - local startDir - startDir="$(pwd)" - - local tempDir - tempDir="$(uget_mktemp)" - - uget_log "Downloading $IDENTIFIER version $VERSION ..." - uget_download "$tempDir" "$kvString" "$url" - - local fullTempBinary="$tempDir/$BINARY" - uget_checksum_check "$kvString" "$fullTempBinary" - - # if everything is fine, place the binary in its final location - mv "$fullTempBinary" "$fullFinalPath" - - if ! $UGET_VERSIONED_BINARIES; then - echo "$VERSION" > "$versionFile" - fi - - uget_log "Installed at $UGET_DIRECTORY/$BINARY." - - cd "$startDir" - rm -rf -- "$tempDir" -} - -# update() downloads the binary, updates the checksums and discards the binary. -uget_update() { - set -e - - local kvString="$1" - local url="$2" - - local startDir - startDir="$(pwd)" - - local tempDir - tempDir="$(uget_mktemp)" - - uget_log " ~> $kvString" - uget_download "$tempDir" "$kvString" "$url" - - local fullBinaryPath="$tempDir/$BINARY" - - local checksum - checksum="$(uget_checksum_calculate "$fullBinaryPath")" - - uget_checksum_write "$kvString" "$checksum" - - cd "$startDir" - rm -rf -- "$tempDir" -} - -############################################################################### -# General Setup Logic - -# get CLI flags -export URL_PATTERN="$1" -export IDENTIFIER="$2" -export VERSION="$3" -BINARY_PATTERN="${4:-**/$IDENTIFIER}" - -export BINARY="$IDENTIFIER" -if $UGET_VERSIONED_BINARIES; then - BINARY="$IDENTIFIER-$VERSION" -fi - -# ensure target directory exists -mkdir -p "$UGET_DIRECTORY" "$UGET_TEMPDIR" - -ABS_UGET_DIRECTORY="$(realpath "$UGET_DIRECTORY")" -ABS_UGET_TEMPDIR="$(realpath "$UGET_TEMPDIR")" - -if uget_cache_enabled; then - mkdir -p "$UGET_CACHE" - UGET_CACHE="$(realpath "$UGET_CACHE")" -fi - -if $GO_MODULE && ! $UGET_GO_CHECKSUMS; then - UGET_CHECKSUMS="" -fi - -if uget_checksum_enabled; then - touch "$UGET_CHECKSUMS" - UGET_CHECKSUMS="$(realpath "$UGET_CHECKSUMS")" -else - if $GO_MODULE; then - if $UGET_UPDATE || $UGET_UPDATE_ONLY; then - uget_error "Checksums are disabled for Go modules, cannot update $IDENTIFIER checksums." - # This is not an error because in complex Makefiles, there might be 3 binaries required - # for one make target, and if one of them is a Go module and you have no direct way - # to just update a single binary, then running "UGET_UPDATE make complex-task" would - # fail at the Go module. It's simply more convenient to just warn and move on to the next - # binary. - fi - fi - - UGET_UPDATE=false - UGET_UPDATE_ONLY=false -fi - -############################################################################### -# Main application logic - -# When in update-only mode, we do not download the binary for the current system -# only, but instead for all known variants based on the checksums file, -# recalculate the checksums and then discard the temporary binaries. Otherwise -# after updating the checksums we continue with the regular install logic. - -if $UGET_UPDATE || $UGET_UPDATE_ONLY; then - uget_log "Updating checksums for $IDENTIFIER ..." - - # Find and process all known variants... - awk -F'|' -v "binary=$IDENTIFIER" '{ if ($1 == binary) print $2 }' "$UGET_CHECKSUMS" | while IFS= read -r kvString; do - result="$(uget_url_build "$kvString")" - url="$(echo "$result" | cut -d'|' -f2)" - - # download binary into tempdir, update checksums, but then delete it again - uget_update "$kvString" "$url" - done - - uget_log "All checksums were updated." -fi - -if ! $UGET_UPDATE_ONLY; then - if ! uget_ready; then - # Replace placeholders in the URL with system-specific data, like arch or OS - result="$(uget_url_build)" - kvString="$(echo "$result" | cut -d'|' -f1)" - url="$(echo "$result" | cut -d'|' -f2)" - - # Go modules usually do not have arch/os infos in their module names, but - # the resulting binary still depends on the local system. To support checksums - # for different machines, we always assume GOARCH and GOOS are "used placeholders". - if $GO_MODULE; then - kvString="$(uget_url_setKeyInPairs "$kvString" "GOARCH" "$(uget_url_placeholder GOARCH)")" - kvString="$(uget_url_setKeyInPairs "$kvString" "GOOS" "$(uget_url_placeholder GOOS)")" - fi - - uget_install "$kvString" "$url" - fi - - case "$UGET_PRINT_PATH" in - absolute) echo "$ABS_UGET_DIRECTORY/$BINARY" ;; - relative) echo "$UGET_DIRECTORY/$BINARY" ;; - esac -fi diff --git a/hack/update-codegen-clients.sh b/hack/update-codegen-clients.sh deleted file mode 100755 index e4fc49da4..000000000 --- a/hack/update-codegen-clients.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2021 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -cd "$(dirname "$0")/.." - -CODEGEN_PKG="${CODEGEN_PKG:-$(go list -f '{{.Dir}}' -m k8s.io/code-generator)}" -source "${CODEGEN_PKG}/kube_codegen.sh" - -pushd sdk -kube::codegen::gen_helpers \ - --boilerplate "../hack/boilerplate/boilerplate.generatego.txt" \ - "./apis" - -rm -rf ./client -kube::codegen::gen_client \ - --with-watch \ - --output-dir "./client" \ - --output-pkg "github.com/kube-bind/kube-bind/sdk/client" \ - --boilerplate "../hack/boilerplate/boilerplate.generatego.txt" \ - "./apis" - -popd diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh deleted file mode 100755 index 0d697902d..000000000 --- a/hack/update-codegen.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2021 The Kube Bind 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. - -set -o errexit -set -o nounset -set -o pipefail - -cd "$(dirname "$0")/.." - -CONTROLLER_GEN="$(UGET_PRINT_PATH=absolute make --no-print-directory install-controller-gen)" -YAML_PATCH="$(UGET_PRINT_PATH=absolute make --no-print-directory install-yaml-patch)" - -# Update generated CRD YAML -( - cd sdk/apis - "$CONTROLLER_GEN" \ - crd \ - rbac:roleName=manager-role \ - webhook \ - paths="./..." \ - output:crd:artifacts:config=../../deploy/crd - - "$CONTROLLER_GEN" \ - crd \ - rbac:roleName=manager-role \ - webhook \ - paths="./..." \ - output:crd:artifacts:config=../../deploy/charts/backend/crds - - # Generate RBAC manifests for Helm chart from backend controllers - "$CONTROLLER_GEN" \ - rbac:roleName=kube-bind-role \ - paths="../../backend/controllers/..." \ - output:rbac:artifacts:config=../../deploy/charts/backend/templates -) - -( - cd deploy/crd - for CRD in *.yaml; do - if [ -f "../patches/${CRD}-patch" ]; then - echo "Applying ${CRD}-patch" - "$YAML_PATCH" -o "../patches/${CRD}-patch" < "${CRD}" > "${CRD}.patched" - mv "${CRD}.patched" "${CRD}" - fi - done -) - -( - make -C contrib/kcp codegen -) diff --git a/hack/verify-codegen-clients.sh b/hack/verify-codegen-clients.sh deleted file mode 100755 index 1938b33b9..000000000 --- a/hack/verify-codegen-clients.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2021 The Kube Bind 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. - -# This script ensures that the generated client code checked into git is up-to-date -# with the generator. If it is not, re-generate the configuration to update it. - -set -o errexit -set -o nounset -set -o pipefail - -"$( dirname "${BASH_SOURCE[0]}")/update-codegen-clients.sh" -if ! git diff --quiet --exit-code -- sdk/; then - cat << EOF -ERROR: This check enforces that the client code is generated correctly. -ERROR: The client code is out of date. Run the following command to re- -ERROR: generate the clients: -ERROR: $ hack/update-generated-clients.sh -ERROR: The following differences were found: -EOF - git diff - exit 1 -fi diff --git a/hack/verify-go-versions.sh b/hack/verify-go-versions.sh deleted file mode 100755 index 883c2a326..000000000 --- a/hack/verify-go-versions.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2022 The Kube Bind 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. - -set -e -set -o pipefail - -gomod_version() { - awk '/^go / { print $2 }' "$1" | sed 's/.0$//' -} - -minimum_go_version="$(gomod_version go.mod)" -build_go_version="$(awk '/go-build-version/ { print $3 }' go.mod)" -errors=0 - -echo "Verifying minimum Go version: $minimum_go_version" - -for gomod in $(git ls-files '**/go.mod'); do - if [[ "$(gomod_version $gomod)" != "$minimum_go_version" ]]; then - echo " Wrong go version in $gomod, expected $minimum_go_version" - errors=$((errors + 1)) - fi -done - -echo "Verifying build Go version: $build_go_version" - -for dockerfile in $(git ls-files Dockerfile '**/Dockerfile'); do - for version in $(sed -nE -e '/^FROM .*golang:/ s#^.*:([1-9.-rc]+).*$#\1#p' "$dockerfile"); do - if [[ "$version" != "$build_go_version" ]]; then - echo " Wrong go version in $dockerfile, expected $build_go_version, found $version" - errors=$((errors + 1)) - fi - done -done - -for workflow in $(git ls-files '.github/workflows/*.yaml' '.github/workflows/*.yml'); do - if grep -q 'go-version-file:' "$workflow"; then - echo " Workflow $workflow uses go-version-file, should use go-version instead" - errors=$((errors + 1)) - fi - - for version in $(sed -nE -e '/go-version:/ s#^.*v([1-9.-rc]+)$#\1#p' "$workflow"); do - if [[ "$version" != "$build_go_version" ]]; then - echo " Wrong go version in $workflow, expected v${build_go_version}, found v${version}" - errors=$((errors + 1)) - fi - done -done - -if [[ "$CI" == true ]] && ! go version | grep -q "go${build_go_version}"; then - echo " Wrong go version detected, expected ${build_go_version}" - errors=$((errors + 1)) -fi - -exit $errors diff --git a/hack/verify_boilerplate.py b/hack/verify_boilerplate.py new file mode 100755 index 000000000..60ddf60cf --- /dev/null +++ b/hack/verify_boilerplate.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 + +# Copyright 2015 The Kubernetes 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. + +# Verifies that all source files contain the necessary copyright boilerplate +# snippet. + +import argparse +import datetime +import glob +import os +import re +import sys + + +def get_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "filenames", + help="list of files to check, all files if unspecified", + nargs='*') + + rootdir = os.path.abspath('.') + parser.add_argument("--rootdir", + default=rootdir, + help="root directory to examine") + + default_boilerplate_dir = os.path.join(rootdir, "verify/boilerplate") + parser.add_argument("--boilerplate-dir", default=default_boilerplate_dir) + + parser.add_argument( + '--skip', + default=[ + 'external/bazel_tools', + '.git', + 'node_modules', + '_output', + 'third_party', + 'vendor', + 'verify/boilerplate/test', + 'verify_boilerplate.py', + ], + action='append', + help='Customize paths to avoid', + ) + return parser.parse_args() + + +def get_refs(): + refs = {} + + template_dir = ARGS.boilerplate_dir + if not os.path.isdir(template_dir): + template_dir = os.path.dirname(template_dir) + for path in glob.glob(os.path.join(template_dir, "boilerplate.*.txt")): + extension = os.path.basename(path).split(".")[1] + + # Pass the encoding parameter to avoid ascii decode error for some + # platform. + ref_file = open(path, 'r', encoding='utf-8') + ref = ref_file.read().splitlines() + ref_file.close() + refs[extension] = ref + + return refs + +# given the file contents, return true if the file appears to be generated +def is_generated(data): + if re.search(r"^// Code generated by .*\. DO NOT EDIT\.$", data, re.MULTILINE): + return True + return False + + +def file_passes(filename, refs, regexs): # pylint: disable=too-many-locals + try: + # Pass the encoding parameter to avoid ascii decode error for some + # platform. + with open(filename, 'r', encoding='utf-8') as fp: + file_data = fp.read() + except IOError: + return False + + if not file_data: + return True # Nothing to copyright in this empty file. + + basename = os.path.basename(filename) + extension = file_extension(filename) + if extension != "": + ref = refs[extension] + else: + ref = refs[basename] + + ref = ref.copy() + + # remove build tags from the top of Go files + if extension == "go": + con = regexs["go_build_constraints"] + (file_data, found) = con.subn("", file_data, 1) + + # remove shebang from the top of shell files + if extension in ("sh", "py"): + she = regexs["shebang"] + (file_data, found) = she.subn("", file_data, 1) + + data = file_data.splitlines() + + # if our test file is smaller than the reference it surely fails! + if len(ref) > len(data): + return False + + # trim our file to the same number of lines as the reference file + data = data[:len(ref)] + + # check if we encounter a 'YEAR' placeholder if the file is generated + if is_generated(file_data): + for i, line in enumerate(data): + if "Copyright YEAR" in line: + return False + return True + + year = regexs["year"] + for datum in data: + if year.search(datum): + return False + + # Replace all occurrences of the regex "2017|2016|2015|2014" with "YEAR" + when = regexs["date"] + for idx, datum in enumerate(data): + (data[idx], found) = when.subn('YEAR', datum) + if found != 0: + break + + # if we don't match the reference at this point, fail + if ref != data: + return False + + return True + + +def file_extension(filename): + return os.path.splitext(filename)[1].split(".")[-1].lower() + + +# even when generated by bazel we will complain about some generated files +# not having the headers. since they're just generated, ignore them +IGNORE_HEADERS = ['// Code generated by go-bindata.'] + + +def has_ignored_header(pathname): + # Pass the encoding parameter to avoid ascii decode error for some + # platform. + with open(pathname, 'r', encoding='utf-8') as myfile: + data = myfile.read() + for header in IGNORE_HEADERS: + if data.startswith(header): + return True + return False + + +def normalize_files(files): + newfiles = [] + for pathname in files: + if any(x in pathname for x in ARGS.skip): + continue + newfiles.append(pathname) + for idx, pathname in enumerate(newfiles): + if not os.path.isabs(pathname): + newfiles[idx] = os.path.join(ARGS.rootdir, pathname) + return newfiles + + +def get_files(extensions): + files = [] + if ARGS.filenames: + files = ARGS.filenames + else: + for root, dirs, walkfiles in os.walk(ARGS.rootdir): + # don't visit certain dirs. This is just a performance improvement + # as we would prune these later in normalize_files(). But doing it + # cuts down the amount of filesystem walking we do and cuts down + # the size of the file list + for dpath in ARGS.skip: + if dpath in dirs: + dirs.remove(dpath) + + for name in walkfiles: + pathname = os.path.join(root, name) + files.append(pathname) + + files = normalize_files(files) + outfiles = [] + for pathname in files: + basename = os.path.basename(pathname) + extension = file_extension(pathname) + if extension in extensions or basename in extensions: + if not has_ignored_header(pathname): + outfiles.append(pathname) + return outfiles + + +def get_dates(): + years = datetime.datetime.now().year + return '(%s)' % '|'.join((str(year) for year in range(2014, years + 1))) + + +def get_regexs(): + regexs = {} + # Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing + regexs["year"] = re.compile('YEAR') + # dates can be any year between 2014 and the current year, company holder names can be anything + regexs["date"] = re.compile(get_dates()) + # strip // +build \n\n build constraints + regexs["go_build_constraints"] = re.compile(r"^(//( \+build|go:build).*\n)+\n", + re.MULTILINE) + # strip #!.* from shell/python scripts + regexs["shebang"] = re.compile(r"^(#!.*\n)\n*", re.MULTILINE) + return regexs + + +def nonconforming_lines(files): + yield '%d files have incorrect boilerplate headers:' % len(files) + for fp in files: + yield os.path.relpath(fp, ARGS.rootdir) + + +def main(): + regexs = get_regexs() + refs = get_refs() + filenames = get_files(refs.keys()) + nonconforming_files = [] + for filename in sorted(filenames): + if not file_passes(filename, refs, regexs): + nonconforming_files.append(filename) + + if nonconforming_files: + for line in nonconforming_lines(nonconforming_files): + print(line) + sys.exit(1) + + +if __name__ == "__main__": + ARGS = get_args() + main() diff --git a/pkg/bootstrap/bootstrap.go b/pkg/bootstrap/bootstrap.go deleted file mode 100644 index 889f6a975..000000000 --- a/pkg/bootstrap/bootstrap.go +++ /dev/null @@ -1,242 +0,0 @@ -/* -Copyright 2021 The Kube Bind 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 bootstrap - -import ( - "bufio" - "bytes" - "context" - "embed" - "errors" - "fmt" - "io" - "strings" - "text/template" - "time" - - extensionsapiserver "k8s.io/apiextensions-apiserver/pkg/apiserver" - 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/apis/meta/v1/unstructured" - apimachineryerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" - kubeyaml "k8s.io/apimachinery/pkg/util/yaml" - "k8s.io/client-go/discovery" - "k8s.io/client-go/discovery/cached/memory" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/restmapper" - "k8s.io/klog/v2" -) - -// TransformFileFunc transforms a resource file before being applied to the cluster. -type TransformFileFunc func(bs []byte) ([]byte, error) - -// Option allows to customize the bootstrap process. -type Option struct { - // TransformFileFunc is a function that transforms a resource file before being applied to the cluster. - TransformFile TransformFileFunc -} - -// ReplaceOption allows to customize the bootstrap process. -func ReplaceOption(pairs ...string) Option { - return Option{ - TransformFile: func(bs []byte) ([]byte, error) { - if len(pairs)%2 != 0 { - return nil, fmt.Errorf("odd number of arguments: %v", pairs) - } - for i := 0; i < len(pairs); i += 2 { - bs = bytes.ReplaceAll(bs, []byte(pairs[i]), []byte(pairs[i+1])) - } - return bs, nil - }, - } -} - -// Bootstrap creates resources in a package's fs by -// continuously retrying the list. This is blocking, i.e. it only returns (with error) -// when the context is closed or with nil when the bootstrapping is successfully completed. -func Bootstrap(ctx context.Context, discoveryClient discovery.DiscoveryInterface, dynamicClient dynamic.Interface, batteriesIncluded sets.Set[string], fs embed.FS, opts ...Option) error { - cache := memory.NewMemCacheClient(discoveryClient) - mapper := restmapper.NewDeferredDiscoveryRESTMapper(cache) - - // bootstrap non-crd resources - transformers := make([]TransformFileFunc, 0, len(opts)) - for _, opt := range opts { - transformers = append(transformers, opt.TransformFile) - } - return wait.PollUntilContextCancel(ctx, time.Second, true, func(ctx context.Context) (bool, error) { - if err := CreateResourcesFromFS(ctx, dynamicClient, mapper, batteriesIncluded, fs, transformers...); err != nil { - klog.V(1).Infof("Failed to bootstrap resources, retrying: %v", err) - // invalidate cache if resources not found - // xref: https://github.com/kcp-dev/kcp/issues/655 - cache.Invalidate() - return false, nil - } - return true, nil - }) -} - -// CreateResourcesFromFS creates all resources from a filesystem. -func CreateResourcesFromFS(ctx context.Context, client dynamic.Interface, mapper meta.RESTMapper, batteriesIncluded sets.Set[string], fs embed.FS, transformers ...TransformFileFunc) error { - files, err := fs.ReadDir(".") - if err != nil { - return err - } - - var errs []error - for _, f := range files { - if f.IsDir() { - continue - } - if err := CreateResourceFromFS(ctx, client, mapper, batteriesIncluded, f.Name(), fs, transformers...); err != nil { - errs = append(errs, err) - } - } - return apimachineryerrors.NewAggregate(errs) -} - -// CreateResourceFromFS creates given resource file. -func CreateResourceFromFS(ctx context.Context, client dynamic.Interface, mapper meta.RESTMapper, batteriesIncluded sets.Set[string], filename string, fs embed.FS, transformers ...TransformFileFunc) error { - raw, err := fs.ReadFile(filename) - if err != nil { - return fmt.Errorf("could not read %s: %w", filename, err) - } - - if len(raw) == 0 { - return nil // ignore empty files - } - - d := kubeyaml.NewYAMLReader(bufio.NewReader(bytes.NewReader(raw))) - var errs []error - for i := 1; ; i++ { - doc, err := d.Read() - if errors.Is(err, io.EOF) { - break - } else if err != nil { - return err - } - if len(bytes.TrimSpace(doc)) == 0 { - continue - } - - for _, transformer := range transformers { - doc, err = transformer(doc) - if err != nil { - return err - } - } - - if err := createResourceFromFS(ctx, client, mapper, doc, batteriesIncluded); err != nil { - errs = append(errs, fmt.Errorf("failed to create resource %s doc %d: %w", filename, i, err)) - } - } - return apimachineryerrors.NewAggregate(errs) -} - -const annotationCreateOnlyKey = "bootstrap.kube-bind.io/create-only" -const annotationBattery = "bootstrap.kube-bind.io/battery" - -func createResourceFromFS(ctx context.Context, client dynamic.Interface, mapper meta.RESTMapper, raw []byte, batteriesIncluded sets.Set[string]) error { - type Input struct { - Batteries map[string]bool - } - input := Input{ - Batteries: map[string]bool{}, - } - for b := range batteriesIncluded { - input.Batteries[b] = true - } - tmpl, err := template.New("manifest").Parse(string(raw)) - if err != nil { - return fmt.Errorf("failed to parse manifest: %w", err) - } - var buf bytes.Buffer - if err := tmpl.Execute(&buf, input); err != nil { - return fmt.Errorf("failed to execute manifest: %w", err) - } - - obj, gvk, err := extensionsapiserver.Codecs.UniversalDeserializer().Decode(buf.Bytes(), nil, &unstructured.Unstructured{}) - if err != nil { - return fmt.Errorf("could not decode raw: %w", err) - } - u, ok := obj.(*unstructured.Unstructured) - if !ok { - return fmt.Errorf("decoded into incorrect type, got %T, wanted %T", obj, &unstructured.Unstructured{}) - } - - if v, found := u.GetAnnotations()[annotationBattery]; found { - partOf := strings.Split(v, ",") - included := false - for _, p := range partOf { - if batteriesIncluded.Has(strings.TrimSpace(p)) { - included = true - break - } - } - if !included { - klog.V(4).Infof("Skipping %s because %s is/are not among included batteries %s", u.GetName(), v, batteriesIncluded) - return nil - } - } - - m, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) - if err != nil { - return fmt.Errorf("could not get REST mapping for %s: %w", gvk, err) - } - - upserted, err := client.Resource(m.Resource).Namespace(u.GetNamespace()).Create(ctx, u, metav1.CreateOptions{}) - if err != nil { - if apierrors.IsAlreadyExists(err) { - existing, err := client.Resource(m.Resource).Namespace(u.GetNamespace()).Get(ctx, u.GetName(), metav1.GetOptions{}) - if err != nil { - return err - } - - if _, exists := existing.GetAnnotations()[annotationCreateOnlyKey]; exists { - klog.V(3).Infof( - "Skipping update of %s %s because it has the create-only annotation", - gvk, - qualifiedObjectName(existing), - ) - - return nil - } - - u.SetResourceVersion(existing.GetResourceVersion()) - if _, err = client.Resource(m.Resource).Namespace(u.GetNamespace()).Update(ctx, u, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("could not update %s %s: %w", gvk.Kind, qualifiedObjectName(existing), err) - } else { - klog.V(1).Infof("Updated %s %s", gvk, qualifiedObjectName(existing)) - return nil - } - } - return err - } - - klog.V(1).Infof("Bootstrapped %s %s", gvk.Kind, qualifiedObjectName(upserted)) - - return nil -} - -func qualifiedObjectName(obj metav1.Object) string { - if len(obj.GetNamespace()) > 0 { - return fmt.Sprintf("%s/%s", obj.GetNamespace(), obj.GetName()) - } - return obj.GetName() -} diff --git a/pkg/committer/committer.go b/pkg/committer/committer.go deleted file mode 100644 index 3e3723e61..000000000 --- a/pkg/committer/committer.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 committer - -import ( - "context" - "encoding/json" - "fmt" - - jsonpatch "github.com/evanphx/json-patch/v5" - "github.com/google/go-cmp/cmp" - "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" -) - -// Resource is a generic wrapper around resources so we can generate patches. -type Resource[Sp any, St any] struct { - metav1.ObjectMeta `json:"metadata,omitempty"` - Spec Sp `json:"spec"` - Status St `json:"status,omitempty"` -} - -// Patcher is just the Patch API with a generic to keep use sites type safe. -type Patcher[R any] interface { - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (R, error) -} - -// ClusterScoped wraps a generic patcher to make it look like a namespaced patcher, but -// it ignores the namespace argument (which is empty string in cluster-scoped code). -func ClusterScoped[R any](p Patcher[R]) NamespacedPatcher[R] { - return func(string) Patcher[R] { - return p - } -} - -type NamespacedPatcher[R any] func(ns string) Patcher[R] - -// NewCommitter returns a function that can patch instances of R based on spec or status changes. -func NewCommitter[R any, Sp any, St any](patcher NamespacedPatcher[R]) func(context.Context, *Resource[Sp, St], *Resource[Sp, St]) error { - focusType := fmt.Sprintf("%T", *new(R)) - return func(ctx context.Context, old, obj *Resource[Sp, St]) error { - logger := klog.FromContext(ctx) - - objectMetaChanged := !equality.Semantic.DeepEqual(old.ObjectMeta, obj.ObjectMeta) - specChanged := !equality.Semantic.DeepEqual(old.Spec, obj.Spec) - statusChanged := !equality.Semantic.DeepEqual(old.Status, obj.Status) - - specOrObjectMetaChanged := specChanged || objectMetaChanged - - // Simultaneous updates of spec and status are never allowed. - if specOrObjectMetaChanged && statusChanged { - panic(fmt.Sprintf("programmer error: spec and status changed in same reconcile iteration. diff=%s", cmp.Diff(old, obj))) - } - - if !specOrObjectMetaChanged && !statusChanged { - return nil - } - - // forPatch ensures that only the spec/objectMeta fields will be changed - // or the status field but never both at the same time. - forPatch := func(r *Resource[Sp, St]) *Resource[Sp, St] { - var ret Resource[Sp, St] - if specOrObjectMetaChanged { - ret.ObjectMeta = r.ObjectMeta - ret.Spec = r.Spec - } else { - ret.Status = r.Status - } - return &ret - } - - ns := old.Namespace - name := old.Name - - oldForPatch := forPatch(old) - // to ensure they appear in the patch as preconditions - oldForPatch.UID = "" - oldForPatch.ResourceVersion = "" - - oldData, err := json.Marshal(oldForPatch) - if err != nil { - return fmt.Errorf("failed to Marshal old data for %s %s/%s: %w", focusType, ns, name, err) - } - - newForPatch := forPatch(obj) - // to ensure they appear in the patch as preconditions - newForPatch.UID = old.UID - newForPatch.ResourceVersion = old.ResourceVersion - - newData, err := json.Marshal(newForPatch) - if err != nil { - return fmt.Errorf("failed to Marshal new data for %s %s/%s: %w", focusType, ns, name, err) - } - - patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData) - if err != nil { - return fmt.Errorf("failed to create patch for %s %s/%s: %w", focusType, ns, name, err) - } - - var subresources []string - if statusChanged { - subresources = []string{"status"} - } - - logger.V(2).Info(fmt.Sprintf("patching %s", focusType), "patch", string(patchBytes)) - _, err = patcher(obj.Namespace).Patch(ctx, obj.Name, types.MergePatchType, patchBytes, metav1.PatchOptions{}, subresources...) - if err != nil { - return fmt.Errorf("failed to patch %s %s/%s: %w", focusType, ns, name, err) - } - - return nil - } -} diff --git a/pkg/indexers/bindableresourcesrequest.go b/pkg/indexers/bindableresourcesrequest.go deleted file mode 100644 index 24260b2b8..000000000 --- a/pkg/indexers/bindableresourcesrequest.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 indexers - -import ( - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - BindableResourcesRequestByTemplate = "BindableResourcesRequestByTemplate" -) - -// IndexBindableResourcesRequestByTemplate is a controller-runtime compatible indexer function -// that indexes BindableResourcesRequests by their template name. -func IndexBindableResourcesRequestByTemplate(obj client.Object) []string { - req, ok := obj.(*kubebindv1alpha2.BindableResourcesRequest) - if !ok { - return nil - } - if req.Spec.TemplateRef.Name == "" { - return nil - } - return []string{req.Spec.TemplateRef.Name} -} diff --git a/pkg/indexers/crd.go b/pkg/indexers/crd.go deleted file mode 100644 index e59fe6bba..000000000 --- a/pkg/indexers/crd.go +++ /dev/null @@ -1,30 +0,0 @@ -package indexers - -import ( - "strings" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - CRDByServiceBinding = "CRDByServiceBinding" -) - -func IndexCRDByServiceBinding(obj any) ([]string, error) { - crd, ok := obj.(*apiextensionsv1.CustomResourceDefinition) - if !ok { - return nil, nil - } - - bindings := []string{} - for _, ref := range crd.OwnerReferences { - parts := strings.SplitN(ref.APIVersion, "/", 2) - if parts[0] != kubebindv1alpha2.SchemeGroupVersion.Group || ref.Kind != "APIServiceBinding" { - continue - } - bindings = append(bindings, ref.Name) - } - return bindings, nil -} diff --git a/pkg/indexers/servicebinding.go b/pkg/indexers/servicebinding.go deleted file mode 100644 index 4c2ce544f..000000000 --- a/pkg/indexers/servicebinding.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 indexers - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - //nolint:gosec - ByServiceBindingKubeconfigSecret = "byKubeconfigSecret" -) - -func IndexServiceBindingByKubeconfigSecret(obj any) ([]string, error) { - binding, ok := obj.(*kubebindv1alpha2.APIServiceBinding) - if !ok { - return nil, nil - } - return []string{ByServiceBindingKubeconfigSecretKey(binding)}, nil -} - -func ByServiceBindingKubeconfigSecretKey(binding *kubebindv1alpha2.APIServiceBinding) string { - ref := &binding.Spec.KubeconfigSecretRef - return ref.Namespace + "/" + ref.Name -} diff --git a/pkg/indexers/servicebindingbundle.go b/pkg/indexers/servicebindingbundle.go deleted file mode 100644 index 3c599ee32..000000000 --- a/pkg/indexers/servicebindingbundle.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 indexers - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - //nolint:gosec - ByServiceBindingBundleKubeconfigSecret = "byKubeconfigSecretBundle" -) - -func IndexServiceBindingBundleByKubeconfigSecret(obj any) ([]string, error) { - bundle, ok := obj.(*kubebindv1alpha2.APIServiceBindingBundle) - if !ok { - return nil, nil - } - return []string{ByServiceBindingBundleKubeconfigSecretKey(bundle)}, nil -} - -func ByServiceBindingBundleKubeconfigSecretKey(bundle *kubebindv1alpha2.APIServiceBindingBundle) string { - ref := &bundle.Spec.KubeconfigSecretRef - return ref.Namespace + "/" + ref.Name -} diff --git a/pkg/indexers/serviceexport.go b/pkg/indexers/serviceexport.go deleted file mode 100644 index 40f5c0993..000000000 --- a/pkg/indexers/serviceexport.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 indexers - -import ( - "sigs.k8s.io/controller-runtime/pkg/client" - - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - ServiceExportByCustomResourceDefinition = "serviceExportByCustomResourceDefinition" - ServiceExportByBoundSchema = "serviceExportByBoundSchema" -) - -func IndexServiceExportByCustomResourceDefinition(obj any) ([]string, error) { - export, ok := obj.(*v1alpha2.APIServiceExport) - if !ok { - return nil, nil - } - - return []string{export.Name}, nil -} - -// IndexServiceExportByBoundSchema is a controller-runtime compatible indexer function. -func IndexServiceExportByBoundSchemaControllerRuntime(obj client.Object) []string { - export, ok := obj.(*v1alpha2.APIServiceExport) - if !ok { - return nil - } - - names := make([]string, 0, len(export.Spec.Resources)) - for _, res := range export.Spec.Resources { - names = append(names, res.ResourceGroupName()) - } - return names -} - -// IndexServiceExportByBoundSchema is a controller-runtime compatible indexer function. -func IndexServiceExportByBoundSchema(obj any) ([]string, error) { - export, ok := obj.(*v1alpha2.APIServiceExport) - if !ok { - return nil, nil - } - - names := make([]string, 0, len(export.Spec.Resources)) - for _, res := range export.Spec.Resources { - names = append(names, res.ResourceGroupName()) - } - return names, nil -} diff --git a/pkg/indexers/serviceexportrequest.go b/pkg/indexers/serviceexportrequest.go deleted file mode 100644 index 986c05edf..000000000 --- a/pkg/indexers/serviceexportrequest.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 indexers - -import ( - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - ServiceExportRequestByGroupResource = "ServiceExportRequestByGroupResource" - ServiceExportRequestByServiceExport = "ServiceExportRequestByServiceExport" -) - -// IndexServiceExportRequestByGroupResource is a controller-runtime compatible indexer function -// that indexes APIServiceExportRequests by their Group.Resource name. -func IndexServiceExportRequestByGroupResource(obj client.Object) []string { - apiServiceExportRequest, ok := obj.(*kubebindv1alpha2.APIServiceExportRequest) - if !ok { - return nil - } - keys := []string{} - for _, gr := range apiServiceExportRequest.Spec.Resources { - keys = append(keys, gr.ResourceGroupName()) - } - return keys -} - -// IndexServiceExportRequestByServiceExport is a controller-runtime compatible indexer function -// that indexes APIServiceExportRequests by their related ServiceExport name. -func IndexServiceExportRequestByServiceExport(obj client.Object) []string { - apiServiceExportRequest, ok := obj.(*kubebindv1alpha2.APIServiceExportRequest) - if !ok { - return nil - } - keys := []string{} - for _, gr := range apiServiceExportRequest.Spec.Resources { - keys = append(keys, apiServiceExportRequest.Namespace+"/"+gr.ResourceGroupName()) - } - return keys -} diff --git a/pkg/indexers/servicenamespace.go b/pkg/indexers/servicenamespace.go deleted file mode 100644 index 5cef0f0da..000000000 --- a/pkg/indexers/servicenamespace.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 indexers - -import ( - "sigs.k8s.io/controller-runtime/pkg/client" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -const ( - ServiceNamespaceByNamespace = "serviceNamespaceByNamespace" -) - -func IndexServiceNamespaceByNamespace(obj any) ([]string, error) { - sn, ok := obj.(*kubebindv1alpha2.APIServiceNamespace) - if !ok || sn.Status.Namespace == "" { - return nil, nil - } - - return []string{sn.Status.Namespace}, nil -} - -// IndexServiceNamespaceByNamespaceControllerRuntime is a controller-runtime compatible indexer function -// that indexes APIServiceNamespaces by their status namespace. -func IndexServiceNamespaceByNamespaceControllerRuntime(obj client.Object) []string { - sn, ok := obj.(*kubebindv1alpha2.APIServiceNamespace) - if !ok || sn.Status.Namespace == "" { - return nil - } - return []string{sn.Status.Namespace} -} diff --git a/pkg/indexers/util.go b/pkg/indexers/util.go deleted file mode 100644 index 12dc083be..000000000 --- a/pkg/indexers/util.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 indexers - -import ( - "fmt" - - "k8s.io/client-go/tools/cache" -) - -// Append is a helper function that merged a set of indexers. -func Append(indexers ...cache.Indexers) (cache.Indexers, error) { - var ret = cache.Indexers{} - for _, ind := range indexers { - for k, v := range ind { - if _, found := ret[k]; found { - return nil, fmt.Errorf("duplicate indexer: %s", k) - } - ret[k] = v - } - } - return ret, nil -} - -func AppendOrDie(indexers ...cache.Indexers) cache.Indexers { - ret, err := Append(indexers...) - if err != nil { - panic(err) - } - return ret -} - -// AddIfNotPresentOrDie tries to add everything from toAdd to indexer's indexers that does not already exist. It panics -// if it encounters an error. -func AddIfNotPresentOrDie(indexer cache.Indexer, toAdd cache.Indexers) { - existing := indexer.GetIndexers() - for indexName := range toAdd { - if _, exists := existing[indexName]; exists { - delete(toAdd, indexName) - } - } - - if err := indexer.AddIndexers(toAdd); err != nil { - panic(fmt.Errorf("error adding indexers: %w", err)) - } -} diff --git a/pkg/konnector/config.go b/pkg/konnector/config.go deleted file mode 100644 index 6edca5eb2..000000000 --- a/pkg/konnector/config.go +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 konnector - -import ( - "time" - - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - apiextensionsinformers "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions" - kubeinformers "k8s.io/client-go/informers" - kubernetesclient "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - - "github.com/kube-bind/kube-bind/pkg/konnector/options" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions" -) - -type Config struct { - ClientConfig *rest.Config - BindClient *bindclient.Clientset - KubeClient *kubernetesclient.Clientset - ApiextensionsClient *apiextensionsclient.Clientset - - KubeInformers kubeinformers.SharedInformerFactory - BindInformers bindinformers.SharedInformerFactory - ApiextensionsInformers apiextensionsinformers.SharedInformerFactory - - ServerAddr string - ProviderPollingInterval time.Duration -} - -func NewConfig(options *options.CompletedOptions) (*Config, error) { - config := &Config{ - ServerAddr: options.ServerAddr, - ProviderPollingInterval: options.ProviderPollingInterval, - } - - // create clients - rules := clientcmd.NewDefaultClientConfigLoadingRules() - rules.ExplicitPath = options.KubeConfigPath - var overrides *clientcmd.ConfigOverrides - if options.Context != "" { - overrides = &clientcmd.ConfigOverrides{ - CurrentContext: options.Context, - } - } - var err error - config.ClientConfig, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig() - if err != nil { - return nil, err - } - config.ClientConfig = rest.CopyConfig(config.ClientConfig) - config.ClientConfig = rest.AddUserAgent(config.ClientConfig, "konnector") - - if config.BindClient, err = bindclient.NewForConfig(config.ClientConfig); err != nil { - return nil, err - } - if config.KubeClient, err = kubernetesclient.NewForConfig(config.ClientConfig); err != nil { - return nil, err - } - if config.ApiextensionsClient, err = apiextensionsclient.NewForConfig(config.ClientConfig); err != nil { - return nil, err - } - - // construct informer factories - config.KubeInformers = kubeinformers.NewSharedInformerFactory(config.KubeClient, time.Minute*30) - config.BindInformers = bindinformers.NewSharedInformerFactory(config.BindClient, time.Minute*30) - config.ApiextensionsInformers = apiextensionsinformers.NewSharedInformerFactory(config.ApiextensionsClient, time.Minute*30) - - return config, nil -} diff --git a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_controller.go b/pkg/konnector/controllers/cluster/claimedresources/claimedresources_controller.go deleted file mode 100644 index d0ae02ed6..000000000 --- a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_controller.go +++ /dev/null @@ -1,546 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 claimedresources - -import ( - "context" - "fmt" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/dynamic/dynamiclister" - "k8s.io/client-go/informers" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/multinsinformer" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - "github.com/kube-bind/kube-bind/pkg/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclientset "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-claimed-object" -) - -// NewController returns a new controller reconciling downstream objects to upstream. -func NewController( - gvr schema.GroupVersionResource, - claim kubebindv1alpha2.PermissionClaim, - apiServiceExport *kubebindv1alpha2.APIServiceExport, - providerNamespace string, - consumerConfig, providerConfig *rest.Config, - consumerDynamicInformer informers.GenericInformer, - providerDynamicInformer multinsinformer.GetterInformer, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], - namespaceCreationNotifyChan <-chan string, -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName, "gvr", gvr) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - providerClient, err := dynamicclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - consumerClient, err := dynamicclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - bindClient, err := bindclientset.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - dynamicConsumerLister := dynamiclister.New(consumerDynamicInformer.Informer().GetIndexer(), gvr) - c := &controller{ - queue: queue, - - claim: claim, - apiServiceExport: apiServiceExport, // used to establish owner references when create happens on the provider side. TODO: Do we really need this? - - consumerClient: consumerClient, - providerClient: providerClient, - providerBindClient: bindClient, - - consumerDynamicLister: dynamicConsumerLister, - consumerDynamicIndexer: consumerDynamicInformer.Informer().GetIndexer(), - - providerDynamicInformer: providerDynamicInformer, - - serviceNamespaceInformer: serviceNamespaceInformer, - - providerNamespace: providerNamespace, - - namespaceCreationNotifyChan: namespaceCreationNotifyChan, - - readReconciler: readReconciler{ - getServiceNamespace: func(upstreamNamespace string) (*kubebindv1alpha2.APIServiceNamespace, error) { - sns, err := serviceNamespaceInformer.Informer().GetIndexer().ByIndex(indexers.ServiceNamespaceByNamespace, upstreamNamespace) - if err != nil { - return nil, err - } - if len(sns) == 0 { - return nil, errors.NewNotFound(kubebindv1alpha2.SchemeGroupVersion.WithResource("APIServiceNamespace").GroupResource(), upstreamNamespace) - } - return sns[0].(*kubebindv1alpha2.APIServiceNamespace), nil - }, - getConsumerObject: func(ctx context.Context, ns, name string) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(ns).Get(ctx, name, metav1.GetOptions{}) - }, - getProviderObject: func(ns, name string) (*unstructured.Unstructured, error) { - obj, err := providerDynamicInformer.Get(ns, name) - if err != nil { - return nil, err - } - return obj.(*unstructured.Unstructured), nil - }, - createProviderObject: func(ctx context.Context, obj *unstructured.Unstructured) error { - _, err := providerClient.Resource(gvr).Namespace(obj.GetNamespace()).Create(ctx, obj, metav1.CreateOptions{}) - return err - }, - updateProviderObject: func(ctx context.Context, obj *unstructured.Unstructured) error { - _, err := providerClient.Resource(gvr).Namespace(obj.GetNamespace()).Update(ctx, obj, metav1.UpdateOptions{}) - return err - }, - deleteProviderObject: func(ctx context.Context, ns, name string) error { - return providerClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) - }, - deleteConsumerObject: func(ctx context.Context, ns, name string) error { - return consumerClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) - }, - updateConsumerObject: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(obj.GetNamespace()).Update(ctx, obj, metav1.UpdateOptions{}) - }, - createConsumerObject: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(obj.GetNamespace()).Create(ctx, obj, metav1.CreateOptions{}) - }, - }, - } - - if _, err = consumerDynamicInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - c.enqueueConsumer(logger, obj) - }, - UpdateFunc: func(_, newObj interface{}) { - c.enqueueConsumer(logger, newObj) - }, - DeleteFunc: func(obj interface{}) { - c.enqueueConsumer(logger, obj) - }, - }); err != nil { - return nil, err - } - - if err := providerDynamicInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - c.enqueueProvider(logger, obj) - }, - UpdateFunc: func(_, newObj interface{}) { - c.enqueueProvider(logger, newObj) - }, - DeleteFunc: func(obj interface{}) { - c.enqueueProvider(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -// controller reconciles upstream objects to downstream. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - claim kubebindv1alpha2.PermissionClaim - apiServiceExport *kubebindv1alpha2.APIServiceExport // used to establish owner references when create happens from the consumer side. - - consumerClient dynamicclient.Interface - providerClient dynamicclient.Interface - providerBindClient bindclientset.Interface - - consumerDynamicLister dynamiclister.Lister - consumerDynamicIndexer cache.Indexer - - providerDynamicInformer multinsinformer.GetterInformer - - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - providerNamespace string - - // Channel to receive notifications when new namespaces are created - namespaceCreationNotifyChan <-chan string - - readReconciler -} - -// isClaimed returns true if the given object is claimed by the controller's claim. -// If consumerSide is true, the check is done for the consumer side (no namespace remapping), and if false, for the provider side object, -// where namespace remapping via APIServiceNamespace is taken into account. -func (c *controller) isClaimed(logger klog.Logger, obj *unstructured.Unstructured, consumerSide bool) bool { - // If owner label is set - it was claimed before and might not be claimed now (example: reference gone or changed). - // So we need to enqueue it to check if it is still needed. - _, wasClaimedBefore := obj.GetLabels()[kubebindv1alpha2.ObjectOwnerLabel] - - currentlyClaimed := resources.IsClaimedWithReference( - logger, - obj, - consumerSide, - c.claim, - c.apiServiceExport, - c.consumerClient, - c.serviceNamespaceInformer. - Lister(). - APIServiceNamespaces(c.providerNamespace), - ) - - return wasClaimedBefore || currentlyClaimed -} - -func (c *controller) enqueueConsumer(logger klog.Logger, obj interface{}) { - // handle tombstones - if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { - obj = tombstone.Obj - } - o, ok := obj.(*unstructured.Unstructured) - if !ok { - runtime.HandleError(fmt.Errorf("unexpected type %T in enqueueConsumer", obj)) - return - } - - if !c.isClaimed(logger, o, true) { - return - } - logger.V(2).Info("queueing consumer object", "gvr", o.GroupVersionKind().String(), "key", fmt.Sprintf("%s/%s", o.GetNamespace(), o.GetName())) - - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - c.enqueueConsumerByKey(logger, key) -} - -// enqueueConsumerByKey will enqueue the given namespaced object. This is split from enqueueConsumer -// so we can accept channel requests from namespace creation watcher. -func (c *controller) enqueueConsumerByKey(logger klog.Logger, key string) { - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return - } - if ns != "" { // Namespaced object. - sn, err := c.serviceNamespaceInformer.Lister().APIServiceNamespaces(c.providerNamespace).Get(ns) - if err != nil { - if errors.IsNotFound(err) { - // No APIServiceNamespace - means claimedresourcesnamespaces controller should create it - logger.V(2).Info("no APIServiceNamespace found for claimed object. Will retry", "namespace", ns, "object", name) - return - } - runtime.HandleError(fmt.Errorf("failed to get APIServiceNamespace %q: %w", ns, err)) - return - } - if sn.Status.Namespace == "" { - return // not ready yet - } - if sn.Namespace == c.providerNamespace && sn.Status.Namespace != "" { - key := fmt.Sprintf("%s/%s", sn.Status.Namespace, name) - logger.V(2).Info("queueing Unstructured", "key", key, "reason", "Consumer") - c.queue.Add(key) - return - } - return - } - - logger.V(2).Info("queueing Unstructured", "key", key, "reason", "Consumer") - c.queue.Add(key) -} - -func (c *controller) enqueueProvider(logger klog.Logger, obj interface{}) { - // handle tombstones - if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { - obj = tombstone.Obj - } - o, ok := obj.(*unstructured.Unstructured) - if !ok { - runtime.HandleError(fmt.Errorf("unexpected type %T in enqueueProvider", obj)) - return - } - - if !c.isClaimed(logger, o, false) { - logger.V(4).Info("object is not claimed, skipping", "object", o.GetObjectKind().GroupVersionKind(), "name", o.GetName()) - return - } - - providerKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, _, err := cache.SplitMetaNamespaceKey(providerKey) - if err != nil { - runtime.HandleError(err) - return - } - - if ns != "" { - sns, err := c.serviceNamespaceInformer.Informer().GetIndexer().ByIndex(indexers.ServiceNamespaceByNamespace, ns) - if err != nil { - if !errors.IsNotFound(err) { - runtime.HandleError(err) - } - return - } - for _, obj := range sns { - sn := obj.(*kubebindv1alpha2.APIServiceNamespace) - if sn.Namespace == c.providerNamespace { - logger.V(2).Info("queueing Unstructured", "key", providerKey) - c.queue.Add(providerKey) - return - } - } - return - } - - logger.V(2).Info("queueing Unstructured", "key", providerKey) - c.queue.Add(providerKey) -} - -func (c *controller) enqueueServiceNamespace(logger klog.Logger, obj interface{}) { - snKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(snKey) - if err != nil { - runtime.HandleError(err) - return - } - if ns != c.providerNamespace { - return // not for us - } - - sn, err := c.serviceNamespaceInformer.Lister().APIServiceNamespaces(ns).Get(name) - if err != nil { - runtime.HandleError(err) - return - } - - if sn.Status.Namespace == "" { - return // not ready - } - - logger.Info("enqueueing service namespace", "upstreamNamespace", sn.Status.Namespace) - objs, err := c.providerDynamicInformer.List(sn.Status.Namespace) - if err != nil { - runtime.HandleError(err) - return - } - for _, obj := range objs { - unstructuredObj, ok := obj.(*unstructured.Unstructured) - if !ok { - continue - } - - // Check if the provider object is actually claimed using the full selector logic. - if !c.isClaimed(logger, unstructuredObj, false) { - continue - } - - key, err := cache.MetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - continue - } - logger.V(2).Info("queueing Unstructured", "key", key, "reason", "APIServiceNamespace", "ServiceNamespaceKey", key) - c.queue.Add(key) - } - - // We need to list all the object which might not got synced at consumer side too: - var sel labels.Selector - switch v := c.claim.Selector; { - case v.LabelSelector == nil && len(v.NamedResources) == 0: - sel = labels.Everything() - case v.LabelSelector != nil: - var err error - sel, err = metav1.LabelSelectorAsSelector(v.LabelSelector) - if err != nil { - runtime.HandleError(err) - return - } - case len(v.NamedResources) > 0: - // namedResource-only: fetch specific objects from cache and enqueue - for _, nr := range v.NamedResources { - // Build consumer cache key; empty namespace implies cluster-scoped - key := nr.Name - if nr.Namespace != "" { - key = fmt.Sprintf("%s/%s", nr.Namespace, nr.Name) - } - // only process objects in this consumer namespace - if nr.Namespace != "" && nr.Namespace != sn.Name { - continue - } - obj, exists, err := c.consumerDynamicIndexer.GetByKey(key) - if err != nil { - runtime.HandleError(err) - continue - } - if !exists { - continue - } - u, ok := obj.(*unstructured.Unstructured) - if !ok || !c.isClaimed(logger, u, true) { - continue - } - // Re-map to provider namespace key - provKey := fmt.Sprintf("%s/%s", sn.Status.Namespace, nr.Name) - logger.V(2).Info("queueing Unstructured", "key", provKey, "reason", "APIServiceNamespace", "ConsumerObject", key) - c.queue.Add(provKey) - } - return - default: - return // nothing is selected - } - objects, err := c.consumerDynamicLister.List(sel) - if err != nil { - runtime.HandleError(err) - return - } - for _, obj := range objects { - // Check if the object is actually claimed using the full selector logic - if !c.isClaimed(logger, obj, true) { - continue - } - objKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - continue - } - objNamespace, name, err := cache.SplitMetaNamespaceKey(objKey) - if err != nil { - runtime.HandleError(err) - continue - } - // only process objects in this consumer namespace - if objNamespace != "" && objNamespace != sn.Name { - continue - } - provKey := fmt.Sprintf("%s/%s", sn.Status.Namespace, name) - logger.V(2).Info("queueing Unstructured", "key", provKey, "reason", "APIServiceNamespace", "ConsumerObject", objKey) - c.queue.Add(provKey) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - c.serviceNamespaceInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - c.enqueueServiceNamespace(logger, obj) - }, - UpdateFunc: func(_, newObj interface{}) { - c.enqueueServiceNamespace(logger, newObj) - }, - DeleteFunc: func(obj interface{}) { - c.enqueueServiceNamespace(logger, obj) - }, - }) - - // Start a goroutine to listen for namespace creation notifications. - go func() { - for key := range c.namespaceCreationNotifyChan { - logger.Info("received namespace creation notification", "namespace", key) - c.enqueueConsumerByKey(logger, key) - } - }() - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - return c.reconcile(ctx, namespace, name) -} diff --git a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler.go b/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler.go deleted file mode 100644 index 0db7a89e8..000000000 --- a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler.go +++ /dev/null @@ -1,270 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 claimedresources - -import ( - "context" - "fmt" - "strings" - - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/klog/v2" - - konnectortypes "github.com/kube-bind/kube-bind/pkg/konnector/types" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type readReconciler struct { - getServiceNamespace func(upstreamNamespace string) (*kubebindv1alpha2.APIServiceNamespace, error) - getProviderObject func(ns, name string) (*unstructured.Unstructured, error) - createProviderObject func(ctx context.Context, obj *unstructured.Unstructured) error - updateProviderObject func(ctx context.Context, obj *unstructured.Unstructured) error - deleteProviderObject func(ctx context.Context, ns, name string) error - - getConsumerObject func(ctx context.Context, ns, name string) (*unstructured.Unstructured, error) - updateConsumerObject func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) - createConsumerObject func(ctx context.Context, ob *unstructured.Unstructured) (*unstructured.Unstructured, error) - deleteConsumerObject func(ctx context.Context, ns, name string) error -} - -// reconcile syncs consumer claimed resources to provider. -func (r *readReconciler) reconcile(ctx context.Context, providerNamespace, name string) error { - logger := klog.FromContext(ctx) - logger = logger.WithValues("name", name, "providerNamespace", providerNamespace) - - logger.Info("reconciling object") - consumerNS := "" - if providerNamespace != "" { - sn, err := r.getServiceNamespace(providerNamespace) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - runtime.HandleError(err) - return err // hoping the APIServiceNamespace will be created soon. Otherwise, this item goes into backoff. - } - if sn.Status.Namespace == "" { - e := fmt.Errorf("APIServiceNamespace %q has empty status.namespace", providerNamespace) - runtime.HandleError(e) - return e // hoping the status is set soon. - } - - logger = logger.WithValues("providerNamespace", sn.Status.Namespace) - consumerNS = sn.Name - logger = logger.WithValues("consumerNamespace", consumerNS) - - ctx = klog.NewContext(ctx, logger) - } - - providerObj, providerErr := r.getProviderObject(providerNamespace, name) - if providerErr != nil && !errors.IsNotFound(providerErr) { - return providerErr - } - consumerObj, consumerErr := r.getConsumerObject(ctx, consumerNS, name) - if consumerErr != nil && !errors.IsNotFound(consumerErr) { - return consumerErr - } - - if errors.IsNotFound(providerErr) && errors.IsNotFound(consumerErr) { - // Nothing to do - return nil - } - - // Determine owner - owner, err := determineOwner(providerObj, consumerObj) - if err != nil { // nothing we can do - logger.Error(err, "could not determine owner") - return nil - } - logger = logger.WithValues("owner", owner) - - switch owner { - case kubebindv1alpha2.OwnerProvider: - if errors.IsNotFound(providerErr) { - err := r.deleteConsumerObject(ctx, consumerNS, name) - if errors.IsNotFound(err) { - return nil - } - return err - } - ownerCandidate := providerObj.DeepCopy() - - // Set owner label if needed - r.makeProviderOwner(ownerCandidate) - if !equality.Semantic.DeepEqual(providerObj, ownerCandidate) { - if err := r.updateProviderObject(ctx, ownerCandidate); err != nil { - return err - } - } - - if errors.IsNotFound(consumerErr) { - logger.Info("Creating missing consumer object", "consumerNamespace", consumerNS, "consumerName", providerObj.GetName()) - - candidate := candidateFromOwnerObj(consumerNS, providerObj) - konnectortypes.SetSourceMetadataAnnotations(candidate, providerObj.GetNamespace(), string(providerObj.GetUID()), - konnectortypes.ProviderNamespaceAnnotationKey, konnectortypes.ProviderUIDAnnotationKey) - r.makeProviderOwner(candidate) - - if _, err := r.createConsumerObject(ctx, candidate); err != nil { - return err - } - - return nil - } - - if !providerObj.GetDeletionTimestamp().IsZero() { - logger.Info("Deleting consumer object because it has been deleted upstream", "consumerNamespace", consumerNS, "consumerName", providerObj.GetName()) - return r.deleteConsumerObject(ctx, consumerNS, providerObj.GetName()) - } - - candidate := candidateFromOwnerObj(consumerNS, providerObj) - konnectortypes.SetSourceMetadataAnnotations(candidate, providerObj.GetNamespace(), string(providerObj.GetUID()), - konnectortypes.ProviderNamespaceAnnotationKey, konnectortypes.ProviderUIDAnnotationKey) - current := candidateFromOwnerObj(consumerNS, consumerObj) - if !equality.Semantic.DeepEqual(candidate, current) { - logger.Info("Updating consumer object data", "consumerNamespace", consumerNS, "consumerName", consumerObj.GetName()) - if _, err := r.updateConsumerObject(ctx, candidate); err != nil { - logger.Error(err, "error updating consumer object") - return err - } - } - - case kubebindv1alpha2.OwnerConsumer: - if errors.IsNotFound(consumerErr) { - logger.Info("Owner copy of the object is gone, deleting downstream object", "name", name, "namespace", providerNamespace) - err := r.deleteProviderObject(ctx, providerNamespace, name) - if errors.IsNotFound(err) { - return nil - } - return err - } - - ownerCandidate := consumerObj.DeepCopy() - r.makeConsumerOwner(ownerCandidate) - if !equality.Semantic.DeepEqual(consumerObj, ownerCandidate) { - logger.Info("setting owner label for Consumer object") - if _, err := r.updateConsumerObject(ctx, ownerCandidate); err != nil { - return err - } - } - - candidate := candidateFromOwnerObj(providerNamespace, ownerCandidate) - konnectortypes.SetSourceMetadataAnnotations(candidate, ownerCandidate.GetNamespace(), string(ownerCandidate.GetUID()), - konnectortypes.ConsumerNamespaceAnnotationKey, konnectortypes.ConsumerUIDAnnotationKey) - r.makeConsumerOwner(candidate) - - if errors.IsNotFound(providerErr) { - logger.Info("creating consumer owned object at provider") - return r.createProviderObject(ctx, candidate) - } - - providerObj := candidateFromOwnerObj(providerNamespace, providerObj) - if !equality.Semantic.DeepEqual(providerObj, candidate) { - logger.Info("updating consumer owned object at provider") - return r.updateProviderObject(ctx, candidate) - } - } - - return nil -} - -func (r readReconciler) makeConsumerOwner(obj *unstructured.Unstructured) { - a := obj.GetLabels() - if a == nil { - a = map[string]string{} - } - a[kubebindv1alpha2.ObjectOwnerLabel] = string(kubebindv1alpha2.OwnerConsumer) - obj.SetLabels(a) -} - -func (r readReconciler) makeProviderOwner(obj *unstructured.Unstructured) { - a := obj.GetLabels() - if a == nil { - a = map[string]string{} - } - a[kubebindv1alpha2.ObjectOwnerLabel] = string(kubebindv1alpha2.OwnerProvider) - obj.SetLabels(a) -} - -func candidateFromOwnerObj(downstreamNS string, obj *unstructured.Unstructured) *unstructured.Unstructured { - // clean up object - candidate := obj.DeepCopy() - candidate.SetUID("") - candidate.SetResourceVersion("") - candidate.SetNamespace(downstreamNS) - candidate.SetManagedFields(nil) - candidate.SetDeletionTimestamp(nil) - candidate.SetDeletionGracePeriodSeconds(nil) - candidate.SetOwnerReferences(nil) - candidate.SetFinalizers(nil) - candidate.SetNamespace(downstreamNS) - candidate.SetCreationTimestamp(v1.Time{}) - - labels := map[string]string{} - for key, label := range obj.GetLabels() { - if strings.Contains(key, "claimed.internal.apis.kcp.io") { - continue - } - labels[key] = label - } - candidate.SetLabels(labels) - - annotations := map[string]string{} - for key, annotation := range obj.GetAnnotations() { - if strings.Contains(key, "kcp.io/cluster") { - continue - } - annotations[key] = annotation - } - candidate.SetAnnotations(annotations) - - return candidate -} - -// determineOwner determines the owner of a resource given at least one object exists either on the -// consumer or provider side. -func determineOwner(providerObj, consumerObj *unstructured.Unstructured) (kubebindv1alpha2.Owner, error) { - if providerObj != nil { - ownerLabel := providerObj.GetLabels()[kubebindv1alpha2.ObjectOwnerLabel] - switch ownerLabel { - case kubebindv1alpha2.OwnerProvider.String(): - return kubebindv1alpha2.OwnerProvider, nil - case kubebindv1alpha2.OwnerConsumer.String(): - return kubebindv1alpha2.OwnerConsumer, nil - } - if ownerLabel == "" && consumerObj == nil { - return kubebindv1alpha2.OwnerProvider, nil - } - } - - if consumerObj != nil { - ownerLabel := consumerObj.GetLabels()[kubebindv1alpha2.ObjectOwnerLabel] - switch ownerLabel { - case kubebindv1alpha2.OwnerProvider.String(): - return kubebindv1alpha2.OwnerProvider, nil - case kubebindv1alpha2.OwnerConsumer.String(): - return kubebindv1alpha2.OwnerConsumer, nil - } - if ownerLabel == "" && providerObj == nil { - return kubebindv1alpha2.OwnerConsumer, nil - } - } - return "", fmt.Errorf("unable to determine owner") -} diff --git a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler_test.go b/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler_test.go deleted file mode 100644 index 842a34b0c..000000000 --- a/pkg/konnector/controllers/cluster/claimedresources/claimedresources_reconciler_test.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 claimedresources - -import ( - "testing" - - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - - konnectortypes "github.com/kube-bind/kube-bind/pkg/konnector/types" -) - -func TestSetSourceMetadataAnnotations(t *testing.T) { - tests := []struct { - name string - obj *unstructured.Unstructured - sourceNS string - sourceUID string - nsKey string - uidKey string - expectedAnnotations map[string]string - }{ - { - name: "provider annotations on empty object", - obj: &unstructured.Unstructured{}, - sourceNS: "provider-ns", - sourceUID: "provider-uid-123", - nsKey: konnectortypes.ProviderNamespaceAnnotationKey, - uidKey: konnectortypes.ProviderUIDAnnotationKey, - expectedAnnotations: map[string]string{ - konnectortypes.ProviderNamespaceAnnotationKey: "provider-ns", - konnectortypes.ProviderUIDAnnotationKey: "provider-uid-123", - }, - }, - { - name: "consumer annotations on empty object", - obj: &unstructured.Unstructured{}, - sourceNS: "consumer-ns", - sourceUID: "consumer-uid-456", - nsKey: konnectortypes.ConsumerNamespaceAnnotationKey, - uidKey: konnectortypes.ConsumerUIDAnnotationKey, - expectedAnnotations: map[string]string{ - konnectortypes.ConsumerNamespaceAnnotationKey: "consumer-ns", - konnectortypes.ConsumerUIDAnnotationKey: "consumer-uid-456", - }, - }, - { - name: "preserves existing annotations", - obj: func() *unstructured.Unstructured { - obj := &unstructured.Unstructured{} - obj.SetAnnotations(map[string]string{ - "existing-key": "existing-value", - }) - return obj - }(), - sourceNS: "my-ns", - sourceUID: "my-uid", - nsKey: konnectortypes.ProviderNamespaceAnnotationKey, - uidKey: konnectortypes.ProviderUIDAnnotationKey, - expectedAnnotations: map[string]string{ - konnectortypes.ProviderNamespaceAnnotationKey: "my-ns", - konnectortypes.ProviderUIDAnnotationKey: "my-uid", - "existing-key": "existing-value", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - konnectortypes.SetSourceMetadataAnnotations(tt.obj, tt.sourceNS, tt.sourceUID, tt.nsKey, tt.uidKey) - - annotations := tt.obj.GetAnnotations() - for key, expected := range tt.expectedAnnotations { - require.Equal(t, expected, annotations[key], "annotation %s mismatch", key) - } - }) - } -} - -func TestCandidateFromOwnerObjPreservesKubeBindAnnotations(t *testing.T) { - obj := &unstructured.Unstructured{} - obj.SetAnnotations(map[string]string{ - konnectortypes.ProviderNamespaceAnnotationKey: "provider-ns", - konnectortypes.ProviderUIDAnnotationKey: "provider-uid", - konnectortypes.ConsumerNamespaceAnnotationKey: "consumer-ns", - konnectortypes.ConsumerUIDAnnotationKey: "consumer-uid", - "kcp.io/cluster": "should-be-stripped", - "user-annotation": "should-be-kept", - }) - obj.SetNamespace("original-ns") - obj.SetName("test-obj") - - candidate := candidateFromOwnerObj("target-ns", obj) - - annotations := candidate.GetAnnotations() - require.Equal(t, "provider-ns", annotations[konnectortypes.ProviderNamespaceAnnotationKey]) - require.Equal(t, "provider-uid", annotations[konnectortypes.ProviderUIDAnnotationKey]) - require.Equal(t, "consumer-ns", annotations[konnectortypes.ConsumerNamespaceAnnotationKey]) - require.Equal(t, "consumer-uid", annotations[konnectortypes.ConsumerUIDAnnotationKey]) - require.Equal(t, "should-be-kept", annotations["user-annotation"]) - _, hasKcp := annotations["kcp.io/cluster"] - require.False(t, hasKcp, "kcp.io/cluster annotation should be stripped") -} diff --git a/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/README.md b/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/README.md deleted file mode 100644 index 960cd02e0..000000000 --- a/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# claimedresourcesnamespaces - -When using claimed resources, it can be situations where resource does not yet exists in the consumer cluster OR -we are operating in cluster scoped mode, and hence no resource namespace is created. In scenarios like this, -`APIServiceNamespace` object is never creates, and hence backend will not create appropriate RBAC for the consumer to be able to -access the resources. - -It will watch same GVR resources, as claimed resources (hence the name of the controller), and will create `APIServiceNamespace` objects, -if object is created in the consumer cluster. - -We can't add this logic into `claimedresource` controller, as it never gets to healthy state until provider has right rbac configured and -consumer can access the resources and hence start the informers. Alternative to this is create `APIServiceNamespace` objects outside reconile -loop, but that would be against the controller pattern. \ No newline at end of file diff --git a/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/claimedresourcesnamespaces_controller.go b/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/claimedresourcesnamespaces_controller.go deleted file mode 100644 index 8cabec8b7..000000000 --- a/pkg/konnector/controllers/cluster/claimedresourcesnamespaces/claimedresourcesnamespaces_controller.go +++ /dev/null @@ -1,309 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 claimedresourcesnamespaces - -import ( - "context" - "fmt" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/informers" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - "github.com/kube-bind/kube-bind/pkg/resources" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclientset "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-claimedresourcesnamespaces" -) - -// NewController returns a new controller ensuring APIServiceNamespaces exist for claimed objects. -func NewController( - gvr schema.GroupVersionResource, - claim kubebindv1alpha2.PermissionClaim, - apiServiceExport *kubebindv1alpha2.APIServiceExport, - providerNamespace string, - providerConfig *rest.Config, - consumerConfig *rest.Config, - consumerDynamicInformer informers.GenericInformer, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], - claimedResourcesEnqueueChan chan<- string, -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName, "gvr", gvr) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - bindClient, err := bindclientset.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - consumerClient, err := dynamicclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - claim: claim, - apiServiceExport: apiServiceExport, - - providerBindClient: bindClient, - consumerClient: consumerClient, - - consumerDynamicInformer: consumerDynamicInformer, - - serviceNamespaceInformer: serviceNamespaceInformer, - - providerNamespace: providerNamespace, - - claimedResourcesEnqueueChan: claimedResourcesEnqueueChan, - } - - // Only watch for ADD events on consumer side to detect when claimed objects are created - if _, err = consumerDynamicInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - c.enqueueConsumer(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -// controller ensures APIServiceNamespaces exist for claimed objects. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - claim kubebindv1alpha2.PermissionClaim - apiServiceExport *kubebindv1alpha2.APIServiceExport - - providerBindClient bindclientset.Interface - consumerClient dynamicclient.Interface - - consumerDynamicInformer informers.GenericInformer - - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - providerNamespace string - - // Channel to notify claimedresources controller when new namespaces are created - // so we don't have to wait for the next resync period. - claimedResourcesEnqueueChan chan<- string -} - -func (c *controller) isClaimed(logger klog.Logger, obj *unstructured.Unstructured, consumerSide bool) bool { - return resources.IsClaimedWithReference( - logger, - obj, - consumerSide, - c.claim, - c.apiServiceExport, - c.consumerClient, - c.serviceNamespaceInformer.Lister().APIServiceNamespaces(c.providerNamespace), - ) -} - -func (c *controller) enqueueConsumer(logger klog.Logger, obj interface{}) { - // handle tombstones - if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { - obj = tombstone.Obj - } - o, ok := obj.(*unstructured.Unstructured) - if !ok { - runtime.HandleError(fmt.Errorf("unexpected type %T in enqueueConsumer", obj)) - return - } - if !c.isClaimed(logger, o, true) { - return - } - - ns := o.GetNamespace() - if ns == "" { - return // cluster-scoped objects don't need namespaces - } - - logger.V(2).Info("checking APIServiceNamespace for claimed object", "namespace", ns, "object", o.GetName()) - - // Check if APIServiceNamespace already exists - _, err := c.serviceNamespaceInformer.Lister().APIServiceNamespaces(c.providerNamespace).Get(ns) - if err != nil { - if errors.IsNotFound(err) { - // No namespace - queue ServiceNamespace creation - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - logger.V(2).Info("queueing ServiceNamespace creation", "key", key) - c.queue.Add(key) - return - } - runtime.HandleError(fmt.Errorf("failed to get APIServiceNamespace %q: %w", ns, err)) - return - } - // APIServiceNamespace already exists, nothing to do -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - ns, _, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil - } - if ns == "" { - return nil // we only handle namespaced objects - } - - created, err := c.ensureServiceNamespace(ctx, ns) - if err != nil { - return err - } - if created { - // Notify claimedresources controller that a new namespace was created - select { - case c.claimedResourcesEnqueueChan <- key: - default: - // Don't block if the channel is full - } - } - return nil -} - -func (c *controller) createServiceNamespace(ctx context.Context, sns *kubebindv1alpha2.APIServiceNamespace) (*kubebindv1alpha2.APIServiceNamespace, error) { - return c.providerBindClient.KubeBindV1alpha2().APIServiceNamespaces(sns.Namespace).Create(ctx, sns, metav1.CreateOptions{}) -} - -// ensureServiceNamespace ensures that the APIServiceNamespace for the given object namespace exists. -func (c *controller) ensureServiceNamespace(ctx context.Context, ns string) (created bool, err error) { - logger := klog.FromContext(ctx).WithValues("namespace", ns) - logger.Info("ensuring APIServiceNamespace exists", "providerNamespace", c.providerNamespace, "namespace", ns) - - _, err = c.serviceNamespaceInformer.Lister().APIServiceNamespaces(c.providerNamespace).Get(ns) - if err == nil { - logger.V(2).Info("APIServiceNamespace already exists") - return false, nil // already exists - } - if !errors.IsNotFound(err) { - return false, err - } - - logger.Info("creating APIServiceNamespace") - _, err = c.createServiceNamespace(ctx, &kubebindv1alpha2.APIServiceNamespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: ns, - Namespace: c.providerNamespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(c.apiServiceExport, kubebindv1alpha2.SchemeGroupVersion.WithKind("APIServiceExport")), - }, - }, - }) - if err != nil && !errors.IsAlreadyExists(err) { - return false, fmt.Errorf("failed to create APIServiceNamespace %q: %w", ns, err) - } - - // Wait until the servicenamespace status has been updated. - // As this controller does not do anything else, we are ok to block here. - err = wait.PollUntilContextCancel(ctx, 500*time.Millisecond, true, func(ctx context.Context) (done bool, err error) { - sns, err := c.serviceNamespaceInformer.Lister().APIServiceNamespaces(c.providerNamespace).Get(ns) - if err != nil { - if errors.IsNotFound(err) { - return false, nil // keep polling - } - return false, err - } - if sns.Status.Namespace != "" { - return true, nil - } - return false, nil - }) - if err != nil { - return false, fmt.Errorf("failed to wait for APIServiceNamespace %q to be ready: %w", ns, err) - } - - logger.Info("APIServiceNamespace created successfully") - return true, nil -} diff --git a/pkg/konnector/controllers/cluster/cluster_controller.go b/pkg/konnector/controllers/cluster/cluster_controller.go deleted file mode 100644 index 64ce6b600..000000000 --- a/pkg/konnector/controllers/cluster/cluster_controller.go +++ /dev/null @@ -1,280 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 cluster - -import ( - "context" - "fmt" - "reflect" - "time" - - crdlisters "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubernetesinformers "k8s.io/client-go/informers" - kubernetesclient "k8s.io/client-go/kubernetes" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/clusterbinding" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/namespacelifecycle" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/servicebinding" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-cluster" - - heartbeatInterval = 5 * time.Minute // TODO: make configurable -) - -// NewController returns a new controller handling one cluster connection. -func NewController( - consumerSecretRefKey string, - providerNamespace string, - reconcileServiceBinding func(binding *kubebindv1alpha2.APIServiceBinding) bool, - consumerConfig, providerConfig *rest.Config, - namespaceInformer dynamic.Informer[corelisters.NamespaceLister], - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister], - crdInformer dynamic.Informer[crdlisters.CustomResourceDefinitionLister], -) (*controller, error) { - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - // create shared informer factories - providerBindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - providerKubeClient, err := kubernetesclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - consumerBindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - consumerKubeClient, err := kubernetesclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - providerBindInformers := bindinformers.NewSharedInformerFactoryWithOptions(providerBindClient, time.Minute*30, bindinformers.WithNamespace(providerNamespace)) - providerKubeInformers := kubernetesinformers.NewSharedInformerFactoryWithOptions(providerKubeClient, time.Minute*30, kubernetesinformers.WithNamespace(providerNamespace)) - consumerSecretNS, consumeSecretName, err := cache.SplitMetaNamespaceKey(consumerSecretRefKey) - if err != nil { - return nil, err - } - consumerSecretInformers := kubernetesinformers.NewSharedInformerFactoryWithOptions(consumerKubeClient, time.Minute*30, - kubernetesinformers.WithNamespace(consumerSecretNS), - kubernetesinformers.WithTweakListOptions(func(options *metav1.ListOptions) { - options.FieldSelector = fmt.Sprintf("metadata.name=%s", consumeSecretName) - }), - ) - - // create controllers - clusterbindingCtrl, err := clusterbinding.NewController( - consumerSecretRefKey, - providerNamespace, - heartbeatInterval, - consumerConfig, - providerConfig, - providerBindInformers.KubeBind().V1alpha2().ClusterBindings(), - serviceBindingInformer, - providerBindInformers.KubeBind().V1alpha2().APIServiceExports(), - consumerSecretInformers.Core().V1().Secrets(), - providerKubeInformers.Core().V1().Secrets(), - ) - if err != nil { - return nil, err - } - namespacelifecycleCtrl, err := namespacelifecycle.NewController( - providerConfig, - consumerConfig, - providerNamespace, - providerBindInformers.KubeBind().V1alpha2().APIServiceNamespaces(), - namespaceInformer, - ) - if err != nil { - return nil, err - } - servicebindingCtrl, err := servicebinding.NewController( - consumerSecretRefKey, - providerNamespace, - reconcileServiceBinding, - consumerConfig, - providerConfig, - serviceBindingInformer, - providerBindInformers.KubeBind().V1alpha2().APIServiceExports(), - providerBindInformers.KubeBind().V1alpha2().APIServiceExportRequests(), - crdInformer, - ) - if err != nil { - return nil, err - } - serviceexportCtrl, err := serviceexport.NewController( - consumerSecretRefKey, - providerNamespace, - consumerConfig, - providerConfig, - providerBindInformers.KubeBind().V1alpha2().APIServiceExports(), - providerBindInformers.KubeBind().V1alpha2().APIServiceNamespaces(), - serviceBindingInformer, - crdInformer, - ) - if err != nil { - return nil, err - } - - return &controller{ - consumerSecretRefKey: consumerSecretRefKey, - - bindClient: consumerBindClient, - - factories: []SharedInformerFactory{ - providerBindInformers, - providerKubeInformers, - consumerSecretInformers, - }, - - serviceBindingLister: serviceBindingInformer.Lister(), - serviceBindingIndexer: serviceBindingInformer.Informer().GetIndexer(), - - clusterbindingCtrl: clusterbindingCtrl, - namespacelifecycleCtrl: namespacelifecycleCtrl, - servicebindingCtrl: servicebindingCtrl, - serviceresourcebindingCtrl: serviceexportCtrl, - }, nil -} - -type GenericController interface { - Start(ctx context.Context, numThreads int) -} - -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool -} - -// controller holding all controller that are per provider cluster. -type controller struct { - consumerSecretRefKey string - - bindClient bindclient.Interface - - serviceBindingLister bindlisters.APIServiceBindingLister - serviceBindingIndexer cache.Indexer - - factories []SharedInformerFactory - - clusterbindingCtrl GenericController - namespacelifecycleCtrl GenericController - servicebindingCtrl GenericController - serviceresourcebindingCtrl GenericController -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context) { - logger := klog.FromContext(ctx).WithValues("controller", controllerName, "accessSecretKey", c.consumerSecretRefKey) - ctx = klog.NewContext(ctx, logger) - - logger.V(2).Info("starting factories") - for _, factory := range c.factories { - factory.Start(ctx.Done()) - } - - if err := wait.PollUntilContextCancel(ctx, heartbeatInterval, true, func(ctx context.Context) (bool, error) { - waitCtx, cancel := context.WithDeadline(ctx, time.Now().Add(heartbeatInterval/2)) - defer cancel() - - logger.V(2).Info("waiting for cache sync") - for _, factory := range c.factories { - synced := factory.WaitForCacheSync(waitCtx.Done()) - logger.V(2).Info("cache sync", "synced", synced) - } - select { - case <-ctx.Done(): - // timeout - logger.Info("informers did not sync in time", "timeout", heartbeatInterval/2) - c.updateServiceBindings(ctx, func(binding *kubebindv1alpha2.APIServiceBinding) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionInformersSynced, - "InformerSyncTimeout", - conditionsapi.ConditionSeverityError, - "Informers did not sync within %s", - heartbeatInterval/2, - ) - }) - - return false, nil - default: - return true, nil - } - }); err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("setting InformersSynced condition to true on service binding") - c.updateServiceBindings(ctx, func(binding *kubebindv1alpha2.APIServiceBinding) { - conditions.MarkTrue(binding, kubebindv1alpha2.APIServiceBindingConditionInformersSynced) - }) - - go c.clusterbindingCtrl.Start(ctx, 2) - go c.namespacelifecycleCtrl.Start(ctx, 2) - go c.servicebindingCtrl.Start(ctx, 2) - go c.serviceresourcebindingCtrl.Start(ctx, 2) - - <-ctx.Done() -} - -func (c *controller) updateServiceBindings(ctx context.Context, update func(*kubebindv1alpha2.APIServiceBinding)) { - logger := klog.FromContext(ctx) - - objs, err := c.serviceBindingIndexer.ByIndex(indexers.ByServiceBindingKubeconfigSecret, c.consumerSecretRefKey) - if err != nil { - logger.Error(err, "failed to list service bindings", "accessSecretKey", c.consumerSecretRefKey) - return - } - for _, obj := range objs { - binding := obj.(*kubebindv1alpha2.APIServiceBinding) - orig := binding - binding = binding.DeepCopy() - update(binding) - if !reflect.DeepEqual(binding.Status.Conditions, orig.Status.Conditions) { - logger.V(2).Info("updating service binding", "binding", binding.Name) - if _, err := c.bindClient.KubeBindV1alpha2().APIServiceBindings().UpdateStatus(ctx, binding, metav1.UpdateOptions{}); err != nil { - logger.Error(err, "failed to update service binding", "binding", binding.Name) - continue - } - } - } -} diff --git a/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_controller.go b/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_controller.go deleted file mode 100644 index 5bf4dc921..000000000 --- a/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_controller.go +++ /dev/null @@ -1,451 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 clusterbinding - -import ( - "context" - "fmt" - "reflect" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - coreinformers "k8s.io/client-go/informers/core/v1" - kubernetesclient "k8s.io/client-go/kubernetes" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-clusterbinding" -) - -// NewController returns a new controller for ClusterBindings. -func NewController( - consumerSecretRefKey string, - providerNamespace string, - heartbeatInterval time.Duration, - consumerConfig, providerConfig *rest.Config, - clusterBindingInformer bindinformers.ClusterBindingInformer, - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister], - serviceExportInformer bindinformers.APIServiceExportInformer, - consumerSecretInformer, providerSecretInformer coreinformers.SecretInformer, -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - providerBindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - providerKubeClient, err := kubernetesclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - consumerBindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - consumerKubeClient, err := kubernetesclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - - providerBindClient: providerBindClient, - providerKubeClient: providerKubeClient, - consumerBindClient: consumerBindClient, - consumerKubeClient: consumerKubeClient, - - clusterBindingLister: clusterBindingInformer.Lister(), - clusterBindingIndexer: clusterBindingInformer.Informer().GetIndexer(), - - serviceBindingInformer: serviceBindingInformer, - - serviceExportLister: serviceExportInformer.Lister(), - serviceExportIndexer: serviceExportInformer.Informer().GetIndexer(), - - consumerSecretLister: consumerSecretInformer.Lister(), - providerSecretLister: providerSecretInformer.Lister(), - - reconciler: reconciler{ - consumerSecretRefKey: consumerSecretRefKey, - providerNamespace: providerNamespace, - heartbeatInterval: heartbeatInterval, - - getProviderSecret: func() (*corev1.Secret, error) { - cb, err := clusterBindingInformer.Lister().ClusterBindings(providerNamespace).Get("cluster") - if err != nil { - return nil, err - } - ref := &cb.Spec.KubeconfigSecretRef - return providerSecretInformer.Lister().Secrets(providerNamespace).Get(ref.Name) - }, - getConsumerSecret: func() (*corev1.Secret, error) { - ns, name, err := cache.SplitMetaNamespaceKey(consumerSecretRefKey) - if err != nil { - return nil, err - } - return consumerSecretInformer.Lister().Secrets(ns).Get(name) - }, - createConsumerSecret: func(ctx context.Context, secret *corev1.Secret) (*corev1.Secret, error) { - return consumerKubeClient.CoreV1().Secrets(secret.Namespace).Create(ctx, secret, metav1.CreateOptions{}) - }, - updateConsumerSecret: func(ctx context.Context, secret *corev1.Secret) (*corev1.Secret, error) { - return consumerKubeClient.CoreV1().Secrets(secret.Namespace).Update(ctx, secret, metav1.UpdateOptions{}) - }, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.ClusterBinding, *kubebindv1alpha2.ClusterBindingSpec, *kubebindv1alpha2.ClusterBindingStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.ClusterBinding] { - return providerBindClient.KubeBindV1alpha2().ClusterBindings(ns) - }, - ), - } - - if _, err := clusterBindingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueClusterBinding(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueClusterBinding(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueClusterBinding(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := providerSecretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueProviderSecret(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueProviderSecret(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueProviderSecret(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := consumerSecretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueConsumerSecret(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := serviceExportInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - UpdateFunc: func(old, newObj any) { - oldExport, ok := old.(*kubebindv1alpha2.APIServiceExport) - if !ok { - return - } - newExport, ok := old.(*kubebindv1alpha2.APIServiceExport) - if !ok { - return - } - if reflect.DeepEqual(oldExport.Status.Conditions, newExport.Status.Conditions) { - return - } - c.enqueueServiceExport(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.ClusterBindingSpec, *kubebindv1alpha2.ClusterBindingStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -// controller reconciles ClusterBindings on the service provider cluster, including heartbeating. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - providerBindClient bindclient.Interface - providerKubeClient kubernetesclient.Interface - consumerBindClient bindclient.Interface - consumerKubeClient kubernetesclient.Interface - - clusterBindingLister bindlisters.ClusterBindingLister - clusterBindingIndexer cache.Indexer - - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister] - - serviceExportLister bindlisters.APIServiceExportLister - serviceExportIndexer cache.Indexer - - consumerSecretLister corelisters.SecretLister - providerSecretLister corelisters.SecretLister - - reconciler - - commit CommitFunc -} - -func (c *controller) enqueueClusterBinding(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing ClusterBinding", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueConsumerSecret(logger klog.Logger, obj any) { - secretKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - if secretKey == c.consumerSecretRefKey { - key := c.providerNamespace + "/cluster" - logger.V(2).Info("queueing ClusterBinding", "key", key, "reason", "ConsumerSecret", "accessSecretKey", secretKey) - c.queue.Add(key) - } -} - -func (c *controller) enqueueProviderSecret(logger klog.Logger, obj any) { - secretKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(secretKey) - if err != nil { - runtime.HandleError(err) - return - } - - if ns != c.providerNamespace { - return // not our secret - } - - binding, err := c.clusterBindingLister.ClusterBindings(ns).Get("cluster") - if err != nil && !errors.IsNotFound(err) { - runtime.HandleError(err) - return - } else if errors.IsNotFound(err) { - return // skip this secret - } - if binding.Spec.KubeconfigSecretRef.Name != name { - return // skip this secret - } - - key := ns + "/cluster" - logger.V(2).Info("queueing ClusterBinding", "key", key, "reason", "Secret", "accessSecretKey", secretKey) - c.queue.Add(key) -} - -func (c *controller) enqueueServiceExport(logger klog.Logger, obj any) { - seKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, _, err := cache.SplitMetaNamespaceKey(seKey) - if err != nil { - runtime.HandleError(err) - return - } - - key := ns + "/cluster" - logger.V(2).Info("queueing ClusterBinding", "key", key, "reason", "APIServiceExport", "ServiceExportKey", seKey) - c.queue.Add(key) -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - // start the heartbeat - //nolint:errcheck - wait.PollUntilContextCancel(ctx, c.heartbeatInterval/2, false, func(ctx context.Context) (bool, error) { - c.queue.Add(c.providerNamespace + "/cluster") - return false, nil - }) - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - if name != "cluster" { - return nil // cannot happen by OpenAPI validation - } - - logger := klog.FromContext(ctx) - - obj, err := c.clusterBindingLister.ClusterBindings(ns).Get("cluster") - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.Error(err, "ClusterBinding disappeared") - return nil - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - - // try to update service bindings - c.updateServiceBindings(ctx, func(binding *kubebindv1alpha2.APIServiceBinding) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionHeartbeating, - "ClusterBindingUpdateFailed", - conditionsapi.ConditionSeverityWarning, - "Failed to update service provider ClusterBinding: %v", err, - ) - }) - } else { - // try to update service bindings - c.updateServiceBindings(ctx, func(binding *kubebindv1alpha2.APIServiceBinding) { - conditions.MarkTrue(binding, kubebindv1alpha2.APIServiceBindingConditionHeartbeating) - }) - } - - return utilerrors.NewAggregate(errs) -} - -func (c *controller) updateServiceBindings(ctx context.Context, update func(*kubebindv1alpha2.APIServiceBinding)) { - logger := klog.FromContext(ctx) - - objs, err := c.serviceBindingInformer.Informer().GetIndexer().ByIndex(indexers.ByServiceBindingKubeconfigSecret, c.consumerSecretRefKey) - if err != nil { - logger.Error(err, "failed to list service bindings", "accessSecretKey", c.consumerSecretRefKey) - return - } - for _, obj := range objs { - binding := obj.(*kubebindv1alpha2.APIServiceBinding) - orig := binding - binding = binding.DeepCopy() - update(binding) - if !reflect.DeepEqual(binding.Status.Conditions, orig.Status.Conditions) { - logger.V(2).Info("updating service binding", "binding", binding.Name) - if _, err := c.consumerBindClient.KubeBindV1alpha2().APIServiceBindings().UpdateStatus(ctx, binding, metav1.UpdateOptions{}); err != nil { - logger.Error(err, "failed to update service binding", "binding", binding.Name) - continue - } - } - } -} diff --git a/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_reconcile.go b/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_reconcile.go deleted file mode 100644 index 48192c43a..000000000 --- a/pkg/konnector/controllers/cluster/clusterbinding/clusterbinding_reconcile.go +++ /dev/null @@ -1,199 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 clusterbinding - -import ( - "context" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/client-go/tools/cache" - componentbaseversion "k8s.io/component-base/version" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/version" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct { - // consumerSecretRefKey is the namespace/name value of the APIServiceBinding kubeconfig secret reference. - consumerSecretRefKey string - providerNamespace string - heartbeatInterval time.Duration - - getProviderSecret func() (*corev1.Secret, error) - getConsumerSecret func() (*corev1.Secret, error) - updateConsumerSecret func(ctx context.Context, secret *corev1.Secret) (*corev1.Secret, error) - createConsumerSecret func(ctx context.Context, secret *corev1.Secret) (*corev1.Secret, error) -} - -func (r *reconciler) reconcile(ctx context.Context, binding *kubebindv1alpha2.ClusterBinding) error { - var errs []error - - if err := r.ensureConsumerSecret(ctx, binding); err != nil { - errs = append(errs, err) - } - - // Must run after ensureConsumerSecret to update the condition based on the provider secret and to set the consumer secret ref in status. - if err := r.ensureConsumerSecretRef(ctx, binding); err != nil { - errs = append(errs, err) - } - - if err := r.ensureHeartbeat(ctx, binding); err != nil { - errs = append(errs, err) - } - - if err := r.ensureKonnectorVersion(ctx, binding); err != nil { - errs = append(errs, err) - } - - conditions.SetSummary(binding) - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureHeartbeat(_ context.Context, binding *kubebindv1alpha2.ClusterBinding) error { - binding.Status.HeartbeatInterval.Duration = r.heartbeatInterval - if now := time.Now(); binding.Status.LastHeartbeatTime.IsZero() || now.After(binding.Status.LastHeartbeatTime.Add(r.heartbeatInterval/2)) { - binding.Status.LastHeartbeatTime.Time = now - } - - return nil -} - -func (r *reconciler) ensureConsumerSecretRef(_ context.Context, binding *kubebindv1alpha2.ClusterBinding) error { - consumerSecret, err := r.getConsumerSecret() - if err != nil && !errors.IsNotFound(err) { - return err - } - - if consumerSecret != nil { - binding.Status.ConsumerSecretRef = &kubebindv1alpha2.LocalSecretRef{ - Name: consumerSecret.Name, - Namespace: consumerSecret.Namespace, - } - } - - return nil -} - -func (r *reconciler) ensureConsumerSecret(ctx context.Context, binding *kubebindv1alpha2.ClusterBinding) error { - logger := klog.FromContext(ctx) - - providerSecret, err := r.getProviderSecret() - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.ClusterBindingConditionSecretValid, - "ProviderSecretNotFound", - conditionsapi.ConditionSeverityWarning, - "Provider secret %s/%s not found", - binding.Namespace, binding.Spec.KubeconfigSecretRef.Name, - ) - return nil - } - - if _, found := providerSecret.Data[binding.Spec.KubeconfigSecretRef.Key]; !found { - conditions.MarkFalse( - binding, - kubebindv1alpha2.ClusterBindingConditionSecretValid, - "ProviderSecretInvalid", - conditionsapi.ConditionSeverityWarning, - "Provider secret %s/%s is missing %q string key.", - r.providerNamespace, - binding.Spec.KubeconfigSecretRef.Name, - binding.Spec.KubeconfigSecretRef.Key, - ) - return nil - } - - consumerSecret, err := r.getConsumerSecret() - if err != nil && !errors.IsNotFound(err) { - return err - } - - if consumerSecret == nil { - ns, name, err := cache.SplitMetaNamespaceKey(r.consumerSecretRefKey) - if err != nil { - return err - } - consumerSecret := corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: ns, - Namespace: name, - }, - Data: providerSecret.Data, - Type: providerSecret.Type, - } - logger.V(2).Info("Creating consumer secret", "namespace", ns, "name", name) - if _, err := r.createConsumerSecret(ctx, &consumerSecret); err != nil { - return err - } - } else { - consumerSecret.Data = providerSecret.Data - consumerSecret.Type = providerSecret.Type - - logger.V(2).Info("Updating consumer secret", "namespace", consumerSecret.Namespace, "name", consumerSecret.Name) - if _, err := r.updateConsumerSecret(ctx, consumerSecret); err != nil { - return err - } - - // TODO: create events - } - - conditions.MarkTrue( - binding, - kubebindv1alpha2.ClusterBindingConditionSecretValid, - ) - - return nil -} - -func (r *reconciler) ensureKonnectorVersion(_ context.Context, binding *kubebindv1alpha2.ClusterBinding) error { - gitVersion := componentbaseversion.Get().GitVersion - ver, err := version.BinaryVersion(gitVersion) - if err != nil { - binding.Status.KonnectorVersion = "unknown" - - conditions.MarkFalse( - binding, - kubebindv1alpha2.ClusterBindingConditionValidVersion, - "ParseError", - conditionsapi.ConditionSeverityWarning, - "Konnector binary version string %q cannot be parsed: %v", - componentbaseversion.Get().GitVersion, - err, - ) - return nil - } - - binding.Status.KonnectorVersion = ver - - conditions.MarkTrue( - binding, - kubebindv1alpha2.ClusterBindingConditionValidVersion, - ) - - return nil -} diff --git a/pkg/konnector/controllers/cluster/namespacelifecycle/namespacelifecycle_controller.go b/pkg/konnector/controllers/cluster/namespacelifecycle/namespacelifecycle_controller.go deleted file mode 100644 index f0b7090ab..000000000 --- a/pkg/konnector/controllers/cluster/namespacelifecycle/namespacelifecycle_controller.go +++ /dev/null @@ -1,297 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 namespacelifecycle - -import ( - "context" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - kubernetesclient "k8s.io/client-go/kubernetes" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-namespacelifecycle" -) - -// NewController returns a new controller lifecycle for ServiceNamespaces and Namespaces. -func NewController( - providerConfig *rest.Config, - consumerConfig *rest.Config, - providerNamespace string, - serviceNamespaceInformer bindinformers.APIServiceNamespaceInformer, - namespaceInformer dynamic.Informer[corelisters.NamespaceLister], -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - bindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - consumerKubeClient, err := kubernetesclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - - providerBindClient: bindClient, - consumerKubeClient: consumerKubeClient, - - serviceNamespaceLister: serviceNamespaceInformer.Lister(), - serviceNamespaceIndexer: serviceNamespaceInformer.Informer().GetIndexer(), - - namespaceInformer: namespaceInformer, - - providerNamespace: providerNamespace, - - getNamespace: namespaceInformer.Lister().Get, - - getServiceNamespace: func(ns, name string) (*kubebindv1alpha2.APIServiceNamespace, error) { - return serviceNamespaceInformer.Lister().APIServiceNamespaces(ns).Get(name) - }, - deleteServiceNamespace: func(ctx context.Context, ns, name string) error { - return bindClient.KubeBindV1alpha2().APIServiceNamespaces(ns).Delete(ctx, name, metav1.DeleteOptions{}) - }, - } - - if _, err := serviceNamespaceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceNamespace(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -// controller reconciles ServiceNamespaces by creating a Namespace for each, and deleting it if -// the APIServiceNamespace is deleted. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - providerBindClient bindclient.Interface - consumerKubeClient kubernetesclient.Interface - - namespaceInformer dynamic.Informer[corelisters.NamespaceLister] - - providerNamespace string - - serviceNamespaceLister bindlisters.APIServiceNamespaceLister - serviceNamespaceIndexer cache.Indexer - - getNamespace func(name string) (*corev1.Namespace, error) - getServiceNamespace func(ns, name string) (*kubebindv1alpha2.APIServiceNamespace, error) - deleteServiceNamespace func(ctx context.Context, ns, name string) error -} - -func (c *controller) enqueueServiceNamespace(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceNamespace", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueNamespace(logger klog.Logger, obj any) { - nsKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - key := fmt.Sprintf("%s/%s", c.providerNamespace, nsKey) - logger.V(2).Info("queueing APIServiceNamespace", "key", key, "reason", "Namespace", "NamespaceKey", nsKey) - c.queue.Add(key) -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - c.namespaceInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueNamespace(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueNamespace(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueNamespace(logger, obj) - }, - }) - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - snsNamespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - if current, err := c.getServiceNamespace(snsNamespace, name); errors.IsNotFound(err) { - return c.handleNamespaceDeletion(ctx, snsNamespace, name) - } else if err != nil { - return err - } else { - return c.handleNamespaceLifecycle(ctx, current) - } -} - -// handleNamespaceDeletion ensures that when an APIServiceNamespace is deleted, -// the corresponding Namespace is also deleted, does not matter who owns it. -func (c *controller) handleNamespaceDeletion(ctx context.Context, snsNamespace, name string) error { - logger := klog.FromContext(ctx).WithValues("APIServiceNamespace", fmt.Sprintf("%s/%s", snsNamespace, name)) - logger.Info("handling deletion of APIServiceNamespace") - - _, err := c.getNamespace(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - // Namespace already deleted, lets check who owns - return nil - } - // We should not delete namespaces in this case as we can't be sure who owns it. - // This might leave hanging namespaces, but it's safer than deleting something we don't own. - logger.Info("not deleting Namespace as we can't be sure who owns it") - return nil -} - -func (c *controller) handleNamespaceLifecycle(ctx context.Context, current *kubebindv1alpha2.APIServiceNamespace) error { - logger := klog.FromContext(ctx).WithValues("APIServiceNamespace", fmt.Sprintf("%s/%s", current.Namespace, current.Name)) - logger.Info("handling creation of APIServiceNamespace") - - // At this point we know that the APIServiceNamespace exists, and we need to see who owns it and - // act accordingly. - // If provider owned, ensure Namespace exists. If consumer owned, and local namespace exists, delete it. - consumerOwned := isConsumerOwned(current) - - if consumerOwned { - // Consumer owned, ensure Namespace is deleted if exists - _, err := c.getNamespace(current.Name) - if errors.IsNotFound(err) { - // No local namespace - delete APIServiceNamespace if exists. - return c.deleteServiceNamespace(ctx, current.Namespace, current.Name) - } else if err != nil { - return err - } - } else { - _, err := c.getNamespace(current.Name) - if errors.IsNotFound(err) { - ns := &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: current.Name, - Labels: map[string]string{ - kubebindv1alpha2.ObjectOwnerLabel: kubebindv1alpha2.OwnerProvider.String(), - }, - }, - } - if _, err := c.consumerKubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}); err != nil { - return err - } - logger.Info("created Namespace for APIServiceNamespace") - return nil - } else if err != nil { - return err - } - } - return nil -} - -// isConsumerOwned checks if the APIServiceNamespace is owned by consumer. -// to prevent the controller from creating namespaces unless explicitly requested). -func isConsumerOwned(sns *kubebindv1alpha2.APIServiceNamespace) bool { - return sns.Labels[kubebindv1alpha2.ObjectOwnerLabel] != kubebindv1alpha2.OwnerProvider.String() -} diff --git a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_controller.go b/pkg/konnector/controllers/cluster/servicebinding/servicebinding_controller.go deleted file mode 100644 index 7777fa8cd..000000000 --- a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_controller.go +++ /dev/null @@ -1,332 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicebinding - -import ( - "context" - "fmt" - "time" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - apiextensionslisters "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-cluster-servicebinding" -) - -// NewController returns a new controller for ServiceBindings. -func NewController( - consumerSecretRefKey, providerNamespace string, - reconcileServiceBinding func(binding *kubebindv1alpha2.APIServiceBinding) bool, - consumerConfig, providerConfig *rest.Config, - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister], - serviceExportInformer bindinformers.APIServiceExportInformer, - serviceExportRequestInformer bindinformers.APIServiceExportRequestInformer, - crdInformer dynamic.Informer[apiextensionslisters.CustomResourceDefinitionLister], -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - consumerBindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - consumerAPIExtensionsClient, err := apiextensionsclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - providerBindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - - serviceBindingInformer: serviceBindingInformer, - - serviceExportLister: serviceExportInformer.Lister(), - serviceExportIndexer: serviceExportInformer.Informer().GetIndexer(), - - crdInformer: crdInformer, - - reconciler: reconciler{ - consumerSecretRefKey: consumerSecretRefKey, - providerNamespace: providerNamespace, - reconcileServiceBinding: reconcileServiceBinding, - - getServiceExport: func(name string) (*kubebindv1alpha2.APIServiceExport, error) { - return serviceExportInformer.Lister().APIServiceExports(providerNamespace).Get(name) - }, - getServiceExportRequest: func(name string) (*kubebindv1alpha2.APIServiceExportRequest, error) { - return serviceExportRequestInformer.Lister().APIServiceExportRequests(providerNamespace).Get(name) - }, - getServiceBinding: func(name string) (*kubebindv1alpha2.APIServiceBinding, error) { - return serviceBindingInformer.Lister().Get(name) - }, - getClusterBinding: func(ctx context.Context) (*kubebindv1alpha2.ClusterBinding, error) { - return providerBindClient.KubeBindV1alpha2().ClusterBindings(providerNamespace).Get(ctx, "cluster", metav1.GetOptions{}) - }, - getBoundSchema: func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) { - return providerBindClient.KubeBindV1alpha2().BoundSchemas(providerNamespace).Get(ctx, name, metav1.GetOptions{}) - }, - updateServiceExportStatus: func(ctx context.Context, export *kubebindv1alpha2.APIServiceExport) (*kubebindv1alpha2.APIServiceExport, error) { - return providerBindClient.KubeBindV1alpha2().APIServiceExports(providerNamespace).UpdateStatus(ctx, export, metav1.UpdateOptions{}) - }, - getCRD: func(name string) (*apiextensionsv1.CustomResourceDefinition, error) { - return crdInformer.Lister().Get(name) - }, - updateCRD: func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) { - return consumerAPIExtensionsClient.ApiextensionsV1().CustomResourceDefinitions().Update(ctx, crd, metav1.UpdateOptions{}) - }, - createCRD: func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) { - return consumerAPIExtensionsClient.ApiextensionsV1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{}) - }, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.APIServiceBinding, *kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.APIServiceBinding] { - return consumerBindClient.KubeBindV1alpha2().APIServiceBindings() - }, - ), - } - - indexers.AddIfNotPresentOrDie(serviceExportInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ServiceExportByCustomResourceDefinition: indexers.IndexServiceExportByCustomResourceDefinition, - }) - - if _, err := serviceExportInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceExport(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -// controller reconciles ServiceBindings with there ServiceExports counterparts. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister] - - serviceExportLister bindlisters.APIServiceExportLister - serviceExportIndexer cache.Indexer - - crdInformer dynamic.Informer[apiextensionslisters.CustomResourceDefinitionLister] - - reconciler - - commit CommitFunc -} - -func (c *controller) enqueueServiceBinding(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceBinding", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueServiceExport(logger klog.Logger, _ any) { - bindings, err := c.serviceBindingInformer.Informer().GetIndexer().ByIndex(indexers.ByServiceBindingKubeconfigSecret, c.reconciler.consumerSecretRefKey) - if err != nil { - runtime.HandleError(err) - return - } - - for _, obj := range bindings { - binding := obj.(*kubebindv1alpha2.APIServiceBinding) - key, err := cache.MetaNamespaceKeyFunc(binding) - if err != nil { - runtime.HandleError(err) - return - } - logger.V(2).Info("queueing APIServiceBinding", "key", key, "reason", "APIServiceExport", "ServiceExportKey", c.consumerSecretRefKey) - c.queue.Add(key) - } -} - -func (c *controller) enqueueCRD(logger klog.Logger, obj any) { - name, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - exports, err := c.serviceExportIndexer.ByIndex(indexers.ServiceExportByCustomResourceDefinition, name) - if err != nil { - runtime.HandleError(err) - return - } - for _, obj := range exports { - export := obj.(*kubebindv1alpha2.APIServiceExport) - key := export.Name - logger.V(2).Info("queueing APIServiceBinding", "key", key, "reason", "CustomResourceDefinition", "CustomResourceDefinitionKey", name) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - c.serviceBindingInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceBinding(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - }) - - c.crdInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueCRD(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueCRD(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueCRD(logger, obj) - }, - }) - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - _, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - obj, err := c.serviceBindingInformer.Lister().Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.Error(err, "APIServiceBinding disappeared") - return nil - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} diff --git a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile.go b/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile.go deleted file mode 100644 index 8a842124f..000000000 --- a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile.go +++ /dev/null @@ -1,307 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicebinding - -import ( - "context" - "fmt" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/utils/ptr" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindhelpers "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2/helpers" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct { - consumerSecretRefKey, providerNamespace string - - reconcileServiceBinding func(binding *kubebindv1alpha2.APIServiceBinding) bool - getServiceExport func(name string) (*kubebindv1alpha2.APIServiceExport, error) - getServiceExportRequest func(name string) (*kubebindv1alpha2.APIServiceExportRequest, error) - getServiceBinding func(name string) (*kubebindv1alpha2.APIServiceBinding, error) - getClusterBinding func(ctx context.Context) (*kubebindv1alpha2.ClusterBinding, error) - getBoundSchema func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) - - updateServiceExportStatus func(ctx context.Context, export *kubebindv1alpha2.APIServiceExport) (*kubebindv1alpha2.APIServiceExport, error) - - getCRD func(name string) (*apiextensionsv1.CustomResourceDefinition, error) - updateCRD func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) - createCRD func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) -} - -func (r *reconciler) reconcile(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - var errs []error - - // As konnector is running APIServiceBinding controller for each provider cluster, - // so each controller should skip others provider's APIServiceBinding object - if !r.reconcileServiceBinding(binding) { - return nil - } - - if err := r.ensureValidServiceExport(ctx, binding); err != nil { - errs = append(errs, err) - } - - if err := r.ensureCRDs(ctx, binding); err != nil { - errs = append(errs, err) - } - - if err := r.ensurePrettyName(ctx, binding); err != nil { - errs = append(errs, err) - } - - conditions.SetSummary(binding) - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureValidServiceExport(_ context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - if _, err := r.getServiceExport(binding.Name); err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - // If serviceexport is not found, check if request is not in failed state already: - request, errRequest := r.getServiceExportRequest(binding.Name) - if errRequest == nil && request.Status.Phase == kubebindv1alpha2.APIServiceExportRequestPhaseFailed { - // If request is in failed state, propagate the message to binding status and mark as failed - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "APIServiceExportFailed", - conditionsapi.ConditionSeverityError, - request.Status.TerminalMessage, - binding.Name, - ) - return fmt.Errorf("APIServiceExportRequest %s is in failed state: %s", binding.Name, request.Status.TerminalMessage) - } - - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "APIServiceExportNotFound", - conditionsapi.ConditionSeverityError, - "APIServiceExport %s not found on the service provider cluster. Rerun kubectl bind for repair.", - binding.Name, - ) - return nil - } - - conditions.MarkTrue( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - ) - - return nil -} - -func (r *reconciler) ensureCRDs(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - var errs []error - - exportOriginal, err := r.getServiceExport(binding.Name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "APIServiceExportNotFound", - conditionsapi.ConditionSeverityError, - "APIServiceExport %s not found on the service provider cluster.", - binding.Name, - ) - return nil // nothing we can do here - } - - export := exportOriginal.DeepCopy() - - // Get all BoundSchema objects referenced by the export - schemas, err := r.getSchemasFromExport(ctx, export) - if err != nil { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "BoundSchemaFetchFailed", - conditionsapi.ConditionSeverityError, - "Failed to fetch BoundSchema objects: %s", - err, - ) - // We dont have schema - try again. Might be a race on provider side. - return err - } - - // Process each schema - for _, schema := range schemas { - if err := r.referenceBoundSchema(ctx, binding, schema.Name); err != nil { - errs = append(errs, err) - } - - if err := r.referencePermissionClaims(ctx, binding, export); err != nil { - errs = append(errs, err) - } - - if err := r.ensureCRDsFromBoundSchema(ctx, binding, schema); err != nil { - errs = append(errs, err) - } - } - - // If we processed all schemas without errors, mark the binding as connected - if len(errs) == 0 && !conditions.IsFalse(binding, kubebindv1alpha2.APIServiceBindingConditionConnected) { - conditions.MarkTrue(binding, kubebindv1alpha2.APIServiceBindingConditionConnected) - conditions.MarkTrue(binding, kubebindv1alpha2.APIServiceBindingConditionSchemaInSync) - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) referenceBoundSchema(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding, name string) error { - boundSchema, err := r.getBoundSchema(ctx, name) - if err != nil && !errors.IsNotFound(err) { - return fmt.Errorf("failed to get BoundSchema %s: %w", name, err) - } - - if boundSchema == nil { - return nil - } - - group := boundSchema.Spec.Group - resource := boundSchema.Spec.Names.Plural - - if len(binding.Status.BoundSchemas) > 0 { - for _, ref := range binding.Status.BoundSchemas { - if ref.Group == group && ref.Resource == resource { - return nil - } - } - } - - if binding.Status.BoundSchemas == nil { - binding.Status.BoundSchemas = []kubebindv1alpha2.BoundSchemaReference{} - } - - binding.Status.BoundSchemas = append(binding.Status.BoundSchemas, - kubebindv1alpha2.BoundSchemaReference{ - GroupResource: kubebindv1alpha2.GroupResource{ - Group: group, - Resource: resource, - }, - }) - - return nil -} - -func (r *reconciler) referencePermissionClaims(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding, export *kubebindv1alpha2.APIServiceExport) error { - binding.Status.PermissionClaims = export.Spec.PermissionClaims - return nil -} - -func (r *reconciler) ensureCRDsFromBoundSchema(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding, schema *kubebindv1alpha2.BoundSchema) error { - var errs []error - crd := kubebindhelpers.BoundSchemaToCRD(schema) - - newReference := metav1.OwnerReference{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "APIServiceBinding", - Name: binding.Name, - UID: binding.UID, - Controller: ptr.To(true), - } - crd.OwnerReferences = append(crd.OwnerReferences, newReference) - - existing, err := r.getCRD(crd.Name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - if _, err := r.createCRD(ctx, crd); err != nil && !errors.IsInvalid(err) { - return err - } else if errors.IsInvalid(err) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "CustomResourceDefinitionCreateFailed", - conditionsapi.ConditionSeverityError, - "CustomResourceDefinition %s cannot be created: %s", - crd.Name, err, - ) - return nil - } - - return nil - } - if !kubebindhelpers.IsOwnedByBinding(binding.Name, binding.UID, existing.OwnerReferences) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "ForeignCustomResourceDefinition", - conditionsapi.ConditionSeverityError, - "CustomResourceDefinition %s is not owned by kube-bind.io.", - crd.Name, - ) - return nil - } - - crd.ObjectMeta = existing.ObjectMeta - if _, err := r.updateCRD(ctx, crd); err != nil && !errors.IsInvalid(err) { - return nil - } else if errors.IsInvalid(err) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionConnected, - "CustomResourceDefinitionUpdateFailed", - conditionsapi.ConditionSeverityError, - "CustomResourceDefinition %s cannot be updated: %s", - binding.Name, err, - ) - return nil - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensurePrettyName(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - clusterBinding, err := r.getClusterBinding(ctx) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - binding.Status.ProviderPrettyName = "" - return nil - } - - binding.Status.ProviderPrettyName = clusterBinding.Spec.ProviderPrettyName - - return nil -} - -// getSchemasFromExport will return all schemas, based on export we are dealing with. -func (r *reconciler) getSchemasFromExport(ctx context.Context, export *kubebindv1alpha2.APIServiceExport) ([]*kubebindv1alpha2.BoundSchema, error) { - schemas := make([]*kubebindv1alpha2.BoundSchema, 0, len(export.Spec.Resources)) - - for _, ref := range export.Spec.Resources { - schema, err := r.getBoundSchema(ctx, ref.ResourceGroupName()) - if err != nil { - return nil, fmt.Errorf("failed to get Schema %s: %w", ref.ResourceGroupName(), err) - } - - schemas = append(schemas, schema) - } - - return schemas, nil -} diff --git a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile_test.go b/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile_test.go deleted file mode 100644 index d51cee75e..000000000 --- a/pkg/konnector/controllers/cluster/servicebinding/servicebinding_reconcile_test.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 servicebinding - -import ( - "context" - "testing" - - "github.com/stretchr/testify/require" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -func TestEnsureCRDs(t *testing.T) { - tests := []struct { - name string - bindingName string - getCRD func(name string) (*apiextensionsv1.CustomResourceDefinition, error) - boundSchema *kubebindv1alpha2.BoundSchema - serviceExport *kubebindv1alpha2.APIServiceExport - expectConditions conditionsapi.Conditions - wantErr bool - }{ - { - name: "create-when-crd-missing", - bindingName: "test-binding", - getCRD: func(name string) (*apiextensionsv1.CustomResourceDefinition, error) { - return nil, errors.NewNotFound(apiextensionsv1.SchemeGroupVersion.WithResource("customresourcedefinitions").GroupResource(), name) - }, - boundSchema: newBoundSchema("tests.example.com", "default", "example.com", "tests"), - serviceExport: newServiceExportWithResources("test-binding", "default", []kubebindv1alpha2.APIServiceExportRequestResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "example.com", Resource: "tests"}}, - }), - expectConditions: conditionsapi.Conditions{ - conditionsapi.Condition{Type: "Connected", Status: "True"}, - conditionsapi.Condition{Type: "SchemaInSync", Status: "True"}, - }, - }, - { - name: "fail-when-external-crd-present", - bindingName: "test-binding", - getCRD: newGetCRD("tests.example.com", newCRD("tests.example.com")), - boundSchema: newBoundSchema("tests.example.com", "default", "example.com", "tests"), - serviceExport: newServiceExportWithResources("test-binding", "default", []kubebindv1alpha2.APIServiceExportRequestResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "example.com", Resource: "tests"}}, - }), - expectConditions: conditionsapi.Conditions{ - conditionsapi.Condition{ - Type: "Connected", - Status: "False", - Severity: "Error", - Reason: "ForeignCustomResourceDefinition", - Message: "CustomResourceDefinition tests.example.com is not owned by kube-bind.io.", - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := &reconciler{ - getCRD: tt.getCRD, - getServiceExport: newGetServiceExport(tt.serviceExport.Name, tt.serviceExport), - getBoundSchema: func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) { - if name == tt.boundSchema.Name { - return tt.boundSchema, nil - } - return nil, errors.NewNotFound(kubebindv1alpha2.SchemeGroupVersion.WithResource("boundschemas").GroupResource(), name) - }, - createCRD: func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) { - return crd.DeepCopy(), nil - }, - updateCRD: func(ctx context.Context, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) { - return crd.DeepCopy(), nil - }, - reconcileServiceBinding: func(binding *kubebindv1alpha2.APIServiceBinding) bool { - return true - }, - } - - b := newBinding(tt.bindingName) - err := r.ensureCRDs(context.Background(), b) - require.NoError(t, err) - - for i := range b.Status.Conditions { - b.Status.Conditions[i].LastTransitionTime = metav1.Time{} // this is hard to compare - } - require.Equal(t, tt.expectConditions, b.Status.Conditions) - }) - } -} -func newBoundSchema(name, namespace string, group, plural string) *kubebindv1alpha2.BoundSchema { - return &kubebindv1alpha2.BoundSchema{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: kubebindv1alpha2.BoundSchemaSpec{ - InformerScope: kubebindv1alpha2.NamespacedScope, - APICRDSpec: kubebindv1alpha2.APICRDSpec{ - Group: group, - Names: apiextensionsv1.CustomResourceDefinitionNames{ - Plural: plural, - }, - Scope: apiextensionsv1.NamespaceScoped, - }, - }, - } -} - -func newServiceExportWithResources(name, namespace string, resources []kubebindv1alpha2.APIServiceExportRequestResource) *kubebindv1alpha2.APIServiceExport { - return &kubebindv1alpha2.APIServiceExport{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: kubebindv1alpha2.APIServiceExportSpec{ - Resources: resources, - InformerScope: kubebindv1alpha2.NamespacedScope, - }, - } -} - -func newGetCRD(name string, crd *apiextensionsv1.CustomResourceDefinition) func(name string) (*apiextensionsv1.CustomResourceDefinition, error) { - return func(n string) (*apiextensionsv1.CustomResourceDefinition, error) { - if n == name { - return crd, nil - } - return nil, errors.NewNotFound(apiextensionsv1.SchemeGroupVersion.WithResource("customresourcedefinitions").GroupResource(), "not found") - } -} - -func newCRD(name string) *apiextensionsv1.CustomResourceDefinition { - return &apiextensionsv1.CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - } -} - -func newGetServiceExport(name string, crd *kubebindv1alpha2.APIServiceExport) func(name string) (*kubebindv1alpha2.APIServiceExport, error) { - return func(n string) (*kubebindv1alpha2.APIServiceExport, error) { - if n == name { - return crd, nil - } - return nil, errors.NewNotFound(kubebindv1alpha2.SchemeGroupVersion.WithResource("apiserviceexports").GroupResource(), "not found") - } -} - -func newBinding(name string) *kubebindv1alpha2.APIServiceBinding { - return &kubebindv1alpha2.APIServiceBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - } -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/namespaced.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/namespaced.go deleted file mode 100644 index 11836a866..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/namespaced.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 isolation - -import ( - "context" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" -) - -type namespacedStrategy struct { - clusterNamespace string -} - -// NewNamespaced returns an isolation strategy that transforms cluster-scoped -// objects from the consumer cluster into namespaced objects on the provider -// cluster. All objects will be placed in the cluster namespace. -func NewNamespaced(clusterNamespace string) Strategy { - return &namespacedStrategy{ - clusterNamespace: clusterNamespace, - } -} - -func (s *namespacedStrategy) ToProviderKey(consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return &types.NamespacedName{ - Namespace: s.clusterNamespace, - Name: consumerKey.Name, - }, nil -} - -func (s *namespacedStrategy) EnsureProviderKey(_ context.Context, consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return s.ToProviderKey(consumerKey) -} - -func (s *namespacedStrategy) ToConsumerKey(providerKey types.NamespacedName) (*types.NamespacedName, error) { - if providerKey.Namespace != s.clusterNamespace { - return nil, nil - } - - return &types.NamespacedName{Name: providerKey.Name}, nil -} - -func (s *namespacedStrategy) MutateMetadataAndSpec(consumerObj *unstructured.Unstructured, providerKey types.NamespacedName) error { - consumerObj.SetName(providerKey.Name) - consumerObj.SetNamespace(providerKey.Namespace) - - return nil -} - -func (s *namespacedStrategy) MutateStatus(providerObj *unstructured.Unstructured, consumerKey types.NamespacedName) error { - providerObj.SetName(consumerKey.Name) - providerObj.SetNamespace(consumerKey.Namespace) - - return nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/none.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/none.go deleted file mode 100644 index 4bd046b9a..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/none.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 isolation - -import ( - "context" - "errors" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" -) - -type noneStrategy struct { - clusterNamespace string - clusterNamespaceUID string -} - -// NewNone returns an isolation strategy for cluster-scoped objects that will not -// change anything about their name. Using this strategy will most likely lead to -// naming conflicts between consumers and should only be used with great care. -// Since this strategy will lead to cluster-scoped objects on the provide side, -// it will add an owner reference to each, pointing to the cluster namespace. -func NewNone(clusterNamespace string, clusterNamespaceUID string) Strategy { - return &noneStrategy{ - clusterNamespace: clusterNamespace, - clusterNamespaceUID: clusterNamespaceUID, - } -} - -func (*noneStrategy) ToProviderKey(consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return &consumerKey, nil -} - -func (s *noneStrategy) EnsureProviderKey(_ context.Context, consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return s.ToProviderKey(consumerKey) -} - -func (*noneStrategy) ToConsumerKey(providerKey types.NamespacedName) (*types.NamespacedName, error) { - return &providerKey, nil -} - -func (s *noneStrategy) MutateMetadataAndSpec(consumerObj *unstructured.Unstructured, providerKey types.NamespacedName) error { - return setOwnerReference(consumerObj, s.clusterNamespace, s.clusterNamespaceUID) -} - -func (*noneStrategy) MutateStatus(providerObj *unstructured.Unstructured, consumerKey types.NamespacedName) error { - return nil -} - -func setOwnerReference(obj *unstructured.Unstructured, clusterNamespace string, clusterNamespaceUID string) error { - ownerRefs := obj.GetOwnerReferences() - ownerRef := findOwnerReference(ownerRefs, clusterNamespace) - if ownerRef != nil && ownerRef.Name != clusterNamespace { - return errors.New("mismatch between existing cluster namespace and given cluster namespace") - } - - if ownerRef == nil { - ownerRefs = append(ownerRefs, metav1.OwnerReference{ - APIVersion: "v1", - Kind: "Namespace", - Name: clusterNamespace, - UID: types.UID(clusterNamespaceUID), - }) - obj.SetOwnerReferences(ownerRefs) - } - - return nil -} - -func findOwnerReference(refs []metav1.OwnerReference, clusterNamespace string) *metav1.OwnerReference { - for _, ref := range refs { - if ref.Kind == "Namespace" && ref.Name == clusterNamespace { - return &ref - } - } - - return nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed.go deleted file mode 100644 index 711321547..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 isolation - -import ( - "context" - "strings" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" -) - -type prefixedStrategy struct { - // On a technical level, this is the same as the basic "none" behaviour, just - // with additional name mutation; since we want to re-use the other code for - // cluster-scoped objects *on the provider side*, we extend the none strategy. - noneStrategy - - clusterNamespace string -} - -// NewPrefixed returns an isolation strategy for cluster-scoped objects where each -// object on the provider cluster gets the name of the cluster namespace prepended -// to their name (i.e. turning "my-obj" into "kube-bind-abc123-my-obj"). This is -// effective and easy since no scoping changes need to be accounted for (i.e. the -// BoundSchema does not need to be adjusted), but could theoretically cause problems -// for objects with very long names that do not have enough room for such a prefix. -func NewPrefixed(clusterNamespace string, clusterNamespaceUID string) Strategy { - return &prefixedStrategy{ - noneStrategy: noneStrategy{ - clusterNamespace: clusterNamespace, - clusterNamespaceUID: clusterNamespaceUID, - }, - clusterNamespace: clusterNamespace, - } -} - -func (s *prefixedStrategy) ToProviderKey(consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return &types.NamespacedName{ - Name: s.clusterNamespace + "-" + consumerKey.Name, - }, nil -} - -func (s *prefixedStrategy) EnsureProviderKey(_ context.Context, consumerKey types.NamespacedName) (*types.NamespacedName, error) { - return s.ToProviderKey(consumerKey) -} - -func (s *prefixedStrategy) ToConsumerKey(providerKey types.NamespacedName) (*types.NamespacedName, error) { - prefix := s.clusterNamespace + "-" - if !strings.HasPrefix(providerKey.Name, prefix) { - return nil, nil - } - - return &types.NamespacedName{ - Name: strings.TrimPrefix(providerKey.Name, prefix), - }, nil -} - -func (s *prefixedStrategy) MutateMetadataAndSpec(consumerObj *unstructured.Unstructured, providerKey types.NamespacedName) error { - consumerObj.SetName(providerKey.Name) - consumerObj.SetNamespace(providerKey.Namespace) - - return s.noneStrategy.MutateMetadataAndSpec(consumerObj, providerKey) -} - -func (s *prefixedStrategy) MutateStatus(providerObj *unstructured.Unstructured, consumerKey types.NamespacedName) error { - providerObj.SetName(consumerKey.Name) - providerObj.SetNamespace(consumerKey.Namespace) - - return s.noneStrategy.MutateStatus(providerObj, consumerKey) -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed_test.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed_test.go deleted file mode 100644 index 654e33d7f..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/prefixed_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 isolation - -import ( - "testing" - - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/types" -) - -func TestPrefixedToProviderKey(t *testing.T) { - tests := []struct { - name string - providerNs string - objectName string - expected string - }{ - { - name: "basic testcase", - providerNs: "kube-bind-zlp9m", - objectName: "example-foo", - expected: "kube-bind-zlp9m-example-foo", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - strategy := NewPrefixed(tt.providerNs, "irrelevant-uid") - - result, err := strategy.ToProviderKey(types.NamespacedName{Name: tt.objectName}) - require.NoError(t, err) - require.NotNil(t, result) - require.Equal(t, "", result.Namespace) - require.Equal(t, tt.expected, result.Name) - }) - } -} - -func TestPrefixedToConsumerKey(t *testing.T) { - tests := []struct { - name string - providerNs string - objectName string - expected string - }{ - { - name: "basic testcase", - providerNs: "kube-bind-zlp9m", - objectName: "kube-bind-zlp9m-example-foo", - expected: "example-foo", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - strategy := NewPrefixed(tt.providerNs, "irrelevant-uid") - - result, err := strategy.ToConsumerKey(types.NamespacedName{Name: tt.objectName}) - require.NoError(t, err) - require.NotNil(t, result) - require.Equal(t, "", result.Namespace) - require.Equal(t, tt.expected, result.Name) - }) - } -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/servicenamespaced.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/servicenamespaced.go deleted file mode 100644 index 7099b18ae..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/servicenamespaced.go +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 isolation - -import ( - "context" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -type ServiceNamespacedStrategy struct { - clusterNamespace string - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - serviceNamespaceCreator func(ctx context.Context, name string) (*kubebindv1alpha2.APIServiceNamespace, error) -} - -// NewServiceNamespaced returns the one and only valid isolation strategy for -// namespaced objects. It is special in a sense that it does not map consumer -// namespaces 1:1 to provider namespaces, but uses APIServiceNamespace objects -// to request the backend to assign a namespace on the provider cluster. This -// strategy must not be used for cluster-scoped resources. -func NewServiceNamespaced( - clusterNamespace string, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], - serviceNamespaceCreator func(ctx context.Context, name string) (*kubebindv1alpha2.APIServiceNamespace, error), -) Strategy { - return &ServiceNamespacedStrategy{ - clusterNamespace: clusterNamespace, - serviceNamespaceInformer: serviceNamespaceInformer, - serviceNamespaceCreator: serviceNamespaceCreator, - } -} - -func (s *ServiceNamespacedStrategy) ProviderNamespace(consumerNamespace string) (string, error) { - sn, err := s.serviceNamespaceInformer.Lister().APIServiceNamespaces(s.clusterNamespace).Get(consumerNamespace) - if err != nil { - if !errors.IsNotFound(err) { - return "", err - } - - return "", nil - } - - return sn.Status.Namespace, nil -} - -// ConsumerNamespace returns the namespace on the consumer cluster that owns the -// API namespace on the provider cluster. This function effectively performs a -// reverse lookup using the APIServiceNamespace's status. -// This function can return an empty name if the APIServiceNamespace is not ready yet. -func (s *ServiceNamespacedStrategy) ConsumerNamespace(namespace string) (string, error) { - sns, err := s.serviceNamespaceInformer.Informer().GetIndexer().ByIndex(indexers.ServiceNamespaceByNamespace, namespace) - if err != nil { - return "", err - } - - for _, obj := range sns { - sns := obj.(*kubebindv1alpha2.APIServiceNamespace) - if sns.Namespace == s.clusterNamespace { - return sns.Name, nil - } - } - - return "", nil -} - -func (s *ServiceNamespacedStrategy) ToProviderKey(consumerKey types.NamespacedName) (*types.NamespacedName, error) { - providerNs, err := s.ProviderNamespace(consumerKey.Namespace) - if err != nil { - return nil, err - } - - // not ready yet - if providerNs == "" { - return nil, nil - } - - return &types.NamespacedName{ - Namespace: providerNs, - Name: consumerKey.Name, - }, nil -} - -func (s *ServiceNamespacedStrategy) EnsureProviderKey(ctx context.Context, consumerKey types.NamespacedName) (*types.NamespacedName, error) { - sn, err := s.serviceNamespaceInformer.Lister().APIServiceNamespaces(s.clusterNamespace).Get(consumerKey.Namespace) - if err != nil && !errors.IsNotFound(err) { - return nil, err - } - - logger := klog.FromContext(ctx).WithValues("namespace", consumerKey.Namespace) - - if errors.IsNotFound(err) { - logger.V(1).Info("creating APIServiceNamespace") - sn, err = s.serviceNamespaceCreator(ctx, consumerKey.Namespace) - if err != nil { - return nil, err - } - } - - if sn.Status.Namespace == "" { - // note: the service provider might implement this synchronously in admission. if so, we can skip the requeue. - logger.V(1).Info("waiting for APIServiceNamespace to be ready") - return nil, nil - } - - return &types.NamespacedName{ - Namespace: sn.Status.Namespace, - Name: consumerKey.Name, - }, nil -} - -func (s *ServiceNamespacedStrategy) ToConsumerKey(providerKey types.NamespacedName) (*types.NamespacedName, error) { - consumerNs, err := s.ConsumerNamespace(providerKey.Namespace) - if err != nil { - return nil, err - } - - // not ready yet - if consumerNs == "" { - return nil, nil - } - - return &types.NamespacedName{ - Namespace: consumerNs, - Name: providerKey.Name, - }, nil -} - -func (s *ServiceNamespacedStrategy) MutateMetadataAndSpec(consumerObj *unstructured.Unstructured, providerKey types.NamespacedName) error { - consumerObj.SetName(providerKey.Name) - consumerObj.SetNamespace(providerKey.Namespace) - - return nil -} - -func (s *ServiceNamespacedStrategy) MutateStatus(providerObj *unstructured.Unstructured, consumerKey types.NamespacedName) error { - providerObj.SetName(consumerKey.Name) - providerObj.SetNamespace(consumerKey.Namespace) - - return nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/isolation/strategy.go b/pkg/konnector/controllers/cluster/serviceexport/isolation/strategy.go deleted file mode 100644 index 73e65f2b5..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/isolation/strategy.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 isolation - -import ( - "context" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" -) - -// Strategy implements the namespace/name translation for Kubernetes objects when -// they are copied from one cluster to another. Not every strategy is necessarily -// applicable to all circumstances (strategies can be for cluster-scoped or -// namespaced objects only, check their documentation). -type Strategy interface { - // ToProviderKey translates the namespace/name (collectively called "key") from - // the consumer side to the provider side. This function can return a nil key - // for invalid/foreign objects, so callers need to be aware. - ToProviderKey(consumerKey types.NamespacedName) (*types.NamespacedName, error) - - // ToConsumerKey translates the namespace/name (collectively called "key") from - // the provider side to the consumer side. This function can return a nil key - // for invalid/foreign objects, so callers need to be aware. - ToConsumerKey(providerKey types.NamespacedName) (*types.NamespacedName, error) - - // EnsureProviderKey is very similar to ToProviderKey, but may make changes - // on the provider side and return a nil key in case the target key is simply - // not ready yet. This is most often the case when waiting for the backend - // to assign a namespace for an APIServiceNamespace. - EnsureProviderKey(ctx context.Context, consumerKey types.NamespacedName) (*types.NamespacedName, error) - - // MutateMetadataAndSpec mutates the object's content (its main resource) when - // syncing from the consumer side to the provide side. This function is also - // responsible for applying the translated keys (from ToProviderKey). - MutateMetadataAndSpec(consumerObj *unstructured.Unstructured, providerKey types.NamespacedName) error - - // MutateStatus is the opposite of MutateMetadataAndSpec and might mutate the - // object status (status subresource) when syncing it back from the provider - // cluster to the consumer cluster. This function is also responsible for - // applying the consumer key to "rename" the object back to its original name - // on the consumer cluster. - MutateStatus(providerObj *unstructured.Unstructured, consumerKey types.NamespacedName) error -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/multinsinformer/informer.go b/pkg/konnector/controllers/cluster/serviceexport/multinsinformer/informer.go deleted file mode 100644 index 141e72955..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/multinsinformer/informer.go +++ /dev/null @@ -1,329 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 multinsinformer - -import ( - "context" - "fmt" - "sync" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/dynamic/dynamicinformer" - "k8s.io/client-go/informers" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "dynamic-multi-namespace-informer" -) - -type GetterInformer interface { - Get(ns, name string) (runtime.Object, error) - List(ns string) ([]runtime.Object, error) - AddEventHandler(handler cache.ResourceEventHandler) error - - Start(ctx context.Context) - WaitForCacheSync(stopCh <-chan struct{}) map[schema.GroupVersionResource]bool -} - -var _ GetterInformer = &DynamicMultiNamespaceInformer{} - -// DynamicMultiNamespaceInformer is a dynamic informer that spans multiple namespaces -// by starting individual informers per namespace and aggregating all of these. -type DynamicMultiNamespaceInformer struct { - gvr schema.GroupVersionResource - providerNamespace string - - providerDynamicClient dynamicclient.Interface - - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - lock sync.RWMutex - namespaceInformers map[string]informers.GenericInformer - namespaceCancel map[string]func() - handlers []cache.ResourceEventHandler -} - -func NewDynamicMultiNamespaceInformer( - gvr schema.GroupVersionResource, - providerNamespace string, - providerConfig *rest.Config, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], -) (*DynamicMultiNamespaceInformer, error) { - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - providerDynamicClient, err := dynamicclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - inf := DynamicMultiNamespaceInformer{ - gvr: gvr, - providerNamespace: providerNamespace, - providerDynamicClient: providerDynamicClient, - serviceNamespaceInformer: serviceNamespaceInformer, - - namespaceInformers: map[string]informers.GenericInformer{}, - namespaceCancel: map[string]func(){}, - } - - return &inf, nil -} - -func (inf *DynamicMultiNamespaceInformer) Start(ctx context.Context) { - defer utilruntime.HandleCrash() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName, "gvk", inf.gvr) - ctx = klog.NewContext(ctx, logger) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - inf.serviceNamespaceInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - inf.enqueueServiceNamespace(obj) - }, - UpdateFunc: func(oldObj, newObj any) { - inf.enqueueServiceNamespace(newObj) - }, - DeleteFunc: func(obj any) { - inf.enqueueServiceNamespace(obj) - }, - }) - - go func() { - <-ctx.Done() - - inf.lock.Lock() - defer inf.lock.Unlock() - for _, cancel := range inf.namespaceCancel { - cancel() - } - }() -} - -func (inf *DynamicMultiNamespaceInformer) enqueueServiceNamespace(obj any) { - logger := klog.FromContext(context.Background()).WithValues("controller", controllerName, "gvr", inf.gvr) - - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - utilruntime.HandleError(err) - return - } - - logger = logger.WithValues("key", key) - logger.V(1).Info("processing APIServiceNamespace") - - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - utilruntime.HandleError(err) - return - } - if ns != inf.providerNamespace { - return - } - - sns, err := inf.serviceNamespaceInformer.Lister().APIServiceNamespaces(ns).Get(name) - if err != nil && !errors.IsNotFound(err) { - utilruntime.HandleError(err) - return - } - if errors.IsNotFound(err) || sns.Status.Namespace == "" { - if sns == nil { - logger.V(2).Info("APIServiceNamespace disappeared") - } else { - logger.V(2).Info("APIServiceNamespace disappeared", "namespace", sns.Status.Namespace) - } - - inf.lock.Lock() - defer inf.lock.Unlock() - if cancel, found := inf.namespaceCancel[name]; found { - if sns == nil { - logger.V(2).Info("stopping informer") - } else { - logger.V(2).Info("stopping informer", "namespace", sns.Status.Namespace) - } - delete(inf.namespaceCancel, name) - delete(inf.namespaceInformers, name) - cancel() - } - return - } - - inf.lock.Lock() - defer inf.lock.Unlock() - if _, found := inf.namespaceCancel[name]; found { - logger.V(2).Info("informer for APIServiceNamespace already started", "namespace", sns.Status.Namespace) - return // nothing to do, already running - } - - logger.V(1).Info("starting dynamic informer", "namespace", sns.Status.Namespace) - ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec - - factory := dynamicinformer.NewFilteredDynamicSharedInformerFactory(inf.providerDynamicClient, time.Minute*30, sns.Status.Namespace, nil) - gvrInf := factory.ForResource(inf.gvr) - gvrInf.Lister() // to wire the GVR up in the informer factory - inf.namespaceCancel[name] = cancel - inf.namespaceInformers[name] = gvrInf - - for _, h := range inf.handlers { - gvrInf.Informer().AddEventHandler(h) //nolint:errcheck - } - - factory.Start(ctx.Done()) -} - -func (inf *DynamicMultiNamespaceInformer) AddEventHandler(handler cache.ResourceEventHandler) error { - inf.lock.Lock() - defer inf.lock.Unlock() - - for _, i := range inf.namespaceInformers { - if _, err := i.Informer().AddEventHandler(handler); err != nil { - return err - } - } - inf.handlers = append(inf.handlers, handler) - - return nil -} - -func (inf *DynamicMultiNamespaceInformer) Get(ns, name string) (runtime.Object, error) { - snss, err := inf.serviceNamespaceInformer.Informer().GetIndexer().ByIndex(indexers.ServiceNamespaceByNamespace, ns) - if err != nil { - return nil, err - } - if len(snss) == 0 { - return nil, errors.NewNotFound(inf.gvr.GroupResource(), name) - } else if len(snss) > 1 { - return nil, fmt.Errorf("unexpected multiple APIServiceNamespaces for namespace %s", ns) - } - sns := snss[0].(*kubebindv1alpha2.APIServiceNamespace) - - inf.lock.RLock() - defer inf.lock.RUnlock() - i, found := inf.namespaceInformers[sns.Name] - if !found { - return nil, errors.NewNotFound(inf.gvr.GroupResource(), name) - } - return i.Lister().ByNamespace(ns).Get(name) -} - -func (inf *DynamicMultiNamespaceInformer) List(ns string) ([]runtime.Object, error) { - snss, err := inf.serviceNamespaceInformer.Informer().GetIndexer().ByIndex(indexers.ServiceNamespaceByNamespace, ns) - if err != nil { - return nil, err - } - if len(snss) == 0 { - return []runtime.Object{}, nil - } else if len(snss) > 1 { - return nil, fmt.Errorf("unexpected multiple APIServiceNamespaces for namespace %s", ns) - } - sns := snss[0].(*kubebindv1alpha2.APIServiceNamespace) - - inf.lock.RLock() - defer inf.lock.RUnlock() - i, found := inf.namespaceInformers[sns.Name] - if !found { - return []runtime.Object{}, nil - } - return i.Lister().ByNamespace(ns).List(labels.Everything()) -} - -func (inf *DynamicMultiNamespaceInformer) WaitForCacheSync(stopCh <-chan struct{}) map[schema.GroupVersionResource]bool { - snss, err := inf.serviceNamespaceInformer.Lister().APIServiceNamespaces(inf.providerNamespace).List(labels.Everything()) - if err != nil { - utilruntime.HandleError(err) - return nil - } - - if err := wait.PollUntilContextCancel(goContext(stopCh), time.Millisecond*100, true, func(ctx context.Context) (done bool, err error) { - inf.lock.RLock() - defer inf.lock.RUnlock() - for _, sns := range snss { - i, found := inf.namespaceInformers[sns.Name] - if !found { - // double check that the namespace is not gone - if _, err := inf.serviceNamespaceInformer.Lister().APIServiceNamespaces(inf.providerNamespace).Get(sns.Name); err != nil { - continue // ignore - } - return false, nil - } - if !i.Informer().HasSynced() { - return false, nil - } - } - return true, nil - }); err != nil { - return map[schema.GroupVersionResource]bool{inf.gvr: false} - } - return map[schema.GroupVersionResource]bool{inf.gvr: true} -} - -var _ GetterInformer = GetterInformerWrapper{} - -type GetterInformerWrapper struct { - GVR schema.GroupVersionResource - Delegate dynamicinformer.DynamicSharedInformerFactory -} - -func (w GetterInformerWrapper) Get(ns, name string) (runtime.Object, error) { - if ns != "" { - return w.Delegate.ForResource(w.GVR).Lister().ByNamespace(ns).Get(name) - } - return w.Delegate.ForResource(w.GVR).Lister().Get(name) -} - -func (w GetterInformerWrapper) List(ns string) ([]runtime.Object, error) { - return w.Delegate.ForResource(w.GVR).Lister().ByNamespace(ns).List(labels.Everything()) -} - -func (w GetterInformerWrapper) AddEventHandler(handler cache.ResourceEventHandler) error { - _, err := w.Delegate.ForResource(w.GVR).Informer().AddEventHandler(handler) - return err -} - -func (w GetterInformerWrapper) Start(ctx context.Context) { - w.Delegate.Start(ctx.Done()) -} - -func (w GetterInformerWrapper) WaitForCacheSync(stopCh <-chan struct{}) map[schema.GroupVersionResource]bool { - return w.Delegate.WaitForCacheSync(stopCh) -} - -func goContext(stopCh <-chan struct{}) context.Context { - ctx, cancel := context.WithCancel(context.Background()) - go func(done <-chan struct{}) { - <-done - cancel() - }(stopCh) - return ctx -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_controller.go b/pkg/konnector/controllers/cluster/serviceexport/serviceexport_controller.go deleted file mode 100644 index d83470dc5..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_controller.go +++ /dev/null @@ -1,319 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexport - -import ( - "context" - "fmt" - "time" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apiextensionslisters "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/contextstore" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-cluster-serviceexport" -) - -// NewController returns a new controller for ServiceExports, spawning spec -// and status syncer on-demand. -func NewController( - consumerSecretRefKey, providerNamespace string, - consumerConfig, providerConfig *rest.Config, - serviceExportInformer bindinformers.APIServiceExportInformer, - serviceNamespaceInformer bindinformers.APIServiceNamespaceInformer, - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister], - crdInformer dynamic.Informer[apiextensionslisters.CustomResourceDefinitionLister], -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - providerBindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - dynamicServiceNamespaceInformer, err := dynamic.NewDynamicInformer(serviceNamespaceInformer) - if err != nil { - return nil, err - } - - indexers.AddIfNotPresentOrDie(dynamicServiceNamespaceInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ServiceNamespaceByNamespace: indexers.IndexServiceNamespaceByNamespace, - }) - - c := &controller{ - queue: queue, - - serviceExportLister: serviceExportInformer.Lister(), - serviceExportIndexer: serviceExportInformer.Informer().GetIndexer(), - - serviceBindingInformer: serviceBindingInformer, - crdInformer: crdInformer, - - reconciler: reconciler{ - consumerSecretRefKey: consumerSecretRefKey, - providerNamespace: providerNamespace, - serviceNamespaceInformer: dynamicServiceNamespaceInformer, - consumerConfig: consumerConfig, - providerConfig: providerConfig, - - syncStore: contextstore.New(), - - getServiceBinding: func(name string) (*kubebindv1alpha2.APIServiceBinding, error) { - return serviceBindingInformer.Lister().Get(name) - }, - getCRD: func(name string) (*apiextensionsv1.CustomResourceDefinition, error) { - return crdInformer.Lister().Get(name) - }, - getRemoteBoundSchema: func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) { - return providerBindClient.KubeBindV1alpha2().BoundSchemas(providerNamespace).Get(ctx, name, metav1.GetOptions{}) - }, - updateRemoteBoundSchema: func(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema) error { - _, err := providerBindClient.KubeBindV1alpha2().BoundSchemas(providerNamespace).UpdateStatus(ctx, boundSchema, metav1.UpdateOptions{}) - return err - }, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.APIServiceExport, *kubebindv1alpha2.APIServiceExportSpec, *kubebindv1alpha2.APIServiceExportStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.APIServiceExport] { - return providerBindClient.KubeBindV1alpha2().APIServiceExports(ns) - }, - ), - } - - indexers.AddIfNotPresentOrDie(serviceExportInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ServiceExportByBoundSchema: indexers.IndexServiceExportByBoundSchema, - }) - - if _, err := serviceExportInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceExport(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceExport(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.APIServiceExportSpec, *kubebindv1alpha2.APIServiceExportStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -// controller reconciles ServiceExportResources and starts and stop syncers. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - serviceExportLister bindlisters.APIServiceExportLister - serviceExportIndexer cache.Indexer - - serviceBindingInformer dynamic.Informer[bindlisters.APIServiceBindingLister] - crdInformer dynamic.Informer[apiextensionslisters.CustomResourceDefinitionLister] - - reconciler - - commit CommitFunc -} - -func (c *controller) enqueueServiceExport(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceExport", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueServiceBinding(logger klog.Logger, obj any) { - binding, ok := obj.(*kubebindv1alpha2.APIServiceBinding) - if !ok { - runtime.HandleError(fmt.Errorf("unexpected type %T", obj)) - return - } - - key := c.providerNamespace + "/" + binding.Name - logger.V(2).Info("queueing APIServiceExport", "key", key, "reason", "APIServiceBinding", "APIServiceBindingKey", binding.Name) - c.queue.Add(key) -} - -func (c *controller) enqueueCRD(logger klog.Logger, obj any) { - name, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - exports, err := c.serviceExportIndexer.ByIndex(indexers.ServiceExportByBoundSchema, name) - if err != nil { - runtime.HandleError(err) - return - } - - for _, obj := range exports { - export := obj.(*kubebindv1alpha2.APIServiceExport) - key, err := cache.MetaNamespaceKeyFunc(export) - if err != nil { - runtime.HandleError(err) - return - } - logger.V(2).Info("queueing APIServiceExport", "key", key, "reason", "CustomResourceDefinition", "name", name) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - c.serviceBindingInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceBinding(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - }) - - c.crdInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueCRD(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueCRD(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueCRD(logger, obj) - }, - }) - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - namespace, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - obj, err := c.serviceExportLister.APIServiceExports(namespace).Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.Error(err, "APIServiceExport disappeared") - return c.reconcile(ctx, namespace, name, nil) - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, namespace, name, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go b/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go deleted file mode 100644 index da788191c..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go +++ /dev/null @@ -1,637 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexport - -import ( - "context" - "fmt" - "maps" - "slices" - "strings" - "time" - - corev1 "k8s.io/api/core/v1" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtimeschema "k8s.io/apimachinery/pkg/runtime/schema" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/dynamic/dynamicinformer" - "k8s.io/client-go/rest" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/claimedresources" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/claimedresourcesnamespaces" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/isolation" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/multinsinformer" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/spec" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/status" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/contextstore" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -type reconciler struct { - // consumerSecretRefKey is the namespace/name value of the APIServiceBinding kubeconfig secret reference. - consumerSecretRefKey string - providerNamespace string - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - consumerConfig, providerConfig *rest.Config - - syncStore contextstore.Store // by APIServiceExport name. This includes same ctx for resourc claims and crds. - - getCRD func(name string) (*apiextensionsv1.CustomResourceDefinition, error) - getServiceBinding func(name string) (*kubebindv1alpha2.APIServiceBinding, error) - getRemoteBoundSchema func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) - - updateRemoteBoundSchema func(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema) error -} - -func (r *reconciler) reconcile(ctx context.Context, namespace, name string, export *kubebindv1alpha2.APIServiceExport) error { - errs := []error{} - - if err := r.ensureControllers(ctx, namespace, name, export); err != nil { - errs = append(errs, err) - } - - if export != nil { - if err := r.ensureServiceBindingConditionCopied(ctx, export); err != nil { - errs = append(errs, err) - } - if err := r.ensureCRDConditionsCopiedToBoundSchema(ctx, export); err != nil { - errs = append(errs, err) - } - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureControllers(ctx context.Context, namespace, name string, export *kubebindv1alpha2.APIServiceExport) error { - logger := klog.FromContext(ctx) - exportKey := contextstore.Key(namespace + "." + name) // Key for the export - - if export == nil { - // Clean up any controllers associated with this export - deleted := r.syncStore.BulkDeletePrefixed(exportKey) - for _, c := range deleted { - logger.V(1).Info("Stopping APIServiceExport sync", "key", c.Key(), "reason", "NoAPIServiceExport") - } - - return nil - } - - // any binding that references this resource? - binding, err := r.getServiceBinding(export.Name) - if err != nil && !errors.IsNotFound(err) { - return err - } - if binding == nil { - // Stop all controllers for this export - deleted := r.syncStore.BulkDeletePrefixed(exportKey) - for _, k := range deleted { - logger.V(1).Info("Stopping APIServiceExport sync", "key", k.Key(), "reason", "NoAPIServiceBinding") - } - return nil - } - - // Process each resource referenced by the export - var errs []error - processedSchemas := make(map[string]bool) - var isClusterScoped bool - - for _, res := range export.Spec.Resources { - name := res.ResourceGroupName() - // Fetch the BoundSchema - schema, err := r.getRemoteBoundSchema(ctx, name) - if err != nil { - if errors.IsNotFound(err) { - // Stop the controller for this schema if it does not exists. - key := contextstore.NewKey(namespace, name, name) - deleted := r.syncStore.BulkDeletePrefixed(key) - for _, k := range deleted { - logger.V(1).Info("Stopping APIServiceExport sync", "key", k.Key(), "reason", "BoundSchema not found") - } - continue - } - errs = append(errs, err) - continue - } - - // Start/update controller for this schema - if err := r.ensureControllerForSchema(ctx, export, schema); err != nil { - errs = append(errs, err) - } - - processedSchemas[name] = true // This is only schemas names (suffix) - isClusterScoped = schema.Spec.InformerScope == kubebindv1alpha2.ClusterScope - } - - // Ensure controller for permission claims - if err := r.ensureControllersForPermissionClaims(ctx, export, binding, isClusterScoped); err != nil { - errs = append(errs, err) - } - - // Stop controllers for schemas that are no longer referenced. - // This will be `exportNamespace.exportName.` - contexts := r.syncStore.ListPrefixed(exportKey) - for _, c := range contexts { - schemaName := strings.TrimPrefix(string(c.Key()), string(exportKey)+".") // schemaName will be processed schema names. - // Skip permission claim controllers - they are handled separately in ensureControllersForPermissionClaims - if strings.HasPrefix(schemaName, "claim.") { - continue - } - if !processedSchemas[schemaName] { - logger.V(1).Info("Stopping APIServiceExport resource sync", "key", c.Key(), "reason", "Schema no longer referenced") - r.syncStore.Delete(c.Key()) - } - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureControllerForSchema(ctx context.Context, export *kubebindv1alpha2.APIServiceExport, schema *kubebindv1alpha2.BoundSchema) error { - logger := klog.FromContext(ctx) - key := contextstore.NewKey(export.Namespace, export.Name, schema.Name) - - c, found := r.syncStore.Get(key) - if found { - if c.Generation == export.Generation { - return nil // all as expected - } - - logger.V(1).Info("Stopping APIServiceExport resource sync", "key", key, "reason", "GenerationChanged", "generation", schema.Generation) - r.syncStore.Delete(key) - } - - // At this point we dont have a controller for this schema. - - // start a new syncer - var syncVersion string - for _, v := range schema.Spec.Versions { - if v.Served { - syncVersion = v.Name - break - } - } - if syncVersion == "" { - return fmt.Errorf("no served version found for BoundSchema %s", schema.Name) - } - - gvr := runtimeschema.GroupVersionResource{ - Group: schema.Spec.Group, - Version: syncVersion, - Resource: schema.Spec.Names.Plural, - } - - dynamicConsumerClient := dynamicclient.NewForConfigOrDie(r.consumerConfig) - dynamicProviderClient := dynamicclient.NewForConfigOrDie(r.providerConfig) - - providerNamespaceUID := "" - if pns, err := dynamicProviderClient.Resource(runtimeschema.GroupVersionResource{ - Group: "", - Version: "v1", - Resource: "namespaces", - }).Get(ctx, r.providerNamespace, metav1.GetOptions{}); err != nil { - return err - } else { - providerNamespaceUID = string(pns.GetUID()) - } - - consumerInf := dynamicinformer.NewDynamicSharedInformerFactory(dynamicConsumerClient, time.Minute*30) - - var providerInf multinsinformer.GetterInformer - - if schema.Spec.Scope == apiextensionsv1.ClusterScoped || schema.Spec.InformerScope == kubebindv1alpha2.ClusterScope { - factory := dynamicinformer.NewDynamicSharedInformerFactory(dynamicProviderClient, time.Minute*30) - factory.ForResource(gvr).Lister() // wire the GVR up in the informer factory - providerInf = multinsinformer.GetterInformerWrapper{ - GVR: gvr, - Delegate: factory, - } - } else { - var err error - providerInf, err = multinsinformer.NewDynamicMultiNamespaceInformer( - gvr, - r.providerNamespace, - r.providerConfig, - r.serviceNamespaceInformer, - ) - if err != nil { - return err - } - } - - var isolationStrategy isolation.Strategy - switch { - case schema.Spec.Scope == apiextensionsv1.NamespaceScoped: - providerBindClient, err := bindclient.NewForConfig(r.providerConfig) - if err != nil { - return err - } - - isolationStrategy = isolation.NewServiceNamespaced( - r.providerNamespace, - r.serviceNamespaceInformer, - func(ctx context.Context, name string) (*kubebindv1alpha2.APIServiceNamespace, error) { - sn := &kubebindv1alpha2.APIServiceNamespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: r.providerNamespace, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(export, kubebindv1alpha2.SchemeGroupVersion.WithKind("APIServiceExport")), - }, - }, - } - - return providerBindClient.KubeBindV1alpha2().APIServiceNamespaces(sn.Namespace).Create(ctx, sn, metav1.CreateOptions{}) - }) - - case export.Spec.Isolation == kubebindv1alpha2.IsolationNone: - logger.V(4).Info("Using None isolation strategy", "export", export.Name) - isolationStrategy = isolation.NewNone(r.providerNamespace, providerNamespaceUID) - - case export.Spec.Isolation == kubebindv1alpha2.IsolationPrefixed: - logger.V(4).Info("Using Prefixed isolation strategy", "export", export.Name) - isolationStrategy = isolation.NewPrefixed(r.providerNamespace, providerNamespaceUID) - - case export.Spec.Isolation == kubebindv1alpha2.IsolationNamespaced: - logger.V(4).Info("Using Namespaced isolation strategy", "export", export.Name) - isolationStrategy = isolation.NewNamespaced(r.providerNamespace) - default: - // Default to None isolation strategy if no valid isolation strategy is specified - // This should never happen due to validation, but we add this as a safety net. - logger.V(2).Info("Using default None isolation strategy", "export", export.Name) - isolationStrategy = isolation.NewNone(r.providerNamespace, providerNamespaceUID) - } - - specCtrl, err := spec.NewController( - isolationStrategy, - export, // pass the export to establish owner references on ServiceNamespace creation - gvr, - r.providerNamespace, - providerNamespaceUID, - r.consumerConfig, - r.providerConfig, - consumerInf.ForResource(gvr), - providerInf, - r.serviceNamespaceInformer, - ) - if err != nil { - runtime.HandleError(err) - return nil // nothing we can do here - } - - statusCtrl, err := status.NewController( - isolationStrategy, - gvr, - r.providerNamespace, - providerNamespaceUID, - r.consumerConfig, - r.providerConfig, - consumerInf.ForResource(gvr), - providerInf, - r.serviceNamespaceInformer, - ) - if err != nil { - runtime.HandleError(err) - return nil // nothing we can do here - } - - // Create a new context for this controller - ctxWithCancel, cancel := context.WithCancel(ctx) //nolint:gosec - - consumerInf.Start(ctxWithCancel.Done()) - providerInf.Start(ctxWithCancel) - - go func() { - // to not block the main thread - consumerSynced := consumerInf.WaitForCacheSync(ctxWithCancel.Done()) - logger.V(2).Info("Synced informers", "key", key, "consumer", slices.Collect(maps.Keys(consumerSynced))) - - providerSynced := providerInf.WaitForCacheSync(ctxWithCancel.Done()) - logger.V(2).Info("Synced informers", "key", key, "provider", slices.Collect(maps.Keys(providerSynced))) - - go specCtrl.Start(ctxWithCancel, 1) - go statusCtrl.Start(ctxWithCancel, 1) - }() - - r.syncStore.Set(key, contextstore.SyncContext{ - Generation: export.Generation, - Cancel: cancel, - }) - - return nil -} - -func (r *reconciler) ensureControllersForPermissionClaims( - ctx context.Context, - export *kubebindv1alpha2.APIServiceExport, - binding *kubebindv1alpha2.APIServiceBinding, - isClusterScoped bool, // schema.Spec.InformerScope == kubebindv1alpha2.ClusterScope -) error { - logger := klog.FromContext(ctx) - - // Track processed claims for cleanup - processedClaims := make(map[string]bool) - var errs []error - - // Process each permission claim - for _, claim := range binding.Status.PermissionClaims { - claimGVR, err := kubebindv1alpha2.ResolveClaimableAPI(claim) - if err != nil { - logger.Info("skipping unsupported claim", "claim", claim, "error", err) - continue - } - - // Create unique key for this claim controller - claimKey := contextstore.NewKey(export.Namespace, export.Name, "claim", claimGVR.String()) - processedClaims[claimKey.String()] = true - - // Check if controller already exists with correct generation - c, found := r.syncStore.Get(claimKey) - if found { - if c.Generation == binding.Generation { - continue // controller is up to date - } - // Generation changed, stop old controller - logger.V(1).Info("Stopping permission claim controller", "key", claimKey, "reason", "GenerationChanged") - r.syncStore.Delete(claimKey) - } - - // Start new controller for this claim - if err := r.ensureControllerForPermissionClaim(ctx, binding, claim, export, claimGVR, isClusterScoped, claimKey); err != nil { - errs = append(errs, err) - } - } - - // Cleanup controllers for claims that are no longer present - claimPrefix := contextstore.NewKey(export.Namespace, export.Name, "claim") - contexts := r.syncStore.ListPrefixed(claimPrefix) - for _, c := range contexts { - if !processedClaims[c.Key().String()] { - logger.V(1).Info("Stopping permission claim controller", "key", c.Key(), "reason", "Claim no longer present") - r.syncStore.Delete(c.Key()) - } - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureControllerForPermissionClaim( - ctx context.Context, - binding *kubebindv1alpha2.APIServiceBinding, - claim kubebindv1alpha2.PermissionClaim, - export *kubebindv1alpha2.APIServiceExport, - claimGVR runtimeschema.GroupVersionResource, - isClusterScoped bool, - claimKey contextstore.Key, -) error { - logger := klog.FromContext(ctx) - - dynamicProviderClient := dynamicclient.NewForConfigOrDie(r.providerConfig) - dynamicConsumerClient := dynamicclient.NewForConfigOrDie(r.consumerConfig) - - // Create consumer informer factory. This is always unfiltered, as we might be getting objcts from reference, - // label or named. We need to see all objects to determine if they are claimed. - defaultConsumerInf := dynamicinformer.NewDynamicSharedInformerFactory(dynamicConsumerClient, time.Minute*30) - - var defaultProviderInf multinsinformer.GetterInformer // will hold the default provider informer either for cluster or namespace scoped. - if isClusterScoped { - factory := dynamicinformer.NewDynamicSharedInformerFactory(dynamicProviderClient, time.Minute*30) - factory.ForResource(claimGVR).Lister() // wire the GVR up in the informer factory - defaultProviderInf = multinsinformer.GetterInformerWrapper{ - GVR: claimGVR, - Delegate: factory, - } - } else { - var err error - defaultProviderInf, err = multinsinformer.NewDynamicMultiNamespaceInformer( - claimGVR, - r.providerNamespace, - r.providerConfig, - r.serviceNamespaceInformer, - ) - - if err != nil { - logger.Info("aborting", "error", err) - return err - } - } - - serviceNamespaceChannel := make(chan string, 100) - - claimedCtrl, err := claimedresources.NewController( - claimGVR, - claim, - export, - r.providerNamespace, - r.consumerConfig, - r.providerConfig, - defaultConsumerInf.ForResource(claimGVR), - defaultProviderInf, - r.serviceNamespaceInformer, - serviceNamespaceChannel, - ) - if err != nil { - return err - } - - claimedNamespacesCtrl, err := claimedresourcesnamespaces.NewController( - claimGVR, - claim, - export, - r.providerNamespace, - r.providerConfig, - r.consumerConfig, - defaultConsumerInf.ForResource(claimGVR), - r.serviceNamespaceInformer, - serviceNamespaceChannel, - ) - if err != nil { - return err - } - - logger.Info("creating claim reconciler", "gvr", claimGVR, "key", claimKey) - - ctxWithCancel, cancel := context.WithCancel(ctx) //nolint:gosec - // Start the informers and controllers in a goroutine - go func() { - defer r.syncStore.Delete(claimKey) - defaultConsumerInf.Start(ctxWithCancel.Done()) - - // Wait for consumer informers to sync - consumerSynced := defaultConsumerInf.WaitForCacheSync(ctxWithCancel.Done()) - logger.V(2).Info("Synced consumer informers", "consumer", slices.Collect(maps.Keys(consumerSynced)), "key", claimKey) - - // IMPORTANT: WE need to start namespaces controller before the claimed resources controller, - // as the later depends on the former to ensure service namespaces are present. - // Else provider informers will never sync and the controller will not start. - // check: claimedresourcesnamespaces/README.md for more details. - go claimedNamespacesCtrl.Start(ctxWithCancel, 1) - - // Start provider informer and wait for sync - defaultProviderInf.Start(ctxWithCancel) - providerSynced := defaultProviderInf.WaitForCacheSync(ctxWithCancel.Done()) - logger.V(2).Info("Synced provider informers", "provider", slices.Collect(maps.Keys(providerSynced)), "key", claimKey) - - // Start the claimed resources controller - claimedCtrl.Start(ctxWithCancel, 1) - }() - - // Store the controller context for tracking - r.syncStore.Set(claimKey, contextstore.SyncContext{ - Generation: binding.Generation, - Cancel: cancel, - }) - - return nil -} - -func (r *reconciler) ensureCRDConditionsCopiedToBoundSchema(ctx context.Context, export *kubebindv1alpha2.APIServiceExport) error { - if export == nil { - return nil - } - var errs []error - allValid := true // assume all BoundAPIResourceSchemas are valid - for _, res := range export.Spec.Resources { - boundSchema, err := r.getRemoteBoundSchema(ctx, res.ResourceGroupName()) - if err != nil { - if errors.IsNotFound(err) { - continue - } - errs = append(errs, err) - continue - } - - crd, err := r.getCRD(boundSchema.Name) - if err != nil { - if errors.IsNotFound(err) { - continue - } - errs = append(errs, err) - continue - } - - boundSchemaIndex := map[conditionsapi.ConditionType]int{} - for i, c := range boundSchema.Status.Conditions { - boundSchemaIndex[c.Type] = i - } - for _, c := range crd.Status.Conditions { - if conditionsapi.ConditionType(c.Type) == conditionsapi.ReadyCondition { - continue - } - - severity := conditionsapi.ConditionSeverityError - if c.Status == apiextensionsv1.ConditionTrue { - severity = conditionsapi.ConditionSeverityNone - } - copied := conditionsapi.Condition{ - Type: conditionsapi.ConditionType(c.Type), - Status: corev1.ConditionStatus(c.Status), - Severity: severity, // CRD conditions have no severity - LastTransitionTime: c.LastTransitionTime, - Reason: c.Reason, - Message: c.Message, - } - - // update or append - if i, found := boundSchemaIndex[conditionsapi.ConditionType(c.Type)]; found { - boundSchema.Status.Conditions[i] = copied - } else { - boundSchema.Status.Conditions = append(boundSchema.Status.Conditions, copied) - } - } - conditions.SetSummary(boundSchema) - - boundSchema.Status.AcceptedNames = crd.Status.AcceptedNames - boundSchema.Status.StoredVersions = crd.Status.StoredVersions - - if err := r.updateRemoteBoundSchema(ctx, boundSchema); err != nil { - errs = append(errs, err) - allValid = false // at least one BoundSchemas is not valid - } - } - - // Set APIServiceExport Ready condition based on all BoundSchemas - if allValid { - conditions.MarkTrue( - export, - kubebindv1alpha2.APIServiceExportConditionConnected, - ) - } else { - conditions.MarkFalse( - export, - kubebindv1alpha2.APIServiceExportConditionConnected, - "BoundSchemasNotValid", - conditionsapi.ConditionSeverityWarning, - "One or more BoundSchemas are not valid", - ) - } - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureServiceBindingConditionCopied(_ context.Context, export *kubebindv1alpha2.APIServiceExport) error { - binding, err := r.getServiceBinding(export.Name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - conditions.MarkFalse( - export, - kubebindv1alpha2.APIServiceExportConditionConnected, - "APIServiceBindingNotFound", - conditionsapi.ConditionSeverityInfo, - "No APIServiceBinding exists.", - ) - - conditions.MarkFalse( - export, - kubebindv1alpha2.APIServiceExportConditionConsumerInSync, - "NA", - conditionsapi.ConditionSeverityInfo, - "No APIServiceBinding exists.", - ) - - return nil - } - - conditions.MarkTrue(export, kubebindv1alpha2.APIServiceExportConditionConnected) - - if inSync := conditions.Get(binding, kubebindv1alpha2.APIServiceBindingConditionSchemaInSync); inSync != nil { - inSync := inSync.DeepCopy() - inSync.Type = kubebindv1alpha2.APIServiceExportConditionConsumerInSync - conditions.Set(export, inSync) - } else { - conditions.MarkFalse( - export, - kubebindv1alpha2.APIServiceExportConditionConsumerInSync, - "Unknown", - conditionsapi.ConditionSeverityInfo, - "APIServiceBinding %s in the consumer cluster does not have a SchemaInSync condition.", - binding.Name, - ) - } - - return nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile_test.go b/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile_test.go deleted file mode 100644 index bbf1c2efb..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile_test.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 serviceexport - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/stretchr/testify/require" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -func TestEnsureCRDConditionsCopiedToBoundSchema(t *testing.T) { - tests := []struct { - name string - getCRD func(name string) (*apiextensionsv1.CustomResourceDefinition, error) - boundSchema *kubebindv1alpha2.BoundSchema - export *kubebindv1alpha2.APIServiceExport - expected *kubebindv1alpha2.BoundSchema - wantErr bool - }{ - { - name: "merging", - getCRD: newGetCRD("foo-schema", newCRD("foo-schema", []apiextensionsv1.CustomResourceDefinitionCondition{ - {Type: "Something", Status: "True", Reason: "Reason", Message: "message"}, - {Type: "Established", Status: "True", Reason: "Reason", Message: "message"}, - })), - boundSchema: newBoundSchema("foo-schema", []conditionsapi.Condition{ - {Type: "Ready", Status: "False", Severity: "Warning", Reason: "SomethingElseWrong", Message: "something else went wrong"}, - {Type: "Established", Status: "True", Severity: "None", Reason: "Reason", Message: "message"}, - {Type: "Structural", Status: "False", Severity: "Warning", Reason: "SomethingWrong", Message: "something went wrong"}, - }), - export: newExportWithResources("test-export", "default", []kubebindv1alpha2.APIServiceExportRequestResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "example.com", Resource: "foos"}}, - }), - expected: newBoundSchema("foo-schema", []conditionsapi.Condition{ - {Type: "Ready", Status: "False", Severity: "Warning", Reason: "SomethingWrong", Message: "something went wrong"}, - {Type: "Established", Status: "True", Severity: "", Reason: "Reason", Message: "message"}, - {Type: "Something", Status: "True", Severity: "", Reason: "Reason", Message: "message"}, - {Type: "Structural", Status: "False", Severity: "Warning", Reason: "SomethingWrong", Message: "something went wrong"}, - }), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Track updated schema - var updatedSchema *kubebindv1alpha2.BoundSchema - ctx := context.Background() - r := &reconciler{ - getCRD: tt.getCRD, - getRemoteBoundSchema: newGetBoundSchema(ctx, tt.boundSchema), - updateRemoteBoundSchema: newUpdateBoundSchema(&updatedSchema), - } - - if err := r.ensureCRDConditionsCopiedToBoundSchema(context.Background(), tt.export); (err != nil) != tt.wantErr { - t.Errorf("ensureCRDConditionsCopiedToBoundSchema() error = %v, wantErr %v", err, tt.wantErr) - } else if err == nil && updatedSchema != nil { - for i := range updatedSchema.Status.Conditions { - updatedSchema.Status.Conditions[i].LastTransitionTime = metav1.Time{} - } - for i := range tt.expected.Status.Conditions { - tt.expected.Status.Conditions[i].LastTransitionTime = metav1.Time{} - } - - require.Equal(t, tt.expected.Status.Conditions, updatedSchema.Status.Conditions, - cmp.Diff(tt.expected.Status.Conditions, updatedSchema.Status.Conditions)) - } - }) - } -} - -func newGetCRD(name string, crd *apiextensionsv1.CustomResourceDefinition) func(name string) (*apiextensionsv1.CustomResourceDefinition, error) { - return func(n string) (*apiextensionsv1.CustomResourceDefinition, error) { - if n == name { - return crd, nil - } - return nil, errors.NewNotFound(apiextensionsv1.SchemeGroupVersion.WithResource("customresourcedefinitions").GroupResource(), "not found") - } -} - -func newCRD(name string, conditions []apiextensionsv1.CustomResourceDefinitionCondition) *apiextensionsv1.CustomResourceDefinition { - return &apiextensionsv1.CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Status: apiextensionsv1.CustomResourceDefinitionStatus{ - Conditions: conditions, - }, - } -} - -func newGetBoundSchema(_ context.Context, boundSchema *kubebindv1alpha2.BoundSchema) func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) { - return func(ctx context.Context, name string) (*kubebindv1alpha2.BoundSchema, error) { - if name == boundSchema.Name { - return boundSchema, nil - } - return nil, errors.NewNotFound(kubebindv1alpha2.SchemeGroupVersion.WithResource("boundschemas").GroupResource(), name) - } -} - -func newUpdateBoundSchema(updatedSchemaPtr **kubebindv1alpha2.BoundSchema) func(context.Context, *kubebindv1alpha2.BoundSchema) error { - return func(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema) error { - *updatedSchemaPtr = boundSchema.DeepCopy() - return nil - } -} - -func newExportWithResources(name, namespace string, resources []kubebindv1alpha2.APIServiceExportRequestResource) *kubebindv1alpha2.APIServiceExport { - return &kubebindv1alpha2.APIServiceExport{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: kubebindv1alpha2.APIServiceExportSpec{ - Resources: resources, - InformerScope: kubebindv1alpha2.NamespacedScope, - }, - } -} - -func newBoundSchema(name string, conditions []conditionsapi.Condition) *kubebindv1alpha2.BoundSchema { - return &kubebindv1alpha2.BoundSchema{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Status: kubebindv1alpha2.BoundSchemaStatus{ - Conditions: conditions, - }, - } -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_controller.go b/pkg/konnector/controllers/cluster/serviceexport/spec/spec_controller.go deleted file mode 100644 index f3c5ff26b..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_controller.go +++ /dev/null @@ -1,357 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 spec - -import ( - "context" - "encoding/json" - "fmt" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/dynamic/dynamiclister" - "k8s.io/client-go/informers" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/isolation" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/multinsinformer" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-cluster-spec" - - applyManager = "kube-bind.io" -) - -// NewController returns a new controller reconciling downstream objects to upstream. -func NewController( - isolationStrategy isolation.Strategy, - apiServiceExport *kubebindv1alpha2.APIServiceExport, // used to establish owner references when create happens from the consumer side. - gvr schema.GroupVersionResource, - providerNamespace string, - providerNamespaceUID string, - consumerConfig, providerConfig *rest.Config, - consumerDynamicInformer informers.GenericInformer, - providerDynamicInformer multinsinformer.GetterInformer, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - providerClient, err := dynamicclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - providerBindClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - consumerClient, err := dynamicclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - dynamicConsumerLister := dynamiclister.New(consumerDynamicInformer.Informer().GetIndexer(), gvr) - c := &controller{ - queue: queue, - - consumerClient: consumerClient, - providerClient: providerClient, - providerNamespace: providerNamespace, - - consumerDynamicLister: dynamicConsumerLister, - consumerDynamicIndexer: consumerDynamicInformer.Informer().GetIndexer(), - - providerDynamicInformer: providerDynamicInformer, - - serviceNamespaceInformer: serviceNamespaceInformer, - - reconciler: reconciler{ - isolationStrategy: isolationStrategy, - clusterNamespace: providerNamespace, - - getServiceNamespace: func(name string) (*kubebindv1alpha2.APIServiceNamespace, error) { - return serviceNamespaceInformer.Lister().APIServiceNamespaces(providerNamespace).Get(name) - }, - createServiceNamespace: func(ctx context.Context, sn *kubebindv1alpha2.APIServiceNamespace) (*kubebindv1alpha2.APIServiceNamespace, error) { - return providerBindClient.KubeBindV1alpha2().APIServiceNamespaces(providerNamespace).Create(ctx, sn, metav1.CreateOptions{}) - }, - getProviderObject: func(ns, name string) (*unstructured.Unstructured, error) { - got, err := providerDynamicInformer.Get(ns, name) - if err != nil { - return nil, err - } - return got.(*unstructured.Unstructured).DeepCopy(), nil - }, - createProviderObject: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return providerClient.Resource(gvr).Namespace(obj.GetNamespace()).Create(ctx, obj, metav1.CreateOptions{}) - }, - updateProviderObject: func(ctx context.Context, obj *unstructured.Unstructured) error { - obj.SetManagedFields(nil) // server side apply does not want this - - data, err := json.Marshal(obj.Object) - if err != nil { - return err - } - _, err = providerClient.Resource(gvr).Namespace(obj.GetNamespace()).Patch(ctx, - obj.GetName(), types.ApplyPatchType, data, metav1.PatchOptions{FieldManager: applyManager, Force: ptr.To(true)}, - ) - return err - }, - deleteProviderObject: func(ctx context.Context, ns, name string) error { - return providerClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) - }, - updateConsumerObject: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(obj.GetNamespace()).Update(ctx, obj, metav1.UpdateOptions{}) - }, - requeue: func(obj *unstructured.Unstructured, after time.Duration) error { - key, err := cache.MetaNamespaceKeyFunc(obj) - if err != nil { - return err - } - queue.AddAfter(key, after) - return nil - }, - }, - } - - if _, err := consumerDynamicInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueConsumer(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueConsumer(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueConsumer(logger, obj) - }, - }); err != nil { - return nil, err - } - - if err := providerDynamicInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueProvider(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueProvider(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueProvider(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -// controller reconciles downstream objects to upstream. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - providerNamespace string - - consumerClient dynamicclient.Interface - providerClient dynamicclient.Interface - - consumerDynamicLister dynamiclister.Lister - consumerDynamicIndexer cache.Indexer - - providerDynamicInformer multinsinformer.GetterInformer - - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - reconciler -} - -func (c *controller) enqueueConsumer(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing Unstructured", "queued", key, "reason", "consumerObject") - c.queue.Add(key) -} - -func (c *controller) enqueueProvider(logger klog.Logger, obj any) { - providerKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(providerKey) - if err != nil { - runtime.HandleError(err) - return - } - - consumerKey, err := c.isolationStrategy.ToConsumerKey(types.NamespacedName{ - Namespace: ns, - Name: name, - }) - if err != nil { - if !errors.IsNotFound(err) { - runtime.HandleError(err) - } - return - } - - if consumerKey == nil { - return - } - - logger.V(2).Info("queueing Unstructured", "queued", consumerKey, "reason", "providerObject") - c.queue.Add(consumerKey.String()) -} - -func (c *controller) enqueueServiceNamespace(logger klog.Logger, obj any) { - snKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(snKey) - if err != nil { - runtime.HandleError(err) - return - } - if ns != c.providerNamespace { - return // not for us - } - - objs, err := c.consumerDynamicIndexer.ByIndex(cache.NamespaceIndex, name) - if err != nil { - runtime.HandleError(err) - return - } - for _, obj := range objs { - key, err := cache.MetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - continue - } - logger.V(2).Info("queueing Unstructured", "queued", key, "reason", "APIServiceNamespace", "ServiceNamespaceKey", snKey) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - c.serviceNamespaceInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceNamespace(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - }) - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - var obj *unstructured.Unstructured - if ns == "" { - obj, err = c.consumerDynamicLister.Get(name) - } else { - obj, err = c.consumerDynamicLister.Namespace(ns).Get(name) - } - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.V(2).Info("Downstream object disappeared") - return nil - } - - return c.reconcile(ctx, obj) -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile.go b/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile.go deleted file mode 100644 index 6fa9eabe5..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile.go +++ /dev/null @@ -1,254 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 spec - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "reflect" - "slices" - "time" - - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/isolation" - konnectortypes "github.com/kube-bind/kube-bind/pkg/konnector/types" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type reconciler struct { - isolationStrategy isolation.Strategy - clusterNamespace string - - getServiceNamespace func(name string) (*kubebindv1alpha2.APIServiceNamespace, error) - createServiceNamespace func(ctx context.Context, sn *kubebindv1alpha2.APIServiceNamespace) (*kubebindv1alpha2.APIServiceNamespace, error) - - getProviderObject func(ns, name string) (*unstructured.Unstructured, error) - createProviderObject func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) - updateProviderObject func(ctx context.Context, obj *unstructured.Unstructured) error - deleteProviderObject func(ctx context.Context, ns, name string) error - - updateConsumerObject func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) - - requeue func(obj *unstructured.Unstructured, after time.Duration) error -} - -// reconcile syncs downstream objects (metadata and spec) with upstream objects. -func (r *reconciler) reconcile(ctx context.Context, obj *unstructured.Unstructured) error { - logger := klog.FromContext(ctx) - - // Translate the namespace/name from the consumer side to the provider side, - // potentially creating eventually-consistent resources, hence the returned - // providerKey can be nil to indicate a requeue is desired. - - providerKey, err := r.isolationStrategy.EnsureProviderKey(ctx, types.NamespacedName{ - Namespace: obj.GetNamespace(), - Name: obj.GetName(), - }) - if err != nil { - return err - } - if providerKey == nil { - return r.requeue(obj, 1*time.Second) - } - - upstream, err := r.getProviderObject(providerKey.Namespace, providerKey.Name) - if err != nil && !apierrors.IsNotFound(err) { - return err - } else if apierrors.IsNotFound(err) { - if !obj.GetDeletionTimestamp().IsZero() { - logger.V(2).Info("object is already deleting, don't sync") - - if _, err := r.removeDownstreamFinalizer(ctx, obj); err != nil { - return err - } - - return nil - } - - if obj, err = r.ensureDownstreamFinalizer(ctx, obj); err != nil { - return err - } - - // clean up object - upstream = obj.DeepCopy() - upstream.SetUID("") - upstream.SetResourceVersion("") - upstream.SetManagedFields(nil) - upstream.SetDeletionTimestamp(nil) - upstream.SetDeletionGracePeriodSeconds(nil) - upstream.SetOwnerReferences(nil) - upstream.SetFinalizers(nil) - unstructured.RemoveNestedField(upstream.Object, "status") - - // Regardless of isolation mode, we always annotate every object with its - // owning cluster namespace. - if err := r.setClusterNamespaceAnnotation(upstream); err != nil { - return err - } - - // Annotate the provider-side object with the consumer source metadata. - konnectortypes.SetSourceMetadataAnnotations(upstream, obj.GetNamespace(), string(obj.GetUID()), - konnectortypes.ConsumerNamespaceAnnotationKey, konnectortypes.ConsumerUIDAnnotationKey) - - // let the isolation perform any changes it desires - if err := r.isolationStrategy.MutateMetadataAndSpec(upstream, *providerKey); err != nil { - return err - } - - logger.Info("Creating upstream object") - logger.V(4).Info("Upstream object", "object", fmt.Sprintf("%s", upstream.Object)) - if _, err := r.createProviderObject(ctx, upstream); err != nil && !apierrors.IsAlreadyExists(err) { - return err - } else if apierrors.IsAlreadyExists(err) { - logger.Info("Upstream object already exists. Waiting for requeue.") // the upstream object will lead to a requeue - } - } - - // here the upstream already exists. Update everything but the status. - - if !obj.GetDeletionTimestamp().IsZero() { - if !upstream.GetDeletionTimestamp().IsZero() { - logger.V(2).Info("upstream is already deleting, wait for it") - return nil // we will get an event when the upstream is deleted - } - - logger.V(1).Info("object is already deleting downstream, deleting upstream too") - if err := r.deleteProviderObject(ctx, providerKey.Namespace, providerKey.Name); err != nil && !apierrors.IsNotFound(err) { - return err - } - - if _, err := r.removeDownstreamFinalizer(ctx, obj); err != nil { - return err - } - - logger.V(2).Info("upstream deleted, finalizer removed in downstream, waiting for downstream deletion to finish") - return nil // we will get an event when the upstream is deleted - } - - // (Re)set the annotation if it's missing, abort if for whatever reason the - // object is annotated with another cluster namespace. - if err := r.setClusterNamespaceAnnotation(upstream); err != nil { - return err - } - - // (Re)set the consumer source metadata annotations. - konnectortypes.SetSourceMetadataAnnotations(upstream, obj.GetNamespace(), string(obj.GetUID()), - konnectortypes.ConsumerNamespaceAnnotationKey, konnectortypes.ConsumerUIDAnnotationKey) - - // just in case, checking for finalizer - if obj, err = r.ensureDownstreamFinalizer(ctx, obj); err != nil { - return err - } - - downstreamSpec, foundDownstreamSpec, err := unstructured.NestedFieldNoCopy(obj.Object, "spec") - if err != nil { - logger.Error(err, "failed to get downstream spec") - return nil - } - upstreamSpec, _, err := unstructured.NestedFieldNoCopy(upstream.Object, "spec") - if err != nil { - logger.Error(err, "failed to get upstream spec") - return nil - } - if reflect.DeepEqual(downstreamSpec, upstreamSpec) { - return nil // nothing to do - } - - upstream = upstream.DeepCopy() - if foundDownstreamSpec { - if err := unstructured.SetNestedField(upstream.Object, downstreamSpec, "spec"); err != nil { - bs, err := json.Marshal(downstreamSpec) - if err != nil { - logger.Error(err, "failed to marshal downstream spec", "spec", fmt.Sprintf("%s", downstreamSpec)) - return nil // nothing we can do - } - logger.Error(err, "failed to set spec", "spec", string(bs)) - return nil // nothing we can do - } - } else { - unstructured.RemoveNestedField(upstream.Object, "spec") - } - - logger.Info("Updating upstream object") - return r.updateProviderObject(ctx, upstream) -} - -func (r *reconciler) ensureDownstreamFinalizer(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - logger := klog.FromContext(ctx) - - if !slices.Contains(obj.GetFinalizers(), kubebindv1alpha2.DownstreamFinalizer) { - logger.V(2).Info("adding finalizer to downstream object") - obj = obj.DeepCopy() - obj.SetFinalizers(append(obj.GetFinalizers(), kubebindv1alpha2.DownstreamFinalizer)) - var err error - if obj, err = r.updateConsumerObject(ctx, obj); err != nil { - return nil, err - } - } - - return obj, nil -} - -func (r *reconciler) removeDownstreamFinalizer(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - logger := klog.FromContext(ctx) - - finalizers := []string{} - found := false - for _, f := range obj.GetFinalizers() { - if f == kubebindv1alpha2.DownstreamFinalizer { - found = true - continue - } - finalizers = append(finalizers, f) - } - - if found { - logger.V(2).Info("removing finalizer from downstream object") - obj = obj.DeepCopy() - obj.SetFinalizers(finalizers) - var err error - if obj, err = r.updateConsumerObject(ctx, obj); err != nil { - return nil, err - } - } - - return obj, nil -} - -func (r *reconciler) setClusterNamespaceAnnotation(obj *unstructured.Unstructured) error { - annnotations := obj.GetAnnotations() - existing, annotationExists := annnotations[konnectortypes.ClusterNamespaceAnnotationKey] - if annotationExists && existing != r.clusterNamespace { - return errors.New("mismatch between existing cluster namespace and given cluster namespace") - } - - if !annotationExists { - if annnotations == nil { - annnotations = map[string]string{} - } - annnotations[konnectortypes.ClusterNamespaceAnnotationKey] = r.clusterNamespace - obj.SetAnnotations(annnotations) - } - - return nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile_test.go b/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile_test.go deleted file mode 100644 index 896dbab3c..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/spec/spec_reconcile_test.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 spec - -import ( - "testing" - - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - - konnectortypes "github.com/kube-bind/kube-bind/pkg/konnector/types" -) - -func TestInjectClusterNamespace(t *testing.T) { - tests := []struct { - name string - obj *unstructured.Unstructured - clusterNs string - clusterNsUID string - expected string - wantErr bool - }{ - { - name: "noExistingClusterNs", - obj: &unstructured.Unstructured{}, - clusterNs: "kube-bind-zlp9m", - clusterNsUID: "real-identity", - expected: "kube-bind-zlp9m", - wantErr: false, - }, - { - name: "oneExistingClusterNs", - obj: newObjectWithClusterNs("kube-bind-zlp9m"), - clusterNs: "kube-bind-s85lc", - clusterNsUID: "real-identity", - expected: "kube-bind-zlp9m", - wantErr: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - originalClusterAnn := tt.obj.GetAnnotations()[konnectortypes.ClusterNamespaceAnnotationKey] - - rec := &reconciler{ - clusterNamespace: tt.clusterNs, - } - - err := rec.setClusterNamespaceAnnotation(tt.obj) - if tt.wantErr { - require.Error(t, err) - - // ensure object was not modified - require.Equal(t, originalClusterAnn, tt.obj.GetAnnotations()[konnectortypes.ClusterNamespaceAnnotationKey]) - } else { - require.NoError(t, err) - require.Equal(t, tt.clusterNs, tt.obj.GetAnnotations()[konnectortypes.ClusterNamespaceAnnotationKey]) - } - }) - } -} - -func TestSetSourceAnnotations(t *testing.T) { - tests := []struct { - name string - obj *unstructured.Unstructured - consumerNamespace string - consumerUID string - expectedAnnotations map[string]string - }{ - { - name: "no existing annotations", - obj: &unstructured.Unstructured{}, - consumerNamespace: "my-namespace", - consumerUID: "abc-123-def", - expectedAnnotations: map[string]string{ - konnectortypes.ConsumerNamespaceAnnotationKey: "my-namespace", - konnectortypes.ConsumerUIDAnnotationKey: "abc-123-def", - }, - }, - { - name: "with existing cluster namespace annotation", - obj: newObjectWithClusterNs("kube-bind-zlp9m"), - consumerNamespace: "other-namespace", - consumerUID: "xyz-456-ghi", - expectedAnnotations: map[string]string{ - konnectortypes.ConsumerNamespaceAnnotationKey: "other-namespace", - konnectortypes.ConsumerUIDAnnotationKey: "xyz-456-ghi", - konnectortypes.ClusterNamespaceAnnotationKey: "kube-bind-zlp9m", - }, - }, - { - name: "cluster-scoped object with empty namespace", - obj: &unstructured.Unstructured{}, - consumerNamespace: "", - consumerUID: "uid-789", - expectedAnnotations: map[string]string{ - konnectortypes.ConsumerNamespaceAnnotationKey: "", - konnectortypes.ConsumerUIDAnnotationKey: "uid-789", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - konnectortypes.SetSourceMetadataAnnotations(tt.obj, tt.consumerNamespace, tt.consumerUID, - konnectortypes.ConsumerNamespaceAnnotationKey, konnectortypes.ConsumerUIDAnnotationKey) - - annotations := tt.obj.GetAnnotations() - for key, expected := range tt.expectedAnnotations { - require.Equal(t, expected, annotations[key], "annotation %s mismatch", key) - } - }) - } -} - -func newObjectWithClusterNs(providerNamespace string) *unstructured.Unstructured { - obj := &unstructured.Unstructured{} - ans := map[string]string{ - konnectortypes.ClusterNamespaceAnnotationKey: providerNamespace, - } - obj.SetAnnotations(ans) - ors := []metav1.OwnerReference{{ - APIVersion: "v1", - Kind: "Namespace", - Name: providerNamespace, - }} - obj.SetOwnerReferences(ors) - - return obj -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/status/status_controller.go b/pkg/konnector/controllers/cluster/serviceexport/status/status_controller.go deleted file mode 100644 index c4b1da98a..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/status/status_controller.go +++ /dev/null @@ -1,404 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 status - -import ( - "context" - "fmt" - "time" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/client-go/dynamic/dynamiclister" - "k8s.io/client-go/informers" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/isolation" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/multinsinformer" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-cluster-status" -) - -// NewController returns a new controller reconciling status of upstream to downstream. -func NewController( - isolationStrategy isolation.Strategy, - gvr schema.GroupVersionResource, - providerNamespace string, - providerNamespaceUID string, - consumerConfig, providerConfig *rest.Config, - consumerDynamicInformer informers.GenericInformer, - providerDynamicInformer multinsinformer.GetterInformer, - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister], -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - consumerClient, err := dynamicclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - providerClient, err := dynamicclient.NewForConfig(providerConfig) - if err != nil { - return nil, err - } - - dynamicConsumerLister := dynamiclister.New(consumerDynamicInformer.Informer().GetIndexer(), gvr) - c := &controller{ - queue: queue, - - gvr: gvr, - providerNamespace: providerNamespace, - - consumerClient: consumerClient, - providerClient: providerClient, - - consumerDynamicLister: dynamicConsumerLister, - consumerDynamicIndexer: consumerDynamicInformer.Informer().GetIndexer(), - - providerDynamicInformer: providerDynamicInformer, - - serviceNamespaceInformer: serviceNamespaceInformer, - - reconciler: reconciler{ - isolationStrategy: isolationStrategy, - - getConsumerObject: func(ns, name string) (obj *unstructured.Unstructured, err error) { - if ns != "" { - obj, err = dynamicConsumerLister.Namespace(ns).Get(name) - } else { - obj, err = dynamicConsumerLister.Get(name) - } - - if err != nil { - return nil, err - } - - return obj.DeepCopy(), nil - }, - updateConsumerObject: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(obj.GetNamespace()).Update(ctx, obj, metav1.UpdateOptions{}) - }, - updateConsumerObjectStatus: func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - return consumerClient.Resource(gvr).Namespace(obj.GetNamespace()).UpdateStatus(ctx, obj, metav1.UpdateOptions{}) - }, - deleteProviderObject: func(ctx context.Context, ns, name string) error { - return providerClient.Resource(gvr).Namespace(ns).Delete(ctx, name, metav1.DeleteOptions{}) - }, - }, - } - - if _, err := consumerDynamicInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueConsumer(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueConsumer(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueConsumer(logger, obj) - }, - }); err != nil { - return nil, err - } - - if err := providerDynamicInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueProvider(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueProvider(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueProvider(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -// controller reconciles status of upstream to downstream. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - gvr schema.GroupVersionResource - providerNamespace string - - consumerClient, providerClient dynamicclient.Interface - - consumerDynamicLister dynamiclister.Lister - consumerDynamicIndexer cache.Indexer - - providerDynamicInformer multinsinformer.GetterInformer - - serviceNamespaceInformer dynamic.Informer[bindlisters.APIServiceNamespaceLister] - - reconciler -} - -func (c *controller) enqueueProvider(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return - } - - // Try to map the provider name back to the consumer name, - // but only to check if we "own" the object; we will actually - // enqueue the provider key after all. - consumerKey, err := c.isolationStrategy.ToConsumerKey(types.NamespacedName{ - Namespace: ns, - Name: name, - }) - if err != nil { - if !errors.IsNotFound(err) { - runtime.HandleError(err) - } - return - } - - if consumerKey == nil { - return - } - - logger.V(2).Info("queueing Unstructured", "queued", key) - c.queue.Add(key) -} - -func (c *controller) enqueueConsumer(logger klog.Logger, obj any) { - downstreamKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(downstreamKey) - if err != nil { - runtime.HandleError(err) - return - } - - providerKey, err := c.isolationStrategy.ToProviderKey(types.NamespacedName{ - Namespace: ns, - Name: name, - }) - if err != nil { - if !errors.IsNotFound(err) { - runtime.HandleError(err) - } - return - } - - if providerKey == nil { - return - } - - logger.V(2).Info("queueing Unstructured", "queued", providerKey) - c.queue.Add(providerKey.String()) -} - -func (c *controller) enqueueServiceNamespace(logger klog.Logger, obj any) { - snKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(snKey) - if err != nil { - runtime.HandleError(err) - return - } - if ns != c.providerNamespace { - return // not for us - } - - strategy, ok := c.isolationStrategy.(*isolation.ServiceNamespacedStrategy) - if !ok { // should not happen... but... - return - } - nsOnProviderCluster, err := strategy.ProviderNamespace(name) - if err != nil { - runtime.HandleError(err) - return - } - if nsOnProviderCluster == "" { - return // not ready - } - - objs, err := c.providerDynamicInformer.List(nsOnProviderCluster) - if err != nil { - runtime.HandleError(err) - return - } - for _, obj := range objs { - key, err := cache.MetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - continue - } - logger.V(2).Info("queueing Unstructured", "queued", key, "reason", "APIServiceNamespace", "ServiceNamespaceKey", snKey) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - // APIServiceNamespaces are only of interest when syncing namespaced - // objects, and since these event handlers need the appropriate isolation - // strategy, we only start them when necessary. - if _, ok := c.isolationStrategy.(*isolation.ServiceNamespacedStrategy); ok { - c.serviceNamespaceInformer.Informer().AddDynamicEventHandler(ctx, controllerName, cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceNamespace(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceNamespace(logger, obj) - }, - }) - } - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - obj, err := c.providerDynamicInformer.Get(ns, name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.V(2).Info("Upstream object disappeared") - - downstream, err := c.consumerDynamicLister.Namespace(ns).Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if err == nil { - if _, err := c.removeDownstreamFinalizer(ctx, downstream); err != nil { - return err - } - } - - return nil - } - - return c.reconcile(ctx, obj.(*unstructured.Unstructured)) -} - -func (c *controller) removeDownstreamFinalizer(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { - logger := klog.FromContext(ctx) - - finalizers := []string{} - found := false - for _, f := range obj.GetFinalizers() { - if f == kubebindv1alpha2.DownstreamFinalizer { - found = true - continue - } - finalizers = append(finalizers, f) - } - - if found { - logger.V(2).Info("removing finalizer from downstream object") - obj = obj.DeepCopy() - obj.SetFinalizers(finalizers) - var err error - if obj, err = c.consumerClient.Resource(c.gvr).Namespace(obj.GetNamespace()).Update(ctx, obj, metav1.UpdateOptions{}); err != nil && !errors.IsNotFound(err) { - return nil, err - } - } - - return obj, nil -} diff --git a/pkg/konnector/controllers/cluster/serviceexport/status/status_reconcile.go b/pkg/konnector/controllers/cluster/serviceexport/status/status_reconcile.go deleted file mode 100644 index efd7a9d48..000000000 --- a/pkg/konnector/controllers/cluster/serviceexport/status/status_reconcile.go +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 status - -import ( - "context" - "reflect" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster/serviceexport/isolation" - konnectortypes "github.com/kube-bind/kube-bind/pkg/konnector/types" -) - -type reconciler struct { - isolationStrategy isolation.Strategy - - getConsumerObject func(ns, name string) (*unstructured.Unstructured, error) - updateConsumerObject func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) - updateConsumerObjectStatus func(ctx context.Context, obj *unstructured.Unstructured) (*unstructured.Unstructured, error) - - deleteProviderObject func(ctx context.Context, ns, name string) error -} - -// reconcile syncs upstream status to consumer objects. -func (r *reconciler) reconcile(ctx context.Context, obj *unstructured.Unstructured) error { - logger := klog.FromContext(ctx) - - // Map the provider object namespace/name to the consumer side. Technically - // consumerKey should never be nil (for it to be nil, the namespace in the - // APIServiceNamespace's status must be blank, but it's blank, how could we - // have found an object in a non-defined namespace)?, but we are on the safe - // side and handle it anyway. - consumerKey, err := r.isolationStrategy.ToConsumerKey(types.NamespacedName{ - Namespace: obj.GetNamespace(), - Name: obj.GetName(), - }) - if err != nil { - if !errors.IsNotFound(err) { - return err - } - - return nil - } - if consumerKey == nil { - return nil - } - - logger = logger.WithValues("downstream", consumerKey) - - downstream, err := r.getConsumerObject(consumerKey.Namespace, consumerKey.Name) - if err != nil { - if errors.IsNotFound(err) { - // downstream is gone. Delete upstream too. Note that we cannot rely on the spec controller because - // due to konnector restart it might have missed the deletion event. - logger.Info("Deleting upstream object because downstream is gone") - return r.deleteProviderObject(ctx, obj.GetNamespace(), obj.GetName()) - } - - logger.Error(err, "failed to get downstream object") - return err - } - - // Set provider source metadata annotations on the consumer object so - // the consumer side can trace where the object came from. This requires - // a full object update because UpdateStatus does not persist metadata. - annotated := downstream.DeepCopy() - konnectortypes.SetSourceMetadataAnnotations(annotated, obj.GetNamespace(), string(obj.GetUID()), - konnectortypes.ProviderNamespaceAnnotationKey, konnectortypes.ProviderUIDAnnotationKey) - if !reflect.DeepEqual(downstream.GetAnnotations(), annotated.GetAnnotations()) { - logger.Info("Updating downstream object provider annotations") - var err error - if downstream, err = r.updateConsumerObject(ctx, annotated); err != nil { - return err - } - } - - // let the isolation perform any changes it desires - if err := r.isolationStrategy.MutateStatus(downstream, *consumerKey); err != nil { - return err - } - - orig := downstream - downstream = downstream.DeepCopy() - status, found, err := unstructured.NestedFieldNoCopy(obj.Object, "status") - if err != nil { - runtime.HandleError(err) - return nil // nothing we can do here - } - if found { - if err := unstructured.SetNestedField(downstream.Object, status, "status"); err != nil { - runtime.HandleError(err) - return nil // nothing we can do here - } - } else { - unstructured.RemoveNestedField(downstream.Object, "status") - } - - if !reflect.DeepEqual(orig, downstream) { - logger.Info("Updating downstream object status") - if _, err := r.updateConsumerObjectStatus(ctx, downstream); err != nil { - return err - } - } - - return nil -} diff --git a/pkg/konnector/controllers/contextstore/contextstore.go b/pkg/konnector/controllers/contextstore/contextstore.go deleted file mode 100644 index cd610d228..000000000 --- a/pkg/konnector/controllers/contextstore/contextstore.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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. -*/ - -// contextstore allows to manage and track context per controllers, stored at the different levels of the controller hierarchy: -// APIServiceExport - schemas and permissionClaims - each schema runs its own gvr controller and each permissionClaim runs its own controller. -// Context are stored at the APIServiceExport level. -package contextstore - -import ( - "strings" - "sync" -) - -type Key string - -func (k Key) String() string { - return string(k) -} - -func NewKey(exportNamespace, exportName string, suffix ...string) Key { - if len(suffix) == 0 { - return Key(exportNamespace + "." + exportName) - } - return Key(exportNamespace + "." + exportName + "." + strings.Join(suffix, ".")) -} - -type Store interface { - Get(key Key) (SyncContext, bool) - ListPrefixed(prefix Key) []SyncContext - Set(key Key, value SyncContext) - Delete(key Key) - BulkDeletePrefixed(prefix Key) []SyncContext -} - -type contextStore struct { - lock sync.Mutex - store map[Key]SyncContext -} - -type SyncContext struct { - key Key // reference key for the context for logging - Generation int64 - Cancel func() -} - -func New() Store { - return &contextStore{ - store: make(map[Key]SyncContext), - } -} - -func (c *SyncContext) Key() Key { - return c.key -} - -func (c *contextStore) Get(key Key) (SyncContext, bool) { - c.lock.Lock() - defer c.lock.Unlock() - val, ok := c.store[key] - return val, ok -} - -func (c *contextStore) ListPrefixed(prefix Key) []SyncContext { - c.lock.Lock() - defer c.lock.Unlock() - - var results []SyncContext - for k, v := range c.store { - if strings.HasPrefix(k.String(), prefix.String()) { - results = append(results, v) - } - } - return results -} - -func (c *contextStore) Set(key Key, value SyncContext) { - c.lock.Lock() - defer c.lock.Unlock() - value.key = key - c.store[key] = value -} - -func (c *contextStore) Delete(key Key) { - c.lock.Lock() - if ctx, ok := c.store[key]; ok { - defer ctx.Cancel() - delete(c.store, key) - } - c.lock.Unlock() -} - -func (c *contextStore) BulkDeletePrefixed(prefix Key) []SyncContext { - c.lock.Lock() - defer c.lock.Unlock() - - var deleted []SyncContext - var keysToDelete []Key - - for k, v := range c.store { - if strings.HasPrefix(k.String(), prefix.String()) { - keysToDelete = append(keysToDelete, k) - deleted = append(deleted, v) - } - } - - for _, k := range keysToDelete { - ctx := c.store[k] - ctx.Cancel() - delete(c.store, k) - } - - return deleted -} diff --git a/pkg/konnector/controllers/dynamic/eventhandler.go b/pkg/konnector/controllers/dynamic/eventhandler.go deleted file mode 100644 index 78a49b498..000000000 --- a/pkg/konnector/controllers/dynamic/eventhandler.go +++ /dev/null @@ -1,134 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 dynamic - -import ( - "context" - "fmt" - "sync" - - "k8s.io/client-go/tools/cache" -) - -type SharedIndexInformer interface { - // AddDynamicEventHandler adds a dynamic event handler to the informer. It's - // like AddEventHandler, but the handler is removed when the context closes. - // handlerName must be unique for each handler. - AddDynamicEventHandler(ctx context.Context, handlerName string, handler cache.ResourceEventHandler) - - // AddEventHandler shadows the method in the embedded SharedIndexInformer. But it - // will panic and should not be called. - AddEventHandler(handler cache.ResourceEventHandler) (cache.ResourceEventHandlerRegistration, error) - - cache.SharedIndexInformer -} - -type Informer[L any] interface { - Informer() SharedIndexInformer - Lister() L -} - -type StaticInformer[L any] interface { - Informer() cache.SharedIndexInformer - Lister() L -} - -type dynamicInformer[L any] struct { - StaticInformer[L] - sharedIndexInformer dynamicSharedIndexInformer -} - -type dynamicSharedIndexInformer struct { - cache.SharedIndexInformer - - lock sync.RWMutex - counter int - handlers map[string]cache.ResourceEventHandler -} - -// NewDynamicInformer returns a shared informer that allows adding and removing event -// handlers dynamically. -func NewDynamicInformer[L any](informer StaticInformer[L]) (Informer[L], error) { - di := &dynamicInformer[L]{ - StaticInformer: informer, - sharedIndexInformer: dynamicSharedIndexInformer{ - SharedIndexInformer: informer.Informer(), - handlers: make(map[string]cache.ResourceEventHandler), - }, - } - - if _, err := informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - di.sharedIndexInformer.lock.RLock() - defer di.sharedIndexInformer.lock.RUnlock() - for _, h := range di.sharedIndexInformer.handlers { - h.OnAdd(obj, false) - } - }, - UpdateFunc: func(oldObj, newObj any) { - di.sharedIndexInformer.lock.RLock() - defer di.sharedIndexInformer.lock.RUnlock() - for _, h := range di.sharedIndexInformer.handlers { - h.OnUpdate(oldObj, newObj) - } - }, - DeleteFunc: func(obj any) { - di.sharedIndexInformer.lock.RLock() - defer di.sharedIndexInformer.lock.RUnlock() - for _, h := range di.sharedIndexInformer.handlers { - h.OnDelete(obj) - } - }, - }); err != nil { - return nil, err - } - - return di, nil -} - -func (i *dynamicInformer[L]) Informer() SharedIndexInformer { - return &i.sharedIndexInformer -} - -func (i *dynamicInformer[L]) Lister() L { - return i.StaticInformer.Lister() -} - -func (i *dynamicSharedIndexInformer) AddDynamicEventHandler(ctx context.Context, handlerName string, handler cache.ResourceEventHandler) { - i.lock.Lock() - handlerName = fmt.Sprintf("%s-%d", handlerName, i.counter) - i.handlers[handlerName] = handler - i.counter++ // make unique - i.lock.Unlock() - - go func() { - <-ctx.Done() - i.lock.Lock() - defer i.lock.Unlock() - delete(i.handlers, handlerName) - }() - - // simulate initial add events for an informer that is already started. - objs := i.GetStore().List() - for _, obj := range objs { - handler.OnAdd(obj, true) - } -} - -func (i *dynamicSharedIndexInformer) AddEventHandler(handler cache.ResourceEventHandler) (cache.ResourceEventHandlerRegistration, error) { - panic("call AddDynamicEventHandler instead") -} diff --git a/pkg/konnector/controllers/servicebinding/servicebinding_controller.go b/pkg/konnector/controllers/servicebinding/servicebinding_controller.go deleted file mode 100644 index 88a9ee319..000000000 --- a/pkg/konnector/controllers/servicebinding/servicebinding_controller.go +++ /dev/null @@ -1,263 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicebinding - -import ( - "context" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - coreinformers "k8s.io/client-go/informers/core/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-servicebinding" -) - -// NewController returns a new controller for ServiceBindings. -func NewController( - consumerConfig *rest.Config, - serviceBindingInformer bindinformers.APIServiceBindingInformer, - consumerSecretInformer coreinformers.SecretInformer, -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - consumerBindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - - serviceBindingLister: serviceBindingInformer.Lister(), - serviceBindingIndexer: serviceBindingInformer.Informer().GetIndexer(), - - consumerSecretLister: consumerSecretInformer.Lister(), - - reconciler: reconciler{ - getConsumerSecret: func(ns, name string) (*corev1.Secret, error) { - return consumerSecretInformer.Lister().Secrets(ns).Get(name) - }, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.APIServiceBinding, *kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.APIServiceBinding] { - return consumerBindClient.KubeBindV1alpha2().APIServiceBindings() - }, - ), - } - - indexers.AddIfNotPresentOrDie(serviceBindingInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ByServiceBindingKubeconfigSecret: indexers.IndexServiceBindingByKubeconfigSecret, - }) - - if _, err := serviceBindingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceBinding(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := consumerSecretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueConsumerSecret(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -// controller reconciles ServiceBindings' kubeconfig secret references. It is -// here as an individual controller because the cluster controller is not running -// if the secret is invalid. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - serviceBindingLister bindlisters.APIServiceBindingLister - serviceBindingIndexer cache.Indexer - - consumerSecretLister corelisters.SecretLister - - reconciler - - commit CommitFunc -} - -func (c *controller) enqueueServiceBinding(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceBinding", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueConsumerSecret(logger klog.Logger, obj any) { - secretKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - bindings, err := c.serviceBindingIndexer.ByIndex(indexers.ByServiceBindingKubeconfigSecret, secretKey) - if err != nil && !errors.IsNotFound(err) { - runtime.HandleError(err) - return - } else if errors.IsNotFound(err) { - return // skip this secret - } - - for _, obj := range bindings { - binding := obj.(*kubebindv1alpha2.APIServiceBinding) - key, err := cache.MetaNamespaceKeyFunc(binding) - if err != nil { - runtime.HandleError(err) - return - } - logger.V(2).Info("queueing APIServiceBinding", "key", key, "reason", "Secret", "accessSecretKey", secretKey) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - <-ctx.Done() -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - _, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - obj, err := c.serviceBindingLister.Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.Error(err, "APIServiceBinding disappeared") - return nil - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} diff --git a/pkg/konnector/controllers/servicebinding/servicebinding_reconcile.go b/pkg/konnector/controllers/servicebinding/servicebinding_reconcile.go deleted file mode 100644 index 688da43a9..000000000 --- a/pkg/konnector/controllers/servicebinding/servicebinding_reconcile.go +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 servicebinding - -import ( - "context" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/client-go/tools/clientcmd" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" -) - -type reconciler struct { - getConsumerSecret func(ns, name string) (*corev1.Secret, error) -} - -func (r *reconciler) reconcile(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - var errs []error - - if err := r.ensureValidKubeconfigSecret(ctx, binding); err != nil { - errs = append(errs, err) - } - - conditions.SetSummary(binding) - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureValidKubeconfigSecret(_ context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - secret, err := r.getConsumerSecret(binding.Spec.KubeconfigSecretRef.Namespace, binding.Spec.KubeconfigSecretRef.Name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretNotFound", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s not found. Rerun kubectl bind for repair.", - binding.Spec.KubeconfigSecretRef.Namespace, binding.Spec.KubeconfigSecretRef.Name, - ) - return nil - } - - kubeconfig, found := secret.Data[binding.Spec.KubeconfigSecretRef.Key] - if !found { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s is missing %q string key.", - binding.Spec.KubeconfigSecretRef.Namespace, - binding.Spec.KubeconfigSecretRef.Name, - binding.Spec.KubeconfigSecretRef.Key, - ) - return nil - } - - cfg, err := clientcmd.Load(kubeconfig) - if err != nil { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: %v", - binding.Spec.KubeconfigSecretRef.Namespace, - binding.Spec.KubeconfigSecretRef.Name, - err, - ) - return nil - } - kubeContext, found := cfg.Contexts[cfg.CurrentContext] - if !found { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: current context %q not found", - binding.Spec.KubeconfigSecretRef.Namespace, - binding.Spec.KubeconfigSecretRef.Name, - cfg.CurrentContext, - ) - return nil - } - if kubeContext.Namespace == "" { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: current context %q has no namespace set", - binding.Spec.KubeconfigSecretRef.Namespace, - binding.Spec.KubeconfigSecretRef.Name, - cfg.CurrentContext, - ) - return nil - } - if _, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig); err != nil { - conditions.MarkFalse( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: %v", - binding.Spec.KubeconfigSecretRef.Namespace, - binding.Spec.KubeconfigSecretRef.Name, - err, - ) - return nil - } - - conditions.MarkTrue( - binding, - kubebindv1alpha2.APIServiceBindingConditionSecretValid, - ) - - return nil -} diff --git a/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_controller.go b/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_controller.go deleted file mode 100644 index ad593e2af..000000000 --- a/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_controller.go +++ /dev/null @@ -1,313 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 servicebindingbundle - -import ( - "context" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - coreinformers "k8s.io/client-go/informers/core/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector-servicebindingbundle" -) - -// NewController returns a new controller for ServiceBindingBundles. -func NewController( - consumerConfig *rest.Config, - serviceBindingBundleInformer bindinformers.APIServiceBindingBundleInformer, - serviceBindingInformer bindinformers.APIServiceBindingInformer, - consumerSecretInformer coreinformers.SecretInformer, - providerPollingInternaval time.Duration, -) (*controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("controller", controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - consumerBindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - c := &controller{ - queue: queue, - - serviceBindingBundleLister: serviceBindingBundleInformer.Lister(), - serviceBindingBundleIndexer: serviceBindingBundleInformer.Informer().GetIndexer(), - - serviceBindingLister: serviceBindingInformer.Lister(), - - consumerSecretLister: consumerSecretInformer.Lister(), - - consumerBindClient: consumerBindClient, - - reconciler: reconciler{ - providerPollingInternaval: providerPollingInternaval, - getConsumerSecret: func(ns, name string) (*corev1.Secret, error) { - return consumerSecretInformer.Lister().Secrets(ns).Get(name) - }, - listAPIServiceBindings: func() ([]*kubebindv1alpha2.APIServiceBinding, error) { - return serviceBindingInformer.Lister().List(labels.Everything()) - }, - consumerBindClient: consumerBindClient, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.APIServiceBindingBundle, *kubebindv1alpha2.APIServiceBindingBundleSpec, *kubebindv1alpha2.APIServiceBindingBundleStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.APIServiceBindingBundle] { - return consumerBindClient.KubeBindV1alpha2().APIServiceBindingBundles() - }, - ), - } - - indexers.AddIfNotPresentOrDie(serviceBindingBundleInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ByServiceBindingBundleKubeconfigSecret: indexers.IndexServiceBindingBundleByKubeconfigSecret, - }) - - if _, err := serviceBindingBundleInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceBindingBundle(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceBindingBundle(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceBindingBundle(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := consumerSecretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueConsumerSecret(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueConsumerSecret(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.APIServiceBindingBundleSpec, *kubebindv1alpha2.APIServiceBindingBundleStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -// controller reconciles ServiceBindingBundles' kubeconfig secret references and creates -// APIServiceBindings for each APIServiceExport found in the provider cluster. -type controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - serviceBindingBundleLister bindlisters.APIServiceBindingBundleLister - serviceBindingBundleIndexer cache.Indexer - - serviceBindingLister bindlisters.APIServiceBindingLister - - consumerSecretLister corelisters.SecretLister - - consumerBindClient bindclient.Interface - - reconciler - - commit CommitFunc -} - -func (c *controller) enqueueServiceBindingBundle(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceBindingBundle", "key", key) - c.queue.Add(key) -} - -func (c *controller) enqueueConsumerSecret(logger klog.Logger, obj any) { - secretKey, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - bundles, err := c.serviceBindingBundleIndexer.ByIndex(indexers.ByServiceBindingBundleKubeconfigSecret, secretKey) - if err != nil && !errors.IsNotFound(err) { - runtime.HandleError(err) - return - } else if errors.IsNotFound(err) { - return // skip this secret - } - - for _, obj := range bundles { - bundle := obj.(*kubebindv1alpha2.APIServiceBindingBundle) - key, err := cache.MetaNamespaceKeyFunc(bundle) - if err != nil { - runtime.HandleError(err) - return - } - logger.V(2).Info("queueing APIServiceBindingBundle", "key", key, "reason", "Secret", "accessSecretKey", secretKey) - c.queue.Add(key) - } -} - -// Start starts the controller, which stops when ctx.Done() is closed. -func (c *controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - - logger.Info("Starting controller") - defer logger.Info("Shutting down controller") - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - // Start polling goroutine that re-queues all bundles every x seconds - // TODO(mjudeikis): make this a long lived watch on the provider cluster instead. - go c.startPoller(ctx) - - <-ctx.Done() -} - -func (c *controller) startPoller(ctx context.Context) { - defer runtime.HandleCrash() - - logger := klog.FromContext(ctx).WithValues("controller", controllerName) - ticker := time.NewTicker(c.providerPollingInternaval) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - // List all bundles and re-queue them for reconciliation - bundles, err := c.serviceBindingBundleLister.List(labels.Everything()) - if err != nil { - logger.Error(err, "failed to list APIServiceBindingBundles for polling") - continue - } - for _, bundle := range bundles { - key, err := cache.MetaNamespaceKeyFunc(bundle) - if err != nil { - runtime.HandleError(err) - continue - } - logger.V(3).Info("polling: queueing APIServiceBindingBundle", "key", key) - c.queue.Add(key) - } - } - } -} - -func (c *controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.V(2).Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -func (c *controller) process(ctx context.Context, key string) error { - _, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - logger := klog.FromContext(ctx) - - obj, err := c.serviceBindingBundleLister.Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - logger.Error(err, "APIServiceBindingBundle disappeared") - return nil - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} diff --git a/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_reconcile.go b/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_reconcile.go deleted file mode 100644 index 7fec08ae1..000000000 --- a/pkg/konnector/controllers/servicebindingbundle/servicebindingbundle_reconcile.go +++ /dev/null @@ -1,307 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 servicebindingbundle - -import ( - "context" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/util/conditions" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" -) - -const ( - // APIServiceBindingBundleConditionSecretValid is set when the secret is valid. - APIServiceBindingBundleConditionSecretValid conditionsapi.ConditionType = "SecretValid" - - // APIServiceBindingBundleConditionSynced is set when all APIServiceBindings are synced. - APIServiceBindingBundleConditionSynced conditionsapi.ConditionType = "Synced" -) - -type reconciler struct { - providerPollingInternaval time.Duration - getConsumerSecret func(ns, name string) (*corev1.Secret, error) - listAPIServiceBindings func() ([]*kubebindv1alpha2.APIServiceBinding, error) - consumerBindClient bindclient.Interface -} - -func (r *reconciler) reconcile(ctx context.Context, bundle *kubebindv1alpha2.APIServiceBindingBundle) error { - var errs []error - - // First validate the kubeconfig secret - providerConfig, providerNamespace, err := r.ensureValidKubeconfigSecret(ctx, bundle) - if err != nil { - errs = append(errs, err) - } - - // Only proceed to sync bindings if we have a valid kubeconfig - if providerConfig != nil { - if err := r.syncAPIServiceBindings(ctx, bundle, providerConfig, providerNamespace); err != nil { - errs = append(errs, err) - } - } - - conditions.SetSummary(bundle) - - return utilerrors.NewAggregate(errs) -} - -func (r *reconciler) ensureValidKubeconfigSecret(_ context.Context, bundle *kubebindv1alpha2.APIServiceBindingBundle) (*rest.Config, string, error) { - secret, err := r.getConsumerSecret(bundle.Spec.KubeconfigSecretRef.Namespace, bundle.Spec.KubeconfigSecretRef.Name) - if err != nil && !errors.IsNotFound(err) { - return nil, "", err - } else if errors.IsNotFound(err) { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretNotFound", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s not found.", - bundle.Spec.KubeconfigSecretRef.Namespace, bundle.Spec.KubeconfigSecretRef.Name, - ) - return nil, "", nil - } - - kubeconfig, found := secret.Data[bundle.Spec.KubeconfigSecretRef.Key] - if !found { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s is missing %q string key.", - bundle.Spec.KubeconfigSecretRef.Namespace, - bundle.Spec.KubeconfigSecretRef.Name, - bundle.Spec.KubeconfigSecretRef.Key, - ) - return nil, "", nil - } - - cfg, err := clientcmd.Load(kubeconfig) - if err != nil { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: %v", - bundle.Spec.KubeconfigSecretRef.Namespace, - bundle.Spec.KubeconfigSecretRef.Name, - err, - ) - return nil, "", nil - } - kubeContext, found := cfg.Contexts[cfg.CurrentContext] - if !found { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: current context %q not found", - bundle.Spec.KubeconfigSecretRef.Namespace, - bundle.Spec.KubeconfigSecretRef.Name, - cfg.CurrentContext, - ) - return nil, "", nil - } - if kubeContext.Namespace == "" { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: current context %q has no namespace set", - bundle.Spec.KubeconfigSecretRef.Namespace, - bundle.Spec.KubeconfigSecretRef.Name, - cfg.CurrentContext, - ) - return nil, "", nil - } - restConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig) - if err != nil { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSecretValid, - "KubeconfigSecretInvalid", - conditionsapi.ConditionSeverityError, - "Kubeconfig secret %s/%s has an invalid kubeconfig: %v", - bundle.Spec.KubeconfigSecretRef.Namespace, - bundle.Spec.KubeconfigSecretRef.Name, - err, - ) - return nil, "", nil - } - - conditions.MarkTrue( - bundle, - APIServiceBindingBundleConditionSecretValid, - ) - - return restConfig, kubeContext.Namespace, nil -} - -func (r *reconciler) syncAPIServiceBindings(ctx context.Context, bundle *kubebindv1alpha2.APIServiceBindingBundle, providerConfig *rest.Config, providerNamespace string) error { - logger := klog.FromContext(ctx) - - // Create a client for the provider cluster - providerClient, err := bindclient.NewForConfig(providerConfig) - if err != nil { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSynced, - "ProviderClientError", - conditionsapi.ConditionSeverityError, - "Failed to create provider cluster client: %v", - err, - ) - return err - } - - // List all APIServiceExports from the provider cluster - exports, err := providerClient.KubeBindV1alpha2().APIServiceExports(providerNamespace).List(ctx, metav1.ListOptions{}) - if err != nil { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSynced, - "ListExportsFailed", - conditionsapi.ConditionSeverityError, - "Failed to list APIServiceExports from provider cluster: %v", - err, - ) - return err - } - - logger.V(2).Info("Found APIServiceExports in provider cluster", "count", len(exports.Items)) - - // Get existing APIServiceBindings owned by this bundle - allBindings, err := r.listAPIServiceBindings() - if err != nil { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSynced, - "ListBindingsFailed", - conditionsapi.ConditionSeverityError, - "Failed to list APIServiceBindings: %v", - err, - ) - return err - } - - // Filter bindings owned by this bundle - ownedBindings := make(map[string]*kubebindv1alpha2.APIServiceBinding) - for _, binding := range allBindings { - for _, ownerRef := range binding.OwnerReferences { - if ownerRef.APIVersion == kubebindv1alpha2.SchemeGroupVersion.String() && - ownerRef.Kind == "APIServiceBindingBundle" && - ownerRef.Name == bundle.Name && - ownerRef.UID == bundle.UID { - ownedBindings[binding.Name] = binding - break - } - } - } - - // Create or update APIServiceBindings for each export - var errs []error - expectedBindings := make(map[string]bool) - for _, export := range exports.Items { - // Generate a unique name for the binding based on bundle name and export - expectedBindings[export.Name] = true - - if existingBinding, exists := ownedBindings[export.Name]; exists { - // Binding already exists, check if it needs update - logger.V(2).Info("APIServiceBinding already exists", "binding", export.Name) - // Check if kubeconfig secret ref matches - if existingBinding.Spec.KubeconfigSecretRef != bundle.Spec.KubeconfigSecretRef { - // Update is needed but spec is immutable, so we skip this - logger.V(2).Info("APIServiceBinding spec differs but is immutable", "binding", export.Name) - } - continue - } - - // Create new APIServiceBinding - binding := &kubebindv1alpha2.APIServiceBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: export.Name, - OwnerReferences: []metav1.OwnerReference{ - { - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "APIServiceBindingBundle", - Name: bundle.Name, - UID: bundle.UID, - Controller: func() *bool { b := true; return &b }(), - }, - }, - }, - Spec: kubebindv1alpha2.APIServiceBindingSpec{ - KubeconfigSecretRef: bundle.Spec.KubeconfigSecretRef, - }, - } - - logger.Info("Creating APIServiceBinding", "binding", export.Name, "export", fmt.Sprintf("%s/%s", export.Namespace, export.Name)) - if _, err := r.consumerBindClient.KubeBindV1alpha2().APIServiceBindings().Create(ctx, binding, metav1.CreateOptions{}); err != nil { - if !errors.IsAlreadyExists(err) { - logger.Error(err, "Failed to create APIServiceBinding", "binding", export.Name) - errs = append(errs, err) - } - } - } - - // Delete orphaned APIServiceBindings (those owned by this bundle but no longer have a corresponding export) - for bindingName, binding := range ownedBindings { - if !expectedBindings[bindingName] { - logger.Info("Deleting orphaned APIServiceBinding", "binding", bindingName) - if err := r.consumerBindClient.KubeBindV1alpha2().APIServiceBindings().Delete(ctx, binding.Name, metav1.DeleteOptions{}); err != nil { - if !errors.IsNotFound(err) { - logger.Error(err, "Failed to delete orphaned APIServiceBinding", "binding", bindingName) - errs = append(errs, err) - } - } - } - } - - if len(errs) > 0 { - conditions.MarkFalse( - bundle, - APIServiceBindingBundleConditionSynced, - "SyncErrors", - conditionsapi.ConditionSeverityWarning, - "Failed to sync some APIServiceBindings: %d error(s)", - len(errs), - ) - return utilerrors.NewAggregate(errs) - } - - conditions.MarkTrue( - bundle, - APIServiceBindingBundleConditionSynced, - ) - - return nil -} diff --git a/pkg/konnector/konnector_controller.go b/pkg/konnector/konnector_controller.go deleted file mode 100644 index c4ac1e402..000000000 --- a/pkg/konnector/konnector_controller.go +++ /dev/null @@ -1,374 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 konnector - -import ( - "context" - "fmt" - "strings" - "time" - - corev1 "k8s.io/api/core/v1" - crdinformers "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - coreinformers "k8s.io/client-go/informers/core/v1" - corelisters "k8s.io/client-go/listers/core/v1" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/pkg/committer" - "github.com/kube-bind/kube-bind/pkg/indexers" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/cluster" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/dynamic" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/servicebinding" - "github.com/kube-bind/kube-bind/pkg/konnector/controllers/servicebindingbundle" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - bindclient "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - bindinformers "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" - bindlisters "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" -) - -const ( - controllerName = "kube-bind-konnector" -) - -// New returns a konnector controller. -func New( - consumerConfig *rest.Config, - serviceBindingInformer bindinformers.APIServiceBindingInformer, - serviceBindingBundleInformer bindinformers.APIServiceBindingBundleInformer, - secretInformer coreinformers.SecretInformer, - namespaceInformer coreinformers.NamespaceInformer, - crdInformer crdinformers.CustomResourceDefinitionInformer, - bundlePollingInterval time.Duration, -) (*Controller, error) { - queue := workqueue.NewTypedRateLimitingQueueWithConfig(workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{Name: controllerName}) - - logger := klog.Background().WithValues("Controller", controllerName) - - consumerConfig = rest.CopyConfig(consumerConfig) - consumerConfig = rest.AddUserAgent(consumerConfig, controllerName) - - bindClient, err := bindclient.NewForConfig(consumerConfig) - if err != nil { - return nil, err - } - - servicebindingCtrl, err := servicebinding.NewController(consumerConfig, serviceBindingInformer, secretInformer) - if err != nil { - return nil, err - } - - servicebindingbundleCtrl, err := servicebindingbundle.NewController(consumerConfig, serviceBindingBundleInformer, serviceBindingInformer, secretInformer, bundlePollingInterval) - if err != nil { - return nil, err - } - - namespaceDynamicInformer, err := dynamic.NewDynamicInformer(namespaceInformer) - if err != nil { - return nil, err - } - serviceBindingDynamicInformer, err := dynamic.NewDynamicInformer(serviceBindingInformer) - if err != nil { - return nil, err - } - crdDynamicInformer, err := dynamic.NewDynamicInformer(crdInformer) - if err != nil { - return nil, err - } - - c := &Controller{ - queue: queue, - - consumerConfig: consumerConfig, - bindClient: bindClient, - - serviceBindingLister: serviceBindingInformer.Lister(), - serviceBindingIndexer: serviceBindingInformer.Informer().GetIndexer(), - - secretLister: secretInformer.Lister(), - secretIndexer: secretInformer.Informer().GetIndexer(), - - ServiceBindingCtrl: servicebindingCtrl, - ServiceBindingBundleCtrl: servicebindingbundleCtrl, - - reconciler: reconciler{ - controllers: map[string]*controllerContext{}, - getSecret: func(ns, name string) (*corev1.Secret, error) { - return secretInformer.Lister().Secrets(ns).Get(name) - }, - newClusterController: func(consumerSecretRefKey, providerNamespace string, reconcileServiceBinding func(binding *kubebindv1alpha2.APIServiceBinding) bool, providerConfig *rest.Config) (startable, error) { - providerConfig = rest.CopyConfig(providerConfig) - providerConfig = rest.AddUserAgent(providerConfig, controllerName) - - return cluster.NewController( - consumerSecretRefKey, - providerNamespace, - reconcileServiceBinding, - consumerConfig, - providerConfig, - namespaceDynamicInformer, - serviceBindingDynamicInformer, - crdDynamicInformer, - ) - }, - }, - - commit: committer.NewCommitter[*kubebindv1alpha2.APIServiceBinding, *kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus]( - func(ns string) committer.Patcher[*kubebindv1alpha2.APIServiceBinding] { - return bindClient.KubeBindV1alpha2().APIServiceBindings() - }, - ), - } - - indexers.AddIfNotPresentOrDie(serviceBindingInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.ByServiceBindingKubeconfigSecret: indexers.IndexServiceBindingByKubeconfigSecret, - }) - - indexers.AddIfNotPresentOrDie(crdInformer.Informer().GetIndexer(), cache.Indexers{ - indexers.CRDByServiceBinding: indexers.IndexCRDByServiceBinding, - }) - - if _, err := serviceBindingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueServiceBinding(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueServiceBinding(logger, obj) - }, - }); err != nil { - return nil, err - } - - if _, err := secretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: func(obj any) { - c.enqueueSecret(logger, obj) - }, - UpdateFunc: func(_, newObj any) { - c.enqueueSecret(logger, newObj) - }, - DeleteFunc: func(obj any) { - c.enqueueSecret(logger, obj) - }, - }); err != nil { - return nil, err - } - - return c, nil -} - -type Resource = committer.Resource[*kubebindv1alpha2.APIServiceBindingSpec, *kubebindv1alpha2.APIServiceBindingStatus] -type CommitFunc = func(context.Context, *Resource, *Resource) error - -type GenericController interface { - Start(ctx context.Context, numThreads int) -} - -// Controller is the top-level Controller watching ServiceBindings and -// service provider credentials, and then starts APIServiceBinding controllers -// dynamically. -type Controller struct { - queue workqueue.TypedRateLimitingInterface[string] - - consumerConfig *rest.Config - bindClient bindclient.Interface - - serviceBindingLister bindlisters.APIServiceBindingLister - serviceBindingIndexer cache.Indexer - - secretLister corelisters.SecretLister - secretIndexer cache.Indexer - - ServiceBindingCtrl GenericController - ServiceBindingBundleCtrl GenericController - - reconciler - - commit CommitFunc -} - -func (c *Controller) enqueueServiceBinding(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - - logger.V(2).Info("queueing APIServiceBinding", "key", key) - c.queue.Add(key) -} - -func (c *Controller) enqueueSecret(logger klog.Logger, obj any) { - key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - return - } - ns, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return - } - - // Check if this is a provider kubeconfig secret (for early heartbeat) - secret, ok := obj.(*corev1.Secret) - if ok && secret.Labels[kubebindv1alpha2.LabelProviderKubeconfig] == "true" { - // Queue it as a heartbeat secret with a special prefix - logger.V(2).Info("queueing heartbeat secret", "key", key) - c.queue.Add("__heartbeat_secret__" + key) - } - - bindings, err := c.serviceBindingIndexer.ByIndex(indexers.ByServiceBindingKubeconfigSecret, fmt.Sprintf("%s/%s", ns, name)) - if err != nil { - runtime.HandleError(err) - return - } - if len(bindings) == 0 { - return - } - - for _, obj := range bindings { - bindingKey, err := cache.MetaNamespaceKeyFunc(obj) - if err != nil { - runtime.HandleError(err) - continue - } - logger.V(2).Info("queueing APIServiceBinding", "key", bindingKey, "reason", "Secret", "SecretKey", key) - c.queue.Add(bindingKey) - } -} - -// Start starts the konnector. It does block. -func (c *Controller) Start(ctx context.Context, numThreads int) { - defer runtime.HandleCrash() - defer c.queue.ShutDown() - - logger := klog.FromContext(ctx).WithValues("Controller", controllerName) - - logger.Info("Starting Controller") - defer logger.Info("Shutting down Controller") - - for i := 0; i < numThreads; i++ { - go wait.UntilWithContext(ctx, c.startWorker, time.Second) - } - - go c.ServiceBindingCtrl.Start(ctx, numThreads) - go c.ServiceBindingBundleCtrl.Start(ctx, numThreads) - - <-ctx.Done() -} - -func (c *Controller) startWorker(ctx context.Context) { - defer runtime.HandleCrash() - - for c.processNextWorkItem(ctx) { - } -} - -func (c *Controller) processNextWorkItem(ctx context.Context) bool { - // Wait until there is a new item in the working queue - key, quit := c.queue.Get() - if quit { - return false - } - - logger := klog.FromContext(ctx).WithValues("key", key) - ctx = klog.NewContext(ctx, logger) - logger.Info("processing key") - - // No matter what, tell the queue we're done with this key, to unblock - // other workers. - defer c.queue.Done(key) - - if err := c.process(ctx, key); err != nil { - runtime.HandleError(fmt.Errorf("%q Controller failed to sync %q, err: %w", controllerName, key, err)) - c.queue.AddRateLimited(key) - return true - } - c.queue.Forget(key) - return true -} - -const heartbeatSecretPrefix = "__heartbeat_secret__" - -func (c *Controller) process(ctx context.Context, key string) error { - logger := klog.FromContext(ctx) - - // Handle heartbeat secret keys (for early heartbeat without APIServiceBinding) - if strings.HasPrefix(key, heartbeatSecretPrefix) { - secretKey := strings.TrimPrefix(key, heartbeatSecretPrefix) - ns, name, err := cache.SplitMetaNamespaceKey(secretKey) - if err != nil { - runtime.HandleError(err) - return nil - } - - secret, err := c.secretLister.Secrets(ns).Get(name) - if err != nil { - if errors.IsNotFound(err) { - logger.V(2).Info("heartbeat secret not found, skipping", "secret", secretKey) - return nil - } - return err - } - - // Start controller for this secret - return c.reconciler.startClusterControllerForSecret(ctx, secret) - } - - _, name, err := cache.SplitMetaNamespaceKey(key) - if err != nil { - runtime.HandleError(err) - return nil // we cannot do anything - } - - obj, err := c.serviceBindingLister.Get(name) - if err != nil && !errors.IsNotFound(err) { - return err - } else if errors.IsNotFound(err) { - // update remote condition - return nil - } - - old := obj - obj = obj.DeepCopy() - - var errs []error - if err := c.reconcile(ctx, obj); err != nil { - errs = append(errs, err) - } - - // Regardless of whether reconcile returned an error or not, always try to patch status if needed. Return the - // reconciliation error at the end. - - // If the object being reconciled changed as a result, update it. - oldResource := &Resource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} - newResource := &Resource{ObjectMeta: obj.ObjectMeta, Spec: &obj.Spec, Status: &obj.Status} - if err := c.commit(ctx, oldResource, newResource); err != nil { - errs = append(errs, err) - } - - return utilerrors.NewAggregate(errs) -} diff --git a/pkg/konnector/konnector_reconcile.go b/pkg/konnector/konnector_reconcile.go deleted file mode 100644 index b472e46d0..000000000 --- a/pkg/konnector/konnector_reconcile.go +++ /dev/null @@ -1,269 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 konnector - -import ( - "context" - "sync" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type startable interface { - Start(ctx context.Context) -} - -// reconciler manages cluster controllers for provider connections. -// -// Controller Sharing Model: -// ------------------------- -// Multiple APIServiceBindings can share the same cluster controller if they use the same -// kubeconfig (i.e., connect to the same provider namespace). This is tracked via controllerContext: -// -// r.controllers map: -// "__heartbeat__kubeconfig-xyz" -> controllerContext{kubeconfig: "...", serviceBindings: ["__heartbeat__kubeconfig-xyz", "binding-a", "binding-b"]} -// "binding-a" -> (same controllerContext as above) -// "binding-b" -> (same controllerContext as above) -// -// Flow when APIServiceBinding arrives using same kubeconfig as existing heartbeat controller: -// 1. reconcile() is called with the new binding -// 2. It extracts kubeconfig from binding.Spec.KubeconfigSecretRef -// 3. It loops through r.controllers looking for matching kubeconfig (lines 174-182) -// 4. Finds the existing controllerContext (created by startClusterControllerForSecret) -// 5. Points r.controllers[binding.Name] to the SAME controllerContext -// 6. Adds binding.Name to controllerContext.serviceBindings set -// 7. No new controller is started - the existing one handles everything -type reconciler struct { - lock sync.RWMutex - controllers map[string]*controllerContext // keyed by binding name or synthetic heartbeat key - - newClusterController func(consumerSecretRefKey, providerNamespace string, reconcileServiceBinding func(binding *kubebindv1alpha2.APIServiceBinding) bool, providerConfig *rest.Config) (startable, error) - getSecret func(ns, name string) (*corev1.Secret, error) -} - -// controllerContext tracks a running cluster controller and the bindings it serves. -// Multiple map entries in reconciler.controllers can point to the same controllerContext -// when they share the same kubeconfig. -type controllerContext struct { - kubeconfig string // the kubeconfig content - used to match bindings to controllers - cancel func() // cancels the controller's context when no bindings remain - serviceBindings sets.Set[string] // all binding names (including synthetic heartbeat keys) using this controller -} - -// startClusterControllerForSecret starts a cluster controller for the given kubeconfig secret. -// This enables heartbeat reporting immediately without requiring an APIServiceBinding. -// -// The controller is registered with a synthetic key "__heartbeat__". -// When an APIServiceBinding later arrives using the same kubeconfig, reconcile() will: -// 1. Find this existing controller by matching kubeconfig content -// 2. Add the binding to the same controllerContext.serviceBindings set -// 3. Point r.controllers[binding.Name] to the same controllerContext -// 4. NOT start a new controller (reuses existing one) -func (r *reconciler) startClusterControllerForSecret(ctx context.Context, secret *corev1.Secret) error { - logger := klog.FromContext(ctx) - - kubeconfig := string(secret.Data["kubeconfig"]) - if kubeconfig == "" { - logger.V(2).Info("secret does not contain kubeconfig", "secret", secret.Namespace+"/"+secret.Name) - return nil - } - - r.lock.Lock() - defer r.lock.Unlock() - - // Check if we already have a controller for this kubeconfig - for _, ctrlContext := range r.controllers { - if ctrlContext.kubeconfig == kubeconfig { - logger.V(2).Info("cluster controller already exists for secret", "secret", secret.Namespace+"/"+secret.Name) - return nil - } - } - - // Extract which namespace this kubeconfig points to - cfg, err := clientcmd.Load([]byte(kubeconfig)) - if err != nil { - logger.Error(err, "invalid kubeconfig in secret", "namespace", secret.Namespace, "name", secret.Name) - return nil // nothing we can do here - } - kubeContext, found := cfg.Contexts[cfg.CurrentContext] - if !found { - logger.Error(err, "kubeconfig in secret does not have a current context", "namespace", secret.Namespace, "name", secret.Name) - return nil - } - if kubeContext.Namespace == "" { - logger.Error(err, "kubeconfig in secret does not have a namespace set for the current context", "namespace", secret.Namespace, "name", secret.Name) - return nil - } - providerNamespace := kubeContext.Namespace - providerConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig)) - if err != nil { - logger.Error(err, "invalid kubeconfig in secret", "namespace", secret.Namespace, "name", secret.Name) - return nil - } - - // Use the secret name as a synthetic binding key for tracking. - // This key is used to track the controller context, but the controller - // will also handle real APIServiceBindings that use the same kubeconfig. - syntheticKey := "__heartbeat__" + secret.Name - - ctrlCtx, cancel := context.WithCancel(ctx) - ctrlContext := &controllerContext{ - kubeconfig: kubeconfig, - cancel: cancel, - serviceBindings: sets.New(syntheticKey), - } - r.controllers[syntheticKey] = ctrlContext - - // Create and start the cluster controller. - // The reconcileServiceBinding function checks if a binding should be processed - // by this controller. We check if the binding is in our serviceBindings set, - // which will include both the synthetic heartbeat key and any real bindings - // that get added later when they use the same kubeconfig. - logger.Info("starting cluster controller for early heartbeat", "secret", secret.Namespace+"/"+secret.Name, "providerNamespace", providerNamespace) - ctrl, err := r.newClusterController( - secret.Namespace+"/"+secret.Name, - providerNamespace, - func(svcBinding *kubebindv1alpha2.APIServiceBinding) bool { - r.lock.RLock() - defer r.lock.RUnlock() - // Check if this binding is registered with this controller context - return ctrlContext.serviceBindings.Has(svcBinding.Name) - }, - providerConfig, - ) - if err != nil { - logger.Error(err, "failed to start cluster controller for heartbeat") - cancel() - delete(r.controllers, syntheticKey) - return err - } - - go ctrl.Start(ctrlCtx) - - return nil -} - -func (r *reconciler) reconcile(ctx context.Context, binding *kubebindv1alpha2.APIServiceBinding) error { - logger := klog.FromContext(ctx) - - var kubeconfig string - - ref := binding.Spec.KubeconfigSecretRef - secret, err := r.getSecret(ref.Namespace, ref.Name) - switch { - case errors.IsNotFound(err): - logger.V(2).Info("secret not found", "secret", ref.Namespace+"/"+ref.Name) - case err != nil: - return err - default: - kubeconfig = string(secret.Data[ref.Key]) - } - - r.lock.Lock() - defer r.lock.Unlock() - ctrlContext, found := r.controllers[binding.Name] - - // stop existing with old kubeconfig - if found && ctrlContext.kubeconfig != kubeconfig { - logger.V(2).Info("stopping Controller with old kubeconfig", "secret", ref.Namespace+"/"+ref.Name) - ctrlContext.serviceBindings.Delete(binding.Name) - if len(ctrlContext.serviceBindings) == 0 { - ctrlContext.cancel() - } - delete(r.controllers, binding.Name) - } - - // no need to start a new one - if kubeconfig == "" { - return nil - } - - // Find existing controller with the same kubeconfig. - // This handles the case where: - // 1. A heartbeat controller was started from a labeled secret (via startClusterControllerForSecret) - // 2. An APIServiceBinding now arrives that uses the same kubeconfig - // 3. Instead of starting a duplicate controller, we reuse the existing one - // - // The binding is added to the existing controllerContext's serviceBindings set, - // and r.controllers[binding.Name] points to the same controllerContext. - for _, ctrlContext := range r.controllers { - if ctrlContext.kubeconfig == kubeconfig { - // Reuse existing controller - no new controller started - logger.V(2).Info("adding binding to existing Controller", "secret", ref.Namespace+"/"+ref.Name) - r.controllers[binding.Name] = ctrlContext - ctrlContext.serviceBindings.Insert(binding.Name) - return nil - } - } - - // extract which namespace this kubeconfig points to - cfg, err := clientcmd.Load([]byte(kubeconfig)) - if err != nil { - logger.Error(err, "invalid kubeconfig in secret", "namespace", ref.Namespace, "name", ref.Name) - return nil // nothing we can do here. The APIServiceBinding Controller will set a condition - } - kubeContext, found := cfg.Contexts[cfg.CurrentContext] - if !found { - logger.Error(err, "kubeconfig in secret does not have a current context", "namespace", ref.Namespace, "name", ref.Name) - return nil // nothing we can do here. The APIServiceBinding Controller will set a condition - } - if kubeContext.Namespace == "" { - logger.Error(err, "kubeconfig in secret does not have a namespace set for the current context", "namespace", ref.Namespace, "name", ref.Name) - return nil // nothing we can do here. The APIServiceBinding Controller will set a condition - } - providerNamespace := kubeContext.Namespace - providerConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig)) - if err != nil { - logger.Error(err, "invalid kubeconfig in secret", "namespace", ref.Namespace, "name", ref.Name) - return nil // nothing we can do here. The APIServiceBinding Controller will set a condition - } - - ctrlCtx, cancel := context.WithCancel(ctx) //nolint:gosec - r.controllers[binding.Name] = &controllerContext{ - kubeconfig: kubeconfig, - cancel: cancel, - serviceBindings: sets.New(binding.Name), - } - - // create new because there is none yet for this kubeconfig - logger.V(2).Info("starting new Controller", "secret", ref.Namespace+"/"+ref.Name) - ctrl, err := r.newClusterController( - binding.Spec.KubeconfigSecretRef.Namespace+"/"+binding.Spec.KubeconfigSecretRef.Name, - providerNamespace, - func(svcBinding *kubebindv1alpha2.APIServiceBinding) bool { - r.lock.RLock() - defer r.lock.RUnlock() - return r.controllers[binding.Name].serviceBindings.Has(svcBinding.Name) - }, - providerConfig, - ) - if err != nil { - logger.Error(err, "failed to start new cluster Controller") - return err - } - - go ctrl.Start(ctrlCtx) - - return nil -} diff --git a/pkg/konnector/options/options.go b/pkg/konnector/options/options.go deleted file mode 100644 index 062014f5e..000000000 --- a/pkg/konnector/options/options.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 options - -import ( - "fmt" - "math/rand" - "os" - "time" - - "github.com/spf13/pflag" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" -) - -type Options struct { - Logs *logs.Options - - ExtraOptions -} - -type ExtraOptions struct { - KubeConfigPath string - Context string - - LeaseLockName string - LeaseLockNamespace string - LeaseLockIdentity string - - ServerAddr string - ProviderPollingInterval time.Duration -} - -type completedOptions struct { - Logs *logs.Options - - ExtraOptions -} - -type CompletedOptions struct { - *completedOptions -} - -func NewOptions() *Options { - // Default to -v=2 - logs := logs.NewOptions() - logs.Verbosity = logsv1.VerbosityLevel(2) - - opts := &Options{ - Logs: logs, - - ExtraOptions: ExtraOptions{ - LeaseLockName: "kube-bind", - LeaseLockNamespace: os.Getenv("POD_NAMESPACE"), - LeaseLockIdentity: os.Getenv("POD_NAME"), - }, - } - - if opts.LeaseLockNamespace == "" { - opts.LeaseLockNamespace = "kube-system" - } - - return opts -} - -func (options *Options) AddFlags(fs *pflag.FlagSet) { - logsv1.AddFlags(options.Logs, fs) - - fs.StringVar(&options.KubeConfigPath, "kubeconfig", options.KubeConfigPath, "Kubeconfig file for the local cluster.") - fs.StringVar(&options.Context, "context", options.Context, "The name of the kubeconfig context to use.") - fs.StringVar(&options.LeaseLockName, "lease-name", options.LeaseLockName, "Name of lease lock") - fs.StringVar(&options.LeaseLockNamespace, "lease-namespace", options.LeaseLockNamespace, "Name of lease lock namespace") - fs.StringVar(&options.ServerAddr, "server-address", options.ServerAddr, "Address for server") - fs.DurationVar(&options.ProviderPollingInterval, "provider-polling-interval", 15*time.Second, "Interval for polling provider for updates") -} - -func (options *Options) Complete() (*CompletedOptions, error) { - if options.LeaseLockIdentity == "" { - options.LeaseLockIdentity = fmt.Sprintf("%d", rand.Int31()) //nolint:gosec - } - - return &CompletedOptions{ - completedOptions: &completedOptions{ - Logs: options.Logs, - ExtraOptions: options.ExtraOptions, - }, - }, nil -} - -func (options *CompletedOptions) Validate() error { - return nil -} diff --git a/pkg/konnector/server.go b/pkg/konnector/server.go deleted file mode 100644 index 1da470c16..000000000 --- a/pkg/konnector/server.go +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 konnector - -import ( - "context" - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/klog/v2" - - "github.com/kube-bind/kube-bind/deploy/crd" - server "github.com/kube-bind/kube-bind/pkg/konnector/server" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type Server struct { - Config *Config - Controller *Controller - - webServer *server.Server -} - -func NewServer(config *Config) (*Server, error) { - // construct controllers - k, err := New( - config.ClientConfig, - config.BindInformers.KubeBind().V1alpha2().APIServiceBindings(), - config.BindInformers.KubeBind().V1alpha2().APIServiceBindingBundles(), - config.KubeInformers.Core().V1().Secrets(), // TODO(sttts): watch individual secrets for security and memory consumption - config.KubeInformers.Core().V1().Namespaces(), - config.ApiextensionsInformers.Apiextensions().V1().CustomResourceDefinitions(), - config.ProviderPollingInterval, - ) - if err != nil { - return nil, err - } - - s := &Server{ - Config: config, - Controller: k, - } - - s.webServer = server.NewServer(server.Config{ - ServerAddr: config.ServerAddr, - }) - - return s, nil -} - -func (s *Server) StartHealthCheck(ctx context.Context) { - s.webServer.Start(ctx) -} - -func (s *Server) AddCheck(check server.HealthChecker) { - s.webServer.Checker.AddCheck(check) -} - -type prepared struct { - Server -} - -type Prepared struct { - *prepared -} - -func (s *Server) PrepareRun(ctx context.Context) (Prepared, error) { - // install/upgrade CRDs - if err := crd.Create(ctx, - s.Config.ApiextensionsClient.ApiextensionsV1().CustomResourceDefinitions(), - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiservicebindings"}, - ); err != nil { - return Prepared{}, err - } - if err := crd.Create(ctx, - s.Config.ApiextensionsClient.ApiextensionsV1().CustomResourceDefinitions(), - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiservicebindingbundles"}, - ); err != nil { - return Prepared{}, err - } - return Prepared{ - prepared: &prepared{ - Server: *s, - }, - }, nil -} - -func (s *Prepared) OptionallyStartInformers(ctx context.Context) { - logger := klog.FromContext(ctx) - - // start informer factories - logger.Info("starting informers") - s.Config.KubeInformers.Start(ctx.Done()) - s.Config.BindInformers.Start(ctx.Done()) - s.Config.ApiextensionsInformers.Start(ctx.Done()) - kubeSynced := s.Config.KubeInformers.WaitForCacheSync(ctx.Done()) - kubeBindSynced := s.Config.BindInformers.WaitForCacheSync(ctx.Done()) - apiextensionsSynced := s.Config.ApiextensionsInformers.WaitForCacheSync(ctx.Done()) - - logger.Info("local informers are synced", - "kubeSynced", fmt.Sprintf("%v", kubeSynced), - "kubeBindSynced", fmt.Sprintf("%v", kubeBindSynced), - "apiextensionsSynced", fmt.Sprintf("%v", apiextensionsSynced), - ) -} - -func (s Prepared) Run(ctx context.Context) error { - s.Controller.Start(ctx, 2) - return nil -} diff --git a/pkg/konnector/server/checker.go b/pkg/konnector/server/checker.go deleted file mode 100644 index ea343e97f..000000000 --- a/pkg/konnector/server/checker.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 server - -import ( - "encoding/json" - "net/http" - - "k8s.io/apiserver/pkg/server/healthz" -) - -type HealthChecker = healthz.HealthChecker - -type checker struct { - checks []healthz.HealthChecker -} - -func (c checker) ServeHTTP(w http.ResponseWriter, r *http.Request) { - status := map[string]string{} - allOk := true - - for _, c := range c.checks { - err := c.Check(r) - if err != nil { - allOk = false - status[c.Name()] = "degraded" - continue - } - status[c.Name()] = "ok" - } - - w.Header().Set("Content-Type", "application/json") - if allOk { - w.WriteHeader(http.StatusOK) - } else { - w.WriteHeader(http.StatusInternalServerError) - } - - json.NewEncoder(w).Encode(status) //nolint:errchkjson,errcheck -} - -func (c *checker) AddCheck(check healthz.HealthChecker) { - c.checks = append(c.checks, check) -} diff --git a/pkg/konnector/server/server.go b/pkg/konnector/server/server.go deleted file mode 100644 index 5e8d29e75..000000000 --- a/pkg/konnector/server/server.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 server - -import ( - "context" - "net" - "net/http" - "time" - - "github.com/gorilla/mux" - "k8s.io/klog/v2" -) - -const listenAddr = ":8090" - -type Server struct { - Router *mux.Router - Checker checker - - ServerAddr string -} - -type Config struct { - ServerAddr string -} - -func NewServer(cfg Config) *Server { - server := &Server{ - Router: mux.NewRouter(), - Checker: checker{}, - ServerAddr: cfg.ServerAddr, - } - server.Router.Handle("/healthz", server.Checker) - - if server.ServerAddr == "" { - server.ServerAddr = listenAddr - } - - return server -} - -func (s *Server) Start(ctx context.Context) { - s.Router.Handle("/healthz", s.Checker) - server := &http.Server{ - Handler: s.Router, - ReadHeaderTimeout: 1 * time.Minute, - } - go func() { - var lc net.ListenConfig - listener, err := lc.Listen(ctx, "tcp", s.ServerAddr) - if err != nil { - if ctx.Err() != nil { - return - } - panic(err) - } - - log := klog.FromContext(ctx) - log.Info("healthz endpoint listening", "address", listener.Addr()) - - server.Serve(listener) //nolint:errcheck - }() - go func() { - <-ctx.Done() - server.Close() - }() -} diff --git a/pkg/konnector/types/types.go b/pkg/konnector/types/types.go deleted file mode 100644 index 1c3ab8d47..000000000 --- a/pkg/konnector/types/types.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 types - -import ( - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -// ClusterNamespaceAnnotationKey is the annotation key to identify the -// cluster namespace that any synced object on the provider side belongs to. -// This annotation is set on all synced objects, regardless of scope or -// isolation mode. -const ClusterNamespaceAnnotationKey = "kube-bind.io/cluster-namespace" - -// ConsumerNamespaceAnnotationKey is the annotation key set on provider-side -// objects to identify the consumer namespace the source object lives in. -const ConsumerNamespaceAnnotationKey = "kube-bind.io/consumer-namespace" - -// ConsumerUIDAnnotationKey is the annotation key set on provider-side objects -// to uniquely identify the consumer source object. -const ConsumerUIDAnnotationKey = "kube-bind.io/consumer-uid" - -// ProviderNamespaceAnnotationKey is the annotation key set on consumer-side -// objects to identify the provider namespace the source object lives in. -const ProviderNamespaceAnnotationKey = "kube-bind.io/provider-namespace" - -// ProviderUIDAnnotationKey is the annotation key set on consumer-side objects -// to uniquely identify the provider source object. -const ProviderUIDAnnotationKey = "kube-bind.io/provider-uid" - -// SetSourceMetadataAnnotations sets source metadata annotations on a synced -// object so the receiving side can trace where the object came from. -func SetSourceMetadataAnnotations(obj *unstructured.Unstructured, sourceNS, sourceUID, nsKey, uidKey string) { - annotations := obj.GetAnnotations() - if annotations == nil { - annotations = map[string]string{} - } - annotations[nsKey] = sourceNS - annotations[uidKey] = sourceUID - obj.SetAnnotations(annotations) -} diff --git a/pkg/konnectorinstall/install.go b/pkg/konnectorinstall/install.go new file mode 100644 index 000000000..614aefacf --- /dev/null +++ b/pkg/konnectorinstall/install.go @@ -0,0 +1,101 @@ +/* +Copyright 2026 The kbind 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 konnectorinstall installs the konnector (CRDs, RBAC, Deployment) +// into a consumer cluster — the CLI's --install-konnector and the gateway's +// browser-apply use it. The embedded CRDs are synced from sdk/config/crd by +// `make codegen`. +package konnectorinstall + +import ( + "bytes" + "context" + "embed" + "fmt" + "io/fs" + "sort" + "strings" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/client-go/rest" + + "github.com/kbind/kbind/pkg/kubeapply" +) + +//go:embed manifests +var manifests embed.FS + +// DefaultImage is the konnector image installed when none is specified. +const DefaultImage = "ghcr.io/kbind-dev/konnector:latest" + +// Manifests returns the full konnector install (CRDs first, then namespace, +// RBAC and Deployment) as one YAML multi-doc with the image resolved. +func Manifests(image string) ([]byte, error) { + if image == "" { + image = DefaultImage + } + var out bytes.Buffer + paths := []string{} + if err := fs.WalkDir(manifests, "manifests", func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".yaml") { + return err + } + paths = append(paths, path) + return nil + }); err != nil { + return nil, err + } + // CRDs sort before the konnector manifest (crds/ subdirectory), which is + // exactly the order we want. + sort.Strings(paths) + for _, path := range paths { + data, err := manifests.ReadFile(path) + if err != nil { + return nil, err + } + if out.Len() > 0 { + out.WriteString("\n---\n") + } + out.Write(bytes.ReplaceAll(data, []byte("__KONNECTOR_IMAGE__"), []byte(image))) + } + return out.Bytes(), nil +} + +// Objects returns the konnector install decoded to unstructured objects. +func Objects(image string) ([]*unstructured.Unstructured, error) { + data, err := Manifests(image) + if err != nil { + return nil, err + } + return kubeapply.DecodeYAML(data) +} + +// Apply installs/upgrades the konnector in the cluster behind cfg. +func Apply(ctx context.Context, cfg *rest.Config, image string) ([]string, error) { + objs, err := Objects(image) + if err != nil { + return nil, err + } + applier, err := kubeapply.New(cfg, "kbind-installer") + if err != nil { + return nil, err + } + applied, err := applier.Apply(ctx, objs) + if err != nil { + return applied, fmt.Errorf("installing konnector: %w", err) + } + return applied, nil +} diff --git a/pkg/konnectorinstall/manifests/crds/core.kbind.io_bindings.yaml b/pkg/konnectorinstall/manifests/crds/core.kbind.io_bindings.yaml new file mode 100644 index 000000000..54687fe19 --- /dev/null +++ b/pkg/konnectorinstall/manifests/crds/core.kbind.io_bindings.yaml @@ -0,0 +1,297 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: bindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Binding + listKind: BindingList + plural: bindings + singular: binding + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Binding activates instance sync for one or more exported APIs within its own + namespace. Namespaced, following the Role convention. It is the v2 answer to + v1's informerScope: Namespaced. Where a ClusterBinding and a Binding cover the + same API on the same connection, the ClusterBinding wins. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict; + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. Not yet synced in the alpha POC. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object detail lives on each object's own condition, not here. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/pkg/konnectorinstall/manifests/crds/core.kbind.io_clusterbindings.yaml b/pkg/konnectorinstall/manifests/crds/core.kbind.io_clusterbindings.yaml new file mode 100644 index 000000000..9f68aaf51 --- /dev/null +++ b/pkg/konnectorinstall/manifests/crds/core.kbind.io_clusterbindings.yaml @@ -0,0 +1,295 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: clusterbindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: ClusterBinding + listKind: ClusterBindingList + plural: clusterbindings + singular: clusterbinding + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClusterBinding activates instance sync for one or more exported APIs + cluster-wide. Cluster-scoped, following the ClusterRole convention. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict; + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. Not yet synced in the alpha POC. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object detail lives on each object's own condition, not here. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/pkg/konnectorinstall/manifests/crds/core.kbind.io_connections.yaml b/pkg/konnectorinstall/manifests/crds/core.kbind.io_connections.yaml new file mode 100644 index 000000000..d222a5bde --- /dev/null +++ b/pkg/konnectorinstall/manifests/crds/core.kbind.io_connections.yaml @@ -0,0 +1,259 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: connections.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Connection + listKind: ConnectionList + plural: connections + singular: connection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .spec.kubeconfigSecretRef.name + name: Secret + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Connection is the link to one provider cluster. It owns the credentials and + schema delivery, and surfaces what the provider exports. Cluster-scoped. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ConnectionSpec defines the desired provider link. + properties: + autoBind: + default: false + description: |- + autoBind, when true, makes the konnector maintain a managed ClusterBinding + (named after this Connection) covering all exported APIs. + type: boolean + kubeconfigSecretRef: + description: |- + kubeconfigSecretRef points at the Secret holding the provider kubeconfig. + Immutable. The only credential reference in the core. + properties: + key: + default: kubeconfig + description: key within the Secret holding the kubeconfig. + type: string + name: + description: name of the Secret. + minLength: 1 + type: string + namespace: + description: namespace of the Secret. Must be the konnector's + designated namespace. + minLength: 1 + type: string + required: + - name + - namespace + type: object + x-kubernetes-validations: + - message: kubeconfigSecretRef is immutable + rule: self == oldSelf + schema: + default: {} + description: schema controls how exported APIs reach the consumer. + properties: + pullPolicy: + default: Bound + description: |- + pullPolicy selects which exported APIs are installed: + Bound - only APIs referenced by a Binding/ClusterBinding (default). + All - every exported API readable by the credentials. + None - never install CRDs (user/extension manages them). + enum: + - Bound + - All + - None + type: string + source: + default: Auto + description: |- + source selects how schemas are obtained: + Auto - CRD if readable on the provider, else OpenAPI (default). + CRD - read apiextensions CRDs verbatim. + OpenAPI - synthesize CRDs from discovery + /openapi/v3. + enum: + - Auto + - CRD + - OpenAPI + type: string + updatePolicy: + default: Always + description: |- + updatePolicy selects whether installed schemas follow provider changes: + Always - follow provider schema changes (default). + Once - pin at first pull. + enum: + - Always + - Once + type: string + type: object + required: + - kubeconfigSecretRef + type: object + status: + description: ConnectionStatus is the observed state of a Connection. + properties: + activeSchemaSource: + description: |- + activeSchemaSource is the schema source actually in effect after resolving + "Auto" (CRD or OpenAPI). The binding uses it to decide whether the + Connection already installed the CRDs (OpenAPI) or it should pull them (CRD). + type: string + conditions: + description: 'conditions: SecretValid, Connected, SchemaInSync, Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + exportedAPIs: + description: 'exportedAPIs is the discovery result: APIs exported + to these credentials.' + items: + description: ExportedAPI describes one API the provider exports + to these credentials. + properties: + group: + description: group of the exported API. + type: string + name: + description: name is the CRD name of the exported API, ".". + type: string + resource: + description: resource is the plural resource name of the exported + API. + type: string + scope: + description: scope is whether the API is Namespaced or Cluster + scoped. + type: string + versions: + description: versions are the served versions of the exported + API. + items: + type: string + type: array + x-kubernetes-list-type: set + required: + - group + - name + - resource + - scope + - versions + type: object + type: array + x-kubernetes-list-type: atomic + localClusterUID: + description: |- + localClusterUID is the identity of the consumer cluster, pinned on first + connect and immutable thereafter. + type: string + x-kubernetes-validations: + - message: localClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + remoteClusterUID: + description: |- + remoteClusterUID is the identity of the provider cluster, pinned on first + connect and immutable thereafter. A Secret later pointing at a different + cluster is rejected rather than silently re-homing synced objects. + type: string + x-kubernetes-validations: + - message: remoteClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/pkg/konnectorinstall/manifests/konnector.yaml b/pkg/konnectorinstall/manifests/konnector.yaml new file mode 100644 index 000000000..a757f82ac --- /dev/null +++ b/pkg/konnectorinstall/manifests/konnector.yaml @@ -0,0 +1,144 @@ +# Static konnector install, mirroring deploy/charts/konnector defaults. +# __KONNECTOR_IMAGE__ is replaced at apply time. +apiVersion: v1 +kind: Namespace +metadata: + name: kbind +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: konnector + namespace: kbind +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: konnector +rules: + # Core kbind objects the konnector reconciles (+ status, + finalizers). + - apiGroups: ["core.kbind.io"] + resources: ["connections", "clusterbindings", "bindings"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["core.kbind.io"] + resources: ["connections/status", "clusterbindings/status", "bindings/status"] + verbs: ["get", "update", "patch"] + - apiGroups: ["core.kbind.io"] + resources: ["connections/finalizers", "clusterbindings/finalizers", "bindings/finalizers"] + verbs: ["update"] + # CRDs: the konnector pulls/synthesizes and installs the bound APIs. + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + # Provider kubeconfig Secrets: read + finalizer (never deleted by the konnector). + - apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "list", "watch", "update", "patch"] + # Namespaces: read for cluster identity; create for related-resource copies. + - apiGroups: [""] + resources: ["namespaces"] + verbs: ["get", "list", "watch", "create"] + # Cluster identity on kcp-shaped consumers (best-effort; harmless if absent). + - apiGroups: ["core.kcp.io"] + resources: ["logicalclusters"] + verbs: ["get", "list", "watch"] + # Events emitted by the reconcilers (conflicts, permission denials). + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] + - apiGroups: ["events.k8s.io"] + resources: ["events"] + verbs: ["create", "patch"] + # Instances of the bound APIs synced between consumer and provider + # (open-ended; narrow via the Helm chart if needed). + - apiGroups: ["*"] + resources: ["*"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: konnector +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: konnector +subjects: + - kind: ServiceAccount + name: konnector + namespace: kbind +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: konnector-leaderelection + namespace: kbind +rules: + - apiGroups: ["coordination.k8s.io"] + resources: ["leases"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: konnector-leaderelection + namespace: kbind +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: konnector-leaderelection +subjects: + - kind: ServiceAccount + name: konnector + namespace: kbind +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: konnector + namespace: kbind +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: konnector + template: + metadata: + labels: + app.kubernetes.io/name: konnector + spec: + serviceAccountName: konnector + containers: + - name: konnector + image: "__KONNECTOR_IMAGE__" + args: + - --metrics-bind-address=:8085 + - --health-probe-bind-address=:8081 + - --leader-elect=false + - --leader-election-id=konnector.kbind.io + ports: + - name: metrics + containerPort: 8085 + - name: probe + containerPort: 8081 + livenessProbe: + httpGet: + path: /healthz + port: probe + initialDelaySeconds: 15 + periodSeconds: 20 + readinessProbe: + httpGet: + path: /readyz + port: probe + initialDelaySeconds: 5 + periodSeconds: 10 + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + readOnlyRootFilesystem: true + runAsNonRoot: true diff --git a/pkg/kubeapply/kubeapply.go b/pkg/kubeapply/kubeapply.go new file mode 100644 index 000000000..d07879b75 --- /dev/null +++ b/pkg/kubeapply/kubeapply.go @@ -0,0 +1,149 @@ +/* +Copyright 2026 The kbind 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 kubeapply is a small server-side-apply helper for applying YAML +// multi-docs (bundles, konnector manifests) to a cluster, used by the CLI and +// the gateway's browser-apply path. It tolerates CRDs and their instances in +// one batch: unresolvable kinds are retried while the just-applied CRDs +// establish. +package kubeapply + +import ( + "bytes" + "context" + "fmt" + "io" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + yamlutil "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/discovery" + "k8s.io/client-go/discovery/cached/memory" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/restmapper" + "sigs.k8s.io/yaml" +) + +// DecodeYAML splits a YAML multi-doc into unstructured objects, skipping +// empty documents. +func DecodeYAML(data []byte) ([]*unstructured.Unstructured, error) { + var objs []*unstructured.Unstructured + decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var obj unstructured.Unstructured + if err := decoder.Decode(&obj); err != nil { + if err == io.EOF { + return objs, nil + } + return nil, fmt.Errorf("decoding manifest: %w", err) + } + if len(obj.Object) == 0 { + continue + } + objs = append(objs, &obj) + } +} + +// NamespaceObject returns a minimal Namespace as unstructured — used to make +// sure the konnector namespace exists before a bundle's Secret lands in it. +func NamespaceObject(name string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "v1", + "kind": "Namespace", + "metadata": map[string]any{"name": name}, + }} +} + +// Applier server-side-applies unstructured objects. +type Applier struct { + dyn dynamic.Interface + mapper *restmapper.DeferredDiscoveryRESTMapper + owner string +} + +// New builds an Applier for the cluster behind cfg. +func New(cfg *rest.Config, fieldOwner string) (*Applier, error) { + dyn, err := dynamic.NewForConfig(cfg) + if err != nil { + return nil, err + } + disco, err := discovery.NewDiscoveryClientForConfig(cfg) + if err != nil { + return nil, err + } + return &Applier{ + dyn: dyn, + mapper: restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(disco)), + owner: fieldOwner, + }, nil +} + +// Apply server-side-applies the objects in order (force-conflicts, so a +// re-apply of a previous bundle wins over drift). Kinds not yet resolvable — +// instances of CRDs applied moments ago — are retried until the mapping +// appears or the timeout passes. Returns "Kind/name" for everything applied. +func (a *Applier) Apply(ctx context.Context, objs []*unstructured.Unstructured) ([]string, error) { + applied := make([]string, 0, len(objs)) + for _, obj := range objs { + if err := a.applyOne(ctx, obj); err != nil { + return applied, fmt.Errorf("applying %s %s: %w", obj.GetKind(), obj.GetName(), err) + } + applied = append(applied, fmt.Sprintf("%s/%s", obj.GetKind(), obj.GetName())) + } + return applied, nil +} + +func (a *Applier) applyOne(ctx context.Context, obj *unstructured.Unstructured) error { + gvk := obj.GroupVersionKind() + deadline := time.Now().Add(30 * time.Second) + for { + mapping, err := a.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err == nil { + return a.patch(ctx, mapping, obj) + } + if !meta.IsNoMatchError(err) || time.Now().After(deadline) { + return err + } + // Likely a CRD applied a moment ago that is still establishing. + a.mapper.Reset() + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } +} + +func (a *Applier) patch(ctx context.Context, mapping *meta.RESTMapping, obj *unstructured.Unstructured) error { + data, err := yaml.Marshal(obj.Object) + if err != nil { + return err + } + var res dynamic.ResourceInterface = a.dyn.Resource(mapping.Resource) + if mapping.Scope.Name() == meta.RESTScopeNameNamespace { + res = a.dyn.Resource(mapping.Resource).Namespace(obj.GetNamespace()) + } + force := true + _, err = res.Patch(ctx, obj.GetName(), types.ApplyPatchType, data, metav1.PatchOptions{ + FieldManager: a.owner, + Force: &force, + }) + return err +} diff --git a/pkg/resources/resources.go b/pkg/resources/resources.go deleted file mode 100644 index 0a97f35b8..000000000 --- a/pkg/resources/resources.go +++ /dev/null @@ -1,300 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 resources - -import ( - "context" - "fmt" - "slices" - "strings" - "time" - - "github.com/tidwall/gjson" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/runtime" - dynamicclient "k8s.io/client-go/dynamic" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// ServiceNamespaceLister is an interface for listing APIServiceNamespaces -type ServiceNamespaceLister interface { - List(selector labels.Selector) ([]*kubebindv1alpha2.APIServiceNamespace, error) -} - -func matchesLabelSelector(logger klog.Logger, selector *metav1.LabelSelector, obj *unstructured.Unstructured) bool { - if selector == nil { - return false - } - - labelSelector, err := metav1.LabelSelectorAsSelector(selector) - if err != nil { - runtime.HandleError(fmt.Errorf("invalid label selector in permission claim: %w", err)) - return false - } - - objLabels := obj.GetLabels() - if objLabels == nil { - objLabels = make(map[string]string) - } - - matches := labelSelector.Matches(labels.Set(objLabels)) - if matches { - logger.Info("resource matched", "name", obj.GetName(), "namespace", obj.GetNamespace(), "claim-type", "labelSelector", "selector", labelSelector.String(), "objectLabels", objLabels) - } - return matches -} - -func matchesNamedResources(logger klog.Logger, namedResources []kubebindv1alpha2.NamedResource, obj *unstructured.Unstructured) bool { - if len(namedResources) == 0 { - return false - } - - for _, nr := range namedResources { - if nr.Namespace != "" && nr.Namespace != obj.GetNamespace() { - continue - } - if nr.Name == obj.GetName() { - logger.Info("resource matched", "name", obj.GetName(), "namespace", obj.GetNamespace(), "claim-type", "namedResource", "namedResource", nr) - return true - } - } - return false -} - -func matchesReferences(logger klog.Logger, - references []kubebindv1alpha2.SelectorReference, - obj *unstructured.Unstructured, - potentiallyReferencedResources *unstructured.UnstructuredList, - isolation kubebindv1alpha2.Isolation, -) bool { - if len(references) == 0 { - return false - } - - logger.V(4).Info("checking references", "references", references, "object", obj, "potentiallyReferencedResources", potentiallyReferencedResources) - - if potentiallyReferencedResources == nil { - return false - } - - for _, refObj := range potentiallyReferencedResources.Items { - jsonData, err := refObj.MarshalJSON() - if err != nil { - continue - } - - for _, ref := range references { - selector := ref - nameResult := gjson.Get(string(jsonData), selector.JSONPath.Name) - var namespaceResult gjson.Result - if selector.JSONPath.Namespace != "" { - namespaceResult = gjson.Get(string(jsonData), selector.JSONPath.Namespace) - } - - if nameResult.Exists() { - var nameValues []string - if nameResult.IsArray() { - for _, elem := range nameResult.Array() { - nameValues = append(nameValues, strings.TrimSpace(elem.String())) - } - } else { - nameValues = append(nameValues, strings.TrimSpace(nameResult.String())) - } - - for _, extractedName := range nameValues { - nameMatches := (extractedName == obj.GetName()) - - namespaceMatches := true - if selector.JSONPath.Namespace != "" && namespaceResult.Exists() { - var namespaceValues []string - if namespaceResult.IsArray() { - for _, elem := range namespaceResult.Array() { - namespaceValues = append(namespaceValues, strings.TrimSpace(elem.String())) - } - } else { - namespaceValues = append(namespaceValues, strings.TrimSpace(namespaceResult.String())) - } - - namespaceMatches = false - objNamespace := obj.GetNamespace() - if slices.Contains(namespaceValues, objNamespace) { - namespaceMatches = true - } - } - - if selector.JSONPath.Namespace == "" && isolation == kubebindv1alpha2.IsolationNamespaced { - namespaceMatches = (refObj.GetNamespace() == obj.GetNamespace()) - logger.V(4).Info("namespace extracted from referenced object", - "referencedObjectNamespace", refObj.GetNamespace(), - "objectNamespace", obj.GetNamespace(), - "namespaceMatches", namespaceMatches, - ) - } - - if nameMatches && namespaceMatches { - logger.Info("resource matched", "name", obj.GetName(), "namespace", obj.GetNamespace(), "claim-type", "reference", "reference", selector) - return true - } - } - } - } - } - return false -} - -// IsClaimed returns true if the given object matches the given selector and named resources. -// Logger here is already at V(4) level. -func IsClaimed(logger klog.Logger, selector kubebindv1alpha2.Selector, obj *unstructured.Unstructured, potentiallyReferencedResources *unstructured.UnstructuredList, isolation kubebindv1alpha2.Isolation) bool { - if obj == nil { - return false - } - // Empty selector selects nothing - if selector.LabelSelector == nil && len(selector.NamedResources) == 0 && len(selector.References) == 0 { - logger.V(4).Info("no selector provided") - return false - } - - labelSelectorMatches := matchesLabelSelector(logger, selector.LabelSelector, obj) - namedResourceMatches := matchesNamedResources(logger, selector.NamedResources, obj) - referenceMatches := matchesReferences(logger, selector.References, obj, potentiallyReferencedResources, isolation) - - return labelSelectorMatches || namedResourceMatches || referenceMatches -} - -// IsClaimedWithReference returns true if the given object is claimed by the given permission claim. -// It handles both consumer side (no namespace remapping) and provider side (namespace remapping via APIServiceNamespace). -// The function fetches potentially referenced resources if a reference selector is present. -func IsClaimedWithReference( - logger klog.Logger, - obj *unstructured.Unstructured, - consumerSide bool, - claim kubebindv1alpha2.PermissionClaim, - apiServiceExport *kubebindv1alpha2.APIServiceExport, - consumerClient dynamicclient.Interface, - serviceNamespaceLister ServiceNamespaceLister, -) bool { - logger = logger.V(4).WithValues("gvr", obj.GroupVersionKind().String(), "namespace", obj.GetNamespace(), "name", obj.GetName(), "claim", claim) - logger.Info("checking if object is claimed") - copy := obj.DeepCopy() - - potentiallyReferencedResources := &unstructured.UnstructuredList{} - var versions []string - - // Handle reference selectors by fetching potentially referenced resources - if len(claim.Selector.References) != 0 { - for _, ref := range claim.Selector.References { - logger := logger.WithValues("referenceGroup", ref.Group, "referenceResource", ref.Resource, "referenceJSONPathName", ref.JSONPath.Name, "referenceJSONPathNamespace", ref.JSONPath.Namespace) - logger.Info("processing reference selector") - - if !isReferenceAllowed(ref, apiServiceExport) { - logger.Info("reference not allowed, resource is not part of the contract", - "isolation", apiServiceExport.Spec.Isolation, - "referenceGroup", ref.Group, - "referenceResource", ref.Resource, - ) - continue - } - - if len(ref.Versions) > 0 { - versions = ref.Versions - } else { - // Find versions from apiServiceExport resources - for v := range apiServiceExport.Spec.Resources { - if ref.Group == apiServiceExport.Spec.Resources[v].Group && ref.Resource == apiServiceExport.Spec.Resources[v].Resource { - versions = apiServiceExport.Spec.Resources[v].Versions - break - } - } - } - - // TODO(mjudeikis): We should wire informers per GVR from above. Now this is bit hack - // and there is no context available here. - ctx, cancel := context.WithTimeout(context.TODO(), time.Second*5) - defer cancel() - - for _, version := range versions { - gvr := schema.GroupVersionResource{ - Group: ref.Group, - Resource: ref.Resource, - Version: version, - } - logger.V(4).Info("listing objects for reference claim", "gvr", gvr) - - objs, err := consumerClient.Resource(gvr).List(ctx, metav1.ListOptions{}) - if err != nil { - logger.Error(err, "failed to list objects for reference claim. Invalidating all claim.", "group", ref.Group, "resource", ref.Resource, "version", version) - return false - } - potentiallyReferencedResources.Items = append(potentiallyReferencedResources.Items, objs.Items...) - } - } - } - - logger.Info("checking claim", "consumerSide", consumerSide, "potentiallyReferencedResourcesCount", len(potentiallyReferencedResources.Items)) - - if consumerSide { - logger.Info("checking claim on consumer side") - result := IsClaimed(logger, claim.Selector, copy, potentiallyReferencedResources, apiServiceExport.Spec.Isolation) - logger.Info("IsClaimed result", "result", result) - return result - } - - // For provider side, remap the namespace using APIServiceNamespace - sns, err := serviceNamespaceLister.List(labels.NewSelector()) - if err != nil && !errors.IsNotFound(err) { - runtime.HandleError(fmt.Errorf("failed to get APIServiceNamespace for claimed check: %w", err)) - return false - } - var sn *kubebindv1alpha2.APIServiceNamespace - for _, candidate := range sns { - if candidate.Status.Namespace == "" { - continue // not ready yet - } - if obj.GetNamespace() == candidate.Status.Namespace { - sn = candidate - break - } - } - if sn != nil { - logger.V(4).Info("remapping namespace for provider side claimed check", "originalNamespace", copy.GetNamespace(), "remappedNamespace", sn.Name) - copy.SetNamespace(sn.Name) - } - - result := IsClaimed(logger, claim.Selector, copy, potentiallyReferencedResources, apiServiceExport.Spec.Isolation) - logger.V(4).Info("IsClaimed result (provider side)", "result", result) - return result -} - -func isReferenceAllowed(ref kubebindv1alpha2.SelectorReference, apiServiceExport *kubebindv1alpha2.APIServiceExport) bool { - // If isolation is None, everything should be allowed, as both ends are owned. - if apiServiceExport.Spec.Isolation == kubebindv1alpha2.IsolationNone { - return true - } - for _, resource := range apiServiceExport.Spec.Resources { - if ref.Group == resource.Group && ref.Resource == resource.Resource { - return true - } - } - - return false -} diff --git a/pkg/resources/resources_test.go b/pkg/resources/resources_test.go deleted file mode 100644 index d2f93b2be..000000000 --- a/pkg/resources/resources_test.go +++ /dev/null @@ -1,1142 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 resources - -import ( - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/klog/v2" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func TestSelector_IsClaimed(t *testing.T) { - tests := []struct { - name string - selector kubebindv1alpha2.Selector - obj *unstructured.Unstructured - potentiallyReferencedResources *unstructured.UnstructuredList - isolation kubebindv1alpha2.Isolation - want bool - }{ - { - name: "empty selector should select nothing", - selector: kubebindv1alpha2.Selector{}, - potentiallyReferencedResources: nil, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - want: false, - }, - { - name: "label selector should match labels", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "test", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - want: true, - }, - { - name: "label selector should not match different labels", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "different", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "named resource selector should match exact name and namespace", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "named resource selector should match name when namespace is empty", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-obj", - Namespace: "", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "named resource selector should not match different name", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "other-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "named resource selector should not match different namespace", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-obj", - Namespace: "other-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "named resource selector should match one of multiple resources", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "other-obj", - Namespace: "test-ns", - }, - { - Name: "test-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "label selector with object having no labels should not match", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "test", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "combination of label selector and named resource should match when both match", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "test", - }, - }, - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "combination of label selector and named resource should match when named resource matches (OR logic)", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "different", - }, - }, - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "combination of label selector and named resource should match when label matches (OR logic)", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "test", - }, - }, - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "other-obj", - Namespace: "test-ns", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-obj", - "namespace": "test-ns", - "labels": map[string]any{ - "app": "test", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "label-only-secret test case - should sync when has matching label (OR logic)", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "secrets", - }, - }, - NamedResources: []kubebindv1alpha2.NamedResource{ - { - Name: "test-secret", - Namespace: "default", - }, - { - Name: "named-secret-1", - Namespace: "default", - }, - { - Name: "named-secret-2", - Namespace: "default", - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "label-only-secret", - "namespace": "default", - "labels": map[string]any{ - "app": "secrets", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, // Should match because label selector matches (OR logic) - }, - // JSONPath Reference tests - { - name: "reference selector should match when JSONPath extracts matching name", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRef": map[string]any{ - "name": "test-secret", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "reference selector should match when JSONPath extracts matching name and namespace", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRef": map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - Namespace: "spec.secretRef.namespace", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "reference selector should not match when JSONPath extracts different name", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRef": map[string]any{ - "name": "other-secret", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "reference selector should not match when JSONPath extracts different namespace", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRef": map[string]any{ - "name": "test-secret", - "namespace": "other-namespace", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - Namespace: "spec.secretRef.namespace", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "reference selector should handle array JSONPath results", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRefs": []any{ - map[string]any{"name": "secret1"}, - map[string]any{"name": "test-secret"}, - map[string]any{"name": "secret3"}, - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRefs.#.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "reference selector should handle array JSONPath with namespace extraction", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRefs": []any{ - map[string]any{ - "name": "secret1", - "namespace": "ns1", - }, - map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - map[string]any{ - "name": "secret3", - "namespace": "ns3", - }, - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRefs.#.name", - Namespace: "spec.secretRefs.#.namespace", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, - }, - { - name: "reference selector should not match with bracket wildcard syntax (unsupported)", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "secretRefs": []any{ - map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRefs[*].name", - Namespace: "spec.secretRefs[*].namespace", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "test-namespace", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, // Should not match because [*] syntax is not supported by gjson - }, - { - name: "reference selector should not match when no referenced resources provided", - potentiallyReferencedResources: nil, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "reference selector should not match when JSONPath does not exist", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "config-obj", - "namespace": "default", - }, - "spec": map[string]any{ - "otherField": "value", - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "apps", - Resource: "deployments", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRef.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "test-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, - }, - { - name: "kubeconfig secret case - should not match when only has kube-bind.io/owner label but selector requires app=sheriff", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "apiVersion": "wildwest.dev/v1alpha1", - "kind": "Sheriff", - "metadata": map[string]any{ - "name": "wyatt-earp", - }, - "spec": map[string]any{ - "secretRefs": []any{ - map[string]any{ - "name": "sheriff-badge-credentials", - "namespace": "wild-west", - }, - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - LabelSelector: &metav1.LabelSelector{ - MatchLabels: map[string]string{ - "app": "sheriff", - }, - }, - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "wildwest.dev", - Resource: "sheriffs", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretRefs.#.name", - Namespace: "spec.secretRefs.#.namespace", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "kubeconfig-9d76b", - "namespace": "kube-bind", - "labels": map[string]any{ - "kube-bind.io/owner": "consumer", - }, - }, - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, // Should NOT match because it doesn't have app=sheriff label and is not referenced by Sheriff - }, - { - name: "cert-manager secret reference - should match when certificate references secret via secretName", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "apiVersion": "cert-manager.io/v1", - "kind": "Certificate", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "default", - }, - "spec": map[string]any{ - "secretName": "my-tls-cert", - "commonName": "my-ca", - "isCA": true, - "issuerRef": map[string]any{ - "kind": "ClusterIssuer", - "name": "kcp-ca", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "cert-manager.io", - Resource: "certificates", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretName", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "apiVersion": "v1", - "kind": "Secret", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "default", - "annotations": map[string]any{ - "cert-manager.io/certificate-name": "my-tls-cert", - }, - }, - "type": "kubernetes.io/tls", - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, // Should match because certificate's .spec.secretName equals secret name and no namespace JSONPath means namespace matching is handled by caller - }, - { - name: "cert-manager secret reference - should not match when certificate references different secret", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "apiVersion": "cert-manager.io/v1", - "kind": "Certificate", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "default", - }, - "spec": map[string]any{ - "secretName": "other-secret", - "commonName": "my-ca", - "isCA": true, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "cert-manager.io", - Resource: "certificates", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretName", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "apiVersion": "v1", - "kind": "Secret", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "default", - }, - "type": "kubernetes.io/tls", - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: false, // Should not match because certificate's .spec.secretName is "other-secret", not "my-tls-cert" - }, - { - name: "cert-manager secret reference - cross-namespace scenario with no namespace JSONPath", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "apiVersion": "cert-manager.io/v1", - "kind": "Certificate", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "default", - }, - "spec": map[string]any{ - "secretName": "my-tls-cert", - "commonName": "my-ca", - "isCA": true, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "cert-manager.io", - Resource: "certificates", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secretName", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "apiVersion": "v1", - "kind": "Secret", - "metadata": map[string]any{ - "name": "my-tls-cert", - "namespace": "remapped-namespace", // Different namespace simulating provider-side remapping - }, - "type": "kubernetes.io/tls", - }, - }, - isolation: kubebindv1alpha2.IsolationPrefixed, - want: true, // Should match because when no namespace JSONPath is provided, namespace matching is delegated to caller - }, - { - name: "namespace inherited from referencing object when JSONPath not provided in the namespaced isolation mode", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "mangodb-instance", - "namespace": "default", - }, - "spec": map[string]any{ - "secret": map[string]any{ - "name": "my-secret", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "mangodb.com", - Resource: "mangodbs", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secret.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "my-secret", - "namespace": "default", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationNamespaced, - want: true, - }, - { - name: "namespace inheritance fails when in different namespace in the namespaced isolation mode", - potentiallyReferencedResources: &unstructured.UnstructuredList{ - Items: []unstructured.Unstructured{ - { - Object: map[string]any{ - "metadata": map[string]any{ - "name": "mangodb-instance", - "namespace": "default", - }, - "spec": map[string]any{ - "secret": map[string]any{ - "name": "my-secret", - }, - }, - }, - }, - }, - }, - selector: kubebindv1alpha2.Selector{ - References: []kubebindv1alpha2.SelectorReference{ - { - GroupResource: kubebindv1alpha2.GroupResource{ - Group: "mangodb.com", - Resource: "mangodbs", - }, - JSONPath: &kubebindv1alpha2.JSONPath{ - Name: "spec.secret.name", - }, - }, - }, - }, - obj: &unstructured.Unstructured{ - Object: map[string]any{ - "metadata": map[string]any{ - "name": "my-secret", - "namespace": "other-namespace", - }, - }, - }, - isolation: kubebindv1alpha2.IsolationNamespaced, - want: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - logger := klog.Background().V(4) - got := IsClaimed(logger, tt.selector, tt.obj, tt.potentiallyReferencedResources, tt.isolation) - if got != tt.want { - t.Errorf("IsClaimed() = %v, want %v", got, tt.want) - } - }) - } -} - -func TestReferenceSelector_IsolationMode(t *testing.T) { - tests := []struct { - name string - isolation kubebindv1alpha2.Isolation - exportedResources []kubebindv1alpha2.APIServiceExportResource - reference kubebindv1alpha2.SelectorReference - shouldAllow bool - }{ - { - name: "IsolationNone allows all references", - isolation: kubebindv1alpha2.IsolationNone, - exportedResources: []kubebindv1alpha2.APIServiceExportResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}}, - }, - reference: kubebindv1alpha2.SelectorReference{ - GroupResource: kubebindv1alpha2.GroupResource{Group: "secret.com", Resource: "secrets"}, - }, - shouldAllow: true, - }, - { - name: "IsolationNamespaced blocks non-exported references", - isolation: kubebindv1alpha2.IsolationNamespaced, - exportedResources: []kubebindv1alpha2.APIServiceExportResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}}, - }, - reference: kubebindv1alpha2.SelectorReference{ - GroupResource: kubebindv1alpha2.GroupResource{Group: "secret.com", Resource: "secrets"}, - }, - shouldAllow: false, - }, - { - name: "IsolationPrefixed blocks non-exported references", - isolation: kubebindv1alpha2.IsolationPrefixed, - exportedResources: []kubebindv1alpha2.APIServiceExportResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}}, - }, - reference: kubebindv1alpha2.SelectorReference{ - GroupResource: kubebindv1alpha2.GroupResource{Group: "secret.com", Resource: "secrets"}, - }, - shouldAllow: false, - }, - { - name: "IsolationPrefixed allows exported references", - isolation: kubebindv1alpha2.IsolationPrefixed, - exportedResources: []kubebindv1alpha2.APIServiceExportResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}}, - }, - reference: kubebindv1alpha2.SelectorReference{ - GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}, - }, - shouldAllow: true, - }, - { - name: "IsolationNamespaced allows exported references", - isolation: kubebindv1alpha2.IsolationNamespaced, - exportedResources: []kubebindv1alpha2.APIServiceExportResource{ - {GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}}, - }, - reference: kubebindv1alpha2.SelectorReference{ - GroupResource: kubebindv1alpha2.GroupResource{Group: "mangodb.com", Resource: "mangodbs"}, - }, - shouldAllow: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - export := &kubebindv1alpha2.APIServiceExport{ - Spec: kubebindv1alpha2.APIServiceExportSpec{ - Isolation: tt.isolation, - Resources: tt.exportedResources, - }, - } - got := isReferenceAllowed(tt.reference, export) - if got != tt.shouldAllow { - t.Errorf("isReferenceAllowed() = %v, want %v", got, tt.shouldAllow) - } - }) - } -} diff --git a/pkg/servicecrds/crds/catalog.kbind.io_collections.yaml b/pkg/servicecrds/crds/catalog.kbind.io_collections.yaml new file mode 100644 index 000000000..16752498c --- /dev/null +++ b/pkg/servicecrds/crds/catalog.kbind.io_collections.yaml @@ -0,0 +1,86 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: collections.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Collection + listKind: CollectionList + plural: collections + singular: collection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Collection groups Exports for UI/CLI browsing. Pure presentation; nothing + binds to a Collection. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: CollectionSpec is a titled grouping of Exports. + properties: + description: + description: description explains the grouping. + type: string + exports: + description: exports lists the member Exports by name. + items: + description: ExportRef references an Export by name. + properties: + name: + description: name of the Export. + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + title: + description: title is the human-facing name of the group. + minLength: 1 + type: string + required: + - exports + - title + type: object + required: + - spec + type: object + served: true + storage: true + subresources: {} diff --git a/pkg/servicecrds/crds/catalog.kbind.io_exports.yaml b/pkg/servicecrds/crds/catalog.kbind.io_exports.yaml new file mode 100644 index 000000000..6717d76b2 --- /dev/null +++ b/pkg/servicecrds/crds/catalog.kbind.io_exports.yaml @@ -0,0 +1,287 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: exports.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Export + listKind: ExportList + plural: exports + singular: export + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Export is one curated offering in the provider's catalog: human-facing + metadata plus defaults on top of one or more exported APIs. The catalog is + derived-from-core-truth: an Export listing an API that is not actually + exported (label/boundary) gets a condition and is hidden by the gateway — + the export label remains the source of truth, the catalog is presentation + and defaults. Lives on the provider; the konnector never sees it. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ExportSpec describes one offering. + properties: + apis: + description: |- + apis lists the exported APIs a binding to this offering syncs, by CRD + name on the provider ("."). + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + defaults: + description: |- + defaults are copied into the generated ClusterBinding of the one-apply + bundle. + properties: + conflictPolicy: + description: |- + conflictPolicy is the default conflict behavior for the generated + ClusterBinding. + enum: + - Fail + - Adopt + type: string + relatedResources: + description: |- + relatedResources are the related-resource selectors for the generated + ClusterBinding. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string + for the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by + label. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact + name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + type: object + description: + description: description explains the offering to a human choosing + it. + type: string + docs: + description: docs optionally links to the offering's documentation. + type: string + icon: + description: icon optionally points at an icon for UIs. + properties: + url: + description: url of the icon image. + minLength: 1 + type: string + required: + - url + type: object + title: + description: title is the human-facing name of the offering. + minLength: 1 + type: string + required: + - apis + - title + type: object + status: + description: ExportStatus is the observed state of an Export. + properties: + conditions: + description: 'conditions: Ready (all listed APIs are actually exported).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/pkg/servicecrds/crds/iam.kbind.io_grants.yaml b/pkg/servicecrds/crds/iam.kbind.io_grants.yaml new file mode 100644 index 000000000..12651a0e1 --- /dev/null +++ b/pkg/servicecrds/crds/iam.kbind.io_grants.yaml @@ -0,0 +1,308 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: grants.iam.kbind.io +spec: + group: iam.kbind.io + names: + categories: + - kbind + kind: Grant + listKind: GrantList + plural: grants + singular: grant + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.identity.subject + name: Subject + type: string + - jsonPath: .spec.exportName + name: Export + type: string + - jsonPath: .status.namespace + name: Namespace + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Grant records that an identity was issued credentials for an export. The + gateway creates it with the export's API list and defaults resolved in + (issuance is a stable record even if the catalog entry changes later); the + issuer controller provisions the tenancy boundary, ServiceAccount, RBAC and + token from the spec and reports the artifacts in status. Deleting the Grant + revokes: the issuer's cleanup finalizer unwinds everything it provisioned. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: GrantSpec is the issuance request/record. + properties: + apis: + description: |- + apis is the export's API list resolved at issuance time, by CRD name on + the provider ("."). The issuer scopes RBAC to exactly + these. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + conflictPolicy: + description: |- + conflictPolicy is the export's default conflict policy resolved at + issuance time, copied into the generated bundle's ClusterBinding. + enum: + - Fail + - Adopt + type: string + exportName: + description: exportName records which catalog Export this Grant was + issued for. + minLength: 1 + type: string + identity: + description: identity is who the credentials were issued to. + properties: + displayName: + description: displayName is a human-facing name (e.g. email), + informational only. + type: string + groups: + description: groups the identity carried at issuance, informational + only. + items: + type: string + type: array + x-kubernetes-list-type: atomic + subject: + description: subject is the stable identity key, "#" + for OIDC. + minLength: 1 + type: string + required: + - subject + type: object + relatedResources: + description: |- + relatedResources are the export's related-resource selectors resolved at + issuance time. They flow into the bundle's ClusterBinding and widen the + issued RBAC (secrets/configmaps in the declared direction). + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - exportName + - identity + type: object + status: + description: GrantStatus reports what the issuer provisioned. + properties: + conditions: + description: 'conditions: Ready (credentials provisioned and token + populated).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + namespace: + description: namespace is the per-consumer tenancy boundary on the + provider. + type: string + serviceAccount: + description: serviceAccount is the name of the issued ServiceAccount + (in namespace). + type: string + tokenSecret: + description: |- + tokenSecret is the name of the long-lived SA token Secret (in + namespace). The gateway reads it to assemble the bundle's kubeconfig. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/pkg/servicecrds/install.go b/pkg/servicecrds/install.go new file mode 100644 index 000000000..4c976c175 --- /dev/null +++ b/pkg/servicecrds/install.go @@ -0,0 +1,109 @@ +/* +Copyright 2026 The kbind 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 servicecrds installs the service-layer CRDs (catalog.kbind.io, +// iam.kbind.io) on the provider cluster. The backend applies them at startup +// (--install-crds) so `go run ./cmd/backend` against a fresh cluster just +// works; the Helm chart ships the same files for out-of-band management. The +// embedded copies are synced from sdk/config/crd by `make codegen`. +package servicecrds + +import ( + "context" + "embed" + "fmt" + "io/fs" + "strings" + "time" + + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/yaml" +) + +//go:embed crds +var files embed.FS + +// Install server-side-applies the service-layer CRDs and waits for them to be +// established. Idempotent — safe to run on every startup and alongside a Helm +// install of the same CRDs. +func Install(ctx context.Context, cfg *rest.Config) error { + scheme := runtime.NewScheme() + if err := apiextensionsv1.AddToScheme(scheme); err != nil { + return err + } + c, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + return err + } + + crds, err := load() + if err != nil { + return err + } + for _, crd := range crds { + if err := c.Patch(ctx, crd, client.Apply, client.FieldOwner("kbind-backend"), client.ForceOwnership); err != nil { + return fmt.Errorf("installing CRD %s: %w", crd.Name, err) + } + } + + // Wait until the API server actually serves them, so controller watches + // and gateway reads start clean instead of erroring until the first sync. + waitCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + for _, crd := range crds { + name := crd.Name + if err := wait.PollUntilContextCancel(waitCtx, 200*time.Millisecond, true, func(ctx context.Context) (bool, error) { + var current apiextensionsv1.CustomResourceDefinition + if err := c.Get(ctx, types.NamespacedName{Name: name}, ¤t); err != nil { + return false, nil //nolint:nilerr // not found yet — keep polling + } + for _, cond := range current.Status.Conditions { + if cond.Type == apiextensionsv1.Established && cond.Status == apiextensionsv1.ConditionTrue { + return true, nil + } + } + return false, nil + }); err != nil { + return fmt.Errorf("waiting for CRD %s to be established: %w", name, err) + } + } + return nil +} + +func load() ([]*apiextensionsv1.CustomResourceDefinition, error) { + var crds []*apiextensionsv1.CustomResourceDefinition + err := fs.WalkDir(files, "crds", func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".yaml") { + return err + } + data, err := files.ReadFile(path) + if err != nil { + return err + } + var crd apiextensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(data, &crd); err != nil { + return fmt.Errorf("parsing %s: %w", path, err) + } + crds = append(crds, &crd) + return nil + }) + return crds, err +} diff --git a/pkg/version/version.go b/pkg/version/version.go deleted file mode 100644 index 18600c312..000000000 --- a/pkg/version/version.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 version - -import ( - "fmt" - "strings" -) - -func BinaryVersion(s string) (string, error) { - if strings.HasPrefix(s, "v0.0.0-") { - return "v0.0.0", nil // special version if no ldflags are set - } - parts := strings.SplitN(s, "+", 2) - if len(parts) < 2 { - return "", fmt.Errorf("failed to parse version %q", s) - } - - prefix := "kube-bind" - if !strings.HasPrefix(parts[1], prefix) { - return "", fmt.Errorf("failed to parse version %q", s) - } - return strings.SplitN(strings.TrimPrefix(parts[1], prefix+"-"), "-", 2)[0], nil -} diff --git a/pkg/version/version_test.go b/pkg/version/version_test.go deleted file mode 100644 index 8849b9e12..000000000 --- a/pkg/version/version_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 version - -import ( - "testing" -) - -func TestBinaryVersion(t *testing.T) { - tests := []struct { - name string - arg string - want string - wantErr bool - }{ - { - name: "happy case", - arg: "v1.25.2+kube-bind-v0.0.15", - want: "v0.0.15", - }, - { - name: "dirty", - arg: "v1.25.2+kube-bind-v0.0.15", - want: "v0.0.15", - }, - { - name: "wrong prefix", - arg: "v1.25.2+kube-bla-v0.0.15", - wantErr: true, - }, - { - name: "garbage", - arg: "v1.25.2+foo", - wantErr: true, - }, - { - name: "no ldflags", - arg: "v0.0.0-master+$Format:%H$", - want: "v0.0.0", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := BinaryVersion(tt.arg) - if (err != nil) != tt.wantErr { - t.Errorf("binaryVersion() error = %v, wantErr %v", err, tt.wantErr) - return - } - if got != tt.want { - t.Errorf("binaryVersion() got = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/sdk/apis/catalog/v1alpha1/collection_types.go b/sdk/apis/catalog/v1alpha1/collection_types.go new file mode 100644 index 000000000..55cb940ce --- /dev/null +++ b/sdk/apis/catalog/v1alpha1/collection_types.go @@ -0,0 +1,80 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Collection groups Exports for UI/CLI browsing. Pure presentation; nothing +// binds to a Collection. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,categories=kbind +// +kubebuilder:printcolumn:name="Title",type=string,JSONPath=`.spec.title` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type Collection struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec CollectionSpec `json:"spec"` +} + +// CollectionSpec is a titled grouping of Exports. +type CollectionSpec struct { + // title is the human-facing name of the group. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Title string `json:"title"` + + // description explains the grouping. + // + // +optional + Description string `json:"description,omitempty"` + + // exports lists the member Exports by name. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinItems=1 + // +listType=map + // +listMapKey=name + Exports []ExportRef `json:"exports"` +} + +// ExportRef references an Export by name. +type ExportRef struct { + // name of the Export. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` +} + +// CollectionList contains a list of Collection. +// +// +kubebuilder:object:root=true +type CollectionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Collection `json:"items"` +} diff --git a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/register.go b/sdk/apis/catalog/v1alpha1/conditions.go similarity index 51% rename from sdk/apis/third_party/conditions/apis/conditions/v1alpha1/register.go rename to sdk/apis/catalog/v1alpha1/conditions.go index 9b46683ff..20a90183d 100644 --- a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/register.go +++ b/sdk/apis/catalog/v1alpha1/conditions.go @@ -1,5 +1,5 @@ /* -Copyright 2024 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,9 +16,16 @@ limitations under the License. package v1alpha1 -import ( - "k8s.io/apimachinery/pkg/runtime/schema" -) +// Condition types and reasons for catalog kinds. +const ( + // ConditionReady is true when every API the Export lists is actually + // exported (carries the export label / boundary). The gateway hides + // Exports that are not Ready. + ConditionReady = "Ready" -// SchemeGroupVersion is group version used to register these objects. -var SchemeGroupVersion = schema.GroupVersion{Group: "conditions.kube-bind.io", Version: "v1alpha1"} + // ReasonAsExpected is the success reason. + ReasonAsExpected = "AsExpected" + // ReasonAPINotExported marks an Export listing an API that is not actually + // exported to consumers. + ReasonAPINotExported = "APINotExported" +) diff --git a/sdk/apis/catalog/v1alpha1/doc.go b/sdk/apis/catalog/v1alpha1/doc.go new file mode 100644 index 000000000..1a34c0b20 --- /dev/null +++ b/sdk/apis/catalog/v1alpha1/doc.go @@ -0,0 +1,26 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 contains the catalog API for the kbind service layer: +// the Export and Collection kinds in the catalog.kbind.io group. The catalog +// is curation on top of the core's raw discovery — human-facing metadata and +// defaults that turn "a list of CRD names" into "a service you'd choose". +// These CRDs live on the provider and are read only by the gateway/UI/CLI; +// the konnector never sees them. See docs/proposals/v2-extended.md. +// +// +kubebuilder:object:generate=true +// +groupName=catalog.kbind.io +package v1alpha1 diff --git a/sdk/apis/catalog/v1alpha1/export_types.go b/sdk/apis/catalog/v1alpha1/export_types.go new file mode 100644 index 000000000..634df48ba --- /dev/null +++ b/sdk/apis/catalog/v1alpha1/export_types.go @@ -0,0 +1,136 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// Export is one curated offering in the provider's catalog: human-facing +// metadata plus defaults on top of one or more exported APIs. The catalog is +// derived-from-core-truth: an Export listing an API that is not actually +// exported (label/boundary) gets a condition and is hidden by the gateway — +// the export label remains the source of truth, the catalog is presentation +// and defaults. Lives on the provider; the konnector never sees it. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,categories=kbind +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Title",type=string,JSONPath=`.spec.title` +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type Export struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec ExportSpec `json:"spec"` + + // +optional + Status ExportStatus `json:"status,omitempty"` +} + +// ExportSpec describes one offering. +type ExportSpec struct { + // title is the human-facing name of the offering. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Title string `json:"title"` + + // description explains the offering to a human choosing it. + // + // +optional + Description string `json:"description,omitempty"` + + // icon optionally points at an icon for UIs. + // + // +optional + Icon *Icon `json:"icon,omitempty"` + + // docs optionally links to the offering's documentation. + // + // +optional + Docs string `json:"docs,omitempty"` + + // apis lists the exported APIs a binding to this offering syncs, by CRD + // name on the provider ("."). + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinItems=1 + // +listType=map + // +listMapKey=name + APIs []corev1alpha1.APIRef `json:"apis"` + + // defaults are copied into the generated ClusterBinding of the one-apply + // bundle. + // + // +optional + Defaults BindingDefaults `json:"defaults,omitempty"` +} + +// Icon points at an icon image for UIs. +type Icon struct { + // url of the icon image. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + URL string `json:"url"` +} + +// BindingDefaults are the binding fields an Export pre-fills in the generated +// bundle. +type BindingDefaults struct { + // conflictPolicy is the default conflict behavior for the generated + // ClusterBinding. + // + // +optional + // +kubebuilder:validation:Enum=Fail;Adopt + ConflictPolicy corev1alpha1.ConflictPolicy `json:"conflictPolicy,omitempty"` + + // relatedResources are the related-resource selectors for the generated + // ClusterBinding. + // + // +optional + // +listType=atomic + RelatedResources []corev1alpha1.RelatedResource `json:"relatedResources,omitempty"` +} + +// ExportStatus is the observed state of an Export. +type ExportStatus struct { + // conditions: Ready (all listed APIs are actually exported). + // + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// ExportList contains a list of Export. +// +// +kubebuilder:object:root=true +type ExportList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Export `json:"items"` +} diff --git a/sdk/apis/catalog/v1alpha1/groupversion_info.go b/sdk/apis/catalog/v1alpha1/groupversion_info.go new file mode 100644 index 000000000..c3f1a06a6 --- /dev/null +++ b/sdk/apis/catalog/v1alpha1/groupversion_info.go @@ -0,0 +1,53 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +const ( + // GroupName is the API group for the kbind catalog (service layer). + GroupName = "catalog.kbind.io" + + // Version is the API version of this package. + Version = "v1alpha1" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: GroupName, Version: Version} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Resource takes an unqualified resource and returns a Group qualified GroupResource. +func Resource(resource string) schema.GroupResource { + return GroupVersion.WithResource(resource).GroupResource() +} + +func init() { + SchemeBuilder.Register( + &Export{}, &ExportList{}, + &Collection{}, &CollectionList{}, + ) +} diff --git a/sdk/apis/catalog/v1alpha1/zz_generated.deepcopy.go b/sdk/apis/catalog/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000..de7353552 --- /dev/null +++ b/sdk/apis/catalog/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,263 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2026 The kbind 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. +*/ +// Code generated by controller-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BindingDefaults) DeepCopyInto(out *BindingDefaults) { + *out = *in + if in.RelatedResources != nil { + in, out := &in.RelatedResources, &out.RelatedResources + *out = make([]corev1alpha1.RelatedResource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingDefaults. +func (in *BindingDefaults) DeepCopy() *BindingDefaults { + if in == nil { + return nil + } + out := new(BindingDefaults) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Collection) DeepCopyInto(out *Collection) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Collection. +func (in *Collection) DeepCopy() *Collection { + if in == nil { + return nil + } + out := new(Collection) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Collection) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CollectionList) DeepCopyInto(out *CollectionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Collection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CollectionList. +func (in *CollectionList) DeepCopy() *CollectionList { + if in == nil { + return nil + } + out := new(CollectionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CollectionList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CollectionSpec) DeepCopyInto(out *CollectionSpec) { + *out = *in + if in.Exports != nil { + in, out := &in.Exports, &out.Exports + *out = make([]ExportRef, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CollectionSpec. +func (in *CollectionSpec) DeepCopy() *CollectionSpec { + if in == nil { + return nil + } + out := new(CollectionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Export) DeepCopyInto(out *Export) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Export. +func (in *Export) DeepCopy() *Export { + if in == nil { + return nil + } + out := new(Export) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Export) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExportList) DeepCopyInto(out *ExportList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Export, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportList. +func (in *ExportList) DeepCopy() *ExportList { + if in == nil { + return nil + } + out := new(ExportList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ExportList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExportRef) DeepCopyInto(out *ExportRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportRef. +func (in *ExportRef) DeepCopy() *ExportRef { + if in == nil { + return nil + } + out := new(ExportRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExportSpec) DeepCopyInto(out *ExportSpec) { + *out = *in + if in.Icon != nil { + in, out := &in.Icon, &out.Icon + *out = new(Icon) + **out = **in + } + if in.APIs != nil { + in, out := &in.APIs, &out.APIs + *out = make([]corev1alpha1.APIRef, len(*in)) + copy(*out, *in) + } + in.Defaults.DeepCopyInto(&out.Defaults) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportSpec. +func (in *ExportSpec) DeepCopy() *ExportSpec { + if in == nil { + return nil + } + out := new(ExportSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExportStatus) DeepCopyInto(out *ExportStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportStatus. +func (in *ExportStatus) DeepCopy() *ExportStatus { + if in == nil { + return nil + } + out := new(ExportStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Icon) DeepCopyInto(out *Icon) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Icon. +func (in *Icon) DeepCopy() *Icon { + if in == nil { + return nil + } + out := new(Icon) + in.DeepCopyInto(out) + return out +} diff --git a/sdk/apis/core/v1alpha1/binding_types.go b/sdk/apis/core/v1alpha1/binding_types.go new file mode 100644 index 000000000..12c5b1620 --- /dev/null +++ b/sdk/apis/core/v1alpha1/binding_types.go @@ -0,0 +1,53 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Binding activates instance sync for one or more exported APIs within its own +// namespace. Namespaced, following the Role convention. It is the v2 answer to +// v1's informerScope: Namespaced. Where a ClusterBinding and a Binding cover the +// same API on the same connection, the ClusterBinding wins. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Namespaced,categories=kbind +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Connection",type=string,JSONPath=`.spec.connectionRef.name` +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type Binding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec BindingSpec `json:"spec"` + + // +optional + Status BindingStatus `json:"status,omitempty"` +} + +// BindingList contains a list of Binding. +// +// +kubebuilder:object:root=true +type BindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Binding `json:"items"` +} diff --git a/sdk/apis/core/v1alpha1/clusterbinding_types.go b/sdk/apis/core/v1alpha1/clusterbinding_types.go new file mode 100644 index 000000000..5e74d7855 --- /dev/null +++ b/sdk/apis/core/v1alpha1/clusterbinding_types.go @@ -0,0 +1,67 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ClusterBinding activates instance sync for one or more exported APIs +// cluster-wide. Cluster-scoped, following the ClusterRole convention. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,categories=kbind +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Connection",type=string,JSONPath=`.spec.connectionRef.name` +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type ClusterBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec BindingSpec `json:"spec"` + + // +optional + Status BindingStatus `json:"status,omitempty"` +} + +// BindingStatus is the observed state shared by ClusterBinding and Binding. +type BindingStatus struct { + // boundAPIs is per-API observed state. + // + // +optional + // +listType=atomic + BoundAPIs []BoundAPI `json:"boundAPIs,omitempty"` + + // conditions: Connected, Synced, Conflicts, PermissionDenied, Ready. + // + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// ClusterBindingList contains a list of ClusterBinding. +// +// +kubebuilder:object:root=true +type ClusterBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ClusterBinding `json:"items"` +} diff --git a/sdk/apis/core/v1alpha1/conditions.go b/sdk/apis/core/v1alpha1/conditions.go new file mode 100644 index 000000000..6e5889ba7 --- /dev/null +++ b/sdk/apis/core/v1alpha1/conditions.go @@ -0,0 +1,72 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +// Condition types used across the core kinds. v2 uses metav1.Condition; the +// konnector sets these with apimachinery's meta.SetStatusCondition helpers. +const ( + // ConditionReady is the top-level summary condition on every core kind. + ConditionReady = "Ready" + + // Connection conditions. + + // ConditionSecretValid is true when the kubeconfigSecretRef resolves to a + // usable kubeconfig in the konnector's namespace. + ConditionSecretValid = "SecretValid" + // ConditionConnected is true when the konnector can reach the provider and + // the pinned cluster identity still matches. + ConditionConnected = "Connected" + // ConditionSchemaInSync is true when exported schemas are installed on the + // consumer per the Connection's schema policy. + ConditionSchemaInSync = "SchemaInSync" + + // Binding conditions. + + // ConditionSynced is true when all listed APIs are installed and their + // instances are syncing. + ConditionSynced = "Synced" + // ConditionConflicts is true when at least one object was skipped due to + // foreign ownership; see boundAPIs[].conflictCount and per-object conditions. + ConditionConflicts = "Conflicts" + // ConditionPermissionDenied is true when an operation was refused by + // provider RBAC; the binding keeps syncing what it can. + ConditionPermissionDenied = "PermissionDenied" +) + +// Condition reasons. +const ( + // ReasonAsExpected is the success reason for a True Ready/Synced condition. + ReasonAsExpected = "AsExpected" + // ReasonPending marks a missing-but-expected dependency (referenced + // Connection/Secret/CRD not present yet). Not an error; resolves on arrival. + ReasonPending = "Pending" + // ReasonSecretNotFound marks an unresolvable kubeconfigSecretRef. + ReasonSecretNotFound = "SecretNotFound" + // ReasonClusterIdentityChanged marks a Secret now pointing at a different + // provider cluster than the one pinned in status. + ReasonClusterIdentityChanged = "ClusterIdentityChanged" + // ReasonAPINotExported marks a binding listing an API the Connection does + // not export to these credentials. + ReasonAPINotExported = "APINotExported" + // ReasonForeignObjectExists marks a conflict with an un-owned target object. + ReasonForeignObjectExists = "ForeignObjectExists" + // ReasonOwnedByAnother marks a conflict with an object owned by a different + // binding/consumer. + ReasonOwnedByAnother = "OwnedByAnother" + // ReasonForbidden marks an operation refused by provider RBAC. + ReasonForbidden = "Forbidden" +) diff --git a/sdk/apis/core/v1alpha1/connection_types.go b/sdk/apis/core/v1alpha1/connection_types.go new file mode 100644 index 000000000..5ee850d25 --- /dev/null +++ b/sdk/apis/core/v1alpha1/connection_types.go @@ -0,0 +1,175 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Connection is the link to one provider cluster. It owns the credentials and +// schema delivery, and surfaces what the provider exports. Cluster-scoped. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,categories=kbind +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +// +kubebuilder:printcolumn:name="Secret",type=string,JSONPath=`.spec.kubeconfigSecretRef.name` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type Connection struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec ConnectionSpec `json:"spec"` + + // +optional + Status ConnectionStatus `json:"status,omitempty"` +} + +// ConnectionSpec defines the desired provider link. +type ConnectionSpec struct { + // kubeconfigSecretRef points at the Secret holding the provider kubeconfig. + // Immutable. The only credential reference in the core. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" + KubeconfigSecretRef SecretKeyRef `json:"kubeconfigSecretRef"` + + // schema controls how exported APIs reach the consumer. + // + // +optional + // +kubebuilder:default={} + Schema SchemaPolicy `json:"schema,omitempty"` + + // autoBind, when true, makes the konnector maintain a managed ClusterBinding + // (named after this Connection) covering all exported APIs. + // + // +kubebuilder:default=false + AutoBind bool `json:"autoBind,omitempty"` +} + +// SchemaPolicy controls schema source, pull and update behavior. +type SchemaPolicy struct { + // source selects how schemas are obtained: + // Auto - CRD if readable on the provider, else OpenAPI (default). + // CRD - read apiextensions CRDs verbatim. + // OpenAPI - synthesize CRDs from discovery + /openapi/v3. + // + // +kubebuilder:validation:Enum=Auto;CRD;OpenAPI + // +kubebuilder:default=Auto + Source SchemaSource `json:"source,omitempty"` + + // pullPolicy selects which exported APIs are installed: + // Bound - only APIs referenced by a Binding/ClusterBinding (default). + // All - every exported API readable by the credentials. + // None - never install CRDs (user/extension manages them). + // + // +kubebuilder:validation:Enum=Bound;All;None + // +kubebuilder:default=Bound + PullPolicy PullPolicy `json:"pullPolicy,omitempty"` + + // updatePolicy selects whether installed schemas follow provider changes: + // Always - follow provider schema changes (default). + // Once - pin at first pull. + // + // +kubebuilder:validation:Enum=Always;Once + // +kubebuilder:default=Always + UpdatePolicy UpdatePolicy `json:"updatePolicy,omitempty"` +} + +// SchemaSource selects how schemas are obtained from the provider. +type SchemaSource string + +const ( + // SchemaSourceAuto probes CRD first, falls back to OpenAPI. + SchemaSourceAuto SchemaSource = "Auto" + // SchemaSourceCRD reads apiextensions CRDs from the provider. + SchemaSourceCRD SchemaSource = "CRD" + // SchemaSourceOpenAPI synthesizes CRDs from discovery + /openapi/v3. + SchemaSourceOpenAPI SchemaSource = "OpenAPI" +) + +// PullPolicy selects which exported APIs are installed on the consumer. +type PullPolicy string + +const ( + // PullPolicyBound installs only APIs referenced by a binding. + PullPolicyBound PullPolicy = "Bound" + // PullPolicyAll installs every exported API. + PullPolicyAll PullPolicy = "All" + // PullPolicyNone never installs CRDs. + PullPolicyNone PullPolicy = "None" +) + +// UpdatePolicy selects whether installed schemas track provider changes. +type UpdatePolicy string + +const ( + // UpdatePolicyAlways follows provider schema changes. + UpdatePolicyAlways UpdatePolicy = "Always" + // UpdatePolicyOnce pins the schema at first pull. + UpdatePolicyOnce UpdatePolicy = "Once" +) + +// ConnectionStatus is the observed state of a Connection. +type ConnectionStatus struct { + // remoteClusterUID is the identity of the provider cluster, pinned on first + // connect and immutable thereafter. A Secret later pointing at a different + // cluster is rejected rather than silently re-homing synced objects. + // + // +optional + // +kubebuilder:validation:XValidation:rule="oldSelf == '' || self == oldSelf",message="remoteClusterUID is immutable once set" + RemoteClusterUID string `json:"remoteClusterUID,omitempty"` + + // localClusterUID is the identity of the consumer cluster, pinned on first + // connect and immutable thereafter. + // + // +optional + // +kubebuilder:validation:XValidation:rule="oldSelf == '' || self == oldSelf",message="localClusterUID is immutable once set" + LocalClusterUID string `json:"localClusterUID,omitempty"` + + // activeSchemaSource is the schema source actually in effect after resolving + // "Auto" (CRD or OpenAPI). The binding uses it to decide whether the + // Connection already installed the CRDs (OpenAPI) or it should pull them (CRD). + // + // +optional + ActiveSchemaSource SchemaSource `json:"activeSchemaSource,omitempty"` + + // exportedAPIs is the discovery result: APIs exported to these credentials. + // + // +optional + // +listType=atomic + ExportedAPIs []ExportedAPI `json:"exportedAPIs,omitempty"` + + // conditions: SecretValid, Connected, SchemaInSync, Ready. + // + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// ConnectionList contains a list of Connection. +// +// +kubebuilder:object:root=true +type ConnectionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Connection `json:"items"` +} diff --git a/sdk/apis/kubebind/v1alpha1/doc.go b/sdk/apis/core/v1alpha1/doc.go similarity index 65% rename from sdk/apis/kubebind/v1alpha1/doc.go rename to sdk/apis/core/v1alpha1/doc.go index a9551c65d..36bee4576 100644 --- a/sdk/apis/kubebind/v1alpha1/doc.go +++ b/sdk/apis/core/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2022 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,10 +14,10 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1alpha1 defines the v1alpha1 version of the Kube Bind API +// Package v1alpha1 contains the v2 "slim core" API for kbind: +// the Connection, ClusterBinding and Binding kinds in the core.kbind.io +// group. See docs/proposals/v2-slim-core.md for the design. // -// +groupName=kube-bind.io -// +groupGoName=KubeBind -// +k8s:deepcopy-gen=package,register -// +kubebuilder:validation:Optional +// +kubebuilder:object:generate=true +// +groupName=core.kbind.io package v1alpha1 diff --git a/sdk/apis/core/v1alpha1/groupversion_info.go b/sdk/apis/core/v1alpha1/groupversion_info.go new file mode 100644 index 000000000..c39265c5e --- /dev/null +++ b/sdk/apis/core/v1alpha1/groupversion_info.go @@ -0,0 +1,54 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +const ( + // GroupName is the API group for the v2 slim core. + GroupName = "core.kbind.io" + + // Version is the API version of this package. + Version = "v1alpha1" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: GroupName, Version: Version} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Resource takes an unqualified resource and returns a Group qualified GroupResource. +func Resource(resource string) schema.GroupResource { + return GroupVersion.WithResource(resource).GroupResource() +} + +func init() { + SchemeBuilder.Register( + &Connection{}, &ConnectionList{}, + &ClusterBinding{}, &ClusterBindingList{}, + &Binding{}, &BindingList{}, + ) +} diff --git a/sdk/apis/core/v1alpha1/helpers.go b/sdk/apis/core/v1alpha1/helpers.go new file mode 100644 index 000000000..25a46663d --- /dev/null +++ b/sdk/apis/core/v1alpha1/helpers.go @@ -0,0 +1,64 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// BindingAccessor is implemented by both ClusterBinding and Binding so a single +// reconciler can drive either kind. The only difference between them is scope. +// It is also a client.Object (metav1.Object + runtime.Object). +// +// +kubebuilder:object:generate=false +type BindingAccessor interface { + metav1.Object + runtime.Object + // BindingSpecP returns a pointer to the shared spec. + BindingSpecP() *BindingSpec + // BindingStatusP returns a pointer to the shared status. + BindingStatusP() *BindingStatus +} + +// BindingSpecP returns a pointer to the ClusterBinding spec. +func (b *ClusterBinding) BindingSpecP() *BindingSpec { return &b.Spec } + +// BindingStatusP returns a pointer to the ClusterBinding status. +func (b *ClusterBinding) BindingStatusP() *BindingStatus { return &b.Status } + +// BindingSpecP returns a pointer to the Binding spec. +func (b *Binding) BindingSpecP() *BindingSpec { return &b.Spec } + +// BindingStatusP returns a pointer to the Binding status. +func (b *Binding) BindingStatusP() *BindingStatus { return &b.Status } + +var ( + _ BindingAccessor = &ClusterBinding{} + _ BindingAccessor = &Binding{} +) + +// ExportsAPI reports whether the Connection exports an API with the given CRD +// name ("."). +func (s *ConnectionStatus) ExportsAPI(crdName string) (ExportedAPI, bool) { + for i := range s.ExportedAPIs { + if s.ExportedAPIs[i].Name == crdName { + return s.ExportedAPIs[i], true + } + } + return ExportedAPI{}, false +} diff --git a/sdk/apis/core/v1alpha1/labels.go b/sdk/apis/core/v1alpha1/labels.go new file mode 100644 index 000000000..912a9572d --- /dev/null +++ b/sdk/apis/core/v1alpha1/labels.go @@ -0,0 +1,75 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +const ( + // LabelExported marks a provider CRD as exported to consumers. The + // konnector's discovery (schema.source: CRD) lists CRDs carrying this label. + // On CRD-less providers the logical-cluster boundary is the export boundary + // instead, and no label is needed. + LabelExported = "core.kbind.io/exported" + + // LabelManaged marks an object (or namespace) written by the konnector on + // the provider. + LabelManaged = "core.kbind.io/managed" + + // AnnotationConnection records the name of the Connection. + // Used on pulled consumer CRD so that the sync engine can pin + // the provider cluster for that API. It's also used on Leases to maintain + // the link between consumer's Connection and provider's Lease. + AnnotationConnection = "core.kbind.io/connection" + + // AnnotationConsumerClusterUID records the consumer cluster identity on a + // synced provider object (ownership marker). + AnnotationConsumerClusterUID = "core.kbind.io/consumer-cluster-uid" + + // AnnotationConsumerObjectUID records the source consumer object UID on a + // synced provider object (ownership marker). + AnnotationConsumerObjectUID = "core.kbind.io/consumer-object-uid" + + // AnnotationRelatedBinding records, on a synced related Secret/ConfigMap, the + // UID of the binding that pulled it in, so it can be GC'd when it stops + // matching the selector or the binding is removed. + AnnotationRelatedBinding = "core.kbind.io/related-binding" + + // AnnotationConflict marks a consumer instance the konnector refused to sync + // because the provider target is owned by another binding/consumer. The + // value is the conflict reason. Bindings count annotated instances to report + // conflictCount. Survives status-schema pruning (it is metadata, not status). + AnnotationConflict = "core.kbind.io/conflict" + + // AnnotationDeletionPolicy on a consumer instance controls what happens to + // its provider copy when the consumer object is deleted or unbound. The only + // non-default value is "Orphan": release the finalizer without deleting the + // provider copy (keep the managed object on the provider). + AnnotationDeletionPolicy = "core.kbind.io/deletion-policy" + + // DeletionPolicyOrphan keeps the provider copy when the consumer object is + // deleted or unbound. + DeletionPolicyOrphan = "Orphan" + + // FinalizerSyncer blocks consumer-object deletion until the provider copy + // has been removed. + FinalizerSyncer = "core.kbind.io/syncer" + + // FinalizerCleanup blocks deletion of a Connection or Binding until the + // konnector has unwound what it created: provider copies of synced + // instances, pulled CRDs, and instance finalizers. It is also placed on a + // Connection's referenced Secret so the credential survives long enough to + // reach the provider during teardown. + FinalizerCleanup = "core.kbind.io/cleanup" +) diff --git a/sdk/apis/core/v1alpha1/shared_types.go b/sdk/apis/core/v1alpha1/shared_types.go new file mode 100644 index 000000000..c7484950c --- /dev/null +++ b/sdk/apis/core/v1alpha1/shared_types.go @@ -0,0 +1,209 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// SecretKeyRef references a key within a Secret. The Secret must live in the +// konnector's designated namespace; a cluster-scoped Connection may not reach +// into arbitrary namespaces (privilege-escalation guard, see proposal F1). +type SecretKeyRef struct { + // namespace of the Secret. Must be the konnector's designated namespace. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Namespace string `json:"namespace"` + + // name of the Secret. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` + + // key within the Secret holding the kubeconfig. + // + // +kubebuilder:default=kubeconfig + Key string `json:"key,omitempty"` +} + +// ConnectionRef references a Connection by name. Connection is cluster-scoped, +// so no namespace is needed. +type ConnectionRef struct { + // name of the Connection. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` +} + +// APIRef identifies an exported API by its CRD name on the provider, +// i.e. "." (for example "mangodbs.mangodb.io"). Under the +// OpenAPI schema source there is no CRD object behind the name; it is still +// just resource + group. +type APIRef struct { + // name is the CRD name of the exported API, ".". + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` +} + +// BindingSpec is the spec shared by ClusterBinding and Binding. The only +// difference between the two kinds is scope (cluster-wide vs. one namespace), +// which is expressed by the kind, not by a field. +type BindingSpec struct { + // connectionRef points at the Connection that provides the provider link + // and credentials for the listed APIs. + // + // +required + // +kubebuilder:validation:Required + ConnectionRef ConnectionRef `json:"connectionRef"` + + // apis lists one or more exported CRDs to sync, by CRD name on the provider. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinItems=1 + APIs []APIRef `json:"apis"` + + // conflictPolicy controls what happens when a target object already exists. + // Fail (default) leaves a foreign object untouched and records a conflict; + // Adopt takes ownership of an un-owned object. Adopt never steals an object + // already carrying another binding's/consumer's markers. + // + // +kubebuilder:validation:Enum=Fail;Adopt + // +kubebuilder:default=Fail + ConflictPolicy ConflictPolicy `json:"conflictPolicy,omitempty"` + + // relatedResources are Secrets/ConfigMaps synced alongside instances of the + // bound APIs. Not yet synced in the alpha POC. + // + // +optional + // +listType=atomic + RelatedResources []RelatedResource `json:"relatedResources,omitempty"` +} + +// ConflictPolicy is the behavior for pre-existing target objects. +type ConflictPolicy string + +const ( + // ConflictPolicyFail leaves a foreign target object untouched and records + // the collision as a conflict. This is the default. + ConflictPolicyFail ConflictPolicy = "Fail" + + // ConflictPolicyAdopt takes ownership of an un-owned target object. + ConflictPolicyAdopt ConflictPolicy = "Adopt" +) + +// RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync +// alongside the bound instances. +type RelatedResource struct { + // group of the related resource. Empty string for the core group. + // + // +kubebuilder:default="" + Group string `json:"group"` + + // resource is the plural resource name. Only "secrets" and "configmaps" + // are permitted in core. + // + // +kubebuilder:validation:Enum=secrets;configmaps + // +required + // +kubebuilder:validation:Required + Resource string `json:"resource"` + + // direction the related resource flows. + // + // +kubebuilder:validation:Enum=FromProvider;FromConsumer + // +required + // +kubebuilder:validation:Required + Direction SyncDirection `json:"direction"` + + // selector restricts which objects are synced. Only labelSelector and + // named selectors are supported in core (no JSONPath reference-following). + // + // +optional + Selector *RelatedResourceSelector `json:"selector,omitempty"` +} + +// SyncDirection is the direction a related resource is synced. +type SyncDirection string + +const ( + // FromProvider syncs the related resource provider -> consumer. + FromProvider SyncDirection = "FromProvider" + // FromConsumer syncs the related resource consumer -> provider. + FromConsumer SyncDirection = "FromConsumer" +) + +// RelatedResourceSelector restricts which related objects are synced. +type RelatedResourceSelector struct { + // labelSelector selects related objects by label. + // + // +optional + LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"` + + // names selects related objects by exact name. + // + // +optional + // +listType=set + Names []string `json:"names,omitempty"` +} + +// BoundAPI is the per-API observed state recorded on a binding's status. +type BoundAPI struct { + // name is the CRD name of the bound API, ".". + Name string `json:"name"` + + // crdHash is a hash of the schema currently applied on the consumer for + // this API. Empty until the schema has been installed. + // + // +optional + CRDHash string `json:"crdHash,omitempty"` + + // conflictCount is the number of objects skipped due to foreign ownership. + // Per-object detail lives on each object's own condition, not here. + // + // +optional + ConflictCount int32 `json:"conflictCount,omitempty"` +} + +// ExportedAPI describes one API the provider exports to these credentials. +type ExportedAPI struct { + // name is the CRD name of the exported API, ".". + Name string `json:"name"` + + // group of the exported API. + Group string `json:"group"` + + // resource is the plural resource name of the exported API. + Resource string `json:"resource"` + + // scope is whether the API is Namespaced or Cluster scoped. + Scope apiextensionsv1.ResourceScope `json:"scope"` + + // versions are the served versions of the exported API. + // + // +listType=set + Versions []string `json:"versions"` +} diff --git a/sdk/apis/core/v1alpha1/zz_generated.deepcopy.go b/sdk/apis/core/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000..d7a603667 --- /dev/null +++ b/sdk/apis/core/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,443 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2026 The kbind 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. +*/ +// Code generated by controller-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIRef) DeepCopyInto(out *APIRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIRef. +func (in *APIRef) DeepCopy() *APIRef { + if in == nil { + return nil + } + out := new(APIRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Binding) DeepCopyInto(out *Binding) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Binding. +func (in *Binding) DeepCopy() *Binding { + if in == nil { + return nil + } + out := new(Binding) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Binding) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BindingList) DeepCopyInto(out *BindingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Binding, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingList. +func (in *BindingList) DeepCopy() *BindingList { + if in == nil { + return nil + } + out := new(BindingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BindingList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BindingSpec) DeepCopyInto(out *BindingSpec) { + *out = *in + out.ConnectionRef = in.ConnectionRef + if in.APIs != nil { + in, out := &in.APIs, &out.APIs + *out = make([]APIRef, len(*in)) + copy(*out, *in) + } + if in.RelatedResources != nil { + in, out := &in.RelatedResources, &out.RelatedResources + *out = make([]RelatedResource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingSpec. +func (in *BindingSpec) DeepCopy() *BindingSpec { + if in == nil { + return nil + } + out := new(BindingSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BindingStatus) DeepCopyInto(out *BindingStatus) { + *out = *in + if in.BoundAPIs != nil { + in, out := &in.BoundAPIs, &out.BoundAPIs + *out = make([]BoundAPI, len(*in)) + copy(*out, *in) + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingStatus. +func (in *BindingStatus) DeepCopy() *BindingStatus { + if in == nil { + return nil + } + out := new(BindingStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BoundAPI) DeepCopyInto(out *BoundAPI) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundAPI. +func (in *BoundAPI) DeepCopy() *BoundAPI { + if in == nil { + return nil + } + out := new(BoundAPI) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBinding) DeepCopyInto(out *ClusterBinding) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBinding. +func (in *ClusterBinding) DeepCopy() *ClusterBinding { + if in == nil { + return nil + } + out := new(ClusterBinding) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBinding) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterBindingList) DeepCopyInto(out *ClusterBindingList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterBinding, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingList. +func (in *ClusterBindingList) DeepCopy() *ClusterBindingList { + if in == nil { + return nil + } + out := new(ClusterBindingList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterBindingList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Connection) DeepCopyInto(out *Connection) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Connection. +func (in *Connection) DeepCopy() *Connection { + if in == nil { + return nil + } + out := new(Connection) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Connection) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionList) DeepCopyInto(out *ConnectionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Connection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionList. +func (in *ConnectionList) DeepCopy() *ConnectionList { + if in == nil { + return nil + } + out := new(ConnectionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConnectionList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionRef) DeepCopyInto(out *ConnectionRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionRef. +func (in *ConnectionRef) DeepCopy() *ConnectionRef { + if in == nil { + return nil + } + out := new(ConnectionRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionSpec) DeepCopyInto(out *ConnectionSpec) { + *out = *in + out.KubeconfigSecretRef = in.KubeconfigSecretRef + out.Schema = in.Schema +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionSpec. +func (in *ConnectionSpec) DeepCopy() *ConnectionSpec { + if in == nil { + return nil + } + out := new(ConnectionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionStatus) DeepCopyInto(out *ConnectionStatus) { + *out = *in + if in.ExportedAPIs != nil { + in, out := &in.ExportedAPIs, &out.ExportedAPIs + *out = make([]ExportedAPI, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionStatus. +func (in *ConnectionStatus) DeepCopy() *ConnectionStatus { + if in == nil { + return nil + } + out := new(ConnectionStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExportedAPI) DeepCopyInto(out *ExportedAPI) { + *out = *in + if in.Versions != nil { + in, out := &in.Versions, &out.Versions + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportedAPI. +func (in *ExportedAPI) DeepCopy() *ExportedAPI { + if in == nil { + return nil + } + out := new(ExportedAPI) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RelatedResource) DeepCopyInto(out *RelatedResource) { + *out = *in + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(RelatedResourceSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RelatedResource. +func (in *RelatedResource) DeepCopy() *RelatedResource { + if in == nil { + return nil + } + out := new(RelatedResource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RelatedResourceSelector) DeepCopyInto(out *RelatedResourceSelector) { + *out = *in + if in.LabelSelector != nil { + in, out := &in.LabelSelector, &out.LabelSelector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + if in.Names != nil { + in, out := &in.Names, &out.Names + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RelatedResourceSelector. +func (in *RelatedResourceSelector) DeepCopy() *RelatedResourceSelector { + if in == nil { + return nil + } + out := new(RelatedResourceSelector) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SchemaPolicy) DeepCopyInto(out *SchemaPolicy) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SchemaPolicy. +func (in *SchemaPolicy) DeepCopy() *SchemaPolicy { + if in == nil { + return nil + } + out := new(SchemaPolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SecretKeyRef) DeepCopyInto(out *SecretKeyRef) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretKeyRef. +func (in *SecretKeyRef) DeepCopy() *SecretKeyRef { + if in == nil { + return nil + } + out := new(SecretKeyRef) + in.DeepCopyInto(out) + return out +} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/doc.go b/sdk/apis/iam/v1alpha1/doc.go similarity index 50% rename from sdk/client/clientset/versioned/typed/kubebind/v1alpha1/doc.go rename to sdk/apis/iam/v1alpha1/doc.go index 05ebc8af6..4b4d24d64 100644 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/doc.go +++ b/sdk/apis/iam/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. +// Package v1alpha1 contains the issuance/identity API for the kbind service +// layer: the Grant kind in the iam.kbind.io group. A Grant is the typed record +// of "identity X was issued credentials Y for export Z" — the anchor for +// revocation, audit and the reaper. Kept out of catalog.kbind.io so that group +// stays purely presentation+defaults. Lives on the provider; the konnector +// never sees it. See docs/proposals/v2-extended.md. +// +// +kubebuilder:object:generate=true +// +groupName=iam.kbind.io package v1alpha1 diff --git a/sdk/apis/iam/v1alpha1/grant_types.go b/sdk/apis/iam/v1alpha1/grant_types.go new file mode 100644 index 000000000..30312e6b4 --- /dev/null +++ b/sdk/apis/iam/v1alpha1/grant_types.go @@ -0,0 +1,150 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// Grant records that an identity was issued credentials for an export. The +// gateway creates it with the export's API list and defaults resolved in +// (issuance is a stable record even if the catalog entry changes later); the +// issuer controller provisions the tenancy boundary, ServiceAccount, RBAC and +// token from the spec and reports the artifacts in status. Deleting the Grant +// revokes: the issuer's cleanup finalizer unwinds everything it provisioned. +// +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster,categories=kbind +// +kubebuilder:subresource:status +// +kubebuilder:printcolumn:name="Subject",type=string,JSONPath=`.spec.identity.subject` +// +kubebuilder:printcolumn:name="Export",type=string,JSONPath=`.spec.exportName` +// +kubebuilder:printcolumn:name="Namespace",type=string,JSONPath=`.status.namespace` +// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` +// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` +type Grant struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + // +required + // +kubebuilder:validation:Required + Spec GrantSpec `json:"spec"` + + // +optional + Status GrantStatus `json:"status,omitempty"` +} + +// GrantSpec is the issuance request/record. +type GrantSpec struct { + // identity is who the credentials were issued to. + // + // +required + // +kubebuilder:validation:Required + Identity Identity `json:"identity"` + + // exportName records which catalog Export this Grant was issued for. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + ExportName string `json:"exportName"` + + // apis is the export's API list resolved at issuance time, by CRD name on + // the provider ("."). The issuer scopes RBAC to exactly + // these. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinItems=1 + // +listType=map + // +listMapKey=name + APIs []corev1alpha1.APIRef `json:"apis"` + + // conflictPolicy is the export's default conflict policy resolved at + // issuance time, copied into the generated bundle's ClusterBinding. + // + // +optional + // +kubebuilder:validation:Enum=Fail;Adopt + ConflictPolicy corev1alpha1.ConflictPolicy `json:"conflictPolicy,omitempty"` + + // relatedResources are the export's related-resource selectors resolved at + // issuance time. They flow into the bundle's ClusterBinding and widen the + // issued RBAC (secrets/configmaps in the declared direction). + // + // +optional + // +listType=atomic + RelatedResources []corev1alpha1.RelatedResource `json:"relatedResources,omitempty"` +} + +// Identity is the consumer identity credentials were issued to. The tenancy +// key is issuer+"/"+subject, so the same human gets the same boundary on +// re-bind. +type Identity struct { + // subject is the stable identity key, "#" for OIDC. + // + // +required + // +kubebuilder:validation:Required + // +kubebuilder:validation:MinLength=1 + Subject string `json:"subject"` + + // displayName is a human-facing name (e.g. email), informational only. + // + // +optional + DisplayName string `json:"displayName,omitempty"` + + // groups the identity carried at issuance, informational only. + // + // +optional + // +listType=atomic + Groups []string `json:"groups,omitempty"` +} + +// GrantStatus reports what the issuer provisioned. +type GrantStatus struct { + // namespace is the per-consumer tenancy boundary on the provider. + // + // +optional + Namespace string `json:"namespace,omitempty"` + + // serviceAccount is the name of the issued ServiceAccount (in namespace). + // + // +optional + ServiceAccount string `json:"serviceAccount,omitempty"` + + // tokenSecret is the name of the long-lived SA token Secret (in + // namespace). The gateway reads it to assemble the bundle's kubeconfig. + // + // +optional + TokenSecret string `json:"tokenSecret,omitempty"` + + // conditions: Ready (credentials provisioned and token populated). + // + // +optional + // +listType=map + // +listMapKey=type + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// GrantList contains a list of Grant. +// +// +kubebuilder:object:root=true +type GrantList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Grant `json:"items"` +} diff --git a/sdk/apis/iam/v1alpha1/groupversion_info.go b/sdk/apis/iam/v1alpha1/groupversion_info.go new file mode 100644 index 000000000..7e3b3aec2 --- /dev/null +++ b/sdk/apis/iam/v1alpha1/groupversion_info.go @@ -0,0 +1,52 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/scheme" +) + +const ( + // GroupName is the API group for kbind issuance records (service layer). + GroupName = "iam.kbind.io" + + // Version is the API version of this package. + Version = "v1alpha1" +) + +var ( + // GroupVersion is group version used to register these objects. + GroupVersion = schema.GroupVersion{Group: GroupName, Version: Version} + + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. + SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} + + // AddToScheme adds the types in this group-version to the given scheme. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Resource takes an unqualified resource and returns a Group qualified GroupResource. +func Resource(resource string) schema.GroupResource { + return GroupVersion.WithResource(resource).GroupResource() +} + +func init() { + SchemeBuilder.Register( + &Grant{}, &GrantList{}, + ) +} diff --git a/sdk/apis/iam/v1alpha1/labels.go b/sdk/apis/iam/v1alpha1/labels.go new file mode 100644 index 000000000..f3c64feab --- /dev/null +++ b/sdk/apis/iam/v1alpha1/labels.go @@ -0,0 +1,66 @@ +/* +Copyright 2026 The kbind 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 v1alpha1 + +const ( + // LabelGrant marks provider objects (namespace, ServiceAccount, RBAC, + // token Secret) provisioned by the issuer for a Grant; the value is the + // Grant's name. + LabelGrant = "iam.kbind.io/grant" + + // AnnotationPickupSHA256 on a Grant holds the SHA-256 of the one-time + // bundle pickup token's random part. The gateway stamps it at bind time + // and removes it (with optimistic concurrency) on pickup, so single-use + // is enforced by the API server and the gateway keeps zero state. + AnnotationPickupSHA256 = "iam.kbind.io/pickup-sha256" + + // AnnotationPickupExpiry on a Grant holds the RFC 3339 expiry of the + // pickup token. Applies to the pickup URL only — the SA token inside a + // picked-up bundle stays valid until the Grant is revoked. + AnnotationPickupExpiry = "iam.kbind.io/pickup-expiry" + + // AnnotationStaleSince on a Grant is stamped by the reaper when the + // consumer's heartbeat Lease has been expired (or absent) beyond the + // configured TTL. Cleared when the heartbeat resumes. + AnnotationStaleSince = "iam.kbind.io/stale-since" + + // FinalizerCleanup blocks Grant deletion until the issuer has unwound the + // provisioned namespace, ServiceAccount, RBAC and token Secret. + FinalizerCleanup = "iam.kbind.io/cleanup" +) + +// Condition types and reasons for iam kinds. +const ( + // ConditionReady is true when the credentials are provisioned and the + // token Secret is populated. + ConditionReady = "Ready" + + // ConditionStale is true when the reaper considers the consumer behind + // this Grant gone (heartbeat Lease expired beyond TTL). + ConditionStale = "Stale" + + // ReasonAsExpected is the success reason. + ReasonAsExpected = "AsExpected" + // ReasonPending marks provisioning still in progress (e.g. token not yet + // populated by the token controller). + ReasonPending = "Pending" + // ReasonLeaseExpired marks a Grant whose consumer heartbeat Lease expired. + ReasonLeaseExpired = "LeaseExpired" + // ReasonNoLease marks a Grant whose boundary namespace never saw a + // heartbeat Lease. + ReasonNoLease = "NoLease" +) diff --git a/sdk/apis/iam/v1alpha1/zz_generated.deepcopy.go b/sdk/apis/iam/v1alpha1/zz_generated.deepcopy.go new file mode 100644 index 000000000..2c2fbede9 --- /dev/null +++ b/sdk/apis/iam/v1alpha1/zz_generated.deepcopy.go @@ -0,0 +1,155 @@ +//go:build !ignore_autogenerated + +/* +Copyright 2026 The kbind 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. +*/ +// Code generated by controller-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Grant) DeepCopyInto(out *Grant) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Grant. +func (in *Grant) DeepCopy() *Grant { + if in == nil { + return nil + } + out := new(Grant) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Grant) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GrantList) DeepCopyInto(out *GrantList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Grant, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrantList. +func (in *GrantList) DeepCopy() *GrantList { + if in == nil { + return nil + } + out := new(GrantList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *GrantList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GrantSpec) DeepCopyInto(out *GrantSpec) { + *out = *in + in.Identity.DeepCopyInto(&out.Identity) + if in.APIs != nil { + in, out := &in.APIs, &out.APIs + *out = make([]corev1alpha1.APIRef, len(*in)) + copy(*out, *in) + } + if in.RelatedResources != nil { + in, out := &in.RelatedResources, &out.RelatedResources + *out = make([]corev1alpha1.RelatedResource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrantSpec. +func (in *GrantSpec) DeepCopy() *GrantSpec { + if in == nil { + return nil + } + out := new(GrantSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GrantStatus) DeepCopyInto(out *GrantStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GrantStatus. +func (in *GrantStatus) DeepCopy() *GrantStatus { + if in == nil { + return nil + } + out := new(GrantStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Identity) DeepCopyInto(out *Identity) { + *out = *in + if in.Groups != nil { + in, out := &in.Groups, &out.Groups + *out = make([]string, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Identity. +func (in *Identity) DeepCopy() *Identity { + if in == nil { + return nil + } + out := new(Identity) + in.DeepCopyInto(out) + return out +} diff --git a/sdk/apis/kubebind/v1alpha1/apiservicebinding_types.go b/sdk/apis/kubebind/v1alpha1/apiservicebinding_types.go deleted file mode 100644 index 19c55d961..000000000 --- a/sdk/apis/kubebind/v1alpha1/apiservicebinding_types.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // APIServiceBindingConditionSecretValid is set when the secret is valid. - APIServiceBindingConditionSecretValid conditionsapi.ConditionType = "SecretValid" - - // APIServiceBindingConditionInformersSynced is set when the informers can sync. - APIServiceBindingConditionInformersSynced conditionsapi.ConditionType = "InformersSynced" - - // APIServiceBindingConditionHeartbeating is set when the ClusterBinding of the service provider - // is successfully heartbeated. - APIServiceBindingConditionHeartbeating conditionsapi.ConditionType = "Heartbeating" - - // APIServiceBindingConditionConnected means the APIServiceBinding has been connected to a APIServiceExport. - APIServiceBindingConditionConnected conditionsapi.ConditionType = "Connected" - - // APIServiceBindingConditionSchemaInSync is set to true when the APIServiceExport's - // schema is applied to the consumer cluster. - APIServiceBindingConditionSchemaInSync conditionsapi.ConditionType = "SchemaInSync" - - // DownstreamFinalizer is put on downstream objects to block their deletion until - // the upstream object has been deleted. - DownstreamFinalizer = "kubebind.io/syncer" -) - -// APIServiceBinding binds an API service represented by a APIServiceExport -// in a service provider cluster into a consumer cluster. This object lives in -// the consumer cluster. -// -// +crd -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bindings,shortName=sb -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Provider",type="string",JSONPath=`.status.providerPrettyName`,priority=0 -// +kubebuilder:printcolumn:name="Resources",type="string",JSONPath=`.metadata.annotations.kube-bind\.io/resources`,priority=1 -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Message",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].message`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - Spec APIServiceBindingSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - Status APIServiceBindingStatus `json:"status,omitempty"` -} - -func (in *APIServiceBinding) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceBinding) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -type APIServiceBindingSpec struct { - // kubeconfigSecretName is the secret ref that contains the kubeconfig of the service cluster. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" - KubeconfigSecretRef ClusterSecretKeyRef `json:"kubeconfigSecretRef"` -} - -type APIServiceBindingStatus struct { - // providerPrettyName is the pretty name of the service provider cluster. This - // can be shared among different APIServiceBindings. - ProviderPrettyName string `json:"providerPrettyName,omitempty"` - - // conditions is a list of conditions that apply to the APIServiceBinding. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceBindingList is a list of APIServiceBindings. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceBinding `json:"items"` -} - -type LocalSecretKeyRef struct { - // Name of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Name string `json:"name"` - - // The key of the secret to select from. Must be "kubeconfig". - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:Enum=kubeconfig - Key string `json:"key"` -} - -type ClusterSecretKeyRef struct { - LocalSecretKeyRef `json:",inline"` - - // Namespace of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Namespace string `json:"namespace"` -} diff --git a/sdk/apis/kubebind/v1alpha1/apiserviceexport_types.go b/sdk/apis/kubebind/v1alpha1/apiserviceexport_types.go deleted file mode 100644 index 8209ab966..000000000 --- a/sdk/apis/kubebind/v1alpha1/apiserviceexport_types.go +++ /dev/null @@ -1,245 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - SourceSpecHashAnnotationKey = "kube-bind.io/source-spec-hash" -) - -const ( - // APIServiceExportConditionConnected means the APIServiceExport has been connected to a APIServiceBinding. - APIServiceExportConditionConnected conditionsapi.ConditionType = "Connected" - - // APIServiceExportConditionProviderInSync is set to true when the APIServiceExport - // is in-sync with the CRD in the service provider cluster. - APIServiceExportConditionProviderInSync conditionsapi.ConditionType = "ProviderInSync" - - // APIServiceExportConditionConsumerInSync is set to true when the APIServiceExport's - // schema is applied to the consumer cluster. - APIServiceExportConditionConsumerInSync conditionsapi.ConditionType = "ConsumerInSync" -) - -// APIServiceExport specifies the resource to be exported. It is mostly a CRD: -// - the spec is a CRD spec, but without webhooks -// - the status reflects that on the consumer cluster -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Established",type="string",JSONPath=`.status.conditions[?(@.type=="Established")].status`,priority=5 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -// +kubebuilder:validation:XValidation:rule="self.metadata.name == self.spec.names.plural+\".\"+self.spec.group",message="informerScope is immutable" -type APIServiceExport struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec specifies the resource. - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportSpec `json:"spec"` - - // status contains reconciliation information for the resource. - Status APIServiceExportStatus `json:"status,omitempty"` -} - -func (in *APIServiceExport) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceExport) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// APIServiceExportSpec defines the desired state of APIServiceExport. -// -// +kubebuilder:validation:XValidation:rule=`self.scope == "Namespaced" || self.informerScope == "Cluster"`,message="informerScope must be Cluster for cluster-scoped resources" -// +kubebuilder:validation:XValidation:rule=`self.scope == "Namespaced" || has(self.clusterScopedIsolation)`,message="clusterScopedIsolation must be defined for cluster-scoped resources" -// +kubebuilder:validation:XValidation:rule=`self.scope == "Cluster" || !has(self.clusterScopedIsolation)`,message="clusterScopedIsolation is not relevant for namespaced resources" -type APIServiceExportSpec struct { - APIServiceExportCRDSpec `json:",inline"` - - // informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - // - // Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - // This is more efficient than watching each namespace individually. - // Namespaced: The konnector has permission to watch only single namespaces. - // This is more resource intensive. And it means cluster-scoped resources cannot be exported. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="informerScope is immutable" - InformerScope Scope `json:"informerScope"` - - // ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - // It can be "Prefixed", "Namespaced", or "None". - ClusterScopedIsolation Isolation `json:"clusterScopedIsolation,omitempty"` -} - -// Isolation is an enum defining the different ways to isolate cluster scoped objects -// -// +kubebuilder:validation:Enum=Prefixed;Namespaced;None -type Isolation string - -const ( - // Prepends the name of the cluster namespace to an object's name. - IsolationPrefixed Isolation = "Prefixed" - - // Maps a consumer side object into a namespaced object inside the corresponding cluster namespace. - IsolationNamespaced Isolation = "Namespaced" - - // Used for the case of a dedicated provider where isolation is not necessary. - IsolationNone Isolation = "None" -) - -type APIServiceExportCRDSpec struct { - // group is the API group of the defined custom resource. Empty string means the - // core API group. The resources are served under `/apis//...` or `/api` for the core group. - // - // +required - Group string `json:"group"` - - // names specify the resource and kind names for the custom resource. - // - // +required - Names apiextensionsv1.CustomResourceDefinitionNames `json:"names"` - - // scope indicates whether the defined custom resource is cluster- or namespace-scoped. - // Allowed values are `Cluster` and `Namespaced`. - // - // +required - // +kubebuilder:validation:Enum=Cluster;Namespaced - Scope apiextensionsv1.ResourceScope `json:"scope"` - - // versions is the API version of the defined custom resource. - // - // Note: the OpenAPI v3 schemas must be equal for all versions until CEL - // version migration is supported. - // - // +required - // +listType=map - // +listMapKey=name - // +kubebuilder:validation:MinItems=1 - Versions []APIServiceExportVersion `json:"versions"` -} - -// APIServiceExportVersion describes one API version of a resource. -type APIServiceExportVersion struct { - // name is the version name, e.g. “v1”, “v2beta1”, etc. - // The custom resources are served under this version at `/apis///...` if `served` is true. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:Pattern=^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - Name string `json:"name"` - // served is a flag enabling/disabling this version from being served via REST APIs - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:default=true - Served bool `json:"served"` - // storage indicates this version should be used when persisting custom resources to storage. - // There must be exactly one version with storage=true. - // - // +required - // +kubebuilder:validation:Required - Storage bool `json:"storage"` - //nolint:gocritic // deprecatedComment: the proper format is - // deprecated indicates this version of the custom resource API is deprecated. - // When set to true, API requests to this version receive a warning header in the server response. - // Defaults to false. - // - // +optional - Deprecated bool `json:"deprecated,omitempty"` - // deprecationWarning overrides the default warning returned to API clients. - // May only be set when `deprecated` is true. - // The default warning indicates this version is deprecated and recommends use - // of the newest served version of equal or greater stability, if one exists. - // - // +optional - DeprecationWarning *string `json:"deprecationWarning,omitempty"` - // schema describes the structural schema used for validation, pruning, and defaulting - // of this version of the custom resource. - // - // +required - // +kubebuilder:validation:Required - Schema APIServiceExportSchema `json:"schema"` - // subresources specify what subresources this version of the defined custom resource have. - // - // +optional - Subresources apiextensionsv1.CustomResourceSubresources `json:"subresources,omitempty"` - // additionalPrinterColumns specifies additional columns returned in Table output. - // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - // If no columns are specified, a single column displaying the age of the custom resource is used. - // - // +optional - // +listType=map - // +listMapKey=name - AdditionalPrinterColumns []apiextensionsv1.CustomResourceColumnDefinition `json:"additionalPrinterColumns,omitempty"` -} - -type APIServiceExportSchema struct { - // openAPIV3Schema is the OpenAPI v3 schema to use for validation and pruning. - // - // +kubebuilder:pruning:PreserveUnknownFields - // +structType=atomic - // +required - // +kubebuilder:validation:Required - OpenAPIV3Schema runtime.RawExtension `json:"openAPIV3Schema"` -} - -// APIServiceExportStatus stores status information about a APIServiceExport. It -// reflects the status of the CRD of the consumer cluster. -type APIServiceExportStatus struct { - // acceptedNames are the names that are actually being used to serve discovery. - // They may be different than the names in spec. - // +optional - AcceptedNames apiextensionsv1.CustomResourceDefinitionNames `json:"acceptedNames"` - - // storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - // versions allows a migration path for stored versions in etcd. The field is mutable - // so a migration controller can finish a migration to another version (ensuring - // no old objects are left in storage), and then remove the rest of the - // versions from this list. - // Versions may not be removed from `spec.versions` while they exist in this list. - // +optional - StoredVersions []string `json:"storedVersions"` - - // conditions is a list of conditions that apply to the APIServiceExport. It is - // updated by the konnector on the consumer cluster. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceExportList is the objects list that represents the APIServiceExport. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceExport `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha1/apiserviceexportrequest_types.go b/sdk/apis/kubebind/v1alpha1/apiserviceexportrequest_types.go deleted file mode 100644 index 8d57242ef..000000000 --- a/sdk/apis/kubebind/v1alpha1/apiserviceexportrequest_types.go +++ /dev/null @@ -1,179 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // APIServiceExportRequestConditionExportsReady is set to true when the - // corresponding APIServiceExport is ready. - APIServiceExportRequestConditionExportsReady conditionsapi.ConditionType = "ExportsReady" -) - -// APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. -// -// The service provider can prune these objects after some time. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceExportRequest struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - // - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportRequestSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - // +kubebuilder:default={} - Status APIServiceExportRequestStatus `json:"status"` -} - -// APIServiceExportRequestResponse is like APIServiceExportRequest but without -// ObjectMeta, to avoid unwanted metadata fields being sent in the response. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportRequestResponse struct { - metav1.TypeMeta `json:",inline"` - ObjectMeta NameObjectMeta `json:"metadata"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - // - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportRequestSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - Status APIServiceExportRequestStatus `json:"status,omitempty"` -} - -type NameObjectMeta struct { - // Name is the name of the object. - Name string `json:"name,omitempty"` -} - -func (in *APIServiceExportRequest) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceExportRequest) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// APIServiceExportRequestSpec is the spec of a APIServiceExportRequest. -type APIServiceExportRequestSpec struct { - // parameters holds service provider specific parameters for this binding - // request. - // - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="parameters are immutable" - Parameters *runtime.RawExtension `json:"parameters,omitempty"` - - // resources is a list of resources that should be exported. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="resources are immutable" - Resources []APIServiceExportRequestResource `json:"resources"` -} - -type APIServiceExportRequestResource struct { - GroupResource `json:",inline"` - - // versions is a list of versions that should be exported. If this is empty - // a sensible default is chosen by the service provider. - Versions []string `json:"versions,omitempty"` -} - -// GroupResource identifies a resource. -type GroupResource struct { - // group is the name of an API group. - // For core groups this is the empty string '""'. - // - // +kubebuilder:validation:Pattern=`^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$` - // +kubebuilder:default="" - Group string `json:"group,omitempty"` - - // resource is the name of the resource. - // Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - // not provided by an service binding export. - // - // +kubebuilder:validation:Pattern=`^[a-z][-a-z0-9]*[a-z0-9]$` - // +required - // +kubebuilder:validation:Required - Resource string `json:"resource"` -} - -// APIServiceExportRequestPhase describes the phase of a binding request. -type APIServiceExportRequestPhase string - -const ( - // APIServiceExportRequestPhasePending indicates that the service binding - // is in progress. - APIServiceExportRequestPhasePending APIServiceExportRequestPhase = "Pending" - // APIServiceExportRequestPhaseFailed indicates that the service binding - // has failed. It will not resume. - APIServiceExportRequestPhaseFailed APIServiceExportRequestPhase = "Failed" - // APIServiceExportRequestPhaseSucceeded indicates that the service binding - // has succeeded. The corresponding APIServiceExport have been created and - // are ready. - APIServiceExportRequestPhaseSucceeded APIServiceExportRequestPhase = "Succeeded" -) - -type APIServiceExportRequestStatus struct { - // phase is the current phase of the binding request. It starts in Pending - // and transitions to Succeeded or Failed. See the condition for detailed - // information. - // - // +optional - // +kubebuilder:validation:Optional - // +kubebuilder:default=Pending - // +kubebuilder:validation:Enum=Pending;Failed;Succeeded - Phase APIServiceExportRequestPhase `json:"phase,omitempty"` - - // terminalMessage is a human readable message that describes the reason - // for the current phase. - TerminalMessage string `json:"terminalMessage,omitempty"` - - // conditions is a list of conditions that apply to the ClusterBinding. It is - // updated by the konnector and the service provider. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceExportRequestList is the list of APIServiceExportRequest. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportRequestList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceExportRequest `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha1/apiservicenamespace_types.go b/sdk/apis/kubebind/v1alpha1/apiservicenamespace_types.go deleted file mode 100644 index 551c60235..000000000 --- a/sdk/apis/kubebind/v1alpha1/apiservicenamespace_types.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - APIServiceNamespaceAnnotationKey = "kube-bind.io/api-service-namespace" -) - -// APIServiceNamespace defines how consumer namespaces map to service namespaces. -// These objects are created by the konnector, and a service namespace is then -// created by the service provider. -// -// The name of the APIServiceNamespace equals the namespace name in the consumer -// cluster. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Namespace",type="string",JSONPath=`.status.namespace`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceNamespace struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec specifies a service namespace. - Spec APIServiceNamespaceSpec `json:"spec"` - - // status contains reconciliation information for a service namespace - Status APIServiceNamespaceStatus `json:"status,omitempty"` -} - -type APIServiceNamespaceSpec struct { -} - -type APIServiceNamespaceStatus struct { - // namespace is the service provider namespace name that will be bound to the - // consumer namespace named like this object. - Namespace string `json:"namespace,omitempty"` -} - -// APIServiceNamespaceList is the list of ServiceNamespaces. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceNamespaceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceNamespace `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha1/bindingprovider_types.go b/sdk/apis/kubebind/v1alpha1/bindingprovider_types.go deleted file mode 100644 index 0031df1a4..000000000 --- a/sdk/apis/kubebind/v1alpha1/bindingprovider_types.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// BindingProvider is a non-CRUD resource that is returned by the server before -// authentication. It specifies which authentication flows the provider supports. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type BindingProvider struct { - metav1.TypeMeta `json:",inline"` - - // providerPrettyName is the name of the provider that is displayed to the user, e.g: - // MangoDB Inc. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - ProviderPrettyName string `json:"providerPrettyName"` - - // version is the kube-bind.io version of the provider. The kubectl bind will check - // this for compatibility. - // - // +required - // +kubebuilder:validation:Required - Version string `json:"version"` - - // authenticationMethods is a list of authentication methods supported by the - // service provider. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - AuthenticationMethods []AuthenticationMethod `json:"authenticationMethods,omitempty"` -} - -type AuthenticationMethod struct { - // method is the name of the authentication method. The follow methods are supported: - // - // - "OAuth2CodeGrant" - // - // The list is ordered by preference by the service provider. The consumer should - // try to use the first method in the list that matches the capabilities of the - // client environment (e.g. does the client support a web browser) and the - // flags provided by the user. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:Enum=OAuth2CodeGrant - Method string `json:"method,omitempty"` - - // OAuth2CodeGrant is the configuration for the OAuth2 code grant flow. - OAuth2CodeGrant *OAuth2CodeGrant `json:"oauth2CodeGrant,omitempty"` -} - -type OAuth2CodeGrant struct { - // authenticatedURL is the service provider url that the service consumer will use to authenticate against - // the service provider in case of using OIDC mode made, e.g: www.mangodb.com/kubernetes/authorize. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - AuthenticatedURL string `json:"authenticatedURL"` -} diff --git a/sdk/apis/kubebind/v1alpha1/bindingresponse_types.go b/sdk/apis/kubebind/v1alpha1/bindingresponse_types.go deleted file mode 100644 index ac04bcbc5..000000000 --- a/sdk/apis/kubebind/v1alpha1/bindingresponse_types.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" -) - -// BindingResponse is a non-CRUD resource that is returned by the server after -// authentication and resource selection on the service prpvider website. It returns -// a list of requests of possibly different types that kubectl bind has to -// pass to the sub-command kubect-bind-, e.g. kubectl-bind-apiservice for -// APIServiceExportRequest. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type BindingResponse struct { - metav1.TypeMeta `json:",inline"` - - // authentication is data specific to the authentication method that was used. - // - // +optional - // +kubebuilder:validation:Optional - Authentication BindingResponseAuthentication `json:"authentication,omitempty"` - - // kubeconfig is a kubeconfig file that can be used to access the service provider cluster. - // - // +required - // +kubebuilder:validation:Required - Kubeconfig []byte `json:"kubeconfig"` - - // requests is a list of binding requests of different types, e.g. APIServiceExportRequest. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - Requests []runtime.RawExtension `json:"requests"` -} - -// BindingResponseAuthentication is the authentication data specific to the -// authentication method that was used. Exactly one field must be set. -type BindingResponseAuthentication struct { - // oauth2CodeGrant is the data returned by the OAuth2 code grant flow. - // - // +optional - // +kubebuilder:validation:Optional - OAuth2CodeGrant *BindingResponseAuthenticationOAuth2CodeGrant `json:"oauth2CodeGrant,omitempty"` -} - -// BindingResponseAuthenticationOAuth2CodeGrant contains the authentication data which is passed back to -// the consumer as BindingResponse.Authentication. It is authentication method -// specific. -type BindingResponseAuthenticationOAuth2CodeGrant struct { - // sessionID is the session ID that was originally passed from the consumer to - // the service provider. It must be checked to equal the original value. - SessionID string `json:"sid"` - - // id is the ID of the authenticated user. It is for informational purposes only. - ID string `json:"id"` -} diff --git a/sdk/apis/kubebind/v1alpha1/clusterbinding_types.go b/sdk/apis/kubebind/v1alpha1/clusterbinding_types.go deleted file mode 100644 index 8882846e5..000000000 --- a/sdk/apis/kubebind/v1alpha1/clusterbinding_types.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // ClusterBindingConditionSecretValid is set when the secret is valid. - ClusterBindingConditionSecretValid = "SecretValid" - - // ClusterBindingConditionValidVersion is set when the binary version is valid. - ClusterBindingConditionValidVersion = "ValidVersion" - - // ClusterBindingConditionHealthy is set when the cluster binding is healthy. - ClusterBindingConditionHealthy = "Healthy" -) - -// ClusterBinding represents a bound consumer cluster. It lives in a service provider cluster -// and is a singleton named "cluster". -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Konnector Version",type="string",JSONPath=`.status.konnectorVersion`,priority=0 -// +kubebuilder:printcolumn:name="Last Heartbeat",type="date",JSONPath=`.status.lastHeartbeatTime`,priority=0 -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -// +kubebuilder:validation:XValidation:rule="self.metadata.name == \"cluster\"",message="cluster binding name should be cluster" -type ClusterBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // spec represents the data in the newly created ClusterBinding. - // +required - // +kubebuilder:validation:Required - Spec ClusterBindingSpec `json:"spec"` - - // status contains reconciliation information for the service binding. - Status ClusterBindingStatus `json:"status,omitempty"` -} - -func (in *ClusterBinding) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *ClusterBinding) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// Scope is the scope of the ClusterBinding. -// -// +kubebuilder:validation:Enum=Cluster;Namespaced -type Scope string - -const ( - // ClusterScope means that the konnector has permission to watch all namespaces at once. - // This is more efficient than watching each namespace individually. - // - // Only Cluster scoped ClusterBindings can export cluster-scoped resources. But Cluster - // scoped ClusterBindings can export namespaced resources as well. - // - // In a Kubernetes cluster, Cluster scoped ClusterBindings don't allow isolation between tenants. - // In a kcp cluster, the platform provides the isolation between workspaces and hence tenants - // are isolated if with full cluster-wide access of a konnector. - ClusterScope Scope = "Cluster" - // NamespacedScope means that the konnector has permission to watch only single namespaces. - // This is more resource intensive than Cluster scope. - // - // Only namespace-scoped resources can be exported in Namespace scope. - NamespacedScope Scope = "Namespaced" -) - -// ClusterBindingSpec represents the data in the newly created ClusterBinding. -type ClusterBindingSpec struct { - // kubeconfigSecretName is the secret ref that contains the kubeconfig of the service cluster. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" - KubeconfigSecretRef LocalSecretKeyRef `json:"kubeconfigSecretRef"` - - // providerPrettyName is the pretty name of the service provider cluster. This - // can be shared among different ServiceBindings. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - ProviderPrettyName string `json:"providerPrettyName"` - - // serviceProviderSpec contains all the data and information about the service which has been bound to the service - // binding request. The service providers decide what they need and what to configure based on what then include in - // this field, such as service region, type, tiers, etc... - ServiceProviderSpec runtime.RawExtension `json:"serviceProviderSpec,omitempty"` -} - -// ClusterBindingStatus stores status information about a service binding. It is -// updated by both the konnector and the service provider. -type ClusterBindingStatus struct { - // lastHeartbeatTime is the last time the konnector updated the status. - LastHeartbeatTime metav1.Time `json:"lastHeartbeatTime,omitempty"` - - // heartbeatInterval is the maximal interval between heartbeats that the - // konnector promises to send. The service provider can assume that the - // konnector is not unhealthy if it does not receive a heartbeat within - // this time. - HeartbeatInterval metav1.Duration `json:"heartbeatInterval,omitempty"` - - // konnectorVersion is the version of the konnector that is running on the - // consumer cluster. - KonnectorVersion string `json:"konnectorVersion,omitempty"` - - // conditions is a list of conditions that apply to the ClusterBinding. It is - // updated by the konnector and the service provider. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// ClusterBindingList is the objects list that represents the ClusterBinding. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type ClusterBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []ClusterBinding `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha1/helpers/crd.go b/sdk/apis/kubebind/v1alpha1/helpers/crd.go deleted file mode 100644 index fffce1f16..000000000 --- a/sdk/apis/kubebind/v1alpha1/helpers/crd.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 helpers - -import ( - "strings" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" -) - -func IsOwnedByBinding(name string, uid types.UID, refs []v1.OwnerReference) bool { - for _, ref := range refs { - parts := strings.SplitN(ref.APIVersion, "/", 2) - if parts[0] != v1alpha1.SchemeGroupVersion.Group || ref.Kind != "APIServiceBinding" { - continue - } - if ref.Name != name { - continue - } - if uid == "" || ref.UID == uid { - return true - } - } - return false -} diff --git a/sdk/apis/kubebind/v1alpha1/helpers/serviceexport.go b/sdk/apis/kubebind/v1alpha1/helpers/serviceexport.go deleted file mode 100644 index a9cdcc841..000000000 --- a/sdk/apis/kubebind/v1alpha1/helpers/serviceexport.go +++ /dev/null @@ -1,144 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 helpers - -import ( - "crypto/sha256" - "encoding/json" - "fmt" - "math/big" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime2 "k8s.io/apimachinery/pkg/util/runtime" - "sigs.k8s.io/yaml" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" -) - -// ServiceExportToCRD converts a APIServiceExport to a CRD. -func ServiceExportToCRD(export *kubebindv1alpha1.APIServiceExport) (*apiextensionsv1.CustomResourceDefinition, error) { - crd := &apiextensionsv1.CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{ - Name: export.Name, - }, - Spec: apiextensionsv1.CustomResourceDefinitionSpec{ - Group: export.Spec.Group, - Names: export.Spec.Names, - Scope: export.Spec.Scope, - }, - } - - for i := range export.Spec.Versions { - resourceVersion := export.Spec.Versions[i] - - crdVersion := apiextensionsv1.CustomResourceDefinitionVersion{ - Name: resourceVersion.Name, - Served: resourceVersion.Served, - Storage: resourceVersion.Storage, - Deprecated: resourceVersion.Deprecated, - DeprecationWarning: resourceVersion.DeprecationWarning, - AdditionalPrinterColumns: resourceVersion.AdditionalPrinterColumns, - } - - if len(resourceVersion.Schema.OpenAPIV3Schema.Raw) > 0 { - var schema apiextensionsv1.JSONSchemaProps - if err := yaml.Unmarshal(resourceVersion.Schema.OpenAPIV3Schema.Raw, &schema); err != nil { - return nil, fmt.Errorf("failed to unmarshal schema for version %q: %w", resourceVersion.Name, err) - } - crdVersion.Schema = &apiextensionsv1.CustomResourceValidation{ - OpenAPIV3Schema: &schema, - } - } - - crdVersion.Subresources = &resourceVersion.Subresources - - crd.Spec.Versions = append(crd.Spec.Versions, crdVersion) - } - - return crd, nil -} - -// CRDToServiceExport converts a CRD to a APIServiceExport. -func CRDToServiceExport(crd *apiextensionsv1.CustomResourceDefinition) (*kubebindv1alpha1.APIServiceExportCRDSpec, error) { - spec := &kubebindv1alpha1.APIServiceExportCRDSpec{ - Group: crd.Spec.Group, - Names: crd.Spec.Names, - Scope: crd.Spec.Scope, - } - - onlyFirstServingVersion := crd.Spec.Conversion != nil && crd.Spec.Conversion.Strategy == apiextensionsv1.WebhookConverter - // TODO: come up with an API to select versions - for i := range crd.Spec.Versions { - crdVersion := crd.Spec.Versions[i] - - // skip non-served versions - if !crdVersion.Served { - continue - } - - apiResourceVersion := kubebindv1alpha1.APIServiceExportVersion{ - Name: crdVersion.Name, - Served: crdVersion.Served, - Storage: crdVersion.Storage, - Deprecated: crdVersion.Deprecated, - DeprecationWarning: crdVersion.DeprecationWarning, - AdditionalPrinterColumns: crdVersion.AdditionalPrinterColumns, - } - - if crdVersion.Schema != nil && crdVersion.Schema.OpenAPIV3Schema != nil { - schema, err := json.Marshal(crdVersion.Schema.OpenAPIV3Schema) - if err != nil { - return nil, fmt.Errorf("failed to marshal CRD %s schema for version %q: %w", crd.Name, crdVersion.Name, err) - } - apiResourceVersion.Schema.OpenAPIV3Schema.Raw = schema - } - - if crdVersion.Subresources != nil { - apiResourceVersion.Subresources = *crdVersion.Subresources - } - - spec.Versions = append(spec.Versions, apiResourceVersion) - - if onlyFirstServingVersion { - spec.Versions[0].Storage = true - break - } - } - - return spec, nil -} - -func APIServiceExportCRDSpecHash(obj *kubebindv1alpha1.APIServiceExportCRDSpec) string { - bs, err := json.Marshal(obj) - if err != nil { - runtime2.HandleError(err) - return "" - } - - return toSha224Base62(string(bs)) -} - -func toSha224Base62(s string) string { - return toBase62(sha256.Sum224([]byte(s))) -} - -func toBase62(hash [28]byte) string { - var i big.Int - i.SetBytes(hash[:]) - return i.Text(62) -} diff --git a/sdk/apis/kubebind/v1alpha1/helpers/serviceexport_test.go b/sdk/apis/kubebind/v1alpha1/helpers/serviceexport_test.go deleted file mode 100644 index 8baf1c82f..000000000 --- a/sdk/apis/kubebind/v1alpha1/helpers/serviceexport_test.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2023 The Kube Bind 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 helpers - -import ( - "testing" - - "github.com/stretchr/testify/require" - v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/utils/ptr" -) - -func TestWebhookCRDStorageVersion(t *testing.T) { - input := v1.CustomResourceDefinition{ - Spec: v1.CustomResourceDefinitionSpec{ - Versions: []v1.CustomResourceDefinitionVersion{ - { - Served: true, - Name: "v1alpha1", - Storage: false, - }, - { - Served: true, - Name: "v1", - Storage: true, - }, - }, - Conversion: &v1.CustomResourceConversion{ - Strategy: v1.WebhookConverter, - Webhook: &v1.WebhookConversion{ - ClientConfig: &v1.WebhookClientConfig{ - URL: ptr.To("https://example.com/webhook"), - CABundle: []byte("1234")}, - }, - }, - }, - } - - output, err := CRDToServiceExport(&input) - - require.NoError(t, err) - - atLeastOneStorageVersion := false - for _, v := range output.Versions { - atLeastOneStorageVersion = atLeastOneStorageVersion || v.Storage - } - if !atLeastOneStorageVersion { - t.Fatal("returned ResourceExport has no storage version", output) - } -} diff --git a/sdk/apis/kubebind/v1alpha1/register.go b/sdk/apis/kubebind/v1alpha1/register.go deleted file mode 100644 index bbfdf10af..000000000 --- a/sdk/apis/kubebind/v1alpha1/register.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -const ( - // GroupName is the group name used in this package. - GroupName = "kube-bind.io" - - // GroupVersion is the group version used in this package. - GroupVersion = "v1alpha1" -) - -// SchemeGroupVersion is group version used to register these objects. -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: GroupVersion} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource. -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &APIServiceExport{}, - &APIServiceExportList{}, - &APIServiceBinding{}, - &APIServiceBindingList{}, - &APIServiceExportRequest{}, - &APIServiceExportRequestList{}, - &APIServiceNamespace{}, - &APIServiceNamespaceList{}, - &ClusterBinding{}, - &ClusterBindingList{}, - &BindingProvider{}, - &BindingResponse{}, - ) - - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/sdk/apis/kubebind/v1alpha1/zz_generated.deepcopy.go b/sdk/apis/kubebind/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 5b411966b..000000000 --- a/sdk/apis/kubebind/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,873 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - conditionsv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBinding) DeepCopyInto(out *APIServiceBinding) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBinding. -func (in *APIServiceBinding) DeepCopy() *APIServiceBinding { - if in == nil { - return nil - } - out := new(APIServiceBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBinding) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingList) DeepCopyInto(out *APIServiceBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingList. -func (in *APIServiceBindingList) DeepCopy() *APIServiceBindingList { - if in == nil { - return nil - } - out := new(APIServiceBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBindingList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingSpec) DeepCopyInto(out *APIServiceBindingSpec) { - *out = *in - out.KubeconfigSecretRef = in.KubeconfigSecretRef - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingSpec. -func (in *APIServiceBindingSpec) DeepCopy() *APIServiceBindingSpec { - if in == nil { - return nil - } - out := new(APIServiceBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingStatus) DeepCopyInto(out *APIServiceBindingStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(conditionsv1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingStatus. -func (in *APIServiceBindingStatus) DeepCopy() *APIServiceBindingStatus { - if in == nil { - return nil - } - out := new(APIServiceBindingStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExport) DeepCopyInto(out *APIServiceExport) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExport. -func (in *APIServiceExport) DeepCopy() *APIServiceExport { - if in == nil { - return nil - } - out := new(APIServiceExport) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExport) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportCRDSpec) DeepCopyInto(out *APIServiceExportCRDSpec) { - *out = *in - in.Names.DeepCopyInto(&out.Names) - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]APIServiceExportVersion, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportCRDSpec. -func (in *APIServiceExportCRDSpec) DeepCopy() *APIServiceExportCRDSpec { - if in == nil { - return nil - } - out := new(APIServiceExportCRDSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportList) DeepCopyInto(out *APIServiceExportList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceExport, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportList. -func (in *APIServiceExportList) DeepCopy() *APIServiceExportList { - if in == nil { - return nil - } - out := new(APIServiceExportList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequest) DeepCopyInto(out *APIServiceExportRequest) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequest. -func (in *APIServiceExportRequest) DeepCopy() *APIServiceExportRequest { - if in == nil { - return nil - } - out := new(APIServiceExportRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequest) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestList) DeepCopyInto(out *APIServiceExportRequestList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceExportRequest, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestList. -func (in *APIServiceExportRequestList) DeepCopy() *APIServiceExportRequestList { - if in == nil { - return nil - } - out := new(APIServiceExportRequestList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequestList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestResource) DeepCopyInto(out *APIServiceExportRequestResource) { - *out = *in - out.GroupResource = in.GroupResource - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestResource. -func (in *APIServiceExportRequestResource) DeepCopy() *APIServiceExportRequestResource { - if in == nil { - return nil - } - out := new(APIServiceExportRequestResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestResponse) DeepCopyInto(out *APIServiceExportRequestResponse) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ObjectMeta = in.ObjectMeta - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestResponse. -func (in *APIServiceExportRequestResponse) DeepCopy() *APIServiceExportRequestResponse { - if in == nil { - return nil - } - out := new(APIServiceExportRequestResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequestResponse) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestSpec) DeepCopyInto(out *APIServiceExportRequestSpec) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]APIServiceExportRequestResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestSpec. -func (in *APIServiceExportRequestSpec) DeepCopy() *APIServiceExportRequestSpec { - if in == nil { - return nil - } - out := new(APIServiceExportRequestSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestStatus) DeepCopyInto(out *APIServiceExportRequestStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(conditionsv1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestStatus. -func (in *APIServiceExportRequestStatus) DeepCopy() *APIServiceExportRequestStatus { - if in == nil { - return nil - } - out := new(APIServiceExportRequestStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportSchema) DeepCopyInto(out *APIServiceExportSchema) { - *out = *in - in.OpenAPIV3Schema.DeepCopyInto(&out.OpenAPIV3Schema) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportSchema. -func (in *APIServiceExportSchema) DeepCopy() *APIServiceExportSchema { - if in == nil { - return nil - } - out := new(APIServiceExportSchema) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportSpec) DeepCopyInto(out *APIServiceExportSpec) { - *out = *in - in.APIServiceExportCRDSpec.DeepCopyInto(&out.APIServiceExportCRDSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportSpec. -func (in *APIServiceExportSpec) DeepCopy() *APIServiceExportSpec { - if in == nil { - return nil - } - out := new(APIServiceExportSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportStatus) DeepCopyInto(out *APIServiceExportStatus) { - *out = *in - in.AcceptedNames.DeepCopyInto(&out.AcceptedNames) - if in.StoredVersions != nil { - in, out := &in.StoredVersions, &out.StoredVersions - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(conditionsv1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportStatus. -func (in *APIServiceExportStatus) DeepCopy() *APIServiceExportStatus { - if in == nil { - return nil - } - out := new(APIServiceExportStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportVersion) DeepCopyInto(out *APIServiceExportVersion) { - *out = *in - if in.DeprecationWarning != nil { - in, out := &in.DeprecationWarning, &out.DeprecationWarning - *out = new(string) - **out = **in - } - in.Schema.DeepCopyInto(&out.Schema) - in.Subresources.DeepCopyInto(&out.Subresources) - if in.AdditionalPrinterColumns != nil { - in, out := &in.AdditionalPrinterColumns, &out.AdditionalPrinterColumns - *out = make([]v1.CustomResourceColumnDefinition, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportVersion. -func (in *APIServiceExportVersion) DeepCopy() *APIServiceExportVersion { - if in == nil { - return nil - } - out := new(APIServiceExportVersion) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespace) DeepCopyInto(out *APIServiceNamespace) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespace. -func (in *APIServiceNamespace) DeepCopy() *APIServiceNamespace { - if in == nil { - return nil - } - out := new(APIServiceNamespace) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceNamespace) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceList) DeepCopyInto(out *APIServiceNamespaceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceNamespace, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceList. -func (in *APIServiceNamespaceList) DeepCopy() *APIServiceNamespaceList { - if in == nil { - return nil - } - out := new(APIServiceNamespaceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceNamespaceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceSpec) DeepCopyInto(out *APIServiceNamespaceSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceSpec. -func (in *APIServiceNamespaceSpec) DeepCopy() *APIServiceNamespaceSpec { - if in == nil { - return nil - } - out := new(APIServiceNamespaceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceStatus) DeepCopyInto(out *APIServiceNamespaceStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceStatus. -func (in *APIServiceNamespaceStatus) DeepCopy() *APIServiceNamespaceStatus { - if in == nil { - return nil - } - out := new(APIServiceNamespaceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AuthenticationMethod) DeepCopyInto(out *AuthenticationMethod) { - *out = *in - if in.OAuth2CodeGrant != nil { - in, out := &in.OAuth2CodeGrant, &out.OAuth2CodeGrant - *out = new(OAuth2CodeGrant) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthenticationMethod. -func (in *AuthenticationMethod) DeepCopy() *AuthenticationMethod { - if in == nil { - return nil - } - out := new(AuthenticationMethod) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingProvider) DeepCopyInto(out *BindingProvider) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.AuthenticationMethods != nil { - in, out := &in.AuthenticationMethods, &out.AuthenticationMethods - *out = make([]AuthenticationMethod, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingProvider. -func (in *BindingProvider) DeepCopy() *BindingProvider { - if in == nil { - return nil - } - out := new(BindingProvider) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindingProvider) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResponse) DeepCopyInto(out *BindingResponse) { - *out = *in - out.TypeMeta = in.TypeMeta - in.Authentication.DeepCopyInto(&out.Authentication) - if in.Kubeconfig != nil { - in, out := &in.Kubeconfig, &out.Kubeconfig - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.Requests != nil { - in, out := &in.Requests, &out.Requests - *out = make([]runtime.RawExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResponse. -func (in *BindingResponse) DeepCopy() *BindingResponse { - if in == nil { - return nil - } - out := new(BindingResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindingResponse) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResponseAuthentication) DeepCopyInto(out *BindingResponseAuthentication) { - *out = *in - if in.OAuth2CodeGrant != nil { - in, out := &in.OAuth2CodeGrant, &out.OAuth2CodeGrant - *out = new(BindingResponseAuthenticationOAuth2CodeGrant) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResponseAuthentication. -func (in *BindingResponseAuthentication) DeepCopy() *BindingResponseAuthentication { - if in == nil { - return nil - } - out := new(BindingResponseAuthentication) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResponseAuthenticationOAuth2CodeGrant) DeepCopyInto(out *BindingResponseAuthenticationOAuth2CodeGrant) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResponseAuthenticationOAuth2CodeGrant. -func (in *BindingResponseAuthenticationOAuth2CodeGrant) DeepCopy() *BindingResponseAuthenticationOAuth2CodeGrant { - if in == nil { - return nil - } - out := new(BindingResponseAuthenticationOAuth2CodeGrant) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBinding) DeepCopyInto(out *ClusterBinding) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBinding. -func (in *ClusterBinding) DeepCopy() *ClusterBinding { - if in == nil { - return nil - } - out := new(ClusterBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBinding) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingList) DeepCopyInto(out *ClusterBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingList. -func (in *ClusterBindingList) DeepCopy() *ClusterBindingList { - if in == nil { - return nil - } - out := new(ClusterBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBindingList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingSpec) DeepCopyInto(out *ClusterBindingSpec) { - *out = *in - out.KubeconfigSecretRef = in.KubeconfigSecretRef - in.ServiceProviderSpec.DeepCopyInto(&out.ServiceProviderSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingSpec. -func (in *ClusterBindingSpec) DeepCopy() *ClusterBindingSpec { - if in == nil { - return nil - } - out := new(ClusterBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingStatus) DeepCopyInto(out *ClusterBindingStatus) { - *out = *in - in.LastHeartbeatTime.DeepCopyInto(&out.LastHeartbeatTime) - out.HeartbeatInterval = in.HeartbeatInterval - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(conditionsv1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingStatus. -func (in *ClusterBindingStatus) DeepCopy() *ClusterBindingStatus { - if in == nil { - return nil - } - out := new(ClusterBindingStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterSecretKeyRef) DeepCopyInto(out *ClusterSecretKeyRef) { - *out = *in - out.LocalSecretKeyRef = in.LocalSecretKeyRef - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSecretKeyRef. -func (in *ClusterSecretKeyRef) DeepCopy() *ClusterSecretKeyRef { - if in == nil { - return nil - } - out := new(ClusterSecretKeyRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GroupResource) DeepCopyInto(out *GroupResource) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GroupResource. -func (in *GroupResource) DeepCopy() *GroupResource { - if in == nil { - return nil - } - out := new(GroupResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LocalSecretKeyRef) DeepCopyInto(out *LocalSecretKeyRef) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalSecretKeyRef. -func (in *LocalSecretKeyRef) DeepCopy() *LocalSecretKeyRef { - if in == nil { - return nil - } - out := new(LocalSecretKeyRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NameObjectMeta) DeepCopyInto(out *NameObjectMeta) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NameObjectMeta. -func (in *NameObjectMeta) DeepCopy() *NameObjectMeta { - if in == nil { - return nil - } - out := new(NameObjectMeta) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OAuth2CodeGrant) DeepCopyInto(out *OAuth2CodeGrant) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuth2CodeGrant. -func (in *OAuth2CodeGrant) DeepCopy() *OAuth2CodeGrant { - if in == nil { - return nil - } - out := new(OAuth2CodeGrant) - in.DeepCopyInto(out) - return out -} diff --git a/sdk/apis/kubebind/v1alpha2/apiservicebinding_types.go b/sdk/apis/kubebind/v1alpha2/apiservicebinding_types.go deleted file mode 100644 index 781f4f787..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiservicebinding_types.go +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // APIServiceBindingConditionSecretValid is set when the secret is valid. - APIServiceBindingConditionSecretValid conditionsapi.ConditionType = "SecretValid" - - // APIServiceBindingConditionInformersSynced is set when the informers can sync. - APIServiceBindingConditionInformersSynced conditionsapi.ConditionType = "InformersSynced" - - // APIServiceBindingConditionHeartbeating is set when the ClusterBinding of the service provider - // is successfully heartbeated. - APIServiceBindingConditionHeartbeating conditionsapi.ConditionType = "Heartbeating" - - // APIServiceBindingConditionConnected means the APIServiceBinding has been connected to a APIServiceExport. - APIServiceBindingConditionConnected conditionsapi.ConditionType = "Connected" - - // APIServiceBindingConditionSchemaInSync is set to true when the APIServiceExport's - // schema is applied to the consumer cluster. - APIServiceBindingConditionSchemaInSync conditionsapi.ConditionType = "SchemaInSync" - - // DownstreamFinalizer is put on downstream objects to block their deletion until - // the upstream object has been deleted. - DownstreamFinalizer = "kubebind.io/syncer" -) - -// APIServiceBinding binds an API service represented by a APIServiceExport -// in a service provider cluster into a consumer cluster. This object lives in -// the consumer cluster. -// -// +crd -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bindings,shortName=sb -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Provider",type="string",JSONPath=`.status.providerPrettyName`,priority=0 -// +kubebuilder:printcolumn:name="Resources",type="string",JSONPath=`.metadata.annotations.kube-bind\.io/resources`,priority=1 -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Message",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].message`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - Spec APIServiceBindingSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - Status APIServiceBindingStatus `json:"status"` -} - -func (in *APIServiceBinding) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceBinding) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -type APIServiceBindingSpec struct { - // kubeconfigSecretName is the secret ref that contains the kubeconfig of the service cluster. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" - KubeconfigSecretRef ClusterSecretKeyRef `json:"kubeconfigSecretRef"` -} - -type APIServiceBindingStatus struct { - // providerPrettyName is the pretty name of the service provider cluster. This - // can be shared among different APIServiceBindings. - ProviderPrettyName string `json:"providerPrettyName,omitempty"` - - // conditions is a list of conditions that apply to the APIServiceBinding. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` - - // BoundSchemas contains references to all BoundAPIResourceSchema objects - // associated with this APIServiceBinding, tracking consumer usage status. - // +optional - // +kubebuilder:validation:MinItems=1 - BoundSchemas []BoundSchemaReference `json:"boundSchemas,omitempty"` - - // PermissionClaims records decisions about permission claims requested by the service provider. - // Access is granted per GroupResource. - PermissionClaims []PermissionClaim `json:"permissionClaims,omitempty"` -} - -// BoundSchemaReference contains a reference to a BoundAPIResourceSchema with status information. -type BoundSchemaReference struct { - GroupResource `json:",inline"` -} - -// APIServiceBindingList is a list of APIServiceBindings. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceBinding `json:"items"` -} - -type LocalSecretKeyRef struct { - // Name of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Name string `json:"name"` - - // The key of the secret to select from. - // - // +required - // +kubebuilder:validation:Required - Key string `json:"key"` -} - -type ClusterSecretKeyRef struct { - LocalSecretKeyRef `json:",inline"` - - // Namespace of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Namespace string `json:"namespace"` -} diff --git a/sdk/apis/kubebind/v1alpha2/apiservicebindingbundle_types.go b/sdk/apis/kubebind/v1alpha2/apiservicebindingbundle_types.go deleted file mode 100644 index c2408003d..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiservicebindingbundle_types.go +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// APIServiceBindingBundle automatically binds multiple API services represented by -// APIServiceExports in a service provider cluster into a consumer cluster. This object lives in consumer clusters, -// and pulls in all API services defined in the provider clusters, based on the kubeconfig secret provided. -// -// +crd -// +genclient -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bindings,shortName=sbb -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Provider",type="string",JSONPath=`.status.providerPrettyName`,priority=0 -// +kubebuilder:printcolumn:name="Resources",type="string",JSONPath=`.metadata.annotations.kube-bind\.io/resources`,priority=1 -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Message",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].message`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceBindingBundle struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - Spec APIServiceBindingBundleSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - Status APIServiceBindingBundleStatus `json:"status"` -} - -func (in *APIServiceBindingBundle) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceBindingBundle) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -type APIServiceBindingBundleSpec struct { - // kubeconfigSecretName is the secret ref that contains the kubeconfig of the service cluster. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" - KubeconfigSecretRef ClusterSecretKeyRef `json:"kubeconfigSecretRef"` -} - -type APIServiceBindingBundleStatus struct { - // conditions is a list of conditions that apply to the APIServiceBindingBundle. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceBindingBundleList is a list of APIServiceBindingBundles. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceBindingBundleList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceBindingBundle `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/apiserviceexport_types.go b/sdk/apis/kubebind/v1alpha2/apiserviceexport_types.go deleted file mode 100644 index b9a6b9ec0..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiserviceexport_types.go +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // SourceSpecHashAnnotationKey is the annotation key used on BoundSchemas and APIServiceExports - // to store a SHA256 hash of the schema spec content. This is used to detect schema drift - // when SchemaUpdatePolicy is Always. - SourceSpecHashAnnotationKey = "kube-bind.io/source-spec-hash" - - // Label is used to indicate which side owns the resource. By changing the label value, - // ownership can be transferred. - ObjectOwnerLabel = "kube-bind.io/owner" -) - -const ( - // APIServiceExportConditionConnected means the APIServiceExport has been connected to a APIServiceBinding. - APIServiceExportConditionConnected conditionsapi.ConditionType = "Connected" - - // APIServiceExportConditionProviderInSync is set to true when the APIServiceExport - // is in-sync with the CRD in the service provider cluster. - APIServiceExportConditionProviderInSync conditionsapi.ConditionType = "ProviderInSync" - - // APIServiceExportConditionConsumerInSync is set to true when the APIServiceExport's - // schema is applied to the consumer cluster. - APIServiceExportConditionConsumerInSync conditionsapi.ConditionType = "ConsumerInSync" - - // APIServiceExportConditionPermissionClaim describes status of the permission claim, requested in the APIServiceExport and APIServiceExportRequest. - APIServiceExportConditionPermissionClaim conditionsapi.ConditionType = "PermissionClaim" -) - -// APIServiceExport specifies the resource to be exported. It is mostly a CRD: -// - the spec is a CRD spec, but without webhooks -// - the status reflects that on the consumer cluster -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Established",type="string",JSONPath=`.status.conditions[?(@.type=="Established")].status`,priority=5 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceExport struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies the resource. - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportSpec `json:"spec"` - - // status contains reconciliation information for the resource. - Status APIServiceExportStatus `json:"status"` -} - -func (in *APIServiceExport) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceExport) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// APIServiceExportResource is a type alias for APIServiceExportRequestResource. -type APIServiceExportResource = APIServiceExportRequestResource - -// APIServiceExportSpec defines the desired state of APIServiceExport. -type APIServiceExportSpec struct { - // resources is a list of resources that should be exported. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="resources are immutable" - Resources []APIServiceExportResource `json:"resources"` - - // PermissionClaims records decisions about permission claims requested by the service provider. - // Access is granted per GroupResource. - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="permissionClaims are immutable" - PermissionClaims []PermissionClaim `json:"permissionClaims,omitempty"` - - // informerScope is the scope of the APIServiceExport. It can be either Cluster or Namespace. - // - // Cluster: The konnector has permission to watch all namespaces at once and cluster-scoped resources. - // This is more efficient than watching each namespace individually. - // Namespaced: The konnector has permission to watch only single namespaces. - // This is more resource intensive. And it means cluster-scoped resources cannot be exported. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="informerScope is immutable" - InformerScope InformerScope `json:"informerScope"` - - // ClusterScopedIsolation specifies how cluster scoped service objects are isolated between multiple consumers on the provider side. - // It can be "Prefixed", "Namespaced", or "None". - // - // Deprecated: ClusterScopedIsolation is deprecated, use Isolation instead. - // - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="clusterScopedIsolation is immutable" - ClusterScopedIsolation Isolation `json:"clusterScopedIsolation,omitempty"` - - // Isolation specifies how service objects are isolated between multiple consumers on the provider side. - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="isolation is immutable" - Isolation Isolation `json:"isolation,omitempty"` -} - -// Isolation is an enum defining the different ways to isolate cluster scoped objects -// -// +kubebuilder:validation:Enum=Prefixed;Namespaced;None -type Isolation string - -const ( - // Prepends the name of the cluster namespace to an object's name. - IsolationPrefixed Isolation = "Prefixed" - - // Maps a consumer side object into a namespaced object inside the corresponding cluster namespace. - IsolationNamespaced Isolation = "Namespaced" - - // Used for the case of a dedicated provider where isolation is not necessary. - IsolationNone Isolation = "None" -) - -// APIServiceExportStatus stores status information about a APIServiceExport. It -// reflects the status of the CRD of the consumer cluster. -type APIServiceExportStatus struct { - // conditions is a list of conditions that apply to the APIServiceExport. It is - // updated by the konnector on the consumer cluster. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceExportList is the objects list that represents the APIServiceExport. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceExport `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/apiserviceexportrequest_types.go b/sdk/apis/kubebind/v1alpha2/apiserviceexportrequest_types.go deleted file mode 100644 index a02abaeb6..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiserviceexportrequest_types.go +++ /dev/null @@ -1,308 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - "fmt" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // APIServiceExportRequestConditionExportsReady is set to true when the - // corresponding APIServiceExport is ready. - APIServiceExportRequestConditionExportsReady conditionsapi.ConditionType = "ExportsReady" -) - -// APIServiceExportRequest is represents a request session of kubectl-bind-apiservice. -// -// The service provider can prune these objects after some time. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceExportRequest struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - // - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportRequestSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - // +kubebuilder:default={} - Status APIServiceExportRequestStatus `json:"status"` -} - -// APIServiceExportRequestResponse is like APIServiceExportRequest but without -// ObjectMeta, to avoid unwanted metadata fields being sent in the response. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportRequestResponse struct { - metav1.TypeMeta `json:",inline"` - ObjectMeta NameObjectMeta `json:"metadata"` - - // spec specifies how an API service from a service provider should be bound in the - // local consumer cluster. - // - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportRequestSpec `json:"spec"` - - // status contains reconciliation information for a service binding. - Status APIServiceExportRequestStatus `json:"status,omitempty"` -} - -type NameObjectMeta struct { - // Name is the name of the object. - Name string `json:"name,omitempty"` -} - -func (in *APIServiceExportRequest) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceExportRequest) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// APIServiceExportRequestSpec is the spec of a APIServiceExportRequest. -type APIServiceExportRequestSpec struct { - // parameters holds service provider specific parameters for this binding - // request. - // - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="parameters are immutable" - Parameters *runtime.RawExtension `json:"parameters,omitempty"` - - // resources is a list of resources that should be exported. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - // +kubebuilder:validation:XListType=map - // +kubebuilder:validation:XListMapKey=resource - // +kubebuilder:validation:XListMapKey=group - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="resources are immutable" - Resources []APIServiceExportRequestResource `json:"resources"` - - // PermissionClaims records decisions about permission claims requested by the service provider. - // Access is granted per GroupResource. - // - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="permissionClaims are immutable" - PermissionClaims []PermissionClaim `json:"permissionClaims,omitempty"` - - // namespaces specifies the namespaces to bootstrap as part of this request. - // When objects originate from provider side, the consumer does not always know the necessary details. - // This field allows provider to pre-heat the necessary namespaces on provider side by creating - // APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="namespaces are immutable" - // +optional - // +kubebuilder:validation:Optional - Namespaces []Namespaces `json:"namespaces,omitempty"` - - // schemaUpdatePolicy defines how BoundSchemas should be updated when the source schema changes. - // This is propagated from the APIServiceExportTemplate. - // Never means schemas are immutable after creation. - // Always means schemas are updated when the source content changes. - // +optional - // +kubebuilder:default="Never" - // +kubebuilder:validation:Enum=Never;Always - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="schemaUpdatePolicy is immutable" - SchemaUpdatePolicy SchemaUpdatePolicy `json:"schemaUpdatePolicy,omitempty"` -} - -type Namespaces struct { - // name is the name of the namespace to create on provider side. - // - // +required - // +kubebuilder:validation:Required - Name string `json:"name"` -} - -type APIServiceExportRequestResource struct { - GroupResource `json:",inline"` - - // versions is a list of versions that should be exported. If this is empty - // a sensible default is chosen by the service provider. - Versions []string `json:"versions,omitempty"` -} - -func (r APIServiceExportRequestResource) ResourceGroupName() string { - if r.Group == "" { - r.Group = "core" - } - return fmt.Sprintf("%s.%s", r.Resource, r.Group) -} - -// Selector is a resource selector that selects objects of a GVR. -// Selectors are ANDed together if multiple are specified. -type Selector struct { - // NamedResource is a shorthand for selecting a single resource by name and namespace. - // +optional - NamedResources []NamedResource `json:"namedResources,omitempty"` - - // LabelSelector is a label selector that selects objects of a GVR. - // +optional - LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"` - - // Reference is a reference to the object that contains jsonPath to select objects of a GVR. - // +optional - References []SelectorReference `json:"references,omitempty"` -} - -// SelectorReference selects objects of a GVR via a reference to another object. -type SelectorReference struct { - GroupResource `json:",inline"` - // versions is a list of versions that should be used to fetch the referenced object. - // If not specified and apiserviceexport contains versions for the same group/resource, - // those versions are used. Otherwise, references is considered invalid. - // +optional - // +kubebuilder:validation:Optional - Versions []string `json:"versions,omitempty"` - // JSONPath is a JSONPath expression that selects the name and namespace of the resource from the referenced object. - // +required - // +kubebuilder:validation:Required - JSONPath *JSONPath `json:"jsonPath,omitempty"` -} - -// JSONPath specifies the JSONPath expression to select name and namespace of a resource. -type JSONPath struct { - Name string `json:"name,omitempty"` - Namespace string `json:"namespace,omitempty"` -} - -// NamedResource selects a specific resource by name and namespace. -type NamedResource struct { - // Name is the name of the resource. - // Name matches the metadata.name field of the underlying object. - // - // +required - // +kubebuilder:validation:Required - Name string `json:"name,omitempty"` - - // Namespace represents namespace where an object of the given group/resource may be managed. - // Namespaces matches against the metadata.namespace field. If not provided, the object is assumed to be cluster-scoped. - // Namespaces field is ignored for namespaced isolation mode. - // - // +optional - Namespace string `json:"namespace,omitempty"` -} - -// GroupResource identifies a resource. -type GroupResource struct { - // group is the name of an API group. - // For core groups this is the empty string '""'. - // - // +kubebuilder:validation:Pattern=`^(|[a-z0-9]([-a-z0-9]*[a-z0-9](\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)?)$` - // +kubebuilder:default="" - Group string `json:"group,omitempty"` - - // resource is the name of the resource. - // Note: it is worth noting that you can not ask for permissions for resource provided by a CRD - // not provided by an service binding export. - // - // +kubebuilder:validation:Pattern=`^[a-z][-a-z0-9]*[a-z0-9]$` - // +required - // +kubebuilder:validation:Required - Resource string `json:"resource"` -} - -func (r GroupResource) String() string { - return fmt.Sprintf("%s.%s", r.Resource, r.Group) -} - -// PermissionClaim selects objects of a GVR that a service provider may -// request and that a consumer may accept and allow the service provider access to. -type PermissionClaim struct { - GroupResource `json:",inline"` - - // Selector is a resource selector that selects objects of a GVR. - // +required - // +kubebuilder:validation:Required - Selector Selector `json:"selector"` -} - -// Owner is the owner of the resource. -type Owner string - -const ( - // OwnerProvider indicates that the resource is owned by the provider. - OwnerProvider Owner = "provider" - // OwnerConsumer indicates that the resource is owned by the consumer. - OwnerConsumer Owner = "consumer" -) - -func (o Owner) String() string { - return string(o) -} - -// APIServiceExportRequestPhase describes the phase of a binding request. -type APIServiceExportRequestPhase string - -const ( - // APIServiceExportRequestPhasePending indicates that the service binding - // is in progress. - APIServiceExportRequestPhasePending APIServiceExportRequestPhase = "Pending" - // APIServiceExportRequestPhaseFailed indicates that the service binding - // has failed. It will not resume. - APIServiceExportRequestPhaseFailed APIServiceExportRequestPhase = "Failed" - // APIServiceExportRequestPhaseSucceeded indicates that the service binding - // has succeeded. The corresponding APIServiceExport have been created and - // are ready. - APIServiceExportRequestPhaseSucceeded APIServiceExportRequestPhase = "Succeeded" -) - -type APIServiceExportRequestStatus struct { - // phase is the current phase of the binding request. It starts in Pending - // and transitions to Succeeded or Failed. See the condition for detailed - // information. - // - // +optional - // +kubebuilder:validation:Optional - // +kubebuilder:default=Pending - // +kubebuilder:validation:Enum=Pending;Failed;Succeeded - Phase APIServiceExportRequestPhase `json:"phase,omitempty"` - - // terminalMessage is a human readable message that describes the reason - // for the current phase. - TerminalMessage string `json:"terminalMessage,omitempty"` - - // conditions is a list of conditions that apply to the ClusterBinding. It is - // updated by the konnector and the service provider. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceExportRequestList is the list of APIServiceExportRequest. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportRequestList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceExportRequest `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/apiserviceexporttemplate_types.go b/sdk/apis/kubebind/v1alpha2/apiserviceexporttemplate_types.go deleted file mode 100644 index 9fca3c2f0..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiserviceexporttemplate_types.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// APIServiceExportTemplate groups multiple CRDs with related resources (permissionClaims) as a Service definition. -// It is used by a web UI or CLI to allow users to select a set of resources to export from provider cluster to consumer cluster. -// This object is considered a static asset on the provider side and is not expected to change frequently. -// -// +crd -// +genclient:nonNamespaced -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bind -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Resources",type="string",JSONPath=`.spec.resources[*].group` -// +kubebuilder:printcolumn:name="PermissionClaims",type="string",JSONPath=`.spec.permissionClaims[*].resource` -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceExportTemplate struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies the template. - // +required - // +kubebuilder:validation:Required - Spec APIServiceExportTemplateSpec `json:"spec"` - - // status contains reconciliation information for the template. - Status APIServiceExportTemplateStatus `json:"status"` -} - -func (in *APIServiceExportTemplate) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *APIServiceExportTemplate) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// APIServiceExportTemplateSpec defines the desired state of APIServiceExportTemplate. -type APIServiceExportTemplateSpec struct { - // description is an optional description of the template. - // - // +optional - Description string `json:"description,omitempty"` - // scope defines the scope of the resources in this template. - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:Enum=Namespaced;Cluster - Scope InformerScope `json:"scope,omitempty"` - // resources defines the CRDs that are part of this template. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - Resources []APIServiceExportResource `json:"resources"` - - // permissionClaims defines the permission claims required by this template. - // - // +optional - PermissionClaims []PermissionClaim `json:"permissionClaims,omitempty"` - - // Namespaces specifies the namespaces that should be bootstrapped as part of this template. - // When objects originate from provider side, consumer does not always know the necessary details - // This field allows provider to pre-heat the necessary namespaces on provider side by creating - // APIServiceNamespace objects attached to the APIServiceExport. More namespaces can be created later by the consumer. - // - // +optional - // +kubebuilder:validation:Optional - Namespaces []Namespaces `json:"namespaces,omitempty"` - - // SchemaUpdatePolicy defines how BoundSchemas should be updated. - // Never means schemas are immutable after creation. - // Always means schemas are updated when the source content changes. - // Default: Never - // - // NOTE: This field is intentionally mutable on the template so that providers - // can change the default for future binding requests. Already-created - // APIServiceExportRequests use CEL validation (self == oldSelf) to lock in - // the policy chosen at binding time. - // - // +optional - // +kubebuilder:default="Never" - // +kubebuilder:validation:Enum=Never;Always - SchemaUpdatePolicy SchemaUpdatePolicy `json:"schemaUpdatePolicy,omitempty"` -} - -// APIServiceExportTemplateStatus stores status information about an APIServiceExportTemplate. -type APIServiceExportTemplateStatus struct { - // conditions is a list of conditions that apply to the APIServiceExportTemplate. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// APIServiceExportTemplateList is the list of APIServiceExportTemplate. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceExportTemplateList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceExportTemplate `json:"items"` -} - -type SchemaUpdatePolicy string - -const ( - // SchemaUpdatePolicyNever means BoundSchemas are immutable after creation (default). - SchemaUpdatePolicyNever SchemaUpdatePolicy = "Never" - // SchemaUpdatePolicyAlways means BoundSchemas are updated when the source schema content changes. - SchemaUpdatePolicyAlways SchemaUpdatePolicy = "Always" -) diff --git a/sdk/apis/kubebind/v1alpha2/apiservicenamespace_types.go b/sdk/apis/kubebind/v1alpha2/apiservicenamespace_types.go deleted file mode 100644 index 215b511a2..000000000 --- a/sdk/apis/kubebind/v1alpha2/apiservicenamespace_types.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -const ( - APIServiceNamespaceAnnotationKey = "kube-bind.io/api-service-namespace" -) - -// APIServiceNamespace defines how consumer namespaces map to service namespaces. -// These objects are created by the konnector, and a service namespace is then -// created by the service provider. -// -// The name of the APIServiceNamespace equals the namespace name in the consumer -// cluster. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Namespace",type="string",JSONPath=`.status.namespace`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type APIServiceNamespace struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies a service namespace. - Spec APIServiceNamespaceSpec `json:"spec"` - - // status contains reconciliation information for a service namespace - Status APIServiceNamespaceStatus `json:"status"` -} - -type APIServiceNamespaceSpec struct { -} - -type APIServiceNamespaceStatus struct { - // namespace is the service provider namespace name that will be bound to the - // consumer namespace named like this object. - Namespace string `json:"namespace,omitempty"` -} - -// APIServiceNamespaceList is the list of ServiceNamespaces. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type APIServiceNamespaceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []APIServiceNamespace `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/bindingprovider_types.go b/sdk/apis/kubebind/v1alpha2/bindingprovider_types.go deleted file mode 100644 index 90ec32ebb..000000000 --- a/sdk/apis/kubebind/v1alpha2/bindingprovider_types.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// BindingProvider is a non-CRUD resource that is returned by the server before -// authentication. It specifies which authentication flows the provider supports. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:storageversion -type BindingProvider struct { - metav1.TypeMeta `json:",inline"` - - // providerPrettyName is the name of the provider that is displayed to the user, e.g: - // MangoDB Inc. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - ProviderPrettyName string `json:"providerPrettyName"` - - // version is the kube-bind.io version of the provider. The kubectl bind will check - // this for compatibility. - // - // +required - // +kubebuilder:validation:Required - Version string `json:"version"` - - // authenticationMethods is a list of authentication methods supported by the - // service provider. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - AuthenticationMethods []AuthenticationMethod `json:"authenticationMethods,omitempty"` -} - -type AuthenticationMethod struct { - // method is the name of the authentication method. The follow methods are supported: - // - // - "OAuth2CodeGrant" - // - // The list is ordered by preference by the service provider. The consumer should - // try to use the first method in the list that matches the capabilities of the - // client environment (e.g. does the client support a web browser) and the - // flags provided by the user. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:Enum=OAuth2CodeGrant - Method string `json:"method,omitempty"` - - // OAuth2CodeGrant is the configuration for the OAuth2 code grant flow. - OAuth2CodeGrant *OAuth2CodeGrant `json:"oauth2CodeGrant,omitempty"` -} - -type OAuth2CodeGrant struct { - // authenticatedURL is the service provider url that the service consumer will use to authenticate against - // the service provider in case of using OIDC mode made, e.g: www.mangodb.com/kubernetes/authorize. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - AuthenticatedURL string `json:"authenticatedURL"` -} diff --git a/sdk/apis/kubebind/v1alpha2/bindingresponse_types.go b/sdk/apis/kubebind/v1alpha2/bindingresponse_types.go deleted file mode 100644 index 2e470ff39..000000000 --- a/sdk/apis/kubebind/v1alpha2/bindingresponse_types.go +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - "errors" - "fmt" - "strings" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/validation" -) - -// BindingResourceResponse is a non-CRUD resource that is returned by the server after -// authentication and resource selection on the service prpvider website. It returns -// a list of requests of possibly different types that kubectl bind has to -// pass to the sub-command kubect-bind-, e.g. kubectl-bind-apiservice for -// APIServiceExportRequest. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:storageversion -type BindingResourceResponse struct { - metav1.TypeMeta `json:",inline"` - - // authentication is data specific to the authentication method that was used. - // - // +optional - // +kubebuilder:validation:Optional - Authentication BindingResponseAuthentication `json:"authentication,omitempty"` - - // kubeconfig is a kubeconfig file that can be used to access the service provider cluster. - // - // +required - // +kubebuilder:validation:Required - Kubeconfig []byte `json:"kubeconfig"` - - // requests is a list of binding requests of different types, e.g. APIServiceExportRequest. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - Requests []runtime.RawExtension `json:"requests"` - - // providerNamespace is the namespace on the service provider cluster where the - // binding resources (APIServiceExport, BoundSchema, etc.) are created and managed. - // This is set when the binding is created via the UI flow. - // - // +optional - // +kubebuilder:validation:Optional - ProviderNamespace string `json:"providerNamespace,omitempty"` - - // bindingName is the confirmed name for this binding, as created on the service - // provider cluster. - // - // +optional - // +kubebuilder:validation:Optional - BindingName string `json:"bindingName,omitempty"` -} - -// BindingResponseAuthentication is the authentication data specific to the -// authentication method that was used. Exactly one field must be set. -type BindingResponseAuthentication struct { - // oauth2CodeGrant is the data returned by the OAuth2 code grant flow. - // - // +optional - // +kubebuilder:validation:Optional - OAuth2CodeGrant *BindingResponseAuthenticationOAuth2CodeGrant `json:"oauth2CodeGrant,omitempty"` -} - -// BindingResponseAuthenticationOAuth2CodeGrant contains the authentication data which is passed back to -// the consumer as BindingResponse.Authentication. It is authentication method -// specific. -type BindingResponseAuthenticationOAuth2CodeGrant struct { - // sessionID is the session ID that was originally passed from the consumer to - // the service provider. It must be checked to equal the original value. - SessionID string `json:"sid"` - - // id is the ID of the authenticated user. It is for informational purposes only. - ID string `json:"id"` -} - -// BindableResourcesRequest is sent by the consumer to the service provider -// to indicate which resources the user wants to bind to. It can be sent via -// the HTTP API after authentication, or created directly as a CRD when the -// backend is running without the HTTP API/OIDC flow (frontend disabled mode). -// -// When created as a CRD, a controller will process the request and create the -// necessary APIServiceExport and related resources. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:subresource:status -// +kubebuilder:storageversion -// +kubebuilder:printcolumn:name="Template",type="string",JSONPath=`.spec.templateRef.name`,priority=0 -// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=`.status.phase`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type BindableResourcesRequest struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies the binding request details. - // - // +required - // +kubebuilder:validation:Required - Spec BindableResourcesRequestSpec `json:"spec"` - - // status contains reconciliation information for the binding request. - // +kubebuilder:default={} - Status BindableResourcesRequestStatus `json:"status,omitempty"` -} - -// BindableResourcesRequestSpec defines the desired state of BindableResourcesRequest. -type BindableResourcesRequestSpec struct { - // TemplateRef specifies the APIServiceExportTemplate to bind to. - // +optional - // +kubebuilder:validation:Optional - TemplateRef APIServiceExportTemplateRef `json:"templateRef"` - - // ClusterIdentity contains information that uniquely identifies the cluster. - // This is used when the request is made via the HTTP API after authentication. - // - // +required - // +kubebuilder:validation:Required - ClusterIdentity ClusterIdentity `json:"clusterIdentity,omitempty"` - - // Author is the identifier of the entity that created this binding request. - // This is used for audit purposes and to track who initiated the binding. - // - // +required - // +kubebuilder:validation:Required - Author string `json:"author"` - - // kubeconfigSecretRef is a reference to an existing secret where the binding response - // will be stored. If specified, the controller will update this secret with the - // binding response data. If not specified, a new secret will be created with - // the name "-binding-response". - // +optional - // +kubebuilder:validation:Optional - KubeconfigSecretRef *LocalSecretKeyRef `json:"kubeconfigSecretRef,omitempty"` - - // ttlAfterFinished is the TTL after the request has succeeded or failed - // before it is automatically deleted. If not set, the request will not be - // automatically deleted. Example values: "1h", "30m", "300s". - // +optional - // +kubebuilder:validation:Optional - TTLAfterFinished *metav1.Duration `json:"ttlAfterFinished,omitempty"` -} - -type APIServiceExportTemplateRef struct { - // name is the name of the APIServiceExportTemplate to bind to. - // - // +required - // +kubebuilder:validation:Required - Name string `json:"name"` -} - -// BindableResourcesRequestPhase describes the phase of a binding request. -type BindableResourcesRequestPhase string - -const ( - // BindableResourcesRequestPhasePending indicates that the binding request is being processed. - BindableResourcesRequestPhasePending BindableResourcesRequestPhase = "Pending" - // BindableResourcesRequestPhaseFailed indicates that the binding request has failed. - BindableResourcesRequestPhaseFailed BindableResourcesRequestPhase = "Failed" - // BindableResourcesRequestPhaseSucceeded indicates that the binding request has succeeded. - BindableResourcesRequestPhaseSucceeded BindableResourcesRequestPhase = "Succeeded" -) - -// BindableResourcesRequestStatus defines the observed state of BindableResourcesRequest. -type BindableResourcesRequestStatus struct { - // phase is the current phase of the binding request. - // - // +optional - // +kubebuilder:validation:Optional - // +kubebuilder:default=Pending - // +kubebuilder:validation:Enum=Pending;Failed;Succeeded - Phase BindableResourcesRequestPhase `json:"phase,omitempty"` - - // namespace is the namespace assigned to this binding request on the service provider cluster. - // This is where the resources for this binding are created and managed. - // - // +optional - // +kubebuilder:validation:Optional - Namespace string `json:"namespace,omitempty"` - - // kubeconfigSecretRef is a reference to a secret containing the kubeconfig, used - // to be used by the konnector agent. - KubeconfigSecretRef *LocalSecretKeyRef `json:"kubeconfigSecretRef,omitempty"` - - // completionTime is the time when the request finished processing (succeeded or failed). - // Used for TTL-based cleanup. - // +optional - // +kubebuilder:validation:Optional - CompletionTime *metav1.Time `json:"completionTime,omitempty"` - - // conditions contains the current conditions of the binding request. - // - // +optional - // +kubebuilder:validation:Optional - Conditions []metav1.Condition `json:"conditions,omitempty"` -} - -// BindableResourcesRequestConditionType defines the condition types for BindableResourcesRequest. -type BindableResourcesRequestConditionType string - -const ( - // BindableResourcesRequestConditionReady indicates that the binding response secret is ready. - BindableResourcesRequestConditionReady BindableResourcesRequestConditionType = "Ready" -) - -// BindableResourcesRequestList is the list of BindableResourcesRequest. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type BindableResourcesRequestList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []BindableResourcesRequest `json:"items"` -} - -func (r *BindableResourcesRequest) Validate() error { - if r.Spec.TemplateRef.Name == "" { - return errors.New("spec.templateRef.name is required") - } - - if r.Name == "" { - return errors.New("name is required") - } - - // Validate DNS name format for the request name - if errs := validation.IsDNS1123Label(r.Name); len(errs) > 0 { - return fmt.Errorf("name %q is not a valid DNS label: %s", r.Name, strings.Join(errs, ", ")) - } - - return nil -} diff --git a/sdk/apis/kubebind/v1alpha2/boundschema_types.go b/sdk/apis/kubebind/v1alpha2/boundschema_types.go deleted file mode 100644 index 68dd3f3ed..000000000 --- a/sdk/apis/kubebind/v1alpha2/boundschema_types.go +++ /dev/null @@ -1,325 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - "encoding/json" - "fmt" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// ExportedSchemas are the schemas exported by the current backend. -// Keys are "resource.group" for quick resolve (version is not part of the key). -type ExportedSchemas map[string]*BoundSchema - -// BoundSchema defines the schema of a bound API resource. It is created on the provider side to track -// CRD status on the consumer side by reflecting the CRD spec and status conditions. -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings,shortName=bs -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" -type BoundSchema struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - Spec BoundSchemaSpec `json:"spec"` - Status BoundSchemaStatus `json:"status"` -} - -// ResourceGroupName returns the group name of the resource. -// -// Important: If you change this, change one for APIServiceExportRequestResource too. -func (b *BoundSchema) ResourceGroupName() string { - return fmt.Sprintf("%s.%s", b.Spec.Names.Plural, b.Spec.Group) -} - -// InformerScope is the scope of the Api. -// -// +kubebuilder:validation:Enum=Cluster;Namespaced -type InformerScope string - -const ( - ClusterScope InformerScope = "Cluster" - NamespacedScope InformerScope = "Namespaced" -) - -// String returns the string representation of the InformerScope. -func (in InformerScope) String() string { - return string(in) -} - -// BoundSchemaSpec defines the desired state of the BoundSchema. -type BoundSchemaSpec struct { - // InformerScope indicates whether the informer for defined custom resource is cluster- or namespace-scoped. - // Allowed values are `Cluster` and `Namespaced`. - // - // +required - // +kubebuilder:validation:Enum=Cluster;Namespaced - InformerScope InformerScope `json:"informerScope"` - - // API CRD Spec is copy paste from apiextensionsv1.CustomResourceDefinitionSpec to allow deep copy - APICRDSpec `json:",inline"` -} - -type APICRDSpec struct { - // group is the API group of the defined custom resource. Empty string means the - // core API group. The resources are served under `/apis//...` or `/api` for the core group. - // - // +required - Group string `json:"group"` - - // names specify the resource and kind names for the custom resource. - // - // +required - Names apiextensionsv1.CustomResourceDefinitionNames `json:"names"` - // scope indicates whether the defined custom resource is cluster- or namespace-scoped. - // Allowed values are `Cluster` and `Namespaced`. - // - // +required - // +kubebuilder:validation:Enum=Cluster;Namespaced - Scope apiextensionsv1.ResourceScope `json:"scope"` - - // versions is the API version of the defined custom resource. - // - // Note: the OpenAPI v3 schemas must be equal for all versions until CEL - // version migration is supported. - // - // +required - // +listType=map - // +listMapKey=name - // +kubebuilder:validation:MinItems=1 - Versions []APIResourceVersion `json:"versions"` - - // conversion defines conversion settings for the defined custom resource. - // +optional - Conversion *CustomResourceConversion `json:"conversion,omitempty"` -} - -// CustomResourceConversion describes how to convert different versions of a CR. -// +kubebuilder:validation:XValidation:message="Webhook must be specified if strategy=Webhook",rule="(self.strategy == 'None' && !has(self.webhook)) || (self.strategy == 'Webhook' && has(self.webhook))" -type CustomResourceConversion struct { - // strategy specifies how custom resources are converted between versions. Allowed values are: - // - `"None"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - // - `"Webhook"`: API Server will call to an external webhook to do the conversion. Additional information - // is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. - // +kubebuilder:validation:Enum=None;Webhook - Strategy ConversionStrategyType `json:"strategy"` - - // webhook describes how to call the conversion webhook. Required when `strategy` is set to `"Webhook"`. - // +optional - Webhook *WebhookConversion `json:"webhook,omitempty"` -} - -// WebhookConversion describes how to call a conversion webhook. -type WebhookConversion struct { - // clientConfig is the instructions for how to call the webhook if strategy is `Webhook`. - // +optional - ClientConfig *WebhookClientConfig `json:"clientConfig,omitempty"` - - // conversionReviewVersions is an ordered list of preferred `ConversionReview` - // versions the Webhook expects. The API server will use the first version in - // the list which it supports. If none of the versions specified in this list - // are supported by API server, conversion will fail for the custom resource. - // If a persisted Webhook configuration specifies allowed versions and does not - // include any versions known to the API Server, calls to the webhook will fail. - // +listType=atomic - ConversionReviewVersions []string `json:"conversionReviewVersions"` -} - -// WebhookClientConfig contains the information to make a TLS connection with the webhook. -type WebhookClientConfig struct { - // url gives the location of the webhook, in standard URL form - // (`scheme://host:port/path`). - // - // Please note that using `localhost` or `127.0.0.1` as a `host` is - // risky unless you take great care to run this webhook on all hosts - // which run an apiserver which might need to make calls to this - // webhook. Such installs are likely to be non-portable, i.e., not easy - // to turn up in a new cluster. - // - // The scheme must be "https"; the URL must begin with "https://". - // - // A path is optional, and if present may be any string permissible in - // a URL. You may use the path to pass an arbitrary string to the - // webhook, for example, a cluster identifier. - // - // Attempting to use a user or basic auth e.g. "user:password@" is not - // allowed. Fragments ("#...") and query parameters ("?...") are not - // allowed, either. - // - // +kubebuilder:validation:Format=uri - URL *string `json:"url,omitempty"` - - // caBundle is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. - // If unspecified, system trust roots on the apiserver are used. - // +optional - CABundle []byte `json:"caBundle,omitempty"` -} - -// ConversionStrategyType describes different conversion types. -type ConversionStrategyType string - -// APIResourceVersion describes one API version of a resource. -type APIResourceVersion struct { - // name is the version name, e.g. “v1”, “v2beta1”, etc. - // The custom resources are served under this version at `/apis///...` if `served` is true. - // - // +required - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:Pattern=^v[1-9][0-9]*([a-z]+[1-9][0-9]*)?$ - Name string `json:"name"` - // served is a flag enabling/disabling this version from being served via REST APIs - // - // +required - // +kubebuilder:default=true - Served bool `json:"served"` - // storage indicates this version should be used when persisting custom resources to storage. - // There must be exactly one version with storage=true. - // - // +required - Storage bool `json:"storage"` - - //nolint:gocritic - // deprecated indicates this version of the custom resource API is deprecated. - // When set to true, API requests to this version receive a warning header in the server response. - // Defaults to false. - // - // +optional - Deprecated bool `json:"deprecated,omitempty"` - // deprecationWarning overrides the default warning returned to API clients. - // May only be set when `deprecated` is true. - // The default warning indicates this version is deprecated and recommends use - // of the newest served version of equal or greater stability, if one exists. - // - // +optional - DeprecationWarning *string `json:"deprecationWarning,omitempty"` - // schema describes the structural schema used for validation, pruning, and defaulting - // of this version of the custom resource. - // - // +required - // +kubebuilder:pruning:PreserveUnknownFields - // +structType=atomic - Schema runtime.RawExtension `json:"schema"` - // subresources specify what subresources this version of the defined custom resource have. - // - // +optional - Subresources apiextensionsv1.CustomResourceSubresources `json:"subresources,omitempty"` - // additionalPrinterColumns specifies additional columns returned in Table output. - // See https://kubernetes.io/docs/reference/using-api/api-concepts/#receiving-resources-as-tables for details. - // If no columns are specified, a single column displaying the age of the custom resource is used. - // - // +optional - // +listType=map - // +listMapKey=name - AdditionalPrinterColumns []apiextensionsv1.CustomResourceColumnDefinition `json:"additionalPrinterColumns,omitempty"` -} - -const ( - // BoundSchemaReady indicates that the API resource schema is ready. - // It is set to true when the API resource schema is accepted and there are no drifts detected. - BoundSchemaValid conditionsapi.ConditionType = "Valid" - // BoundSchemaDriftDetected indicates that there is a drift between the consumer's API and the expected API. - // It is set to true when the API resource schema is not accepted or there are drifts detected. - BoundSchemaInvalid conditionsapi.ConditionType = "Invalid" -) - -// BoundSchemaConditionReason is the set of reasons for specific condition type. -// +kubebuilder:validation:Enum=Accepted;Rejected;Pending;DriftDetected -type BoundSchemaConditionReason string - -const ( - // BoundSchemaAccepted indicates that the API resource schema is accepted. - BoundSchemaAccepted BoundSchemaConditionReason = "Accepted" - // BoundSchemaRejected indicates that the API resource schema is rejected. - BoundSchemaRejected BoundSchemaConditionReason = "Rejected" - // BoundSchemaPending indicates that the API resource schema is pending. - BoundSchemaPending BoundSchemaConditionReason = "Pending" - // BoundSchemaDriftDetected indicates that there is a drift between the consumer's API and the expected API. - BoundSchemaDriftDetected BoundSchemaConditionReason = "DriftDetected" -) - -func (b *BoundSchema) GetConditions() conditionsapi.Conditions { - return b.Status.Conditions -} - -func (b *BoundSchema) SetConditions(conditions conditionsapi.Conditions) { - b.Status.Conditions = conditions -} - -// BoundSchemaStatus defines the observed state of the BoundSchema. -type BoundSchemaStatus struct { - // acceptedNames are the names that are actually being used to serve discovery. - // They may be different than the names in spec. - // +optional - AcceptedNames apiextensionsv1.CustomResourceDefinitionNames `json:"acceptedNames"` - - // storedVersions lists all versions of CustomResources that were ever persisted. Tracking these - // versions allows a migration path for stored versions in etcd. The field is mutable - // so a migration controller can finish a migration to another version (ensuring - // no old objects are left in storage), and then remove the rest of the - // versions from this list. - // Versions may not be removed from `spec.versions` while they exist in this list. - // +optional - StoredVersions []string `json:"storedVersions"` - // Conditions represent the latest available observations of the object's state. - // +optional - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` - - // Instantiations tracks the number of instances of the resource on the consumer side. - // +optional - Instantiations int `json:"instantiations,omitempty"` -} - -// BoundSchemaList is a list of BoundSchemas. -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type BoundSchemaList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []BoundSchema `json:"items"` -} - -func (v *APIResourceVersion) GetSchema() (*apiextensionsv1.JSONSchemaProps, error) { - if v.Schema.Raw == nil { - return nil, nil - } - var schema apiextensionsv1.JSONSchemaProps - if err := json.Unmarshal(v.Schema.Raw, &schema); err != nil { - return nil, err - } - return &schema, nil -} - -func (v *APIResourceVersion) SetSchema(schema *apiextensionsv1.JSONSchemaProps) error { - if schema == nil { - v.Schema.Raw = nil - return nil - } - raw, err := json.Marshal(schema) - if err != nil { - return err - } - v.Schema.Raw = raw - return nil -} diff --git a/sdk/apis/kubebind/v1alpha2/claimable_apis.go b/sdk/apis/kubebind/v1alpha2/claimable_apis.go deleted file mode 100644 index 6e76f37f0..000000000 --- a/sdk/apis/kubebind/v1alpha2/claimable_apis.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - "fmt" - - corev1 "k8s.io/api/core/v1" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// InternalAPI describes an API to be imported from some schemes and generated OpenAPI V2 definitions. -type InternalAPI struct { - Names apiextensionsv1.CustomResourceDefinitionNames - GroupVersionResource schema.GroupVersionResource - Instance runtime.Object - ResourceScope apiextensionsv1.ResourceScope - HasStatus bool -} - -// ClaimableAPIs is a list of APIs that can be claimed by a user. -var ClaimableAPIs = []InternalAPI{ - { - Names: apiextensionsv1.CustomResourceDefinitionNames{ - Plural: "configmaps", - Singular: "configmap", - Kind: "ConfigMap", - }, - GroupVersionResource: schema.GroupVersionResource{ - Group: "", - Version: "v1", - Resource: "configmaps", - }, - Instance: &corev1.ConfigMap{}, - ResourceScope: apiextensionsv1.NamespaceScoped, - }, - { - Names: apiextensionsv1.CustomResourceDefinitionNames{ - Plural: "secrets", - Singular: "secret", - Kind: "Secret", - }, - GroupVersionResource: schema.GroupVersionResource{ - Group: "", - Version: "v1", - Resource: "secrets", - }, - Instance: &corev1.Secret{}, - ResourceScope: apiextensionsv1.NamespaceScoped, - }, - { - Names: apiextensionsv1.CustomResourceDefinitionNames{ - Plural: "serviceaccounts", - Singular: "serviceaccount", - Kind: "ServiceAccount", - }, - GroupVersionResource: schema.GroupVersionResource{ - Group: "", - Version: "v1", - Resource: "serviceaccounts", - }, - Instance: &corev1.ServiceAccount{}, - ResourceScope: apiextensionsv1.NamespaceScoped, - }, -} - -func ResolveClaimableAPI(claim PermissionClaim) (schema.GroupVersionResource, error) { - for _, api := range ClaimableAPIs { - if api.Names.Plural == claim.Resource && api.GroupVersionResource.Group == claim.Group { - return api.GroupVersionResource, nil - } - } - return schema.GroupVersionResource{}, fmt.Errorf("no matching API found") -} diff --git a/sdk/apis/kubebind/v1alpha2/cluster_types.go b/sdk/apis/kubebind/v1alpha2/cluster_types.go deleted file mode 100644 index a8f7b27fd..000000000 --- a/sdk/apis/kubebind/v1alpha2/cluster_types.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // ClusterConditionHealthy is set when the cluster is healthy. - ClusterConditionHealthy = "Healthy" -) - -const ( - // DefaultClusterName is the name of the default cluster. - DefaultClusterName = "default" -) - -// Cluster represents a cluster, managed by kube-bind. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bind -// +kubebuilder:storageversion -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -type Cluster struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec represents the data in the newly created ClusterBinding. - // +required - // +kubebuilder:validation:Required - Spec ClusterSpec `json:"spec"` - - // status contains reconciliation information for the service binding. - Status ClusterStatus `json:"status"` -} - -func (in *Cluster) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *Cluster) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// ClusterSpec represents the data in the newly created Cluster. -type ClusterSpec struct { -} - -// ClusterStatus stores status information about a service binding. It is -// updated by both the konnector and the service provider. -type ClusterStatus struct { - // conditions is a list of conditions that apply to the ClusterBinding. It is - // updated by the konnector and the service provider. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// ClusterIdentity contains information that uniquely identifies the cluster. -type ClusterIdentity struct { - // Identity is the unique identifier of the cluster. - Identity string `json:"identity,omitempty"` - - // PrettyName is a human-readable name for the cluster, used for display - // purposes. If not provided, the controller defaults it to the request name. - // +optional - PrettyName string `json:"prettyName,omitempty"` -} - -// ClusterList is the objects list that represents the Cluster. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type ClusterList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Cluster `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/clusterbinding_types.go b/sdk/apis/kubebind/v1alpha2/clusterbinding_types.go deleted file mode 100644 index 8eb83b99f..000000000 --- a/sdk/apis/kubebind/v1alpha2/clusterbinding_types.go +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -const ( - // ClusterBindingConditionSecretValid is set when the secret is valid. - ClusterBindingConditionSecretValid = "SecretValid" - - // ClusterBindingConditionValidVersion is set when the binary version is valid. - ClusterBindingConditionValidVersion = "ValidVersion" - - // ClusterBindingConditionHealthy is set when the cluster binding is healthy. - ClusterBindingConditionHealthy = "Healthy" -) - -// ClusterBinding represents a bound consumer cluster. It lives in a service -// provider cluster and is a singleton named "cluster" per namespace. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Namespaced,categories=kube-bindings -// +kubebuilder:storageversion -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Konnector Version",type="string",JSONPath=`.status.konnectorVersion`,priority=0 -// +kubebuilder:printcolumn:name="Last Heartbeat",type="date",JSONPath=`.status.lastHeartbeatTime`,priority=0 -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=`.status.conditions[?(@.type=="Ready")].status`,priority=0 -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -// +kubebuilder:validation:XValidation:rule="self.metadata.name == \"cluster\"",message="cluster binding name should be cluster" -type ClusterBinding struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec represents the data in the newly created ClusterBinding. - // +required - // +kubebuilder:validation:Required - Spec ClusterBindingSpec `json:"spec"` - - // status contains reconciliation information for the service binding. - Status ClusterBindingStatus `json:"status"` -} - -func (in *ClusterBinding) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *ClusterBinding) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// ClusterBindingSpec represents the data in the newly created ClusterBinding. -type ClusterBindingSpec struct { - // kubeconfigSecretName is the secret ref that contains the kubeconfig of the service cluster. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="kubeconfigSecretRef is immutable" - KubeconfigSecretRef LocalSecretKeyRef `json:"kubeconfigSecretRef"` - - // providerPrettyName is the pretty name of the service provider cluster. This - // can be shared among different ServiceBindings. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - ProviderPrettyName string `json:"providerPrettyName"` - - // serviceProviderSpec contains all the data and information about the service which has been bound to the service - // binding request. The service providers decide what they need and what to configure based on what then include in - // this field, such as service region, type, tiers, etc... - ServiceProviderSpec runtime.RawExtension `json:"serviceProviderSpec,omitempty"` -} - -// ClusterBindingStatus stores status information about a service binding. It is -// updated by both the konnector and the service provider. -type ClusterBindingStatus struct { - // lastHeartbeatTime is the last time the konnector updated the status. - LastHeartbeatTime metav1.Time `json:"lastHeartbeatTime,omitempty"` - - // heartbeatInterval is the maximal interval between heartbeats that the - // konnector promises to send. The service provider can assume that the - // konnector is not unhealthy if it does not receive a heartbeat within - // this time. - HeartbeatInterval metav1.Duration `json:"heartbeatInterval,omitempty"` - - // konnectorVersion is the version of the konnector that is running on the - // consumer cluster. - KonnectorVersion string `json:"konnectorVersion,omitempty"` - - // consumerSecretRef is the reference to the secret in the consumer cluster - // that contains the kubeconfig for connecting to the service provider. - ConsumerSecretRef *LocalSecretRef `json:"consumerSecretRef,omitempty"` - - // conditions is a list of conditions that apply to the ClusterBinding. It is - // updated by the konnector and the service provider. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// LocalSecretRef is a reference to a secret in a specific namespace. -type LocalSecretRef struct { - // Name of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Name string `json:"name"` - - // Namespace of the referent. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinLength=1 - Namespace string `json:"namespace"` -} - -// ClusterBindingList is the objects list that represents the ClusterBinding. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type ClusterBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []ClusterBinding `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/collection_types.go b/sdk/apis/kubebind/v1alpha2/collection_types.go deleted file mode 100644 index 53a82870b..000000000 --- a/sdk/apis/kubebind/v1alpha2/collection_types.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// Collection groups multiple APIServiceExportTemplates into a logical group. This functions as a grouping mechanism -// in UIs or CLIs to allow users to select a set of resources to export from provider cluster to consumer cluster. -// -// +crd -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +kubebuilder:resource:scope=Cluster,categories=kube-bind -// +kubebuilder:subresource:status -// +kubebuilder:printcolumn:name="Description",type="string",JSONPath=`.spec.description` -// +kubebuilder:printcolumn:name="Templates",type="string",JSONPath=`.spec.templates[*].name` -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=`.metadata.creationTimestamp`,priority=0 -type Collection struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata"` - - // spec specifies the collection. - // +required - // +kubebuilder:validation:Required - Spec CollectionSpec `json:"spec"` - - // status contains reconciliation information for the collection. - Status CollectionStatus `json:"status"` -} - -func (in *Collection) GetConditions() conditionsapi.Conditions { - return in.Status.Conditions -} - -func (in *Collection) SetConditions(conditions conditionsapi.Conditions) { - in.Status.Conditions = conditions -} - -// CollectionSpec defines the desired state of Collection. -type CollectionSpec struct { - // description is a human readable description of this collection. - // - // +optional - Description string `json:"description,omitempty"` - - // templates is a list of template references that are part of this collection. - // - // +required - // +kubebuilder:validation:Required - // +kubebuilder:validation:MinItems=1 - Templates []APIServiceExportTemplateReference `json:"templates"` -} - -// APIServiceExportTemplateReference references an APIServiceExportTemplate by name. -type APIServiceExportTemplateReference struct { - // name is the name of the template. - // - // +required - // +kubebuilder:validation:Required - Name string `json:"name"` -} - -// CollectionStatus stores status information about a Collection. -type CollectionStatus struct { - // conditions is a list of conditions that apply to the Collection. - Conditions conditionsapi.Conditions `json:"conditions,omitempty"` -} - -// CollectionList is the list of Collection. -// -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type CollectionList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []Collection `json:"items"` -} diff --git a/sdk/apis/kubebind/v1alpha2/doc.go b/sdk/apis/kubebind/v1alpha2/doc.go deleted file mode 100644 index 35aca2a27..000000000 --- a/sdk/apis/kubebind/v1alpha2/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 defines the v1alpha2 version of the Kube Bind API -// -// +groupName=kube-bind.io -// +groupGoName=KubeBind -// +k8s:deepcopy-gen=package,register -// +kubebuilder:validation:Optional -package v1alpha2 diff --git a/sdk/apis/kubebind/v1alpha2/error_types.go b/sdk/apis/kubebind/v1alpha2/error_types.go deleted file mode 100644 index 51d498df8..000000000 --- a/sdk/apis/kubebind/v1alpha2/error_types.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// Error represents a structured error response from the kube-bind backend -// +kubebuilder:object:root=true -type Error struct { - metav1.TypeMeta `json:",inline"` - // Message is the human-readable error message - Message string `json:"message"` - // Code is the error code that can be used for programmatic handling - Code string `json:"code"` - // Details provides additional context about the error - // +optional - Details string `json:"details,omitempty"` -} - -// Common error codes -const ( - // ErrorCodeAuthenticationFailed indicates authentication failure - ErrorCodeAuthenticationFailed = "AUTHENTICATION_FAILED" - // ErrorCodeAuthorizationFailed indicates authorization failure - ErrorCodeAuthorizationFailed = "AUTHORIZATION_FAILED" - // ErrorCodeResourceNotFound indicates a requested resource was not found - ErrorCodeResourceNotFound = "RESOURCE_NOT_FOUND" - // ErrorCodeInternalError indicates an internal server error - ErrorCodeInternalError = "INTERNAL_ERROR" - // ErrorCodeBadRequest indicates a malformed request - ErrorCodeBadRequest = "BAD_REQUEST" - // ErrorCodeClusterConnectionFailed indicates failure to connect to cluster - ErrorCodeClusterConnectionFailed = "CLUSTER_CONNECTION_FAILED" -) - -// NewError creates a new Error with the specified code, message and optional details -func NewError(code, message, details string) *Error { - return &Error{ - TypeMeta: metav1.TypeMeta{ - APIVersion: SchemeGroupVersion.String(), - Kind: "Error", - }, - Code: code, - Message: message, - Details: details, - } -} - -// Error implements the error interface -func (e *Error) Error() string { - return e.Message -} diff --git a/sdk/apis/kubebind/v1alpha2/helpers/boundschema.go b/sdk/apis/kubebind/v1alpha2/helpers/boundschema.go deleted file mode 100644 index 7af1be82c..000000000 --- a/sdk/apis/kubebind/v1alpha2/helpers/boundschema.go +++ /dev/null @@ -1,210 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 helpers - -import ( - "crypto/sha256" - "encoding/json" - "fmt" - - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -// CRDToBoundSchema converts a CustomResourceDefinition to an BoundSchema. -func CRDToBoundSchema(crd *apiextensionsv1.CustomResourceDefinition, prefix string) (*kubebindv1alpha2.BoundSchema, error) { - name := crd.Name - if prefix != "" { - name = prefix + "." + crd.Name - } - // Derive informer scope from the CRD scope. - informerScope := kubebindv1alpha2.InformerScope(crd.Spec.Scope) - boundSchema := &kubebindv1alpha2.BoundSchema{ - TypeMeta: metav1.TypeMeta{ - APIVersion: kubebindv1alpha2.SchemeGroupVersion.String(), - Kind: "BoundSchema", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: name, - }, - Spec: kubebindv1alpha2.BoundSchemaSpec{ - InformerScope: informerScope, - APICRDSpec: kubebindv1alpha2.APICRDSpec{ - Group: crd.Spec.Group, - Names: crd.Spec.Names, - Scope: crd.Spec.Scope, - }, - }, - } - - if len(crd.Spec.Versions) == 0 { - return nil, fmt.Errorf("no versions specified for CRD %q", crd.Name) - } - if len(crd.Spec.Versions) > 1 && crd.Spec.Conversion == nil { - return nil, fmt.Errorf("multiple versions specified for CRD %q but no conversion strategy", crd.Name) - } - - if crd.Spec.Conversion != nil { - crConversion := &kubebindv1alpha2.CustomResourceConversion{ - Strategy: kubebindv1alpha2.ConversionStrategyType(crd.Spec.Conversion.Strategy), - } - - if crd.Spec.Conversion.Strategy == "Webhook" { - crConversion.Webhook = &kubebindv1alpha2.WebhookConversion{ - ConversionReviewVersions: crd.Spec.Conversion.Webhook.ConversionReviewVersions, - } - - if crd.Spec.Conversion.Webhook.ClientConfig != nil { - crConversion.Webhook.ClientConfig = &kubebindv1alpha2.WebhookClientConfig{ - URL: crd.Spec.Conversion.Webhook.ClientConfig.URL, - CABundle: crd.Spec.Conversion.Webhook.ClientConfig.CABundle, - } - } - } - - boundSchema.Spec.Conversion = crConversion - } - - for _, crdVersion := range crd.Spec.Versions { - apiResourceVersion := kubebindv1alpha2.APIResourceVersion{ - Name: crdVersion.Name, - Served: crdVersion.Served, - Storage: crdVersion.Storage, - Deprecated: crdVersion.Deprecated, - DeprecationWarning: crdVersion.DeprecationWarning, - AdditionalPrinterColumns: crdVersion.AdditionalPrinterColumns, - } - if crdVersion.Schema != nil && crdVersion.Schema.OpenAPIV3Schema != nil { - rawSchema, err := json.Marshal(crdVersion.Schema.OpenAPIV3Schema) - if err != nil { - return nil, fmt.Errorf("error converting schema for version %q: %w", crdVersion.Name, err) - } - apiResourceVersion.Schema = runtime.RawExtension{Raw: rawSchema} - } - - if crdVersion.Subresources != nil { - apiResourceVersion.Subresources = *crdVersion.Subresources - } - - boundSchema.Spec.Versions = append(boundSchema.Spec.Versions, apiResourceVersion) - } - - return boundSchema, nil -} - -func UnstructuredToBoundSchema(u unstructured.Unstructured) (*kubebindv1alpha2.BoundSchema, error) { - boundSchema := &kubebindv1alpha2.BoundSchema{} - if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.UnstructuredContent(), boundSchema); err != nil { - return nil, err - } - - boundSchema.ObjectMeta = metav1.ObjectMeta{Name: boundSchema.Name} - return boundSchema, nil -} - -func BoundSchemaSpecHash(spec *kubebindv1alpha2.BoundSchemaSpec) (string, error) { - hash := sha256.New() - if err := json.NewEncoder(hash).Encode(spec); err != nil { - return "", fmt.Errorf("failed to encode schema spec: %w", err) - } - return fmt.Sprintf("%x", hash.Sum(nil)), nil -} - -func BoundSchemasSpecHash(schemas []*kubebindv1alpha2.BoundSchema) (string, error) { - hash := sha256.New() - for _, schema := range schemas { - if err := json.NewEncoder(hash).Encode(schema.Spec); err != nil { - return "", fmt.Errorf("failed to encode schema spec %s: %w", schema.Name, err) - } - } - return fmt.Sprintf("%x", hash.Sum(nil)), nil -} - -func BoundSchemaToCRD(schema *kubebindv1alpha2.BoundSchema) *apiextensionsv1.CustomResourceDefinition { - crd := &apiextensionsv1.CustomResourceDefinition{ - TypeMeta: metav1.TypeMeta{ - APIVersion: "apiextensions.k8s.io/v1", - Kind: "CustomResourceDefinition", - }, - ObjectMeta: metav1.ObjectMeta{ - Name: schema.Spec.Names.Plural + "." + schema.Spec.Group, - }, - Spec: apiextensionsv1.CustomResourceDefinitionSpec{ - Group: schema.Spec.Group, - Names: schema.Spec.Names, - Scope: schema.Spec.Scope, - }, - } - - if schema.Spec.Conversion != nil { - crConversion := &apiextensionsv1.CustomResourceConversion{ - Strategy: apiextensionsv1.ConversionStrategyType(schema.Spec.Conversion.Strategy), - } - - if apiextensionsv1.ConversionStrategyType(schema.Spec.Conversion.Strategy) == apiextensionsv1.WebhookConverter && schema.Spec.Conversion.Webhook != nil { - crConversion.Webhook = &apiextensionsv1.WebhookConversion{ - ConversionReviewVersions: schema.Spec.Conversion.Webhook.ConversionReviewVersions, - } - - if schema.Spec.Conversion.Webhook.ClientConfig != nil { - crConversion.Webhook.ClientConfig = &apiextensionsv1.WebhookClientConfig{ - URL: schema.Spec.Conversion.Webhook.ClientConfig.URL, - CABundle: schema.Spec.Conversion.Webhook.ClientConfig.CABundle, - } - } - } - - crd.Spec.Conversion = crConversion - } - - for _, version := range schema.Spec.Versions { - crdVersion := apiextensionsv1.CustomResourceDefinitionVersion{ - Name: version.Name, - Served: version.Served, - Storage: version.Storage, - Deprecated: version.Deprecated, - DeprecationWarning: version.DeprecationWarning, - AdditionalPrinterColumns: version.AdditionalPrinterColumns, - Subresources: &version.Subresources, - } - // Now schema can be openapiv3 or v2. - // we do some poor man checking: - if len(version.Schema.Raw) > 0 { - // Try to unmarshal as CustomResourceValidation first (contains openAPIV3Schema field) - var validation apiextensionsv1.CustomResourceValidation - if err := json.Unmarshal(version.Schema.Raw, &validation); err == nil && validation.OpenAPIV3Schema != nil { - crdVersion.Schema = &validation - } else { - // Fall back to direct JSONSchemaProps - var jsonSchema apiextensionsv1.JSONSchemaProps - if err := json.Unmarshal(version.Schema.Raw, &jsonSchema); err == nil { - crdVersion.Schema = &apiextensionsv1.CustomResourceValidation{ - OpenAPIV3Schema: &jsonSchema, - } - } - } - } - - crd.Spec.Versions = append(crd.Spec.Versions, crdVersion) - } - - return crd -} diff --git a/sdk/apis/kubebind/v1alpha2/helpers/boundschema_test.go b/sdk/apis/kubebind/v1alpha2/helpers/boundschema_test.go deleted file mode 100644 index 7cc203ecb..000000000 --- a/sdk/apis/kubebind/v1alpha2/helpers/boundschema_test.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright 2026 The Kube Bind 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 helpers - -import ( - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" -) - -func TestUnstructuredToBoundSchema_PreservesNameAndStripsMetadata(t *testing.T) { - u := unstructured.Unstructured{} - u.SetName("sheriffs.wildwest.dev") - u.SetManagedFields([]metav1.ManagedFieldsEntry{ - { - Manager: "some-manager", - APIVersion: "apiextensions.k8s.io/v1", - }, - }) - - got, err := UnstructuredToBoundSchema(u) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if got.Name != "sheriffs.wildwest.dev" { - t.Errorf("expected Name %q, got %q", "sheriffs.wildwest.dev", got.Name) - } - - if len(got.ManagedFields) != 0 { - t.Errorf("expected ManagedFields to be empty, got %v", got.ManagedFields) - } -} diff --git a/sdk/apis/kubebind/v1alpha2/helpers/crd.go b/sdk/apis/kubebind/v1alpha2/helpers/crd.go deleted file mode 100644 index f4898c103..000000000 --- a/sdk/apis/kubebind/v1alpha2/helpers/crd.go +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 helpers - -import ( - "strings" - - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - - "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func IsOwnedByBinding(name string, uid types.UID, refs []v1.OwnerReference) bool { - for _, ref := range refs { - parts := strings.SplitN(ref.APIVersion, "/", 2) - if parts[0] != v1alpha2.SchemeGroupVersion.Group || ref.Kind != "APIServiceBinding" { - continue - } - if ref.Name != name { - continue - } - if uid == "" || ref.UID == uid { - return true - } - } - return false -} diff --git a/sdk/apis/kubebind/v1alpha2/helpers/namespaces.go b/sdk/apis/kubebind/v1alpha2/helpers/namespaces.go deleted file mode 100644 index c055d36a2..000000000 --- a/sdk/apis/kubebind/v1alpha2/helpers/namespaces.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 helpers - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func APIServiceNamespaceFromExport(export *kubebindv1alpha2.APIServiceExport, namespaceName string) *kubebindv1alpha2.APIServiceNamespace { - return &kubebindv1alpha2.APIServiceNamespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: namespaceName, - Namespace: export.Namespace, - Labels: map[string]string{ - kubebindv1alpha2.ObjectOwnerLabel: kubebindv1alpha2.OwnerProvider.String(), - }, - OwnerReferences: []metav1.OwnerReference{ - *metav1.NewControllerRef(export, kubebindv1alpha2.SchemeGroupVersion.WithKind("APIServiceExport")), - }, - }, - Spec: kubebindv1alpha2.APIServiceNamespaceSpec{}, - } -} diff --git a/sdk/apis/kubebind/v1alpha2/register.go b/sdk/apis/kubebind/v1alpha2/register.go deleted file mode 100644 index d54c4377a..000000000 --- a/sdk/apis/kubebind/v1alpha2/register.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -const ( - // GroupName is the group name used in this package. - GroupName = "kube-bind.io" - - // GroupVersion is the group version used in this package. - GroupVersion = "v1alpha2" -) - -// SchemeGroupVersion is group version used to register these objects. -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: GroupVersion} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource. -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// Adds the list of known types to api.Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &BoundSchema{}, - &BoundSchemaList{}, - &APIServiceBinding{}, - &APIServiceBindingList{}, - &APIServiceBindingBundle{}, - &APIServiceBindingBundleList{}, - &APIServiceExport{}, - &APIServiceExportList{}, - &APIServiceExportRequest{}, - &APIServiceExportRequestList{}, - &APIServiceNamespace{}, - &APIServiceNamespaceList{}, - &ClusterBinding{}, - &ClusterBindingList{}, - &BindingProvider{}, - &BindingResourceResponse{}, - &APIServiceExportTemplate{}, - &APIServiceExportTemplateList{}, - &Collection{}, - &CollectionList{}, - &Cluster{}, - &ClusterList{}, - &BindableResourcesRequest{}, - &BindableResourcesRequestList{}, - ) - - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/sdk/apis/kubebind/v1alpha2/types.go b/sdk/apis/kubebind/v1alpha2/types.go deleted file mode 100644 index 636765abf..000000000 --- a/sdk/apis/kubebind/v1alpha2/types.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 v1alpha2 - -const ( - // OIDCProviderTypeEmbedded represents an embedded OIDC provider managed by kube-bind. - OIDCProviderTypeEmbedded = "embedded" - // OIDCProviderTypeExternal represents an external OIDC provider managed outside of kube-bind. - OIDCProviderTypeExternal = "external" - - // LabelProviderKubeconfig identifies secrets containing provider kubeconfig. - // Secrets with this label are used by konnector to start heartbeat reporting - // immediately at startup, even without APIServiceBinding resources. - LabelProviderKubeconfig = "kube-bind.io/provider-kubeconfig" -) diff --git a/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go b/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go deleted file mode 100644 index 3f0d391bf..000000000 --- a/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go +++ /dev/null @@ -1,1899 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APICRDSpec) DeepCopyInto(out *APICRDSpec) { - *out = *in - in.Names.DeepCopyInto(&out.Names) - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]APIResourceVersion, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Conversion != nil { - in, out := &in.Conversion, &out.Conversion - *out = new(CustomResourceConversion) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APICRDSpec. -func (in *APICRDSpec) DeepCopy() *APICRDSpec { - if in == nil { - return nil - } - out := new(APICRDSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIResourceVersion) DeepCopyInto(out *APIResourceVersion) { - *out = *in - if in.DeprecationWarning != nil { - in, out := &in.DeprecationWarning, &out.DeprecationWarning - *out = new(string) - **out = **in - } - in.Schema.DeepCopyInto(&out.Schema) - in.Subresources.DeepCopyInto(&out.Subresources) - if in.AdditionalPrinterColumns != nil { - in, out := &in.AdditionalPrinterColumns, &out.AdditionalPrinterColumns - *out = make([]v1.CustomResourceColumnDefinition, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIResourceVersion. -func (in *APIResourceVersion) DeepCopy() *APIResourceVersion { - if in == nil { - return nil - } - out := new(APIResourceVersion) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBinding) DeepCopyInto(out *APIServiceBinding) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBinding. -func (in *APIServiceBinding) DeepCopy() *APIServiceBinding { - if in == nil { - return nil - } - out := new(APIServiceBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBinding) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingBundle) DeepCopyInto(out *APIServiceBindingBundle) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingBundle. -func (in *APIServiceBindingBundle) DeepCopy() *APIServiceBindingBundle { - if in == nil { - return nil - } - out := new(APIServiceBindingBundle) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBindingBundle) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingBundleList) DeepCopyInto(out *APIServiceBindingBundleList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceBindingBundle, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingBundleList. -func (in *APIServiceBindingBundleList) DeepCopy() *APIServiceBindingBundleList { - if in == nil { - return nil - } - out := new(APIServiceBindingBundleList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBindingBundleList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingBundleSpec) DeepCopyInto(out *APIServiceBindingBundleSpec) { - *out = *in - out.KubeconfigSecretRef = in.KubeconfigSecretRef - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingBundleSpec. -func (in *APIServiceBindingBundleSpec) DeepCopy() *APIServiceBindingBundleSpec { - if in == nil { - return nil - } - out := new(APIServiceBindingBundleSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingBundleStatus) DeepCopyInto(out *APIServiceBindingBundleStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingBundleStatus. -func (in *APIServiceBindingBundleStatus) DeepCopy() *APIServiceBindingBundleStatus { - if in == nil { - return nil - } - out := new(APIServiceBindingBundleStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingList) DeepCopyInto(out *APIServiceBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingList. -func (in *APIServiceBindingList) DeepCopy() *APIServiceBindingList { - if in == nil { - return nil - } - out := new(APIServiceBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceBindingList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingSpec) DeepCopyInto(out *APIServiceBindingSpec) { - *out = *in - out.KubeconfigSecretRef = in.KubeconfigSecretRef - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingSpec. -func (in *APIServiceBindingSpec) DeepCopy() *APIServiceBindingSpec { - if in == nil { - return nil - } - out := new(APIServiceBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceBindingStatus) DeepCopyInto(out *APIServiceBindingStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.BoundSchemas != nil { - in, out := &in.BoundSchemas, &out.BoundSchemas - *out = make([]BoundSchemaReference, len(*in)) - copy(*out, *in) - } - if in.PermissionClaims != nil { - in, out := &in.PermissionClaims, &out.PermissionClaims - *out = make([]PermissionClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceBindingStatus. -func (in *APIServiceBindingStatus) DeepCopy() *APIServiceBindingStatus { - if in == nil { - return nil - } - out := new(APIServiceBindingStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExport) DeepCopyInto(out *APIServiceExport) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExport. -func (in *APIServiceExport) DeepCopy() *APIServiceExport { - if in == nil { - return nil - } - out := new(APIServiceExport) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExport) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportList) DeepCopyInto(out *APIServiceExportList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceExport, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportList. -func (in *APIServiceExportList) DeepCopy() *APIServiceExportList { - if in == nil { - return nil - } - out := new(APIServiceExportList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequest) DeepCopyInto(out *APIServiceExportRequest) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequest. -func (in *APIServiceExportRequest) DeepCopy() *APIServiceExportRequest { - if in == nil { - return nil - } - out := new(APIServiceExportRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequest) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestList) DeepCopyInto(out *APIServiceExportRequestList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceExportRequest, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestList. -func (in *APIServiceExportRequestList) DeepCopy() *APIServiceExportRequestList { - if in == nil { - return nil - } - out := new(APIServiceExportRequestList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequestList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestResource) DeepCopyInto(out *APIServiceExportRequestResource) { - *out = *in - out.GroupResource = in.GroupResource - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestResource. -func (in *APIServiceExportRequestResource) DeepCopy() *APIServiceExportRequestResource { - if in == nil { - return nil - } - out := new(APIServiceExportRequestResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestResponse) DeepCopyInto(out *APIServiceExportRequestResponse) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ObjectMeta = in.ObjectMeta - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestResponse. -func (in *APIServiceExportRequestResponse) DeepCopy() *APIServiceExportRequestResponse { - if in == nil { - return nil - } - out := new(APIServiceExportRequestResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportRequestResponse) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestSpec) DeepCopyInto(out *APIServiceExportRequestSpec) { - *out = *in - if in.Parameters != nil { - in, out := &in.Parameters, &out.Parameters - *out = new(runtime.RawExtension) - (*in).DeepCopyInto(*out) - } - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]APIServiceExportRequestResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.PermissionClaims != nil { - in, out := &in.PermissionClaims, &out.PermissionClaims - *out = make([]PermissionClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Namespaces != nil { - in, out := &in.Namespaces, &out.Namespaces - *out = make([]Namespaces, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestSpec. -func (in *APIServiceExportRequestSpec) DeepCopy() *APIServiceExportRequestSpec { - if in == nil { - return nil - } - out := new(APIServiceExportRequestSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportRequestStatus) DeepCopyInto(out *APIServiceExportRequestStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportRequestStatus. -func (in *APIServiceExportRequestStatus) DeepCopy() *APIServiceExportRequestStatus { - if in == nil { - return nil - } - out := new(APIServiceExportRequestStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportSpec) DeepCopyInto(out *APIServiceExportSpec) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]APIServiceExportRequestResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.PermissionClaims != nil { - in, out := &in.PermissionClaims, &out.PermissionClaims - *out = make([]PermissionClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportSpec. -func (in *APIServiceExportSpec) DeepCopy() *APIServiceExportSpec { - if in == nil { - return nil - } - out := new(APIServiceExportSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportStatus) DeepCopyInto(out *APIServiceExportStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportStatus. -func (in *APIServiceExportStatus) DeepCopy() *APIServiceExportStatus { - if in == nil { - return nil - } - out := new(APIServiceExportStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplate) DeepCopyInto(out *APIServiceExportTemplate) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplate. -func (in *APIServiceExportTemplate) DeepCopy() *APIServiceExportTemplate { - if in == nil { - return nil - } - out := new(APIServiceExportTemplate) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportTemplate) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplateList) DeepCopyInto(out *APIServiceExportTemplateList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceExportTemplate, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplateList. -func (in *APIServiceExportTemplateList) DeepCopy() *APIServiceExportTemplateList { - if in == nil { - return nil - } - out := new(APIServiceExportTemplateList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceExportTemplateList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplateRef) DeepCopyInto(out *APIServiceExportTemplateRef) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplateRef. -func (in *APIServiceExportTemplateRef) DeepCopy() *APIServiceExportTemplateRef { - if in == nil { - return nil - } - out := new(APIServiceExportTemplateRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplateReference) DeepCopyInto(out *APIServiceExportTemplateReference) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplateReference. -func (in *APIServiceExportTemplateReference) DeepCopy() *APIServiceExportTemplateReference { - if in == nil { - return nil - } - out := new(APIServiceExportTemplateReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplateSpec) DeepCopyInto(out *APIServiceExportTemplateSpec) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]APIServiceExportRequestResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.PermissionClaims != nil { - in, out := &in.PermissionClaims, &out.PermissionClaims - *out = make([]PermissionClaim, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Namespaces != nil { - in, out := &in.Namespaces, &out.Namespaces - *out = make([]Namespaces, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplateSpec. -func (in *APIServiceExportTemplateSpec) DeepCopy() *APIServiceExportTemplateSpec { - if in == nil { - return nil - } - out := new(APIServiceExportTemplateSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceExportTemplateStatus) DeepCopyInto(out *APIServiceExportTemplateStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceExportTemplateStatus. -func (in *APIServiceExportTemplateStatus) DeepCopy() *APIServiceExportTemplateStatus { - if in == nil { - return nil - } - out := new(APIServiceExportTemplateStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespace) DeepCopyInto(out *APIServiceNamespace) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespace. -func (in *APIServiceNamespace) DeepCopy() *APIServiceNamespace { - if in == nil { - return nil - } - out := new(APIServiceNamespace) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceNamespace) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceList) DeepCopyInto(out *APIServiceNamespaceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]APIServiceNamespace, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceList. -func (in *APIServiceNamespaceList) DeepCopy() *APIServiceNamespaceList { - if in == nil { - return nil - } - out := new(APIServiceNamespaceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *APIServiceNamespaceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceSpec) DeepCopyInto(out *APIServiceNamespaceSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceSpec. -func (in *APIServiceNamespaceSpec) DeepCopy() *APIServiceNamespaceSpec { - if in == nil { - return nil - } - out := new(APIServiceNamespaceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *APIServiceNamespaceStatus) DeepCopyInto(out *APIServiceNamespaceStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIServiceNamespaceStatus. -func (in *APIServiceNamespaceStatus) DeepCopy() *APIServiceNamespaceStatus { - if in == nil { - return nil - } - out := new(APIServiceNamespaceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AuthenticationMethod) DeepCopyInto(out *AuthenticationMethod) { - *out = *in - if in.OAuth2CodeGrant != nil { - in, out := &in.OAuth2CodeGrant, &out.OAuth2CodeGrant - *out = new(OAuth2CodeGrant) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthenticationMethod. -func (in *AuthenticationMethod) DeepCopy() *AuthenticationMethod { - if in == nil { - return nil - } - out := new(AuthenticationMethod) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindableResourcesRequest) DeepCopyInto(out *BindableResourcesRequest) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindableResourcesRequest. -func (in *BindableResourcesRequest) DeepCopy() *BindableResourcesRequest { - if in == nil { - return nil - } - out := new(BindableResourcesRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindableResourcesRequest) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindableResourcesRequestList) DeepCopyInto(out *BindableResourcesRequestList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]BindableResourcesRequest, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindableResourcesRequestList. -func (in *BindableResourcesRequestList) DeepCopy() *BindableResourcesRequestList { - if in == nil { - return nil - } - out := new(BindableResourcesRequestList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindableResourcesRequestList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindableResourcesRequestSpec) DeepCopyInto(out *BindableResourcesRequestSpec) { - *out = *in - out.TemplateRef = in.TemplateRef - out.ClusterIdentity = in.ClusterIdentity - if in.KubeconfigSecretRef != nil { - in, out := &in.KubeconfigSecretRef, &out.KubeconfigSecretRef - *out = new(LocalSecretKeyRef) - **out = **in - } - if in.TTLAfterFinished != nil { - in, out := &in.TTLAfterFinished, &out.TTLAfterFinished - *out = new(metav1.Duration) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindableResourcesRequestSpec. -func (in *BindableResourcesRequestSpec) DeepCopy() *BindableResourcesRequestSpec { - if in == nil { - return nil - } - out := new(BindableResourcesRequestSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindableResourcesRequestStatus) DeepCopyInto(out *BindableResourcesRequestStatus) { - *out = *in - if in.KubeconfigSecretRef != nil { - in, out := &in.KubeconfigSecretRef, &out.KubeconfigSecretRef - *out = new(LocalSecretKeyRef) - **out = **in - } - if in.CompletionTime != nil { - in, out := &in.CompletionTime, &out.CompletionTime - *out = (*in).DeepCopy() - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindableResourcesRequestStatus. -func (in *BindableResourcesRequestStatus) DeepCopy() *BindableResourcesRequestStatus { - if in == nil { - return nil - } - out := new(BindableResourcesRequestStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingProvider) DeepCopyInto(out *BindingProvider) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.AuthenticationMethods != nil { - in, out := &in.AuthenticationMethods, &out.AuthenticationMethods - *out = make([]AuthenticationMethod, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingProvider. -func (in *BindingProvider) DeepCopy() *BindingProvider { - if in == nil { - return nil - } - out := new(BindingProvider) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindingProvider) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResourceResponse) DeepCopyInto(out *BindingResourceResponse) { - *out = *in - out.TypeMeta = in.TypeMeta - in.Authentication.DeepCopyInto(&out.Authentication) - if in.Kubeconfig != nil { - in, out := &in.Kubeconfig, &out.Kubeconfig - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.Requests != nil { - in, out := &in.Requests, &out.Requests - *out = make([]runtime.RawExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResourceResponse. -func (in *BindingResourceResponse) DeepCopy() *BindingResourceResponse { - if in == nil { - return nil - } - out := new(BindingResourceResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BindingResourceResponse) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResponseAuthentication) DeepCopyInto(out *BindingResponseAuthentication) { - *out = *in - if in.OAuth2CodeGrant != nil { - in, out := &in.OAuth2CodeGrant, &out.OAuth2CodeGrant - *out = new(BindingResponseAuthenticationOAuth2CodeGrant) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResponseAuthentication. -func (in *BindingResponseAuthentication) DeepCopy() *BindingResponseAuthentication { - if in == nil { - return nil - } - out := new(BindingResponseAuthentication) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BindingResponseAuthenticationOAuth2CodeGrant) DeepCopyInto(out *BindingResponseAuthenticationOAuth2CodeGrant) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BindingResponseAuthenticationOAuth2CodeGrant. -func (in *BindingResponseAuthenticationOAuth2CodeGrant) DeepCopy() *BindingResponseAuthenticationOAuth2CodeGrant { - if in == nil { - return nil - } - out := new(BindingResponseAuthenticationOAuth2CodeGrant) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BoundSchema) DeepCopyInto(out *BoundSchema) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundSchema. -func (in *BoundSchema) DeepCopy() *BoundSchema { - if in == nil { - return nil - } - out := new(BoundSchema) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BoundSchema) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BoundSchemaList) DeepCopyInto(out *BoundSchemaList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]BoundSchema, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundSchemaList. -func (in *BoundSchemaList) DeepCopy() *BoundSchemaList { - if in == nil { - return nil - } - out := new(BoundSchemaList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *BoundSchemaList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BoundSchemaReference) DeepCopyInto(out *BoundSchemaReference) { - *out = *in - out.GroupResource = in.GroupResource - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundSchemaReference. -func (in *BoundSchemaReference) DeepCopy() *BoundSchemaReference { - if in == nil { - return nil - } - out := new(BoundSchemaReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BoundSchemaSpec) DeepCopyInto(out *BoundSchemaSpec) { - *out = *in - in.APICRDSpec.DeepCopyInto(&out.APICRDSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundSchemaSpec. -func (in *BoundSchemaSpec) DeepCopy() *BoundSchemaSpec { - if in == nil { - return nil - } - out := new(BoundSchemaSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BoundSchemaStatus) DeepCopyInto(out *BoundSchemaStatus) { - *out = *in - in.AcceptedNames.DeepCopyInto(&out.AcceptedNames) - if in.StoredVersions != nil { - in, out := &in.StoredVersions, &out.StoredVersions - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BoundSchemaStatus. -func (in *BoundSchemaStatus) DeepCopy() *BoundSchemaStatus { - if in == nil { - return nil - } - out := new(BoundSchemaStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Cluster) DeepCopyInto(out *Cluster) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cluster. -func (in *Cluster) DeepCopy() *Cluster { - if in == nil { - return nil - } - out := new(Cluster) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Cluster) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBinding) DeepCopyInto(out *ClusterBinding) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBinding. -func (in *ClusterBinding) DeepCopy() *ClusterBinding { - if in == nil { - return nil - } - out := new(ClusterBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBinding) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingList) DeepCopyInto(out *ClusterBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ClusterBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingList. -func (in *ClusterBindingList) DeepCopy() *ClusterBindingList { - if in == nil { - return nil - } - out := new(ClusterBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterBindingList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingSpec) DeepCopyInto(out *ClusterBindingSpec) { - *out = *in - out.KubeconfigSecretRef = in.KubeconfigSecretRef - in.ServiceProviderSpec.DeepCopyInto(&out.ServiceProviderSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingSpec. -func (in *ClusterBindingSpec) DeepCopy() *ClusterBindingSpec { - if in == nil { - return nil - } - out := new(ClusterBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterBindingStatus) DeepCopyInto(out *ClusterBindingStatus) { - *out = *in - in.LastHeartbeatTime.DeepCopyInto(&out.LastHeartbeatTime) - out.HeartbeatInterval = in.HeartbeatInterval - if in.ConsumerSecretRef != nil { - in, out := &in.ConsumerSecretRef, &out.ConsumerSecretRef - *out = new(LocalSecretRef) - **out = **in - } - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterBindingStatus. -func (in *ClusterBindingStatus) DeepCopy() *ClusterBindingStatus { - if in == nil { - return nil - } - out := new(ClusterBindingStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterIdentity) DeepCopyInto(out *ClusterIdentity) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterIdentity. -func (in *ClusterIdentity) DeepCopy() *ClusterIdentity { - if in == nil { - return nil - } - out := new(ClusterIdentity) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterList) DeepCopyInto(out *ClusterList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Cluster, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterList. -func (in *ClusterList) DeepCopy() *ClusterList { - if in == nil { - return nil - } - out := new(ClusterList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ClusterList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterSecretKeyRef) DeepCopyInto(out *ClusterSecretKeyRef) { - *out = *in - out.LocalSecretKeyRef = in.LocalSecretKeyRef - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSecretKeyRef. -func (in *ClusterSecretKeyRef) DeepCopy() *ClusterSecretKeyRef { - if in == nil { - return nil - } - out := new(ClusterSecretKeyRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSpec. -func (in *ClusterSpec) DeepCopy() *ClusterSpec { - if in == nil { - return nil - } - out := new(ClusterSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ClusterStatus) DeepCopyInto(out *ClusterStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterStatus. -func (in *ClusterStatus) DeepCopy() *ClusterStatus { - if in == nil { - return nil - } - out := new(ClusterStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Collection) DeepCopyInto(out *Collection) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Collection. -func (in *Collection) DeepCopy() *Collection { - if in == nil { - return nil - } - out := new(Collection) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Collection) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CollectionList) DeepCopyInto(out *CollectionList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Collection, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CollectionList. -func (in *CollectionList) DeepCopy() *CollectionList { - if in == nil { - return nil - } - out := new(CollectionList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CollectionList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CollectionSpec) DeepCopyInto(out *CollectionSpec) { - *out = *in - if in.Templates != nil { - in, out := &in.Templates, &out.Templates - *out = make([]APIServiceExportTemplateReference, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CollectionSpec. -func (in *CollectionSpec) DeepCopy() *CollectionSpec { - if in == nil { - return nil - } - out := new(CollectionSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CollectionStatus) DeepCopyInto(out *CollectionStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make(v1alpha1.Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CollectionStatus. -func (in *CollectionStatus) DeepCopy() *CollectionStatus { - if in == nil { - return nil - } - out := new(CollectionStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomResourceConversion) DeepCopyInto(out *CustomResourceConversion) { - *out = *in - if in.Webhook != nil { - in, out := &in.Webhook, &out.Webhook - *out = new(WebhookConversion) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomResourceConversion. -func (in *CustomResourceConversion) DeepCopy() *CustomResourceConversion { - if in == nil { - return nil - } - out := new(CustomResourceConversion) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Error) DeepCopyInto(out *Error) { - *out = *in - out.TypeMeta = in.TypeMeta - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Error. -func (in *Error) DeepCopy() *Error { - if in == nil { - return nil - } - out := new(Error) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in ExportedSchemas) DeepCopyInto(out *ExportedSchemas) { - { - in := &in - *out = make(ExportedSchemas, len(*in)) - for key, val := range *in { - var outVal *BoundSchema - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = new(BoundSchema) - (*in).DeepCopyInto(*out) - } - (*out)[key] = outVal - } - return - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExportedSchemas. -func (in ExportedSchemas) DeepCopy() ExportedSchemas { - if in == nil { - return nil - } - out := new(ExportedSchemas) - in.DeepCopyInto(out) - return *out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *GroupResource) DeepCopyInto(out *GroupResource) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GroupResource. -func (in *GroupResource) DeepCopy() *GroupResource { - if in == nil { - return nil - } - out := new(GroupResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *InternalAPI) DeepCopyInto(out *InternalAPI) { - *out = *in - in.Names.DeepCopyInto(&out.Names) - out.GroupVersionResource = in.GroupVersionResource - if in.Instance != nil { - out.Instance = in.Instance.DeepCopyObject() - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InternalAPI. -func (in *InternalAPI) DeepCopy() *InternalAPI { - if in == nil { - return nil - } - out := new(InternalAPI) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *JSONPath) DeepCopyInto(out *JSONPath) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new JSONPath. -func (in *JSONPath) DeepCopy() *JSONPath { - if in == nil { - return nil - } - out := new(JSONPath) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LocalSecretKeyRef) DeepCopyInto(out *LocalSecretKeyRef) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalSecretKeyRef. -func (in *LocalSecretKeyRef) DeepCopy() *LocalSecretKeyRef { - if in == nil { - return nil - } - out := new(LocalSecretKeyRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LocalSecretRef) DeepCopyInto(out *LocalSecretRef) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalSecretRef. -func (in *LocalSecretRef) DeepCopy() *LocalSecretRef { - if in == nil { - return nil - } - out := new(LocalSecretRef) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NameObjectMeta) DeepCopyInto(out *NameObjectMeta) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NameObjectMeta. -func (in *NameObjectMeta) DeepCopy() *NameObjectMeta { - if in == nil { - return nil - } - out := new(NameObjectMeta) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NamedResource) DeepCopyInto(out *NamedResource) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedResource. -func (in *NamedResource) DeepCopy() *NamedResource { - if in == nil { - return nil - } - out := new(NamedResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Namespaces) DeepCopyInto(out *Namespaces) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Namespaces. -func (in *Namespaces) DeepCopy() *Namespaces { - if in == nil { - return nil - } - out := new(Namespaces) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *OAuth2CodeGrant) DeepCopyInto(out *OAuth2CodeGrant) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OAuth2CodeGrant. -func (in *OAuth2CodeGrant) DeepCopy() *OAuth2CodeGrant { - if in == nil { - return nil - } - out := new(OAuth2CodeGrant) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PermissionClaim) DeepCopyInto(out *PermissionClaim) { - *out = *in - out.GroupResource = in.GroupResource - in.Selector.DeepCopyInto(&out.Selector) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PermissionClaim. -func (in *PermissionClaim) DeepCopy() *PermissionClaim { - if in == nil { - return nil - } - out := new(PermissionClaim) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Selector) DeepCopyInto(out *Selector) { - *out = *in - if in.NamedResources != nil { - in, out := &in.NamedResources, &out.NamedResources - *out = make([]NamedResource, len(*in)) - copy(*out, *in) - } - if in.LabelSelector != nil { - in, out := &in.LabelSelector, &out.LabelSelector - *out = new(metav1.LabelSelector) - (*in).DeepCopyInto(*out) - } - if in.References != nil { - in, out := &in.References, &out.References - *out = make([]SelectorReference, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Selector. -func (in *Selector) DeepCopy() *Selector { - if in == nil { - return nil - } - out := new(Selector) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SelectorReference) DeepCopyInto(out *SelectorReference) { - *out = *in - out.GroupResource = in.GroupResource - if in.Versions != nil { - in, out := &in.Versions, &out.Versions - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.JSONPath != nil { - in, out := &in.JSONPath, &out.JSONPath - *out = new(JSONPath) - **out = **in - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SelectorReference. -func (in *SelectorReference) DeepCopy() *SelectorReference { - if in == nil { - return nil - } - out := new(SelectorReference) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *WebhookClientConfig) DeepCopyInto(out *WebhookClientConfig) { - *out = *in - if in.URL != nil { - in, out := &in.URL, &out.URL - *out = new(string) - **out = **in - } - if in.CABundle != nil { - in, out := &in.CABundle, &out.CABundle - *out = make([]byte, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookClientConfig. -func (in *WebhookClientConfig) DeepCopy() *WebhookClientConfig { - if in == nil { - return nil - } - out := new(WebhookClientConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *WebhookConversion) DeepCopyInto(out *WebhookConversion) { - *out = *in - if in.ClientConfig != nil { - in, out := &in.ClientConfig, &out.ClientConfig - *out = new(WebhookClientConfig) - (*in).DeepCopyInto(*out) - } - if in.ConversionReviewVersions != nil { - in, out := &in.ConversionReviewVersions, &out.ConversionReviewVersions - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookConversion. -func (in *WebhookConversion) DeepCopy() *WebhookConversion { - if in == nil { - return nil - } - out := new(WebhookConversion) - in.DeepCopyInto(out) - return out -} diff --git a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/constants.go b/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/constants.go deleted file mode 100644 index a6657cd12..000000000 --- a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/constants.go +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2021 The Kubernetes 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 v1alpha1 - -// ANCHOR: CommonConditions - -// Common ConditionTypes used by objects. -const ( - // ReadyCondition defines the Ready condition type that summarizes the operational state of an object. - ReadyCondition ConditionType = "Ready" -) - -// Common ConditionReason used by objects. -const ( - // DeletingReason (Severity=Info) documents an condition not in Status=True because the underlying object it is currently being deleted. - DeletingReason = "Deleting" - - // DeletionFailedReason (Severity=Warning) documents an condition not in Status=True because the underlying object - // encountered problems during deletion. This is a warning because the reconciler will retry deletion. - DeletionFailedReason = "DeletionFailed" - - // DeletedReason (Severity=Info) documents an condition not in Status=True because the underlying object was deleted. - DeletedReason = "Deleted" - - // IncorrectExternalRefReason (Severity=Error) documents an object with an incorrect external object reference. - IncorrectExternalRefReason = "IncorrectExternalRef" -) - -const ( - // InfrastructureReadyCondition reports a summary of current status of the infrastructure object defined for this cluster/machine/machinepool. - // This condition is mirrored from the Ready condition in the infrastructure ref object, and - // the absence of this condition might signal problems in the reconcile external loops or the fact that - // the infrastructure provider does not implement the Ready condition yet. - InfrastructureReadyCondition ConditionType = "InfrastructureReady" - - // WaitingForInfrastructureFallbackReason (Severity=Info) documents a cluster/machine/machinepool waiting for the underlying infrastructure - // to be available. - // NOTE: This reason is used only as a fallback when the infrastructure object is not reporting its own ready condition. - WaitingForInfrastructureFallbackReason = "WaitingForInfrastructure" -) - -// ANCHOR_END: CommonConditions - -// Conditions and condition Reasons for the Cluster object. - -const ( - // ControlPlaneInitializedCondition reports if the cluster's control plane has been initialized such that the - // cluster's apiserver is reachable and at least one control plane Machine has a node reference. Once this - // condition is marked true, its value is never changed. See the ControlPlaneReady condition for an indication of - // the current readiness of the cluster's control plane. - ControlPlaneInitializedCondition ConditionType = "ControlPlaneInitialized" - - // MissingNodeRefReason (Severity=Info) documents a cluster waiting for at least one control plane Machine to have - // its node reference populated. - MissingNodeRefReason = "MissingNodeRef" - - // WaitingForControlPlaneProviderInitializedReason (Severity=Info) documents a cluster waiting for the control plane - // provider to report successful control plane initialization. - WaitingForControlPlaneProviderInitializedReason = "WaitingForControlPlaneProviderInitialized" - - // ControlPlaneReadyCondition reports the ready condition from the control plane object defined for this cluster. - // This condition is mirrored from the Ready condition in the control plane ref object, and - // the absence of this condition might signal problems in the reconcile external loops or the fact that - // the control plane provider does not implements the Ready condition yet. - ControlPlaneReadyCondition ConditionType = "ControlPlaneReady" - - // WaitingForControlPlaneFallbackReason (Severity=Info) documents a cluster waiting for the control plane - // to be available. - // NOTE: This reason is used only as a fallback when the control plane object is not reporting its own ready condition. - WaitingForControlPlaneFallbackReason = "WaitingForControlPlane" - - // WaitingForControlPlaneAvailableReason (Severity=Info) documents an object - // waiting for the control plane machine to be available. - // - // NOTE: Having the control plane machine available is a pre-condition for joining additional control planes - // or workers nodes. - WaitingForControlPlaneAvailableReason = "WaitingForControlPlaneAvailable" -) - -// Conditions and condition Reasons for the Machine object. - -const ( - // BootstrapReadyCondition reports a summary of current status of the bootstrap object defined for this machine. - // This condition is mirrored from the Ready condition in the bootstrap ref object, and - // the absence of this condition might signal problems in the reconcile external loops or the fact that - // the bootstrap provider does not implement the Ready condition yet. - BootstrapReadyCondition ConditionType = "BootstrapReady" - - // WaitingForDataSecretFallbackReason (Severity=Info) documents a machine waiting for the bootstrap data secret - // to be available. - // NOTE: This reason is used only as a fallback when the bootstrap object is not reporting its own ready condition. - WaitingForDataSecretFallbackReason = "WaitingForDataSecret" - - // DrainingSucceededCondition provide evidence of the status of the node drain operation which happens during the machine - // deletion process. - DrainingSucceededCondition ConditionType = "DrainingSucceeded" - - // DrainingReason (Severity=Info) documents a machine node being drained. - DrainingReason = "Draining" - - // DrainingFailedReason (Severity=Warning) documents a machine node drain operation failed. - DrainingFailedReason = "DrainingFailed" - - // PreDrainDeleteHookSucceededCondition reports a machine waiting for a PreDrainDeleteHook before being delete. - PreDrainDeleteHookSucceededCondition ConditionType = "PreDrainDeleteHookSucceeded" - - // PreTerminateDeleteHookSucceededCondition reports a machine waiting for a PreDrainDeleteHook before being delete. - PreTerminateDeleteHookSucceededCondition ConditionType = "PreTerminateDeleteHookSucceeded" - - // WaitingExternalHookReason (Severity=Info) provide evidence that we are waiting for an external hook to complete. - WaitingExternalHookReason = "WaitingExternalHook" - - // VolumeDetachSucceededCondition reports a machine waiting for volumes to be detached. - VolumeDetachSucceededCondition ConditionType = "VolumeDetachSucceeded" - - // WaitingForVolumeDetachReason (Severity=Info) provide evidence that a machine node waiting for volumes to be attached. - WaitingForVolumeDetachReason = "WaitingForVolumeDetach" -) - -const ( - // MachineHealthCheckSuccededCondition is set on machines that have passed a healthcheck by the MachineHealthCheck controller. - // In the event that the health check fails it will be set to False. - MachineHealthCheckSuccededCondition ConditionType = "HealthCheckSucceeded" - - // MachineHasFailureReason is the reason used when a machine has either a FailureReason or a FailureMessage set on its status. - MachineHasFailureReason = "MachineHasFailure" - - // NodeStartupTimeoutReason is the reason used when a machine's node does not appear within the specified timeout. - NodeStartupTimeoutReason = "NodeStartupTimeout" - - // UnhealthyNodeConditionReason is the reason used when a machine's node has one of the MachineHealthCheck's unhealthy conditions. - UnhealthyNodeConditionReason = "UnhealthyNode" -) - -const ( - // MachineOwnerRemediatedCondition is set on machines that have failed a healthcheck by the MachineHealthCheck controller. - // MachineOwnerRemediatedCondition is set to False after a health check fails, but should be changed to True by the owning controller after remediation succeeds. - MachineOwnerRemediatedCondition ConditionType = "OwnerRemediated" - - // WaitingForRemediationReason is the reason used when a machine fails a health check and remediation is needed. - WaitingForRemediationReason = "WaitingForRemediation" - - // RemediationFailedReason is the reason used when a remediation owner fails to remediate an unhealthy machine. - RemediationFailedReason = "RemediationFailed" - - // RemediationInProgressReason is the reason used when an unhealthy machine is being remediated by the remediation owner. - RemediationInProgressReason = "RemediationInProgress" - - // ExternalRemediationTemplateAvailable is set on machinehealthchecks when MachineHealthCheck controller uses external remediation. - // ExternalRemediationTemplateAvailable is set to false if external remediation template is not found. - ExternalRemediationTemplateAvailable ConditionType = "ExternalRemediationTemplateAvailable" - - // ExternalRemediationTemplateNotFound is the reason used when a machine health check fails to find external remediation template. - ExternalRemediationTemplateNotFound = "ExternalRemediationTemplateNotFound" - - // ExternalRemediationRequestAvailable is set on machinehealthchecks when MachineHealthCheck controller uses external remediation. - // ExternalRemediationRequestAvailable is set to false if creating external remediation request fails. - ExternalRemediationRequestAvailable ConditionType = "ExternalRemediationRequestAvailable" - - // ExternalRemediationRequestCreationFailed is the reason used when a machine health check fails to create external remediation request. - ExternalRemediationRequestCreationFailed = "ExternalRemediationRequestCreationFailed" -) - -// Conditions and condition Reasons for the Machine's Node object. -const ( - // MachineNodeHealthyCondition provides info about the operational state of the Kubernetes node hosted on the machine by summarizing node conditions. - // If the conditions defined in a Kubernetes node (i.e., NodeReady, NodeMemoryPressure, NodeDiskPressure, NodePIDPressure, and NodeNetworkUnavailable) are in a healthy state, it will be set to True. - MachineNodeHealthyCondition ConditionType = "NodeHealthy" - - // WaitingForNodeRefReason (Severity=Info) documents a machine.spec.providerId is not assigned yet. - WaitingForNodeRefReason = "WaitingForNodeRef" - - // NodeProvisioningReason (Severity=Info) documents machine in the process of provisioning a node. - // NB. provisioning --> NodeRef == "". - NodeProvisioningReason = "NodeProvisioning" - - // NodeNotFoundReason (Severity=Error) documents a machine's node has previously been observed but is now gone. - // NB. provisioned --> NodeRef != "". - NodeNotFoundReason = "NodeNotFound" - - // NodeConditionsFailedReason (Severity=Warning) documents a node is not in a healthy state due to the failed state of at least 1 Kubelet condition. - NodeConditionsFailedReason = "NodeConditionsFailed" -) - -// Conditions and condition Reasons for the MachineHealthCheck object. - -const ( - // RemediationAllowedCondition is set on MachineHealthChecks to show the status of whether the MachineHealthCheck is - // allowed to remediate any Machines or whether it is blocked from remediating any further. - RemediationAllowedCondition ConditionType = "RemediationAllowed" - - // TooManyUnhealthyReason is the reason used when too many Machines are unhealthy and the MachineHealthCheck is blocked - // from making any further remediations. - TooManyUnhealthyReason = "TooManyUnhealthy" -) - -// Conditions and condition Reasons for MachineDeployments. - -const ( - // MachineDeploymentAvailableCondition means the MachineDeployment is available, that is, at least the minimum available - // machines required (i.e. Spec.Replicas-MaxUnavailable when MachineDeploymentStrategyType = RollingUpdate) are up and running for at least minReadySeconds. - MachineDeploymentAvailableCondition ConditionType = "Available" - - // WaitingForAvailableMachinesReason (Severity=Warning) reflects the fact that the required minimum number of machines for a machinedeployment are not available. - WaitingForAvailableMachinesReason = "WaitingForAvailableMachines" -) - -// Conditions and condition Reasons for MachineSets. - -const ( - // MachinesCreatedCondition documents that the machines controlled by the MachineSet are created. - // When this condition is false, it indicates that there was an error when cloning the infrastructure/bootstrap template or - // when generating the machine object. - MachinesCreatedCondition ConditionType = "MachinesCreated" - - // MachinesReadyCondition reports an aggregate of current status of the machines controlled by the MachineSet. - MachinesReadyCondition ConditionType = "MachinesReady" - - // BootstrapTemplateCloningFailedReason (Severity=Error) documents a MachineSet failing to - // clone the bootstrap template. - BootstrapTemplateCloningFailedReason = "BootstrapTemplateCloningFailed" - - // InfrastructureTemplateCloningFailedReason (Severity=Error) documents a MachineSet failing to - // clone the infrastructure template. - InfrastructureTemplateCloningFailedReason = "InfrastructureTemplateCloningFailed" - - // MachineCreationFailedReason (Severity=Error) documents a MachineSet failing to - // generate a machine object. - MachineCreationFailedReason = "MachineCreationFailed" - - // ResizedCondition documents a MachineSet is resizing the set of controlled machines. - ResizedCondition ConditionType = "Resized" - - // ScalingUpReason (Severity=Info) documents a MachineSet is increasing the number of replicas. - ScalingUpReason = "ScalingUp" - - // ScalingDownReason (Severity=Info) documents a MachineSet is decreasing the number of replicas. - ScalingDownReason = "ScalingDown" -) diff --git a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/doc.go b/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/doc.go deleted file mode 100644 index 90b26c6bc..000000000 --- a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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. -*/ - -// +k8s:openapi-gen=true -// +k8s:deepcopy-gen=package,register -package v1alpha1 diff --git a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/types.go b/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/types.go deleted file mode 100644 index 910178d26..000000000 --- a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/types.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2021 The Kubernetes 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 v1alpha1 - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// ANCHOR: ConditionSeverity - -// ConditionSeverity expresses the severity of a Condition Type failing. -type ConditionSeverity string - -const ( - // ConditionSeverityError specifies that a condition with `Status=False` is an error. - ConditionSeverityError ConditionSeverity = "Error" - - // ConditionSeverityWarning specifies that a condition with `Status=False` is a warning. - ConditionSeverityWarning ConditionSeverity = "Warning" - - // ConditionSeverityInfo specifies that a condition with `Status=False` is informative. - ConditionSeverityInfo ConditionSeverity = "Info" - - // ConditionSeverityNone should apply only to conditions with `Status=True`. - ConditionSeverityNone ConditionSeverity = "" -) - -// ANCHOR_END: ConditionSeverity - -// ANCHOR: ConditionType - -// ConditionType is a valid value for Condition.Type. -type ConditionType string - -// ANCHOR_END: ConditionType - -// ANCHOR: Condition - -// Condition defines an observation of a object operational state. -type Condition struct { - // Type of condition in CamelCase or in foo.example.com/CamelCase. - // Many .condition.type values are consistent across resources like Available, but because arbitrary conditions - // can be useful (see .node.status.conditions), the ability to deconflict is important. - Type ConditionType `json:"type"` - - // Status of the condition, one of True, False, Unknown. - Status corev1.ConditionStatus `json:"status"` - - // Severity provides an explicit classification of Reason code, so the users or machines can immediately - // understand the current situation and act accordingly. - // The Severity field MUST be set only when Status=False. - // +optional - Severity ConditionSeverity `json:"severity,omitempty"` - - // Last time the condition transitioned from one status to another. - // This should be when the underlying condition changed. If that is not known, then using the time when - // the API field changed is acceptable. - LastTransitionTime metav1.Time `json:"lastTransitionTime"` - - // The reason for the condition's last transition in CamelCase. - // The specific API may choose whether or not this field is considered a guaranteed API. - // This field may not be empty. - // +optional - Reason string `json:"reason,omitempty"` - - // A human readable message indicating details about the transition. - // This field may be empty. - // +optional - Message string `json:"message,omitempty"` -} - -// ANCHOR_END: Condition - -// ANCHOR: Conditions - -// Conditions provide observations of the operational state of a object. -type Conditions []Condition - -// ANCHOR_END: Conditions diff --git a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/zz_generated.deepcopy.go b/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 7bb4b719d..000000000 --- a/sdk/apis/third_party/conditions/apis/conditions/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,61 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Condition) DeepCopyInto(out *Condition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition. -func (in *Condition) DeepCopy() *Condition { - if in == nil { - return nil - } - out := new(Condition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in Conditions) DeepCopyInto(out *Conditions) { - { - in := &in - *out = make(Conditions, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - return - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Conditions. -func (in Conditions) DeepCopy() Conditions { - if in == nil { - return nil - } - out := new(Conditions) - in.DeepCopyInto(out) - return *out -} diff --git a/sdk/apis/third_party/conditions/util/conditions/doc.go b/sdk/apis/third_party/conditions/util/conditions/doc.go deleted file mode 100644 index 019d42d7c..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions implements condition utilities. -package conditions diff --git a/sdk/apis/third_party/conditions/util/conditions/getter.go b/sdk/apis/third_party/conditions/util/conditions/getter.go deleted file mode 100644 index c869c1293..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/getter.go +++ /dev/null @@ -1,260 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// Getter interface defines methods that an object should implement in order to -// use the conditions package for getting conditions. -type Getter interface { - metav1.Object - runtime.Object - - // GetConditions returns the list of conditions for an object. - GetConditions() conditionsapi.Conditions -} - -// Get returns the condition with the given type, if the condition does not exists, -// it returns nil. -func Get(from Getter, t conditionsapi.ConditionType) *conditionsapi.Condition { - conditions := from.GetConditions() - if conditions == nil { - return nil - } - - for _, condition := range conditions { - if condition.Type == t { - return &condition - } - } - return nil -} - -// Has returns true if a condition with the given type exists. -func Has(from Getter, t conditionsapi.ConditionType) bool { - return Get(from, t) != nil -} - -// IsTrue is true if the condition with the given type is True, otherwise it return false -// if the condition is not True or if the condition does not exist (is nil). -func IsTrue(from Getter, t conditionsapi.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionTrue - } - return false -} - -// IsFalse is true if the condition with the given type is False, otherwise it return false -// if the condition is not False or if the condition does not exist (is nil). -func IsFalse(from Getter, t conditionsapi.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionFalse - } - return false -} - -// IsUnknown is true if the condition with the given type is Unknown or if the condition -// does not exist (is nil). -func IsUnknown(from Getter, t conditionsapi.ConditionType) bool { - if c := Get(from, t); c != nil { - return c.Status == corev1.ConditionUnknown - } - return true -} - -// GetReason returns a nil safe string of Reason for the condition with the given type. -func GetReason(from Getter, t conditionsapi.ConditionType) string { - if c := Get(from, t); c != nil { - return c.Reason - } - return "" -} - -// GetMessage returns a nil safe string of Message. -func GetMessage(from Getter, t conditionsapi.ConditionType) string { - if c := Get(from, t); c != nil { - return c.Message - } - return "" -} - -// GetSeverity returns the condition Severity or nil if the condition -// does not exist (is nil). -func GetSeverity(from Getter, t conditionsapi.ConditionType) *conditionsapi.ConditionSeverity { - if c := Get(from, t); c != nil { - return &c.Severity - } - return nil -} - -// GetLastTransitionTime returns the condition Severity or nil if the condition -// does not exist (is nil). -func GetLastTransitionTime(from Getter, t conditionsapi.ConditionType) *metav1.Time { - if c := Get(from, t); c != nil { - return &c.LastTransitionTime - } - return nil -} - -// summary returns a Ready condition with the summary of all the conditions existing -// on an object. If the object does not have other conditions, no summary condition is generated. -func summary(from Getter, options ...MergeOption) *conditionsapi.Condition { - conditions := from.GetConditions() - - mergeOpt := &mergeOptions{} - for _, o := range options { - o(mergeOpt) - } - - // Identifies the conditions in scope for the Summary by taking all the existing conditions except Ready, - // or, if a list of conditions types is specified, only the conditions the condition in that list. - conditionsInScope := make([]localizedCondition, 0, len(conditions)) - for i := range conditions { - c := conditions[i] - if c.Type == conditionsapi.ReadyCondition { - continue - } - - if mergeOpt.conditionTypes != nil { - found := false - for _, t := range mergeOpt.conditionTypes { - if c.Type == t { - found = true - break - } - } - if !found { - continue - } - } - - conditionsInScope = append(conditionsInScope, localizedCondition{ - Condition: &c, - Getter: from, - }) - } - - // If it is required to add a step counter only if a subset of condition exists, check if the conditions - // in scope are included in this subset or not. - if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { - for _, c := range conditionsInScope { - found := false - for _, t := range mergeOpt.addStepCounterIfOnlyConditionTypes { - if c.Type == t { - found = true - break - } - } - if !found { - mergeOpt.addStepCounter = false - break - } - } - } - - // If it is required to add a step counter, determine the total number of conditions defaulting - // to the selected conditions or, if defined, to the total number of conditions type to be considered. - if mergeOpt.addStepCounter { - mergeOpt.stepCounter = len(conditionsInScope) - if mergeOpt.conditionTypes != nil { - mergeOpt.stepCounter = len(mergeOpt.conditionTypes) - } - if mergeOpt.addStepCounterIfOnlyConditionTypes != nil { - mergeOpt.stepCounter = len(mergeOpt.addStepCounterIfOnlyConditionTypes) - } - } - - return merge(conditionsInScope, conditionsapi.ReadyCondition, mergeOpt) -} - -// mirrorOptions allows to set options for the mirror operation. -type mirrorOptions struct { - fallbackTo *bool - fallbackReason string - fallbackSeverity conditionsapi.ConditionSeverity - fallbackMessage string -} - -// MirrorOptions defines an option for mirroring conditions. -type MirrorOptions func(*mirrorOptions) - -// WithFallbackValue specify a fallback value to use in case the mirrored condition does not exists; -// in case the fallbackValue is false, given values for reason, severity and message will be used. -func WithFallbackValue(fallbackValue bool, reason string, severity conditionsapi.ConditionSeverity, message string) MirrorOptions { - return func(c *mirrorOptions) { - c.fallbackTo = &fallbackValue - c.fallbackReason = reason - c.fallbackSeverity = severity - c.fallbackMessage = message - } -} - -// mirror mirrors the Ready condition from a dependent object into the target condition; -// if the Ready condition does not exists in the source object, no target conditions is generated. -func mirror(from Getter, targetCondition conditionsapi.ConditionType, options ...MirrorOptions) *conditionsapi.Condition { - mirrorOpt := &mirrorOptions{} - for _, o := range options { - o(mirrorOpt) - } - - condition := Get(from, conditionsapi.ReadyCondition) - - if mirrorOpt.fallbackTo != nil && condition == nil { - switch *mirrorOpt.fallbackTo { - case true: - condition = TrueCondition(targetCondition) - case false: - condition = FalseCondition(targetCondition, mirrorOpt.fallbackReason, mirrorOpt.fallbackSeverity, "%s", mirrorOpt.fallbackMessage) - } - } - - if condition != nil { - condition.Type = targetCondition - } - - return condition -} - -// Aggregates all the Ready condition from a list of dependent objects into the target object; -// if the Ready condition does not exists in one of the source object, the object is excluded from -// the aggregation; if none of the source object have ready condition, no target conditions is generated. -func aggregate(from []Getter, targetCondition conditionsapi.ConditionType, options ...MergeOption) *conditionsapi.Condition { - conditionsInScope := make([]localizedCondition, 0, len(from)) - for i := range from { - condition := Get(from[i], conditionsapi.ReadyCondition) - - conditionsInScope = append(conditionsInScope, localizedCondition{ - Condition: condition, - Getter: from[i], - }) - } - - mergeOpt := &mergeOptions{ - addStepCounter: true, - stepCounter: len(from), - } - for _, o := range options { - o(mergeOpt) - } - return merge(conditionsInScope, targetCondition, mergeOpt) -} diff --git a/sdk/apis/third_party/conditions/util/conditions/getter_test.go b/sdk/apis/third_party/conditions/util/conditions/getter_test.go deleted file mode 100644 index 167cf2f6f..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/getter_test.go +++ /dev/null @@ -1,329 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "testing" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -var ( - nil1 *conditionsapi.Condition - true1 = TrueCondition("true1") - unknown1 = UnknownCondition("unknown1", "reason unknown1", "message unknown1") - falseInfo1 = FalseCondition("falseInfo1", "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1") - falseWarning1 = FalseCondition("falseWarning1", "reason falseWarning1", conditionsapi.ConditionSeverityWarning, "message falseWarning1") - falseError1 = FalseCondition("falseError1", "reason falseError1", conditionsapi.ConditionSeverityError, "message falseError1") -) - -func newConditioned(name string) *conditioned { - return &conditioned{ - Unstructured: &unstructured.Unstructured{ - Object: map[string]any{ - "kind": "Foo", - "metadata": map[string]any{ - "name": name, - }, - }, - }, - } -} - -type conditioned struct { - *unstructured.Unstructured - conditions conditionsapi.Conditions -} - -func (c *conditioned) SetConditions(conditions conditionsapi.Conditions) { - c.conditions = conditions -} - -func (c *conditioned) GetConditions() conditionsapi.Conditions { - return c.conditions -} - -var _ Getter = &conditioned{} -var _ Setter = &conditioned{} - -func TestGetAndHas(t *testing.T) { - g := NewWithT(t) - - cluster := newConditioned("test") - - g.Expect(Has(cluster, "conditionBaz")).To(BeFalse()) - g.Expect(Get(cluster, "conditionBaz")).To(BeNil()) - - cluster.SetConditions(conditionList(TrueCondition("conditionBaz"))) - - g.Expect(Has(cluster, "conditionBaz")).To(BeTrue()) - g.Expect(Get(cluster, "conditionBaz")).To(HaveSameStateOf(TrueCondition("conditionBaz"))) -} - -func TestIsMethods(t *testing.T) { - g := NewWithT(t) - - obj := getterWithConditions(nil1, true1, unknown1, falseInfo1, falseWarning1, falseError1) - - // test isTrue - g.Expect(IsTrue(obj, "nil1")).To(BeFalse()) - g.Expect(IsTrue(obj, "true1")).To(BeTrue()) - g.Expect(IsTrue(obj, "falseInfo1")).To(BeFalse()) - g.Expect(IsTrue(obj, "unknown1")).To(BeFalse()) - - // test isFalse - g.Expect(IsFalse(obj, "nil1")).To(BeFalse()) - g.Expect(IsFalse(obj, "true1")).To(BeFalse()) - g.Expect(IsFalse(obj, "falseInfo1")).To(BeTrue()) - g.Expect(IsFalse(obj, "unknown1")).To(BeFalse()) - - // test isUnknown - g.Expect(IsUnknown(obj, "nil1")).To(BeTrue()) - g.Expect(IsUnknown(obj, "true1")).To(BeFalse()) - g.Expect(IsUnknown(obj, "falseInfo1")).To(BeFalse()) - g.Expect(IsUnknown(obj, "unknown1")).To(BeTrue()) - - // test GetReason - g.Expect(GetReason(obj, "nil1")).To(Equal("")) - g.Expect(GetReason(obj, "falseInfo1")).To(Equal("reason falseInfo1")) - - // test GetMessage - g.Expect(GetMessage(obj, "nil1")).To(Equal("")) - g.Expect(GetMessage(obj, "falseInfo1")).To(Equal("message falseInfo1")) - - // test GetSeverity - g.Expect(GetSeverity(obj, "nil1")).To(BeNil()) - severity := GetSeverity(obj, "falseInfo1") - expectedSeverity := conditionsapi.ConditionSeverityInfo - g.Expect(severity).To(Equal(&expectedSeverity)) - - // test GetMessage - g.Expect(GetLastTransitionTime(obj, "nil1")).To(BeNil()) - g.Expect(GetLastTransitionTime(obj, "falseInfo1")).ToNot(BeNil()) -} - -func TestMirror(t *testing.T) { - foo := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityInfo, "message foo") - ready := TrueCondition(conditionsapi.ReadyCondition) - readyBar := ready.DeepCopy() - readyBar.Type = "bar" - - tests := []struct { - name string - from Getter - t conditionsapi.ConditionType - want *conditionsapi.Condition - }{ - { - name: "Returns nil when the ready condition does not exists", - from: getterWithConditions(foo), - want: nil, - }, - { - name: "Returns ready condition from source", - from: getterWithConditions(ready, foo), - t: "bar", - want: readyBar, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - got := mirror(tt.from, tt.t) - if tt.want == nil { - g.Expect(got).To(BeNil()) - return - } - g.Expect(got).To(HaveSameStateOf(tt.want)) - }) - } -} - -func TestSummary(t *testing.T) { - foo := TrueCondition("foo") - bar := FalseCondition("bar", "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1") - baz := FalseCondition("baz", "reason falseInfo2", conditionsapi.ConditionSeverityInfo, "message falseInfo2") - existingReady := FalseCondition(conditionsapi.ReadyCondition, "reason falseError1", conditionsapi.ConditionSeverityError, "message falseError1") // NB. existing ready has higher priority than other conditions - - tests := []struct { - name string - from Getter - options []MergeOption - want *conditionsapi.Condition - }{ - { - name: "Returns nil when there are no conditions to summarize", - from: getterWithConditions(), - want: nil, - }, - { - name: "Returns ready condition with the summary of existing conditions (with default options)", - from: getterWithConditions(foo, bar), - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - { - name: "Returns ready condition with the summary of existing conditions (using WithStepCounter options)", - from: getterWithConditions(foo, bar), - options: []MergeOption{WithStepCounter()}, - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "1 of 2 completed"), - }, - { - name: "Returns ready condition with the summary of existing conditions (using WithStepCounterIf options)", - from: getterWithConditions(foo, bar), - options: []MergeOption{WithStepCounterIf(false)}, - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - { - name: "Returns ready condition with the summary of existing conditions (using WithStepCounterIf options)", - from: getterWithConditions(foo, bar), - options: []MergeOption{WithStepCounterIf(true)}, - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "1 of 2 completed"), - }, - { - name: "Returns ready condition with the summary of existing conditions (using WithStepCounterIf and WithStepCounterIfOnly options)", - from: getterWithConditions(bar), - options: []MergeOption{WithStepCounter(), WithStepCounterIfOnly("bar")}, - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "0 of 1 completed"), - }, - { - name: "Returns ready condition with the summary of existing conditions (using WithStepCounterIf and WithStepCounterIfOnly options)", - from: getterWithConditions(foo, bar), - options: []MergeOption{WithStepCounter(), WithStepCounterIfOnly("foo")}, - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - { - name: "Returns ready condition with the summary of selected conditions (using WithConditions options)", - from: getterWithConditions(foo, bar), - options: []MergeOption{WithConditions("foo")}, // bar should be ignored - want: TrueCondition(conditionsapi.ReadyCondition), - }, - { - name: "Returns ready condition with the summary of selected conditions (using WithConditions and WithStepCounter options)", - from: getterWithConditions(foo, bar, baz), - options: []MergeOption{WithConditions("foo", "bar"), WithStepCounter()}, // baz should be ignored, total steps should be 2 - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "1 of 2 completed"), - }, - { - name: "Returns ready condition with the summary of selected conditions (using WithConditions and WithStepCounterIfOnly options)", - from: getterWithConditions(bar), - options: []MergeOption{WithConditions("bar", "baz"), WithStepCounter(), WithStepCounterIfOnly("bar")}, // there is only bar, the step counter should be set and counts only a subset of conditions - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "0 of 1 completed"), - }, - { - name: "Returns ready condition with the summary of selected conditions (using WithConditions and WithStepCounterIfOnly options - with inconsistent order between the two)", - from: getterWithConditions(bar), - options: []MergeOption{WithConditions("baz", "bar"), WithStepCounter(), WithStepCounterIfOnly("bar", "baz")}, // conditions in WithStepCounterIfOnly could be in different order than in WithConditions - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "0 of 2 completed"), - }, - { - name: "Returns ready condition with the summary of selected conditions (using WithConditions and WithStepCounterIfOnly options)", - from: getterWithConditions(bar, baz), - options: []MergeOption{WithConditions("bar", "baz"), WithStepCounter(), WithStepCounterIfOnly("bar")}, // there is also baz, so the step counter should not be set - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - { - name: "Ready condition respects merge order", - from: getterWithConditions(bar, baz), - options: []MergeOption{WithConditions("baz", "bar")}, // baz should take precedence on bar - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo2", conditionsapi.ConditionSeverityInfo, "message falseInfo2"), - }, - { - name: "Ignores existing Ready condition when computing the summary", - from: getterWithConditions(existingReady, foo, bar), - want: FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - got := summary(tt.from, tt.options...) - if tt.want == nil { - g.Expect(got).To(BeNil()) - return - } - g.Expect(got).To(HaveSameStateOf(tt.want)) - }) - } -} - -func TestAggregate(t *testing.T) { - ready1 := TrueCondition(conditionsapi.ReadyCondition) - ready2 := FalseCondition(conditionsapi.ReadyCondition, "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1") - bar := FalseCondition("bar", "reason falseError1", conditionsapi.ConditionSeverityError, "message falseError1") // NB. bar has higher priority than other conditions - - tests := []struct { - name string - from []Getter - t conditionsapi.ConditionType - want *conditionsapi.Condition - }{ - { - name: "Returns nil when there are no conditions to aggregate", - from: []Getter{}, - want: nil, - }, - { - name: "Returns foo condition with the aggregation of object's ready conditions", - from: []Getter{ - getterWithConditions(ready1), - getterWithConditions(ready1), - getterWithConditions(ready2, bar), - getterWithConditions(), - getterWithConditions(bar), - }, - t: "foo", - want: FalseCondition("foo", "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "2 of 5 completed"), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - got := aggregate(tt.from, tt.t) - if tt.want == nil { - g.Expect(got).To(BeNil()) - return - } - g.Expect(got).To(HaveSameStateOf(tt.want)) - }) - } -} - -func getterWithConditions(conditions ...*conditionsapi.Condition) Getter { - obj := newConditioned("test") - obj.SetConditions(conditionList(conditions...)) - return obj -} - -func conditionList(conditions ...*conditionsapi.Condition) conditionsapi.Conditions { - cs := conditionsapi.Conditions{} - for _, x := range conditions { - if x != nil { - cs = append(cs, *x) - } - } - return cs -} diff --git a/sdk/apis/third_party/conditions/util/conditions/matcher.go b/sdk/apis/third_party/conditions/util/conditions/matcher.go deleted file mode 100644 index afe678996..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/matcher.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "fmt" - - "github.com/onsi/gomega" - "github.com/onsi/gomega/types" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// MatchConditions returns a custom matcher to check equality of conditionsapi.Conditions. -func MatchConditions(expected conditionsapi.Conditions) types.GomegaMatcher { - return &matchConditions{ - expected: expected, - } -} - -type matchConditions struct { - expected conditionsapi.Conditions -} - -func (m matchConditions) Match(actual any) (success bool, err error) { - elems := make([]any, 0, len(m.expected)) - for _, condition := range m.expected { - elems = append(elems, MatchCondition(condition)) - } - - return gomega.ConsistOf(elems).Match(actual) -} - -func (m matchConditions) FailureMessage(actual any) (message string) { - return fmt.Sprintf("expected\n\t%#v\nto match\n\t%#v\n", actual, m.expected) -} - -func (m matchConditions) NegatedFailureMessage(actual any) (message string) { - return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) -} - -// MatchCondition returns a custom matcher to check equality of conditionsapi.Condition. -func MatchCondition(expected conditionsapi.Condition) types.GomegaMatcher { - return &matchCondition{ - expected: expected, - } -} - -type matchCondition struct { - expected conditionsapi.Condition -} - -func (m matchCondition) Match(actual any) (success bool, err error) { - actualCondition, ok := actual.(conditionsapi.Condition) - if !ok { - return false, fmt.Errorf("actual should be of type Condition") - } - - ok, err = gomega.Equal(m.expected.Type).Match(actualCondition.Type) - if !ok { - return ok, err - } - ok, err = gomega.Equal(m.expected.Status).Match(actualCondition.Status) - if !ok { - return ok, err - } - ok, err = gomega.Equal(m.expected.Severity).Match(actualCondition.Severity) - if !ok { - return ok, err - } - ok, err = gomega.Equal(m.expected.Reason).Match(actualCondition.Reason) - if !ok { - return ok, err - } - ok, err = gomega.Equal(m.expected.Message).Match(actualCondition.Message) - if !ok { - return ok, err - } - - return ok, err -} - -func (m matchCondition) FailureMessage(actual any) (message string) { - return fmt.Sprintf("expected\n\t%#v\nto match\n\t%#v\n", actual, m.expected) -} - -func (m matchCondition) NegatedFailureMessage(actual any) (message string) { - return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) -} diff --git a/sdk/apis/third_party/conditions/util/conditions/matcher_test.go b/sdk/apis/third_party/conditions/util/conditions/matcher_test.go deleted file mode 100644 index 465686ce1..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/matcher_test.go +++ /dev/null @@ -1,318 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -func TestMatchConditions(t *testing.T) { - testCases := []struct { - name string - actual any - expected conditionsapi.Conditions - expectMatch bool - }{ - { - name: "with an empty conditions", - actual: conditionsapi.Conditions{}, - expected: conditionsapi.Conditions{}, - expectMatch: true, - }, - { - name: "with matching conditions", - actual: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - }, - expected: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - }, - expectMatch: true, - }, - { - name: "with non-matching conditions", - actual: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - }, - expected: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - { - Type: conditionsapi.ConditionType("different"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "different", - Message: "different", - }, - }, - expectMatch: false, - }, - { - name: "with a different number of conditions", - actual: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - }, - expected: conditionsapi.Conditions{ - { - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - }, - expectMatch: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - g := NewWithT(t) - if tc.expectMatch { - g.Expect(tc.actual).To(MatchConditions(tc.expected)) - } else { - g.Expect(tc.actual).ToNot(MatchConditions(tc.expected)) - } - }) - } -} - -func TestMatchCondition(t *testing.T) { - testCases := []struct { - name string - actual any - expected conditionsapi.Condition - expectMatch bool - }{ - { - name: "with an empty condition", - actual: conditionsapi.Condition{}, - expected: conditionsapi.Condition{}, - expectMatch: true, - }, - { - name: "with a matching condition", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expectMatch: true, - }, - { - name: "with a different time", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Time{}, - Reason: "reason", - Message: "message", - }, - expectMatch: true, - }, - { - name: "with a different type", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("different"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expectMatch: false, - }, - { - name: "with a different status", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionFalse, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expectMatch: false, - }, - { - name: "with a different severity", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityInfo, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expectMatch: false, - }, - { - name: "with a different reason", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "different", - Message: "message", - }, - expectMatch: false, - }, - { - name: "with a different message", - actual: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "message", - }, - expected: conditionsapi.Condition{ - Type: conditionsapi.ConditionType("type"), - Status: corev1.ConditionTrue, - Severity: conditionsapi.ConditionSeverityNone, - LastTransitionTime: metav1.Now(), - Reason: "reason", - Message: "different", - }, - expectMatch: false, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - g := NewWithT(t) - if tc.expectMatch { - g.Expect(tc.actual).To(MatchCondition(tc.expected)) - } else { - g.Expect(tc.actual).ToNot(MatchCondition(tc.expected)) - } - }) - } -} diff --git a/sdk/apis/third_party/conditions/util/conditions/matchers.go b/sdk/apis/third_party/conditions/util/conditions/matchers.go deleted file mode 100644 index 49977a938..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/matchers.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "errors" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// HaveSameStateOf matches a condition to have the same state of another. -func HaveSameStateOf(expected *conditionsapi.Condition) types.GomegaMatcher { - return &conditionMatcher{ - Expected: expected, - } -} - -type conditionMatcher struct { - Expected *conditionsapi.Condition -} - -func (matcher *conditionMatcher) Match(actual any) (success bool, err error) { - actualCondition, ok := actual.(*conditionsapi.Condition) - if !ok { - return false, errors.New("value should be a condition") - } - - return hasSameState(actualCondition, matcher.Expected), nil -} - -func (matcher *conditionMatcher) FailureMessage(actual any) (message string) { - return format.Message(actual, "to have the same state of", matcher.Expected) -} -func (matcher *conditionMatcher) NegatedFailureMessage(actual any) (message string) { - return format.Message(actual, "not to have the same state of", matcher.Expected) -} diff --git a/sdk/apis/third_party/conditions/util/conditions/merge.go b/sdk/apis/third_party/conditions/util/conditions/merge.go deleted file mode 100644 index 2adb58453..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/merge.go +++ /dev/null @@ -1,199 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "sort" - - corev1 "k8s.io/api/core/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// localizedCondition defines a condition with the information of the object the conditions -// was originated from. -type localizedCondition struct { - *conditionsapi.Condition - Getter -} - -// merge a list of condition into a single one. -// This operation is designed to ensure visibility of the most relevant conditions for defining the -// operational state of a component. E.g. If there is one error in the condition list, this one takes -// priority over the other conditions and it is should be reflected in the target condition. -// -// More specifically: -// 1. Conditions are grouped by status, severity -// 2. The resulting condition groups are sorted according to the following priority: -// - P0 - Status=False, Severity=Error -// - P1 - Status=False, Severity=Warning -// - P2 - Status=False, Severity=Info -// - P3 - Status=True -// - P4 - Status=Unknown -// -// 3. The group with highest priority is used to determine status, severity and other info of the target condition. -// -// Please note that the last operation includes also the task of computing the Reason and the Message for the target -// condition; in order to complete such task some trade-off should be made, because there is no a golden rule -// for summarizing many Reason/Message into single Reason/Message. -// mergeOptions allows the user to adapt this process to the specific needs by exposing a set of merge strategies. -func merge(conditions []localizedCondition, targetCondition conditionsapi.ConditionType, options *mergeOptions) *conditionsapi.Condition { - g := getConditionGroups(conditions) - if len(g) == 0 { - return nil - } - - if g.TopGroup().status == corev1.ConditionTrue { - return TrueCondition(targetCondition) - } - - targetReason := getReason(g, options) - targetMessage := getMessage(g, options) - if g.TopGroup().status == corev1.ConditionFalse { - return FalseCondition(targetCondition, targetReason, g.TopGroup().severity, "%s", targetMessage) - } - return UnknownCondition(targetCondition, targetReason, "%s", targetMessage) -} - -// getConditionGroups groups a list of conditions according to status, severity values. -// Additionally, the resulting groups are sorted by mergePriority. -func getConditionGroups(conditions []localizedCondition) conditionGroups { - groups := conditionGroups{} - - for _, condition := range conditions { - if condition.Condition == nil { - continue - } - - added := false - for i := range groups { - if groups[i].status == condition.Status && groups[i].severity == condition.Severity { - groups[i].conditions = append(groups[i].conditions, condition) - added = true - break - } - } - if !added { - groups = append(groups, conditionGroup{ - conditions: []localizedCondition{condition}, - status: condition.Status, - severity: condition.Severity, - }) - } - } - - // sort groups by priority - sort.Sort(groups) - - // sorts conditions in the TopGroup so we ensure predictable result for merge strategies. - // condition are sorted using the same lexicographic order used by Set; in case two conditions - // have the same type, condition are sorted using according to the alphabetical order of the source object name. - if len(groups) > 0 { - sort.Slice(groups[0].conditions, func(i, j int) bool { - a := groups[0].conditions[i] - b := groups[0].conditions[j] - if a.Type != b.Type { - return lexicographicLess(a.Condition, b.Condition) - } - return a.GetName() < b.GetName() - }) - } - - return groups -} - -// conditionGroups provides supports for grouping a list of conditions to be -// merged into a single condition. ConditionGroups can be sorted by mergePriority. -type conditionGroups []conditionGroup - -func (g conditionGroups) Len() int { - return len(g) -} - -func (g conditionGroups) Less(i, j int) bool { - return g[i].mergePriority() < g[j].mergePriority() -} - -func (g conditionGroups) Swap(i, j int) { - g[i], g[j] = g[j], g[i] -} - -// TopGroup returns the condition group with the highest mergePriority. -func (g conditionGroups) TopGroup() *conditionGroup { - if len(g) == 0 { - return nil - } - return &g[0] -} - -// TrueGroup returns the condition group with status True, if any. -func (g conditionGroups) TrueGroup() *conditionGroup { - return g.getByStatusAndSeverity(corev1.ConditionTrue, conditionsapi.ConditionSeverityNone) -} - -// ErrorGroup returns the condition group with status False and severity Error, if any. -func (g conditionGroups) ErrorGroup() *conditionGroup { - return g.getByStatusAndSeverity(corev1.ConditionFalse, conditionsapi.ConditionSeverityError) -} - -// WarningGroup returns the condition group with status False and severity Warning, if any. -func (g conditionGroups) WarningGroup() *conditionGroup { - return g.getByStatusAndSeverity(corev1.ConditionFalse, conditionsapi.ConditionSeverityWarning) -} - -func (g conditionGroups) getByStatusAndSeverity(status corev1.ConditionStatus, severity conditionsapi.ConditionSeverity) *conditionGroup { - if len(g) == 0 { - return nil - } - for _, group := range g { - if group.status == status && group.severity == severity { - return &group - } - } - return nil -} - -// conditionGroup define a group of conditions with the same status and severity, -// and thus with the same priority when merging into a Ready condition. -type conditionGroup struct { - status corev1.ConditionStatus - severity conditionsapi.ConditionSeverity - conditions []localizedCondition -} - -// mergePriority provides a priority value for the status and severity tuple that identifies this -// condition group. The mergePriority value allows an easier sorting of conditions groups. -func (g conditionGroup) mergePriority() int { - switch g.status { - case corev1.ConditionFalse: - switch g.severity { - case conditionsapi.ConditionSeverityError: - return 0 - case conditionsapi.ConditionSeverityWarning: - return 1 - case conditionsapi.ConditionSeverityInfo: - return 2 - } - case corev1.ConditionTrue: - return 3 - case corev1.ConditionUnknown: - return 4 - } - - // this should never happen - return 99 -} diff --git a/sdk/apis/third_party/conditions/util/conditions/merge_strategies.go b/sdk/apis/third_party/conditions/util/conditions/merge_strategies.go deleted file mode 100644 index 1f1793602..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/merge_strategies.go +++ /dev/null @@ -1,169 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "fmt" - "strings" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// mergeOptions allows to set strategies for merging a set of conditions into a single condition, -// and more specifically for computing the target Reason and the target Message. -type mergeOptions struct { - conditionTypes []conditionsapi.ConditionType - addSourceRef bool - addStepCounter bool - addStepCounterIfOnlyConditionTypes []conditionsapi.ConditionType - stepCounter int -} - -// MergeOption defines an option for computing a summary of conditions. -type MergeOption func(*mergeOptions) - -// WithConditions instructs merge about the condition types to consider when doing a merge operation; -// if this option is not specified, all the conditions (excepts Ready) will be considered. This is required -// so we can provide some guarantees about the semantic of the target condition without worrying about -// side effects if someone or something adds custom conditions to the objects. -// -// NOTE: The order of conditions types defines the priority for determining the Reason and Message for the -// target condition. -// IMPORTANT: This options works only while generating the Summary condition. -func WithConditions(t ...conditionsapi.ConditionType) MergeOption { - return func(c *mergeOptions) { - c.conditionTypes = t - } -} - -// WithStepCounter instructs merge to add a "x of y completed" string to the message, -// where x is the number of conditions with Status=true and y is the number of conditions in scope. -func WithStepCounter() MergeOption { - return func(c *mergeOptions) { - c.addStepCounter = true - } -} - -// WithStepCounterIf adds a step counter if the value is true. -// This can be used e.g. to add a step counter only if the object is not being deleted. -// -// IMPORTANT: This options works only while generating the Summary condition. -func WithStepCounterIf(value bool) MergeOption { - return func(c *mergeOptions) { - c.addStepCounter = value - } -} - -// WithStepCounterIfOnly ensure a step counter is show only if a subset of condition exists. -// This applies for example on Machines, where we want to use -// the step counter notation while provisioning the machine, but then we want to move away from this notation -// as soon as the machine is provisioned and e.g. a Machine health check condition is generated -// -// IMPORTANT: This options requires WithStepCounter or WithStepCounterIf to be set. -// IMPORTANT: This options works only while generating the Summary condition. -func WithStepCounterIfOnly(t ...conditionsapi.ConditionType) MergeOption { - return func(c *mergeOptions) { - c.addStepCounterIfOnlyConditionTypes = t - } -} - -// AddSourceRef instructs merge to add info about the originating object to the target Reason. -func AddSourceRef() MergeOption { - return func(c *mergeOptions) { - c.addSourceRef = true - } -} - -// getReason returns the reason to be applied to the condition resulting by merging a set of condition groups. -// The reason is computed according to the given mergeOptions. -func getReason(groups conditionGroups, options *mergeOptions) string { - return getFirstReason(groups, options.conditionTypes, options.addSourceRef) -} - -// getFirstReason returns the first reason from the ordered list of conditions in the top group. -// If required, the reason gets localized with the source object reference. -func getFirstReason(g conditionGroups, order []conditionsapi.ConditionType, addSourceRef bool) string { - if condition := getFirstCondition(g, order); condition != nil { - reason := condition.Reason - if addSourceRef { - return localizeReason(reason, condition.Getter) - } - return reason - } - return "" -} - -// localizeReason adds info about the originating object to the target Reason. -func localizeReason(reason string, from Getter) string { - if strings.Contains(reason, "@") { - return reason - } - return fmt.Sprintf("%s @ %s/%s", reason, from.GetObjectKind().GroupVersionKind().Kind, from.GetName()) -} - -// getMessage returns the message to be applied to the condition resulting by merging a set of condition groups. -// The message is computed according to the given mergeOptions, but in case of errors or warning a -// summary of existing errors is automatically added. -func getMessage(groups conditionGroups, options *mergeOptions) string { - if options.addStepCounter { - return getStepCounterMessage(groups, options.stepCounter) - } - - return getFirstMessage(groups, options.conditionTypes) -} - -// getStepCounterMessage returns a message "x of y completed", where x is the number of conditions -// with Status=true and y is the number passed to this method. -func getStepCounterMessage(groups conditionGroups, to int) string { - ct := 0 - if trueGroup := groups.TrueGroup(); trueGroup != nil { - ct = len(trueGroup.conditions) - } - return fmt.Sprintf("%d of %d completed", ct, to) -} - -// getFirstMessage returns the message from the ordered list of conditions in the top group. -func getFirstMessage(groups conditionGroups, order []conditionsapi.ConditionType) string { - if condition := getFirstCondition(groups, order); condition != nil { - return condition.Message - } - return "" -} - -// getFirstCondition returns a first condition from the ordered list of conditions in the top group. -func getFirstCondition(g conditionGroups, priority []conditionsapi.ConditionType) *localizedCondition { - topGroup := g.TopGroup() - if topGroup == nil { - return nil - } - - switch len(topGroup.conditions) { - case 0: - return nil - case 1: - return &topGroup.conditions[0] - default: - for _, p := range priority { - for _, c := range topGroup.conditions { - if c.Type == p { - return &c - } - } - } - return &topGroup.conditions[0] - } -} diff --git a/sdk/apis/third_party/conditions/util/conditions/merge_strategies_test.go b/sdk/apis/third_party/conditions/util/conditions/merge_strategies_test.go deleted file mode 100644 index 91dc95370..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/merge_strategies_test.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "testing" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -func TestGetStepCounterMessage(t *testing.T) { - g := NewWithT(t) - - groups := getConditionGroups(conditionsWithSource(&conditioned{}, - nil1, - true1, true1, - falseInfo1, - falseWarning1, falseWarning1, - falseError1, - unknown1, - )) - - got := getStepCounterMessage(groups, 8) - - // step count message should report n° if true conditions over to number - g.Expect(got).To(Equal("2 of 8 completed")) -} - -func TestLocalizeReason(t *testing.T) { - g := NewWithT(t) - - getter := &conditioned{ - Unstructured: &unstructured.Unstructured{ - Object: map[string]any{ - "kind": "Foo", - "metadata": map[string]any{ - "name": "test-cluster", - }, - }, - }, - } - - // localize should reason location - got := localizeReason("foo", getter) - g.Expect(got).To(Equal("foo @ Foo/test-cluster")) - - // localize should not alter existing location - got = localizeReason("foo @ SomeKind/some-name", getter) - g.Expect(got).To(Equal("foo @ SomeKind/some-name")) -} - -func TestGetFirstReasonAndMessage(t *testing.T) { - g := NewWithT(t) - - foo := FalseCondition("foo", "falseFoo", conditionsapi.ConditionSeverityInfo, "message falseFoo") - bar := FalseCondition("bar", "falseBar", conditionsapi.ConditionSeverityInfo, "message falseBar") - - getter := &conditioned{ - Unstructured: &unstructured.Unstructured{ - Object: map[string]any{ - "kind": "Foo", - "metadata": map[string]any{ - "name": "test-cluster", - }, - }, - }, - } - - groups := getConditionGroups(conditionsWithSource(getter, foo, bar)) - - // getFirst should report first condition in lexicografical order if no order is specified - gotReason := getFirstReason(groups, nil, false) - g.Expect(gotReason).To(Equal("falseBar")) - gotMessage := getFirstMessage(groups, nil) - g.Expect(gotMessage).To(Equal("message falseBar")) - - // getFirst should report should respect order - gotReason = getFirstReason(groups, []conditionsapi.ConditionType{"foo", "bar"}, false) - g.Expect(gotReason).To(Equal("falseFoo")) - gotMessage = getFirstMessage(groups, []conditionsapi.ConditionType{"foo", "bar"}) - g.Expect(gotMessage).To(Equal("message falseFoo")) - - // getFirst should report should respect order in case of missing conditions - gotReason = getFirstReason(groups, []conditionsapi.ConditionType{"missingBaz", "foo", "bar"}, false) - g.Expect(gotReason).To(Equal("falseFoo")) - gotMessage = getFirstMessage(groups, []conditionsapi.ConditionType{"missingBaz", "foo", "bar"}) - g.Expect(gotMessage).To(Equal("message falseFoo")) - - // getFirst should fallback to first condition if none of the conditions in the list exists - gotReason = getFirstReason(groups, []conditionsapi.ConditionType{"missingBaz"}, false) - g.Expect(gotReason).To(Equal("falseBar")) - gotMessage = getFirstMessage(groups, []conditionsapi.ConditionType{"missingBaz"}) - g.Expect(gotMessage).To(Equal("message falseBar")) - - // getFirstReason should localize reason if required - gotReason = getFirstReason(groups, nil, true) - g.Expect(gotReason).To(Equal("falseBar @ Foo/test-cluster")) -} diff --git a/sdk/apis/third_party/conditions/util/conditions/merge_test.go b/sdk/apis/third_party/conditions/util/conditions/merge_test.go deleted file mode 100644 index 2fec24093..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/merge_test.go +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "testing" - - corev1 "k8s.io/api/core/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -func TestNewConditionsGroup(t *testing.T) { - g := NewWithT(t) - - conditions := []*conditionsapi.Condition{nil1, true1, true1, falseInfo1, falseWarning1, falseWarning1, falseError1, unknown1} - - got := getConditionGroups(conditionsWithSource(&conditioned{}, conditions...)) - - g.Expect(got).ToNot(BeNil()) - g.Expect(got).To(HaveLen(5)) - - // The top group should be False/Error and it should have one condition - g.Expect(got.TopGroup().status).To(Equal(corev1.ConditionFalse)) - g.Expect(got.TopGroup().severity).To(Equal(conditionsapi.ConditionSeverityError)) - g.Expect(got.TopGroup().conditions).To(HaveLen(1)) - - // The true group should be true and it should have two conditions - g.Expect(got.TrueGroup().status).To(Equal(corev1.ConditionTrue)) - g.Expect(got.TrueGroup().severity).To(Equal(conditionsapi.ConditionSeverityNone)) - g.Expect(got.TrueGroup().conditions).To(HaveLen(2)) - - // The error group should be False/Error and it should have one condition - g.Expect(got.ErrorGroup().status).To(Equal(corev1.ConditionFalse)) - g.Expect(got.ErrorGroup().severity).To(Equal(conditionsapi.ConditionSeverityError)) - g.Expect(got.ErrorGroup().conditions).To(HaveLen(1)) - - // The warning group should be False/Warning and it should have two conditions - g.Expect(got.WarningGroup().status).To(Equal(corev1.ConditionFalse)) - g.Expect(got.WarningGroup().severity).To(Equal(conditionsapi.ConditionSeverityWarning)) - g.Expect(got.WarningGroup().conditions).To(HaveLen(2)) - - // got[0] should be False/Error and it should have one condition - g.Expect(got[0].status).To(Equal(corev1.ConditionFalse)) - g.Expect(got[0].severity).To(Equal(conditionsapi.ConditionSeverityError)) - g.Expect(got[0].conditions).To(HaveLen(1)) - - // got[1] should be False/Warning and it should have two conditions - g.Expect(got[1].status).To(Equal(corev1.ConditionFalse)) - g.Expect(got[1].severity).To(Equal(conditionsapi.ConditionSeverityWarning)) - g.Expect(got[1].conditions).To(HaveLen(2)) - - // got[2] should be False/Info and it should have one condition - g.Expect(got[2].status).To(Equal(corev1.ConditionFalse)) - g.Expect(got[2].severity).To(Equal(conditionsapi.ConditionSeverityInfo)) - g.Expect(got[2].conditions).To(HaveLen(1)) - - // got[3] should be True and it should have two conditions - g.Expect(got[3].status).To(Equal(corev1.ConditionTrue)) - g.Expect(got[3].severity).To(Equal(conditionsapi.ConditionSeverityNone)) - g.Expect(got[3].conditions).To(HaveLen(2)) - - // got[4] should be Unknown and it should have one condition - g.Expect(got[4].status).To(Equal(corev1.ConditionUnknown)) - g.Expect(got[4].severity).To(Equal(conditionsapi.ConditionSeverityNone)) - g.Expect(got[4].conditions).To(HaveLen(1)) - - // nil conditions are ignored -} - -func TestMergeRespectPriority(t *testing.T) { - tests := []struct { - name string - conditions []*conditionsapi.Condition - want *conditionsapi.Condition - }{ - { - name: "aggregate nil list return nil", - conditions: nil, - want: nil, - }, - { - name: "aggregate empty list return nil", - conditions: []*conditionsapi.Condition{}, - want: nil, - }, - { - name: "When there is false/error it returns false/error", - conditions: []*conditionsapi.Condition{falseError1, falseWarning1, falseInfo1, unknown1, true1}, - want: FalseCondition("foo", "reason falseError1", conditionsapi.ConditionSeverityError, "message falseError1"), - }, - { - name: "When there is false/warning and no false/error, it returns false/warning", - conditions: []*conditionsapi.Condition{falseWarning1, falseInfo1, unknown1, true1}, - want: FalseCondition("foo", "reason falseWarning1", conditionsapi.ConditionSeverityWarning, "message falseWarning1"), - }, - { - name: "When there is false/info and no false/error or false/warning, it returns false/info", - conditions: []*conditionsapi.Condition{falseInfo1, unknown1, true1}, - want: FalseCondition("foo", "reason falseInfo1", conditionsapi.ConditionSeverityInfo, "message falseInfo1"), - }, - { - name: "When there is true and no false/*, it returns info", - conditions: []*conditionsapi.Condition{unknown1, true1}, - want: TrueCondition("foo"), - }, - { - name: "When there is unknown and no true or false/*, it returns unknown", - conditions: []*conditionsapi.Condition{unknown1}, - want: UnknownCondition("foo", "reason unknown1", "message unknown1"), - }, - { - name: "nil conditions are ignored", - conditions: []*conditionsapi.Condition{nil1, nil1, nil1}, - want: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - got := merge(conditionsWithSource(&conditioned{}, tt.conditions...), "foo", &mergeOptions{}) - - if tt.want == nil { - g.Expect(got).To(BeNil()) - return - } - g.Expect(got).To(HaveSameStateOf(tt.want)) - }) - } -} - -func conditionsWithSource(obj Setter, conditions ...*conditionsapi.Condition) []localizedCondition { - obj.SetConditions(conditionList(conditions...)) - - ret := make([]localizedCondition, 0, len(conditions)) - for i := range conditions { - ret = append(ret, localizedCondition{ - Condition: conditions[i], - Getter: obj, - }) - } - - return ret -} diff --git a/sdk/apis/third_party/conditions/util/conditions/patch.go b/sdk/apis/third_party/conditions/util/conditions/patch.go deleted file mode 100644 index d1bd987e1..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/patch.go +++ /dev/null @@ -1,201 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "fmt" - "reflect" - - "github.com/google/go-cmp/cmp" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// Patch defines a list of operations to change a list of conditions into another. -type Patch []PatchOperation - -// PatchOperation define an operation that changes a single condition. -type PatchOperation struct { - Before *conditionsapi.Condition - After *conditionsapi.Condition - Op PatchOperationType -} - -// PatchOperationType defines patch operation types. -type PatchOperationType string - -const ( - // AddConditionPatch defines an add condition patch operation. - AddConditionPatch PatchOperationType = "Add" - - // ChangeConditionPatch defines an change condition patch operation. - ChangeConditionPatch PatchOperationType = "Change" - - // RemoveConditionPatch defines a remove condition patch operation. - RemoveConditionPatch PatchOperationType = "Remove" -) - -// NewPatch returns the list of Patch required to align source conditions to after conditions. -func NewPatch(before Getter, after Getter) Patch { - var patch Patch - - // Identify AddCondition and ModifyCondition changes. - targetConditions := after.GetConditions() - for i := range targetConditions { - targetCondition := targetConditions[i] - currentCondition := Get(before, targetCondition.Type) - if currentCondition == nil { - patch = append(patch, PatchOperation{Op: AddConditionPatch, After: &targetCondition}) - continue - } - - if !reflect.DeepEqual(&targetCondition, currentCondition) { - patch = append(patch, PatchOperation{Op: ChangeConditionPatch, After: &targetCondition, Before: currentCondition}) - } - } - - // Identify RemoveCondition changes. - baseConditions := before.GetConditions() - for i := range baseConditions { - baseCondition := baseConditions[i] - targetCondition := Get(after, baseCondition.Type) - if targetCondition == nil { - patch = append(patch, PatchOperation{Op: RemoveConditionPatch, Before: &baseCondition}) - } - } - return patch -} - -// applyOptions allows to set strategies for patch apply. -type applyOptions struct { - ownedConditions []conditionsapi.ConditionType - forceOverwrite bool -} - -func (o *applyOptions) isOwnedCondition(t conditionsapi.ConditionType) bool { - for _, i := range o.ownedConditions { - if i == t { - return true - } - } - return false -} - -// ApplyOption defines an option for applying a condition patch. -type ApplyOption func(*applyOptions) - -// WithOwnedConditions allows to define condition types owned by the controller. -// In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -func WithOwnedConditions(t ...conditionsapi.ConditionType) ApplyOption { - return func(c *applyOptions) { - c.ownedConditions = t - } -} - -// WithForceOverwrite In case of conflicts for the owned conditions, the patch helper will always use the value provided by the controller. -func WithForceOverwrite(v bool) ApplyOption { - return func(c *applyOptions) { - c.forceOverwrite = v - } -} - -// Apply executes a three-way merge of a list of Patch. -// When merge conflicts are detected (latest deviated from before in an incompatible way), an error is returned. -func (p Patch) Apply(latest Setter, options ...ApplyOption) error { - if len(p) == 0 { - return nil - } - - applyOpt := &applyOptions{} - for _, o := range options { - o(applyOpt) - } - - for _, conditionPatch := range p { - switch conditionPatch.Op { - case AddConditionPatch: - // If the conditions is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { - Set(latest, conditionPatch.After) - continue - } - - // If the condition is already on latest, check if latest and after agree on the change; if not, this is a conflict. - if latestCondition := Get(latest, conditionPatch.After.Type); latestCondition != nil { - // If latest and after agree on the change, then it is a conflict. - if !hasSameState(latestCondition, conditionPatch.After) { - return fmt.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/AddCondition conflict: %v", conditionPatch.After.Type, cmp.Diff(latestCondition, conditionPatch.After)) - } - // otherwise, the latest is already as intended. - // NOTE: We are preserving LastTransitionTime from the latest in order to avoid altering the existing value. - continue - } - // If the condition does not exists on the latest, add the new after condition. - Set(latest, conditionPatch.After) - - case ChangeConditionPatch: - // If the conditions is owned, always keep the after value. - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.After.Type) { - Set(latest, conditionPatch.After) - continue - } - - latestCondition := Get(latest, conditionPatch.After.Type) - - // If the condition does not exist anymore on the latest, this is a conflict. - if latestCondition == nil { - return fmt.Errorf("error patching conditions: The condition %q was deleted by a different process and this caused a merge/ChangeCondition conflict", conditionPatch.After.Type) - } - - // If the condition on the latest is different from the base condition, check if - // the after state corresponds to the desired value. If not this is a conflict (unless we should ignore conflicts for this condition type). - if !reflect.DeepEqual(latestCondition, conditionPatch.Before) { - if !hasSameState(latestCondition, conditionPatch.After) { - return fmt.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/ChangeCondition conflict: %v", conditionPatch.After.Type, cmp.Diff(latestCondition, conditionPatch.After)) - } - // Otherwise the latest is already as intended. - // NOTE: We are preserving LastTransitionTime from the latest in order to avoid altering the existing value. - continue - } - // Otherwise apply the new after condition. - Set(latest, conditionPatch.After) - - case RemoveConditionPatch: - // If the conditions is owned, always keep the after value (condition should be deleted). - if applyOpt.forceOverwrite || applyOpt.isOwnedCondition(conditionPatch.Before.Type) { - Delete(latest, conditionPatch.Before.Type) - continue - } - - // If the condition is still on the latest, check if it is changed in the meantime; - // if so then this is a conflict. - if latestCondition := Get(latest, conditionPatch.Before.Type); latestCondition != nil { - if !hasSameState(latestCondition, conditionPatch.Before) { - return fmt.Errorf("error patching conditions: The condition %q was modified by a different process and this caused a merge/RemoveCondition conflict: %v", conditionPatch.Before.Type, cmp.Diff(latestCondition, conditionPatch.Before)) - } - } - // Otherwise the latest and after agreed on the delete operation, so there's nothing to change. - Delete(latest, conditionPatch.Before.Type) - } - } - return nil -} - -// IsZero returns true if the patch has no changes. -func (p Patch) IsZero() bool { - return len(p) == 0 -} diff --git a/sdk/apis/third_party/conditions/util/conditions/patch_test.go b/sdk/apis/third_party/conditions/util/conditions/patch_test.go deleted file mode 100644 index f1fcc2a66..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/patch_test.go +++ /dev/null @@ -1,290 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "testing" - "time" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -func TestNewPatch(t *testing.T) { - fooTrue := TrueCondition("foo") - fooFalse := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityInfo, "message foo") - - tests := []struct { - name string - before Getter - after Getter - want Patch - }{ - { - name: "No changes return empty patch", - before: getterWithConditions(), - after: getterWithConditions(), - want: nil, - }, - { - name: "No changes return empty patch", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooTrue), - want: nil, - }, - { - name: "Detects AddConditionPatch", - before: getterWithConditions(), - after: getterWithConditions(fooTrue), - want: Patch{ - { - Before: nil, - After: fooTrue, - Op: AddConditionPatch, - }, - }, - }, - { - name: "Detects ChangeConditionPatch", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooFalse), - want: Patch{ - { - Before: fooTrue, - After: fooFalse, - Op: ChangeConditionPatch, - }, - }, - }, - { - name: "Detects RemoveConditionPatch", - before: getterWithConditions(fooTrue), - after: getterWithConditions(), - want: Patch{ - { - Before: fooTrue, - After: nil, - Op: RemoveConditionPatch, - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - got := NewPatch(tt.before, tt.after) - - g.Expect(got).To(Equal(tt.want)) - }) - } -} - -func TestApply(t *testing.T) { - fooTrue := TrueCondition("foo") - fooFalse := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityInfo, "message foo") - fooWarning := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityWarning, "message foo") - - tests := []struct { - name string - before Getter - after Getter - latest Setter - options []ApplyOption - want conditionsapi.Conditions - wantErr bool - }{ - { - name: "No patch return same list", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(fooTrue), - want: conditionList(fooTrue), - wantErr: false, - }, - { - name: "Add: When a condition does not exists, it should add", - before: getterWithConditions(), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(), - want: conditionList(fooTrue), - wantErr: false, - }, - { - name: "Add: When a condition already exists but without conflicts, it should add", - before: getterWithConditions(), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(fooTrue), - want: conditionList(fooTrue), - wantErr: false, - }, - { - name: "Add: When a condition already exists but with conflicts, it should error", - before: getterWithConditions(), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(fooFalse), - want: nil, - wantErr: true, - }, - { - name: "Add: When a condition already exists but with conflicts, it should not error if the condition is owned", - before: getterWithConditions(), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(fooFalse), - options: []ApplyOption{WithOwnedConditions("foo")}, - want: conditionList(fooTrue), // after condition should be kept in case of error - wantErr: false, - }, - { - name: "Remove: When a condition was already deleted, it should pass", - before: getterWithConditions(fooTrue), - after: getterWithConditions(), - latest: setterWithConditions(), - want: conditionList(), - wantErr: false, - }, - { - name: "Remove: When a condition already exists but without conflicts, it should delete", - before: getterWithConditions(fooTrue), - after: getterWithConditions(), - latest: setterWithConditions(fooTrue), - want: conditionList(), - wantErr: false, - }, - { - name: "Remove: When a condition already exists but with conflicts, it should error", - before: getterWithConditions(fooTrue), - after: getterWithConditions(), - latest: setterWithConditions(fooFalse), - want: nil, - wantErr: true, - }, - { - name: "Remove: When a condition already exists but with conflicts, it should not error if the condition is owned", - before: getterWithConditions(fooTrue), - after: getterWithConditions(), - latest: setterWithConditions(fooFalse), - options: []ApplyOption{WithOwnedConditions("foo")}, - want: conditionList(), // after condition should be kept in case of error - wantErr: false, - }, - { - name: "Change: When a condition exists without conflicts, it should change", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooFalse), - latest: setterWithConditions(fooTrue), - want: conditionList(fooFalse), - wantErr: false, - }, - { - name: "Change: When a condition exists with conflicts but there is agreement on the final state, it should change", - before: getterWithConditions(fooFalse), - after: getterWithConditions(fooTrue), - latest: setterWithConditions(fooTrue), - want: conditionList(fooTrue), - wantErr: false, - }, - { - name: "Change: When a condition exists with conflicts but there is no agreement on the final state, it should error", - before: getterWithConditions(fooWarning), - after: getterWithConditions(fooFalse), - latest: setterWithConditions(fooTrue), - want: nil, - wantErr: true, - }, - { - name: "Change: When a condition exists with conflicts but there is no agreement on the final state, it should not error if the condition is owned", - before: getterWithConditions(fooWarning), - after: getterWithConditions(fooFalse), - latest: setterWithConditions(fooTrue), - options: []ApplyOption{WithOwnedConditions("foo")}, - want: conditionList(fooFalse), // after condition should be kept in case of error - wantErr: false, - }, - { - name: "Change: When a condition was deleted, it should error", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooFalse), - latest: setterWithConditions(), - want: nil, - wantErr: true, - }, - { - name: "Change: When a condition was deleted, it should not error if the condition is owned", - before: getterWithConditions(fooTrue), - after: getterWithConditions(fooFalse), - latest: setterWithConditions(), - options: []ApplyOption{WithOwnedConditions("foo")}, - want: conditionList(fooFalse), // after condition should be kept in case of error - wantErr: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - patch := NewPatch(tt.before, tt.after) - - err := patch.Apply(tt.latest, tt.options...) - if tt.wantErr { - g.Expect(err).To(HaveOccurred()) - return - } - g.Expect(err).ToNot(HaveOccurred()) - - g.Expect(tt.latest.GetConditions()).To(haveSameConditionsOf(tt.want)) - }) - } -} - -func TestApplyDoesNotAlterLastTransitionTime(t *testing.T) { - g := NewWithT(t) - - before := newConditioned("test") - after := &conditioned{ - Unstructured: &unstructured.Unstructured{ - Object: map[string]any{ - "status": map[string]any{ - "conditions": conditionsapi.Conditions{ - conditionsapi.Condition{ - Type: "foo", - Status: corev1.ConditionTrue, - LastTransitionTime: metav1.NewTime(time.Now().UTC().Truncate(time.Second)), - }, - }, - }, - }, - }, - } - latest := newConditioned("test") - - // latest has no conditions, so we are actually adding the condition but in this case we should not set the LastTransition Time - // but we should preserve the LastTransition set in after - - diff := NewPatch(before, after) - err := diff.Apply(latest) - - g.Expect(err).ToNot(HaveOccurred()) - g.Expect(latest.GetConditions()).To(Equal(after.GetConditions())) -} diff --git a/sdk/apis/third_party/conditions/util/conditions/setter.go b/sdk/apis/third_party/conditions/util/conditions/setter.go deleted file mode 100644 index af0ad1a61..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/setter.go +++ /dev/null @@ -1,176 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "fmt" - "sort" - "time" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" -) - -// Setter interface defines methods that an object should implement in order to -// use the conditions package for setting conditions. -type Setter interface { - Getter - SetConditions(conditionsapi.Conditions) -} - -// Set sets the given condition. -// -// NOTE: If a condition already exists, the LastTransitionTime is updated only if a change is detected -// in any of the following fields: Status, Reason, Severity and Message. -func Set(to Setter, condition *conditionsapi.Condition) { - if to == nil || condition == nil { - return - } - - // Check if the new conditions already exists, and change it only if there is a status - // transition (otherwise we should preserve the current last transition time)- - conditions := to.GetConditions() - exists := false - for i := range conditions { - existingCondition := conditions[i] - if existingCondition.Type == condition.Type { - exists = true - if !hasSameState(&existingCondition, condition) { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - conditions[i] = *condition - break - } - condition.LastTransitionTime = existingCondition.LastTransitionTime - break - } - } - - // If the condition does not exist, add it, setting the transition time only if not already set - if !exists { - if condition.LastTransitionTime.IsZero() { - condition.LastTransitionTime = metav1.NewTime(time.Now().UTC().Truncate(time.Second)) - } - conditions = append(conditions, *condition) - } - - // Sorts conditions for convenience of the consumer, i.e. kubectl. - sort.Slice(conditions, func(i, j int) bool { - return lexicographicLess(&conditions[i], &conditions[j]) - }) - - to.SetConditions(conditions) -} - -// TrueCondition returns a condition with Status=True and the given type. -func TrueCondition(t conditionsapi.ConditionType) *conditionsapi.Condition { - return &conditionsapi.Condition{ - Type: t, - Status: corev1.ConditionTrue, - } -} - -// FalseCondition returns a condition with Status=False and the given type. -func FalseCondition(t conditionsapi.ConditionType, reason string, severity conditionsapi.ConditionSeverity, messageFormat string, messageArgs ...any) *conditionsapi.Condition { - return &conditionsapi.Condition{ - Type: t, - Status: corev1.ConditionFalse, - Reason: reason, - Severity: severity, - Message: fmt.Sprintf(messageFormat, messageArgs...), - } -} - -// UnknownCondition returns a condition with Status=Unknown and the given type. -func UnknownCondition(t conditionsapi.ConditionType, reason string, messageFormat string, messageArgs ...any) *conditionsapi.Condition { - return &conditionsapi.Condition{ - Type: t, - Status: corev1.ConditionUnknown, - Reason: reason, - Message: fmt.Sprintf(messageFormat, messageArgs...), - } -} - -// MarkTrue sets Status=True for the condition with the given type. -func MarkTrue(to Setter, t conditionsapi.ConditionType) { - Set(to, TrueCondition(t)) -} - -// MarkUnknown sets Status=Unknown for the condition with the given type. -func MarkUnknown(to Setter, t conditionsapi.ConditionType, reason, messageFormat string, messageArgs ...any) { - Set(to, UnknownCondition(t, reason, messageFormat, messageArgs...)) -} - -// MarkFalse sets Status=False for the condition with the given type. -func MarkFalse(to Setter, t conditionsapi.ConditionType, reason string, severity conditionsapi.ConditionSeverity, messageFormat string, messageArgs ...any) { - Set(to, FalseCondition(t, reason, severity, messageFormat, messageArgs...)) -} - -// SetSummary sets a Ready condition with the summary of all the conditions existing -// on an object. If the object does not have other conditions, no summary condition is generated. -func SetSummary(to Setter, options ...MergeOption) { - Set(to, summary(to, options...)) -} - -// SetMirror creates a new condition by mirroring the Ready condition from a dependent object; -// if the Ready condition does not exists in the source object, no target conditions is generated. -func SetMirror(to Setter, targetCondition conditionsapi.ConditionType, from Getter, options ...MirrorOptions) { - Set(to, mirror(from, targetCondition, options...)) -} - -// SetAggregate creates a new condition with the aggregation of all the Ready condition -// from a list of dependent objects; if the Ready condition does not exists in one of the source object, -// the object is excluded from the aggregation; if none of the source object have ready condition, -// no target conditions is generated. -func SetAggregate(to Setter, targetCondition conditionsapi.ConditionType, from []Getter, options ...MergeOption) { - Set(to, aggregate(from, targetCondition, options...)) -} - -// Delete deletes the condition with the given type. -func Delete(to Setter, t conditionsapi.ConditionType) { - if to == nil { - return - } - - conditions := to.GetConditions() - newConditions := make(conditionsapi.Conditions, 0, len(conditions)) - for _, condition := range conditions { - if condition.Type != t { - newConditions = append(newConditions, condition) - } - } - to.SetConditions(newConditions) -} - -// lexicographicLess returns true if a condition is less than another with regards to the -// to order of conditions designed for convenience of the consumer, i.e. kubectl. -// According to this order the Ready condition always goes first, followed by all the other -// conditions sorted by Type. -func lexicographicLess(i, j *conditionsapi.Condition) bool { - return (i.Type == conditionsapi.ReadyCondition || i.Type < j.Type) && j.Type != conditionsapi.ReadyCondition -} - -// hasSameState returns true if a condition has the same state of another; state is defined -// by the union of following fields: Type, Status, Reason, Severity and Message (it excludes LastTransitionTime). -func hasSameState(i, j *conditionsapi.Condition) bool { - return i.Type == j.Type && - i.Status == j.Status && - i.Reason == j.Reason && - i.Severity == j.Severity && - i.Message == j.Message -} diff --git a/sdk/apis/third_party/conditions/util/conditions/setter_test.go b/sdk/apis/third_party/conditions/util/conditions/setter_test.go deleted file mode 100644 index 688b85da0..000000000 --- a/sdk/apis/third_party/conditions/util/conditions/setter_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* -Copyright 2020 The Kubernetes 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 conditions - -import ( - "errors" - "testing" - "time" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - conditionsapi "github.com/kube-bind/kube-bind/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" - - . "github.com/onsi/gomega" -) - -func TestHasSameState(t *testing.T) { - g := NewWithT(t) - - // same condition - falseInfo2 := falseInfo1.DeepCopy() - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeTrue()) - - // different LastTransitionTime does not impact state - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.LastTransitionTime = metav1.NewTime(time.Date(1900, time.November, 10, 23, 0, 0, 0, time.UTC)) - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeTrue()) - - // different Type, Status, Reason, Severity and Message determine different state - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.Type = "another type" - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeFalse()) - - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.Status = corev1.ConditionTrue - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeFalse()) - - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.Severity = conditionsapi.ConditionSeverityWarning - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeFalse()) - - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.Reason = "another severity" - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeFalse()) - - falseInfo2 = falseInfo1.DeepCopy() - falseInfo2.Message = "another message" - g.Expect(hasSameState(falseInfo1, falseInfo2)).To(BeFalse()) -} - -func TestLexicographicLess(t *testing.T) { - g := NewWithT(t) - - // alphabetical order of Type is respected - a := TrueCondition("A") - b := TrueCondition("B") - g.Expect(lexicographicLess(a, b)).To(BeTrue()) - - a = TrueCondition("B") - b = TrueCondition("A") - g.Expect(lexicographicLess(a, b)).To(BeFalse()) - - // Ready condition is treated as an exception and always goes first - a = TrueCondition(conditionsapi.ReadyCondition) - b = TrueCondition("A") - g.Expect(lexicographicLess(a, b)).To(BeTrue()) - - a = TrueCondition("A") - b = TrueCondition(conditionsapi.ReadyCondition) - g.Expect(lexicographicLess(a, b)).To(BeFalse()) -} - -func TestSet(t *testing.T) { - a := TrueCondition("a") - b := TrueCondition("b") - ready := TrueCondition(conditionsapi.ReadyCondition) - - tests := []struct { - name string - to Setter - condition *conditionsapi.Condition - want conditionsapi.Conditions - }{ - { - name: "Set adds a condition", - to: setterWithConditions(), - condition: a, - want: conditionList(a), - }, - { - name: "Set adds more conditions", - to: setterWithConditions(a), - condition: b, - want: conditionList(a, b), - }, - { - name: "Set does not duplicate existing conditions", - to: setterWithConditions(a, b), - condition: a, - want: conditionList(a, b), - }, - { - name: "Set sorts conditions in lexicographic order", - to: setterWithConditions(b, a), - condition: ready, - want: conditionList(ready, a, b), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - Set(tt.to, tt.condition) - - g.Expect(tt.to.GetConditions()).To(haveSameConditionsOf(tt.want)) - }) - } -} - -func TestSetLastTransitionTime(t *testing.T) { - x := metav1.Date(2012, time.January, 1, 12, 15, 30, 5e8, time.UTC) - - foo := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityInfo, "message foo") - fooWithLastTransitionTime := FalseCondition("foo", "reason foo", conditionsapi.ConditionSeverityInfo, "message foo") - fooWithLastTransitionTime.LastTransitionTime = x - fooWithAnotherState := TrueCondition("foo") - - tests := []struct { - name string - to Setter - new *conditionsapi.Condition - LastTransitionTimeCheck func(*WithT, metav1.Time) - }{ - { - name: "Set a condition that does not exists should set the last transition time if not defined", - to: setterWithConditions(), - new: foo, - LastTransitionTimeCheck: func(g *WithT, lastTransitionTime metav1.Time) { - g.Expect(lastTransitionTime).ToNot(BeZero()) - }, - }, - { - name: "Set a condition that does not exists should preserve the last transition time if defined", - to: setterWithConditions(), - new: fooWithLastTransitionTime, - LastTransitionTimeCheck: func(g *WithT, lastTransitionTime metav1.Time) { - g.Expect(lastTransitionTime).To(Equal(x)) - }, - }, - { - name: "Set a condition that already exists with the same state should preserves the last transition time", - to: setterWithConditions(fooWithLastTransitionTime), - new: foo, - LastTransitionTimeCheck: func(g *WithT, lastTransitionTime metav1.Time) { - g.Expect(lastTransitionTime).To(Equal(x)) - }, - }, - { - name: "Set a condition that already exists but with different state should changes the last transition time", - to: setterWithConditions(fooWithLastTransitionTime), - new: fooWithAnotherState, - LastTransitionTimeCheck: func(g *WithT, lastTransitionTime metav1.Time) { - g.Expect(lastTransitionTime).ToNot(Equal(x)) - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - g := NewWithT(t) - - Set(tt.to, tt.new) - - tt.LastTransitionTimeCheck(g, Get(tt.to, "foo").LastTransitionTime) - }) - } -} - -func TestMarkMethods(t *testing.T) { - g := NewWithT(t) - - cluster := newConditioned("test") - - // test MarkTrue - MarkTrue(cluster, "conditionFoo") - g.Expect(Get(cluster, "conditionFoo")).To(HaveSameStateOf(&conditionsapi.Condition{ - Type: "conditionFoo", - Status: corev1.ConditionTrue, - })) - - // test MarkFalse - MarkFalse(cluster, "conditionBar", "reasonBar", conditionsapi.ConditionSeverityError, "messageBar") - g.Expect(Get(cluster, "conditionBar")).To(HaveSameStateOf(&conditionsapi.Condition{ - Type: "conditionBar", - Status: corev1.ConditionFalse, - Severity: conditionsapi.ConditionSeverityError, - Reason: "reasonBar", - Message: "messageBar", - })) - - // test MarkUnknown - MarkUnknown(cluster, "conditionBaz", "reasonBaz", "messageBaz") - g.Expect(Get(cluster, "conditionBaz")).To(HaveSameStateOf(&conditionsapi.Condition{ - Type: "conditionBaz", - Status: corev1.ConditionUnknown, - Reason: "reasonBaz", - Message: "messageBaz", - })) -} - -func TestSetSummary(t *testing.T) { - g := NewWithT(t) - target := setterWithConditions(TrueCondition("foo")) - - SetSummary(target) - - g.Expect(Has(target, conditionsapi.ReadyCondition)).To(BeTrue()) -} - -func TestSetMirror(t *testing.T) { - g := NewWithT(t) - source := getterWithConditions(TrueCondition(conditionsapi.ReadyCondition)) - target := setterWithConditions() - - SetMirror(target, "foo", source) - - g.Expect(Has(target, "foo")).To(BeTrue()) -} - -func TestSetAggregate(t *testing.T) { - g := NewWithT(t) - source1 := getterWithConditions(TrueCondition(conditionsapi.ReadyCondition)) - source2 := getterWithConditions(TrueCondition(conditionsapi.ReadyCondition)) - target := setterWithConditions() - - SetAggregate(target, "foo", []Getter{source1, source2}) - - g.Expect(Has(target, "foo")).To(BeTrue()) -} - -func setterWithConditions(conditions ...*conditionsapi.Condition) Setter { - obj := newConditioned("test") - obj.SetConditions(conditionList(conditions...)) - return obj -} - -func haveSameConditionsOf(expected conditionsapi.Conditions) types.GomegaMatcher { - return &ConditionsMatcher{ - Expected: expected, - } -} - -type ConditionsMatcher struct { - Expected conditionsapi.Conditions -} - -func (matcher *ConditionsMatcher) Match(actual any) (success bool, err error) { - actualConditions, ok := actual.(conditionsapi.Conditions) - if !ok { - return false, errors.New("value should be a conditions list") - } - - if len(actualConditions) != len(matcher.Expected) { - return false, nil - } - - for i := range actualConditions { - if !hasSameState(&actualConditions[i], &matcher.Expected[i]) { - return false, nil - } - } - return true, nil -} - -func (matcher *ConditionsMatcher) FailureMessage(actual any) (message string) { - return format.Message(actual, "to have the same conditions of", matcher.Expected) -} -func (matcher *ConditionsMatcher) NegatedFailureMessage(actual any) (message string) { - return format.Message(actual, "not to have the same conditions of", matcher.Expected) -} diff --git a/sdk/client/clientset/versioned/clientset.go b/sdk/client/clientset/versioned/clientset.go deleted file mode 100644 index 18c5494c9..000000000 --- a/sdk/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package versioned - -import ( - fmt "fmt" - http "net/http" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - KubeBindV1alpha1() kubebindv1alpha1.KubeBindV1alpha1Interface - KubeBindV1alpha2() kubebindv1alpha2.KubeBindV1alpha2Interface -} - -// Clientset contains the clients for groups. -type Clientset struct { - *discovery.DiscoveryClient - kubeBindV1alpha1 *kubebindv1alpha1.KubeBindV1alpha1Client - kubeBindV1alpha2 *kubebindv1alpha2.KubeBindV1alpha2Client -} - -// KubeBindV1alpha1 retrieves the KubeBindV1alpha1Client -func (c *Clientset) KubeBindV1alpha1() kubebindv1alpha1.KubeBindV1alpha1Interface { - return c.kubeBindV1alpha1 -} - -// KubeBindV1alpha2 retrieves the KubeBindV1alpha2Client -func (c *Clientset) KubeBindV1alpha2() kubebindv1alpha2.KubeBindV1alpha2Interface { - return c.kubeBindV1alpha2 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), -// where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - - if configShallowCopy.UserAgent == "" { - configShallowCopy.UserAgent = rest.DefaultKubernetesUserAgent() - } - - // share the transport between all clients - httpClient, err := rest.HTTPClientFor(&configShallowCopy) - if err != nil { - return nil, err - } - - return NewForConfigAndClient(&configShallowCopy, httpClient) -} - -// NewForConfigAndClient creates a new Clientset for the given config and http client. -// Note the http client provided takes precedence over the configured transport values. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfigAndClient will generate a rate-limiter in configShallowCopy. -func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - - var cs Clientset - var err error - cs.kubeBindV1alpha1, err = kubebindv1alpha1.NewForConfigAndClient(&configShallowCopy, httpClient) - if err != nil { - return nil, err - } - cs.kubeBindV1alpha2, err = kubebindv1alpha2.NewForConfigAndClient(&configShallowCopy, httpClient) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - cs, err := NewForConfig(c) - if err != nil { - panic(err) - } - return cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.kubeBindV1alpha1 = kubebindv1alpha1.New(c) - cs.kubeBindV1alpha2 = kubebindv1alpha2.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/sdk/client/clientset/versioned/fake/clientset_generated.go b/sdk/client/clientset/versioned/fake/clientset_generated.go deleted file mode 100644 index 23e4fa996..000000000 --- a/sdk/client/clientset/versioned/fake/clientset_generated.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - clientset "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - fakekubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - fakekubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/discovery" - fakediscovery "k8s.io/client-go/discovery/fake" - "k8s.io/client-go/testing" -) - -// NewSimpleClientset returns a clientset that will respond with the provided objects. -// It's backed by a very simple object tracker that processes creates, updates and deletions as-is, -// without applying any field management, validations and/or defaults. It shouldn't be considered a replacement -// for a real clientset and is mostly useful in simple unit tests. -// -// Deprecated: NewClientset replaces this with support for field management, which significantly improves -// server side apply testing. NewClientset is only available when apply configurations are generated (e.g. -// via --with-applyconfig). -func NewSimpleClientset(objects ...runtime.Object) *Clientset { - o := testing.NewObjectTracker(scheme, codecs.UniversalDecoder()) - for _, obj := range objects { - if err := o.Add(obj); err != nil { - panic(err) - } - } - - cs := &Clientset{tracker: o} - cs.discovery = &fakediscovery.FakeDiscovery{Fake: &cs.Fake} - cs.AddReactor("*", "*", testing.ObjectReaction(o)) - cs.AddWatchReactor("*", func(action testing.Action) (handled bool, ret watch.Interface, err error) { - var opts metav1.ListOptions - if watchAction, ok := action.(testing.WatchActionImpl); ok { - opts = watchAction.ListOptions - } - gvr := action.GetResource() - ns := action.GetNamespace() - watch, err := o.Watch(gvr, ns, opts) - if err != nil { - return false, nil, err - } - return true, watch, nil - }) - - return cs -} - -// Clientset implements clientset.Interface. Meant to be embedded into a -// struct to get a default implementation. This makes faking out just the method -// you want to test easier. -type Clientset struct { - testing.Fake - discovery *fakediscovery.FakeDiscovery - tracker testing.ObjectTracker -} - -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - return c.discovery -} - -func (c *Clientset) Tracker() testing.ObjectTracker { - return c.tracker -} - -// IsWatchListSemanticsSupported informs the reflector that this client -// doesn't support WatchList semantics. -// -// This is a synthetic method whose sole purpose is to satisfy the optional -// interface check performed by the reflector. -// Returning true signals that WatchList can NOT be used. -// No additional logic is implemented here. -func (c *Clientset) IsWatchListSemanticsUnSupported() bool { - return true -} - -var ( - _ clientset.Interface = &Clientset{} - _ testing.FakeClient = &Clientset{} -) - -// KubeBindV1alpha1 retrieves the KubeBindV1alpha1Client -func (c *Clientset) KubeBindV1alpha1() kubebindv1alpha1.KubeBindV1alpha1Interface { - return &fakekubebindv1alpha1.FakeKubeBindV1alpha1{Fake: &c.Fake} -} - -// KubeBindV1alpha2 retrieves the KubeBindV1alpha2Client -func (c *Clientset) KubeBindV1alpha2() kubebindv1alpha2.KubeBindV1alpha2Interface { - return &fakekubebindv1alpha2.FakeKubeBindV1alpha2{Fake: &c.Fake} -} diff --git a/sdk/client/clientset/versioned/fake/doc.go b/sdk/client/clientset/versioned/fake/doc.go deleted file mode 100644 index ca4191ad7..000000000 --- a/sdk/client/clientset/versioned/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated fake clientset. -package fake diff --git a/sdk/client/clientset/versioned/fake/register.go b/sdk/client/clientset/versioned/fake/register.go deleted file mode 100644 index 12ccd7b59..000000000 --- a/sdk/client/clientset/versioned/fake/register.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) - -var localSchemeBuilder = runtime.SchemeBuilder{ - kubebindv1alpha1.AddToScheme, - kubebindv1alpha2.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(scheme)) -} diff --git a/sdk/client/clientset/versioned/scheme/doc.go b/sdk/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index b5ec927c6..000000000 --- a/sdk/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/sdk/client/clientset/versioned/scheme/register.go b/sdk/client/clientset/versioned/scheme/register.go deleted file mode 100644 index 8dbf25157..000000000 --- a/sdk/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package scheme - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - kubebindv1alpha1.AddToScheme, - kubebindv1alpha2.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicebinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicebinding.go deleted file mode 100644 index 6d5452bfb..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicebinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceBindingsGetter has a method to return a APIServiceBindingInterface. -// A group's client should implement this interface. -type APIServiceBindingsGetter interface { - APIServiceBindings() APIServiceBindingInterface -} - -// APIServiceBindingInterface has methods to work with APIServiceBinding resources. -type APIServiceBindingInterface interface { - Create(ctx context.Context, aPIServiceBinding *kubebindv1alpha1.APIServiceBinding, opts v1.CreateOptions) (*kubebindv1alpha1.APIServiceBinding, error) - Update(ctx context.Context, aPIServiceBinding *kubebindv1alpha1.APIServiceBinding, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceBinding, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceBinding *kubebindv1alpha1.APIServiceBinding, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceBinding, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha1.APIServiceBinding, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha1.APIServiceBindingList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha1.APIServiceBinding, err error) - APIServiceBindingExpansion -} - -// aPIServiceBindings implements APIServiceBindingInterface -type aPIServiceBindings struct { - *gentype.ClientWithList[*kubebindv1alpha1.APIServiceBinding, *kubebindv1alpha1.APIServiceBindingList] -} - -// newAPIServiceBindings returns a APIServiceBindings -func newAPIServiceBindings(c *KubeBindV1alpha1Client) *aPIServiceBindings { - return &aPIServiceBindings{ - gentype.NewClientWithList[*kubebindv1alpha1.APIServiceBinding, *kubebindv1alpha1.APIServiceBindingList]( - "apiservicebindings", - c.RESTClient(), - scheme.ParameterCodec, - "", - func() *kubebindv1alpha1.APIServiceBinding { return &kubebindv1alpha1.APIServiceBinding{} }, - func() *kubebindv1alpha1.APIServiceBindingList { return &kubebindv1alpha1.APIServiceBindingList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexport.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexport.go deleted file mode 100644 index 71920e8d0..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexport.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceExportsGetter has a method to return a APIServiceExportInterface. -// A group's client should implement this interface. -type APIServiceExportsGetter interface { - APIServiceExports(namespace string) APIServiceExportInterface -} - -// APIServiceExportInterface has methods to work with APIServiceExport resources. -type APIServiceExportInterface interface { - Create(ctx context.Context, aPIServiceExport *kubebindv1alpha1.APIServiceExport, opts v1.CreateOptions) (*kubebindv1alpha1.APIServiceExport, error) - Update(ctx context.Context, aPIServiceExport *kubebindv1alpha1.APIServiceExport, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceExport, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceExport *kubebindv1alpha1.APIServiceExport, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceExport, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha1.APIServiceExport, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha1.APIServiceExportList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha1.APIServiceExport, err error) - APIServiceExportExpansion -} - -// aPIServiceExports implements APIServiceExportInterface -type aPIServiceExports struct { - *gentype.ClientWithList[*kubebindv1alpha1.APIServiceExport, *kubebindv1alpha1.APIServiceExportList] -} - -// newAPIServiceExports returns a APIServiceExports -func newAPIServiceExports(c *KubeBindV1alpha1Client, namespace string) *aPIServiceExports { - return &aPIServiceExports{ - gentype.NewClientWithList[*kubebindv1alpha1.APIServiceExport, *kubebindv1alpha1.APIServiceExportList]( - "apiserviceexports", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha1.APIServiceExport { return &kubebindv1alpha1.APIServiceExport{} }, - func() *kubebindv1alpha1.APIServiceExportList { return &kubebindv1alpha1.APIServiceExportList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexportrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexportrequest.go deleted file mode 100644 index c31a7c23c..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiserviceexportrequest.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceExportRequestsGetter has a method to return a APIServiceExportRequestInterface. -// A group's client should implement this interface. -type APIServiceExportRequestsGetter interface { - APIServiceExportRequests(namespace string) APIServiceExportRequestInterface -} - -// APIServiceExportRequestInterface has methods to work with APIServiceExportRequest resources. -type APIServiceExportRequestInterface interface { - Create(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha1.APIServiceExportRequest, opts v1.CreateOptions) (*kubebindv1alpha1.APIServiceExportRequest, error) - Update(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha1.APIServiceExportRequest, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceExportRequest, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha1.APIServiceExportRequest, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceExportRequest, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha1.APIServiceExportRequest, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha1.APIServiceExportRequestList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha1.APIServiceExportRequest, err error) - APIServiceExportRequestExpansion -} - -// aPIServiceExportRequests implements APIServiceExportRequestInterface -type aPIServiceExportRequests struct { - *gentype.ClientWithList[*kubebindv1alpha1.APIServiceExportRequest, *kubebindv1alpha1.APIServiceExportRequestList] -} - -// newAPIServiceExportRequests returns a APIServiceExportRequests -func newAPIServiceExportRequests(c *KubeBindV1alpha1Client, namespace string) *aPIServiceExportRequests { - return &aPIServiceExportRequests{ - gentype.NewClientWithList[*kubebindv1alpha1.APIServiceExportRequest, *kubebindv1alpha1.APIServiceExportRequestList]( - "apiserviceexportrequests", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha1.APIServiceExportRequest { return &kubebindv1alpha1.APIServiceExportRequest{} }, - func() *kubebindv1alpha1.APIServiceExportRequestList { - return &kubebindv1alpha1.APIServiceExportRequestList{} - }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicenamespace.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicenamespace.go deleted file mode 100644 index a966be151..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/apiservicenamespace.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceNamespacesGetter has a method to return a APIServiceNamespaceInterface. -// A group's client should implement this interface. -type APIServiceNamespacesGetter interface { - APIServiceNamespaces(namespace string) APIServiceNamespaceInterface -} - -// APIServiceNamespaceInterface has methods to work with APIServiceNamespace resources. -type APIServiceNamespaceInterface interface { - Create(ctx context.Context, aPIServiceNamespace *kubebindv1alpha1.APIServiceNamespace, opts v1.CreateOptions) (*kubebindv1alpha1.APIServiceNamespace, error) - Update(ctx context.Context, aPIServiceNamespace *kubebindv1alpha1.APIServiceNamespace, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceNamespace, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceNamespace *kubebindv1alpha1.APIServiceNamespace, opts v1.UpdateOptions) (*kubebindv1alpha1.APIServiceNamespace, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha1.APIServiceNamespace, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha1.APIServiceNamespaceList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha1.APIServiceNamespace, err error) - APIServiceNamespaceExpansion -} - -// aPIServiceNamespaces implements APIServiceNamespaceInterface -type aPIServiceNamespaces struct { - *gentype.ClientWithList[*kubebindv1alpha1.APIServiceNamespace, *kubebindv1alpha1.APIServiceNamespaceList] -} - -// newAPIServiceNamespaces returns a APIServiceNamespaces -func newAPIServiceNamespaces(c *KubeBindV1alpha1Client, namespace string) *aPIServiceNamespaces { - return &aPIServiceNamespaces{ - gentype.NewClientWithList[*kubebindv1alpha1.APIServiceNamespace, *kubebindv1alpha1.APIServiceNamespaceList]( - "apiservicenamespaces", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha1.APIServiceNamespace { return &kubebindv1alpha1.APIServiceNamespace{} }, - func() *kubebindv1alpha1.APIServiceNamespaceList { return &kubebindv1alpha1.APIServiceNamespaceList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/clusterbinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/clusterbinding.go deleted file mode 100644 index 22949e4c9..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/clusterbinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// ClusterBindingsGetter has a method to return a ClusterBindingInterface. -// A group's client should implement this interface. -type ClusterBindingsGetter interface { - ClusterBindings(namespace string) ClusterBindingInterface -} - -// ClusterBindingInterface has methods to work with ClusterBinding resources. -type ClusterBindingInterface interface { - Create(ctx context.Context, clusterBinding *kubebindv1alpha1.ClusterBinding, opts v1.CreateOptions) (*kubebindv1alpha1.ClusterBinding, error) - Update(ctx context.Context, clusterBinding *kubebindv1alpha1.ClusterBinding, opts v1.UpdateOptions) (*kubebindv1alpha1.ClusterBinding, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, clusterBinding *kubebindv1alpha1.ClusterBinding, opts v1.UpdateOptions) (*kubebindv1alpha1.ClusterBinding, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha1.ClusterBinding, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha1.ClusterBindingList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha1.ClusterBinding, err error) - ClusterBindingExpansion -} - -// clusterBindings implements ClusterBindingInterface -type clusterBindings struct { - *gentype.ClientWithList[*kubebindv1alpha1.ClusterBinding, *kubebindv1alpha1.ClusterBindingList] -} - -// newClusterBindings returns a ClusterBindings -func newClusterBindings(c *KubeBindV1alpha1Client, namespace string) *clusterBindings { - return &clusterBindings{ - gentype.NewClientWithList[*kubebindv1alpha1.ClusterBinding, *kubebindv1alpha1.ClusterBindingList]( - "clusterbindings", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha1.ClusterBinding { return &kubebindv1alpha1.ClusterBinding{} }, - func() *kubebindv1alpha1.ClusterBindingList { return &kubebindv1alpha1.ClusterBindingList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/doc.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/doc.go deleted file mode 100644 index a0ee34800..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicebinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicebinding.go deleted file mode 100644 index f03c5cf41..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicebinding.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceBindings implements APIServiceBindingInterface -type fakeAPIServiceBindings struct { - *gentype.FakeClientWithList[*v1alpha1.APIServiceBinding, *v1alpha1.APIServiceBindingList] - Fake *FakeKubeBindV1alpha1 -} - -func newFakeAPIServiceBindings(fake *FakeKubeBindV1alpha1) kubebindv1alpha1.APIServiceBindingInterface { - return &fakeAPIServiceBindings{ - gentype.NewFakeClientWithList[*v1alpha1.APIServiceBinding, *v1alpha1.APIServiceBindingList]( - fake.Fake, - "", - v1alpha1.SchemeGroupVersion.WithResource("apiservicebindings"), - v1alpha1.SchemeGroupVersion.WithKind("APIServiceBinding"), - func() *v1alpha1.APIServiceBinding { return &v1alpha1.APIServiceBinding{} }, - func() *v1alpha1.APIServiceBindingList { return &v1alpha1.APIServiceBindingList{} }, - func(dst, src *v1alpha1.APIServiceBindingList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.APIServiceBindingList) []*v1alpha1.APIServiceBinding { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha1.APIServiceBindingList, items []*v1alpha1.APIServiceBinding) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexport.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexport.go deleted file mode 100644 index a5c13ea9e..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexport.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceExports implements APIServiceExportInterface -type fakeAPIServiceExports struct { - *gentype.FakeClientWithList[*v1alpha1.APIServiceExport, *v1alpha1.APIServiceExportList] - Fake *FakeKubeBindV1alpha1 -} - -func newFakeAPIServiceExports(fake *FakeKubeBindV1alpha1, namespace string) kubebindv1alpha1.APIServiceExportInterface { - return &fakeAPIServiceExports{ - gentype.NewFakeClientWithList[*v1alpha1.APIServiceExport, *v1alpha1.APIServiceExportList]( - fake.Fake, - namespace, - v1alpha1.SchemeGroupVersion.WithResource("apiserviceexports"), - v1alpha1.SchemeGroupVersion.WithKind("APIServiceExport"), - func() *v1alpha1.APIServiceExport { return &v1alpha1.APIServiceExport{} }, - func() *v1alpha1.APIServiceExportList { return &v1alpha1.APIServiceExportList{} }, - func(dst, src *v1alpha1.APIServiceExportList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.APIServiceExportList) []*v1alpha1.APIServiceExport { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha1.APIServiceExportList, items []*v1alpha1.APIServiceExport) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexportrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexportrequest.go deleted file mode 100644 index 26b5d8c65..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiserviceexportrequest.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceExportRequests implements APIServiceExportRequestInterface -type fakeAPIServiceExportRequests struct { - *gentype.FakeClientWithList[*v1alpha1.APIServiceExportRequest, *v1alpha1.APIServiceExportRequestList] - Fake *FakeKubeBindV1alpha1 -} - -func newFakeAPIServiceExportRequests(fake *FakeKubeBindV1alpha1, namespace string) kubebindv1alpha1.APIServiceExportRequestInterface { - return &fakeAPIServiceExportRequests{ - gentype.NewFakeClientWithList[*v1alpha1.APIServiceExportRequest, *v1alpha1.APIServiceExportRequestList]( - fake.Fake, - namespace, - v1alpha1.SchemeGroupVersion.WithResource("apiserviceexportrequests"), - v1alpha1.SchemeGroupVersion.WithKind("APIServiceExportRequest"), - func() *v1alpha1.APIServiceExportRequest { return &v1alpha1.APIServiceExportRequest{} }, - func() *v1alpha1.APIServiceExportRequestList { return &v1alpha1.APIServiceExportRequestList{} }, - func(dst, src *v1alpha1.APIServiceExportRequestList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.APIServiceExportRequestList) []*v1alpha1.APIServiceExportRequest { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha1.APIServiceExportRequestList, items []*v1alpha1.APIServiceExportRequest) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicenamespace.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicenamespace.go deleted file mode 100644 index 37e8a2aa7..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_apiservicenamespace.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceNamespaces implements APIServiceNamespaceInterface -type fakeAPIServiceNamespaces struct { - *gentype.FakeClientWithList[*v1alpha1.APIServiceNamespace, *v1alpha1.APIServiceNamespaceList] - Fake *FakeKubeBindV1alpha1 -} - -func newFakeAPIServiceNamespaces(fake *FakeKubeBindV1alpha1, namespace string) kubebindv1alpha1.APIServiceNamespaceInterface { - return &fakeAPIServiceNamespaces{ - gentype.NewFakeClientWithList[*v1alpha1.APIServiceNamespace, *v1alpha1.APIServiceNamespaceList]( - fake.Fake, - namespace, - v1alpha1.SchemeGroupVersion.WithResource("apiservicenamespaces"), - v1alpha1.SchemeGroupVersion.WithKind("APIServiceNamespace"), - func() *v1alpha1.APIServiceNamespace { return &v1alpha1.APIServiceNamespace{} }, - func() *v1alpha1.APIServiceNamespaceList { return &v1alpha1.APIServiceNamespaceList{} }, - func(dst, src *v1alpha1.APIServiceNamespaceList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.APIServiceNamespaceList) []*v1alpha1.APIServiceNamespace { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha1.APIServiceNamespaceList, items []*v1alpha1.APIServiceNamespace) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_clusterbinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_clusterbinding.go deleted file mode 100644 index d37540d9c..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_clusterbinding.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - gentype "k8s.io/client-go/gentype" -) - -// fakeClusterBindings implements ClusterBindingInterface -type fakeClusterBindings struct { - *gentype.FakeClientWithList[*v1alpha1.ClusterBinding, *v1alpha1.ClusterBindingList] - Fake *FakeKubeBindV1alpha1 -} - -func newFakeClusterBindings(fake *FakeKubeBindV1alpha1, namespace string) kubebindv1alpha1.ClusterBindingInterface { - return &fakeClusterBindings{ - gentype.NewFakeClientWithList[*v1alpha1.ClusterBinding, *v1alpha1.ClusterBindingList]( - fake.Fake, - namespace, - v1alpha1.SchemeGroupVersion.WithResource("clusterbindings"), - v1alpha1.SchemeGroupVersion.WithKind("ClusterBinding"), - func() *v1alpha1.ClusterBinding { return &v1alpha1.ClusterBinding{} }, - func() *v1alpha1.ClusterBindingList { return &v1alpha1.ClusterBindingList{} }, - func(dst, src *v1alpha1.ClusterBindingList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha1.ClusterBindingList) []*v1alpha1.ClusterBinding { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha1.ClusterBindingList, items []*v1alpha1.ClusterBinding) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_kubebind_client.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_kubebind_client.go deleted file mode 100644 index 86ba5adc0..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/fake/fake_kubebind_client.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeKubeBindV1alpha1 struct { - *testing.Fake -} - -func (c *FakeKubeBindV1alpha1) APIServiceBindings() v1alpha1.APIServiceBindingInterface { - return newFakeAPIServiceBindings(c) -} - -func (c *FakeKubeBindV1alpha1) APIServiceExports(namespace string) v1alpha1.APIServiceExportInterface { - return newFakeAPIServiceExports(c, namespace) -} - -func (c *FakeKubeBindV1alpha1) APIServiceExportRequests(namespace string) v1alpha1.APIServiceExportRequestInterface { - return newFakeAPIServiceExportRequests(c, namespace) -} - -func (c *FakeKubeBindV1alpha1) APIServiceNamespaces(namespace string) v1alpha1.APIServiceNamespaceInterface { - return newFakeAPIServiceNamespaces(c, namespace) -} - -func (c *FakeKubeBindV1alpha1) ClusterBindings(namespace string) v1alpha1.ClusterBindingInterface { - return newFakeClusterBindings(c, namespace) -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeKubeBindV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/generated_expansion.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/generated_expansion.go deleted file mode 100644 index 3b60d85b6..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type APIServiceBindingExpansion interface{} - -type APIServiceExportExpansion interface{} - -type APIServiceExportRequestExpansion interface{} - -type APIServiceNamespaceExpansion interface{} - -type ClusterBindingExpansion interface{} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/kubebind_client.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/kubebind_client.go deleted file mode 100644 index ee181a374..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha1/kubebind_client.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - http "net/http" - - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type KubeBindV1alpha1Interface interface { - RESTClient() rest.Interface - APIServiceBindingsGetter - APIServiceExportsGetter - APIServiceExportRequestsGetter - APIServiceNamespacesGetter - ClusterBindingsGetter -} - -// KubeBindV1alpha1Client is used to interact with features provided by the kube-bind.io group. -type KubeBindV1alpha1Client struct { - restClient rest.Interface -} - -func (c *KubeBindV1alpha1Client) APIServiceBindings() APIServiceBindingInterface { - return newAPIServiceBindings(c) -} - -func (c *KubeBindV1alpha1Client) APIServiceExports(namespace string) APIServiceExportInterface { - return newAPIServiceExports(c, namespace) -} - -func (c *KubeBindV1alpha1Client) APIServiceExportRequests(namespace string) APIServiceExportRequestInterface { - return newAPIServiceExportRequests(c, namespace) -} - -func (c *KubeBindV1alpha1Client) APIServiceNamespaces(namespace string) APIServiceNamespaceInterface { - return newAPIServiceNamespaces(c, namespace) -} - -func (c *KubeBindV1alpha1Client) ClusterBindings(namespace string) ClusterBindingInterface { - return newClusterBindings(c, namespace) -} - -// NewForConfig creates a new KubeBindV1alpha1Client for the given config. -// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), -// where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*KubeBindV1alpha1Client, error) { - config := *c - setConfigDefaults(&config) - httpClient, err := rest.HTTPClientFor(&config) - if err != nil { - return nil, err - } - return NewForConfigAndClient(&config, httpClient) -} - -// NewForConfigAndClient creates a new KubeBindV1alpha1Client for the given config and http client. -// Note the http client provided takes precedence over the configured transport values. -func NewForConfigAndClient(c *rest.Config, h *http.Client) (*KubeBindV1alpha1Client, error) { - config := *c - setConfigDefaults(&config) - client, err := rest.RESTClientForConfigAndClient(&config, h) - if err != nil { - return nil, err - } - return &KubeBindV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new KubeBindV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *KubeBindV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new KubeBindV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *KubeBindV1alpha1Client { - return &KubeBindV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) { - gv := kubebindv1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *KubeBindV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebinding.go deleted file mode 100644 index fca5cfb57..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceBindingsGetter has a method to return a APIServiceBindingInterface. -// A group's client should implement this interface. -type APIServiceBindingsGetter interface { - APIServiceBindings() APIServiceBindingInterface -} - -// APIServiceBindingInterface has methods to work with APIServiceBinding resources. -type APIServiceBindingInterface interface { - Create(ctx context.Context, aPIServiceBinding *kubebindv1alpha2.APIServiceBinding, opts v1.CreateOptions) (*kubebindv1alpha2.APIServiceBinding, error) - Update(ctx context.Context, aPIServiceBinding *kubebindv1alpha2.APIServiceBinding, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceBinding, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceBinding *kubebindv1alpha2.APIServiceBinding, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceBinding, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.APIServiceBinding, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.APIServiceBindingList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.APIServiceBinding, err error) - APIServiceBindingExpansion -} - -// aPIServiceBindings implements APIServiceBindingInterface -type aPIServiceBindings struct { - *gentype.ClientWithList[*kubebindv1alpha2.APIServiceBinding, *kubebindv1alpha2.APIServiceBindingList] -} - -// newAPIServiceBindings returns a APIServiceBindings -func newAPIServiceBindings(c *KubeBindV1alpha2Client) *aPIServiceBindings { - return &aPIServiceBindings{ - gentype.NewClientWithList[*kubebindv1alpha2.APIServiceBinding, *kubebindv1alpha2.APIServiceBindingList]( - "apiservicebindings", - c.RESTClient(), - scheme.ParameterCodec, - "", - func() *kubebindv1alpha2.APIServiceBinding { return &kubebindv1alpha2.APIServiceBinding{} }, - func() *kubebindv1alpha2.APIServiceBindingList { return &kubebindv1alpha2.APIServiceBindingList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebindingbundle.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebindingbundle.go deleted file mode 100644 index 032a552f2..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicebindingbundle.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceBindingBundlesGetter has a method to return a APIServiceBindingBundleInterface. -// A group's client should implement this interface. -type APIServiceBindingBundlesGetter interface { - APIServiceBindingBundles() APIServiceBindingBundleInterface -} - -// APIServiceBindingBundleInterface has methods to work with APIServiceBindingBundle resources. -type APIServiceBindingBundleInterface interface { - Create(ctx context.Context, aPIServiceBindingBundle *kubebindv1alpha2.APIServiceBindingBundle, opts v1.CreateOptions) (*kubebindv1alpha2.APIServiceBindingBundle, error) - Update(ctx context.Context, aPIServiceBindingBundle *kubebindv1alpha2.APIServiceBindingBundle, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceBindingBundle, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceBindingBundle *kubebindv1alpha2.APIServiceBindingBundle, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceBindingBundle, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.APIServiceBindingBundle, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.APIServiceBindingBundleList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.APIServiceBindingBundle, err error) - APIServiceBindingBundleExpansion -} - -// aPIServiceBindingBundles implements APIServiceBindingBundleInterface -type aPIServiceBindingBundles struct { - *gentype.ClientWithList[*kubebindv1alpha2.APIServiceBindingBundle, *kubebindv1alpha2.APIServiceBindingBundleList] -} - -// newAPIServiceBindingBundles returns a APIServiceBindingBundles -func newAPIServiceBindingBundles(c *KubeBindV1alpha2Client) *aPIServiceBindingBundles { - return &aPIServiceBindingBundles{ - gentype.NewClientWithList[*kubebindv1alpha2.APIServiceBindingBundle, *kubebindv1alpha2.APIServiceBindingBundleList]( - "apiservicebindingbundles", - c.RESTClient(), - scheme.ParameterCodec, - "", - func() *kubebindv1alpha2.APIServiceBindingBundle { return &kubebindv1alpha2.APIServiceBindingBundle{} }, - func() *kubebindv1alpha2.APIServiceBindingBundleList { - return &kubebindv1alpha2.APIServiceBindingBundleList{} - }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexport.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexport.go deleted file mode 100644 index fb6eaed42..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexport.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceExportsGetter has a method to return a APIServiceExportInterface. -// A group's client should implement this interface. -type APIServiceExportsGetter interface { - APIServiceExports(namespace string) APIServiceExportInterface -} - -// APIServiceExportInterface has methods to work with APIServiceExport resources. -type APIServiceExportInterface interface { - Create(ctx context.Context, aPIServiceExport *kubebindv1alpha2.APIServiceExport, opts v1.CreateOptions) (*kubebindv1alpha2.APIServiceExport, error) - Update(ctx context.Context, aPIServiceExport *kubebindv1alpha2.APIServiceExport, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceExport, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceExport *kubebindv1alpha2.APIServiceExport, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceExport, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.APIServiceExport, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.APIServiceExportList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.APIServiceExport, err error) - APIServiceExportExpansion -} - -// aPIServiceExports implements APIServiceExportInterface -type aPIServiceExports struct { - *gentype.ClientWithList[*kubebindv1alpha2.APIServiceExport, *kubebindv1alpha2.APIServiceExportList] -} - -// newAPIServiceExports returns a APIServiceExports -func newAPIServiceExports(c *KubeBindV1alpha2Client, namespace string) *aPIServiceExports { - return &aPIServiceExports{ - gentype.NewClientWithList[*kubebindv1alpha2.APIServiceExport, *kubebindv1alpha2.APIServiceExportList]( - "apiserviceexports", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.APIServiceExport { return &kubebindv1alpha2.APIServiceExport{} }, - func() *kubebindv1alpha2.APIServiceExportList { return &kubebindv1alpha2.APIServiceExportList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexportrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexportrequest.go deleted file mode 100644 index df400ff58..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiserviceexportrequest.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceExportRequestsGetter has a method to return a APIServiceExportRequestInterface. -// A group's client should implement this interface. -type APIServiceExportRequestsGetter interface { - APIServiceExportRequests(namespace string) APIServiceExportRequestInterface -} - -// APIServiceExportRequestInterface has methods to work with APIServiceExportRequest resources. -type APIServiceExportRequestInterface interface { - Create(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha2.APIServiceExportRequest, opts v1.CreateOptions) (*kubebindv1alpha2.APIServiceExportRequest, error) - Update(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha2.APIServiceExportRequest, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceExportRequest, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceExportRequest *kubebindv1alpha2.APIServiceExportRequest, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceExportRequest, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.APIServiceExportRequest, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.APIServiceExportRequestList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.APIServiceExportRequest, err error) - APIServiceExportRequestExpansion -} - -// aPIServiceExportRequests implements APIServiceExportRequestInterface -type aPIServiceExportRequests struct { - *gentype.ClientWithList[*kubebindv1alpha2.APIServiceExportRequest, *kubebindv1alpha2.APIServiceExportRequestList] -} - -// newAPIServiceExportRequests returns a APIServiceExportRequests -func newAPIServiceExportRequests(c *KubeBindV1alpha2Client, namespace string) *aPIServiceExportRequests { - return &aPIServiceExportRequests{ - gentype.NewClientWithList[*kubebindv1alpha2.APIServiceExportRequest, *kubebindv1alpha2.APIServiceExportRequestList]( - "apiserviceexportrequests", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.APIServiceExportRequest { return &kubebindv1alpha2.APIServiceExportRequest{} }, - func() *kubebindv1alpha2.APIServiceExportRequestList { - return &kubebindv1alpha2.APIServiceExportRequestList{} - }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicenamespace.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicenamespace.go deleted file mode 100644 index 6dcf3f70a..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/apiservicenamespace.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// APIServiceNamespacesGetter has a method to return a APIServiceNamespaceInterface. -// A group's client should implement this interface. -type APIServiceNamespacesGetter interface { - APIServiceNamespaces(namespace string) APIServiceNamespaceInterface -} - -// APIServiceNamespaceInterface has methods to work with APIServiceNamespace resources. -type APIServiceNamespaceInterface interface { - Create(ctx context.Context, aPIServiceNamespace *kubebindv1alpha2.APIServiceNamespace, opts v1.CreateOptions) (*kubebindv1alpha2.APIServiceNamespace, error) - Update(ctx context.Context, aPIServiceNamespace *kubebindv1alpha2.APIServiceNamespace, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceNamespace, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, aPIServiceNamespace *kubebindv1alpha2.APIServiceNamespace, opts v1.UpdateOptions) (*kubebindv1alpha2.APIServiceNamespace, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.APIServiceNamespace, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.APIServiceNamespaceList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.APIServiceNamespace, err error) - APIServiceNamespaceExpansion -} - -// aPIServiceNamespaces implements APIServiceNamespaceInterface -type aPIServiceNamespaces struct { - *gentype.ClientWithList[*kubebindv1alpha2.APIServiceNamespace, *kubebindv1alpha2.APIServiceNamespaceList] -} - -// newAPIServiceNamespaces returns a APIServiceNamespaces -func newAPIServiceNamespaces(c *KubeBindV1alpha2Client, namespace string) *aPIServiceNamespaces { - return &aPIServiceNamespaces{ - gentype.NewClientWithList[*kubebindv1alpha2.APIServiceNamespace, *kubebindv1alpha2.APIServiceNamespaceList]( - "apiservicenamespaces", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.APIServiceNamespace { return &kubebindv1alpha2.APIServiceNamespace{} }, - func() *kubebindv1alpha2.APIServiceNamespaceList { return &kubebindv1alpha2.APIServiceNamespaceList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/bindableresourcesrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/bindableresourcesrequest.go deleted file mode 100644 index d9415018f..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/bindableresourcesrequest.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// BindableResourcesRequestsGetter has a method to return a BindableResourcesRequestInterface. -// A group's client should implement this interface. -type BindableResourcesRequestsGetter interface { - BindableResourcesRequests(namespace string) BindableResourcesRequestInterface -} - -// BindableResourcesRequestInterface has methods to work with BindableResourcesRequest resources. -type BindableResourcesRequestInterface interface { - Create(ctx context.Context, bindableResourcesRequest *kubebindv1alpha2.BindableResourcesRequest, opts v1.CreateOptions) (*kubebindv1alpha2.BindableResourcesRequest, error) - Update(ctx context.Context, bindableResourcesRequest *kubebindv1alpha2.BindableResourcesRequest, opts v1.UpdateOptions) (*kubebindv1alpha2.BindableResourcesRequest, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, bindableResourcesRequest *kubebindv1alpha2.BindableResourcesRequest, opts v1.UpdateOptions) (*kubebindv1alpha2.BindableResourcesRequest, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.BindableResourcesRequest, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.BindableResourcesRequestList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.BindableResourcesRequest, err error) - BindableResourcesRequestExpansion -} - -// bindableResourcesRequests implements BindableResourcesRequestInterface -type bindableResourcesRequests struct { - *gentype.ClientWithList[*kubebindv1alpha2.BindableResourcesRequest, *kubebindv1alpha2.BindableResourcesRequestList] -} - -// newBindableResourcesRequests returns a BindableResourcesRequests -func newBindableResourcesRequests(c *KubeBindV1alpha2Client, namespace string) *bindableResourcesRequests { - return &bindableResourcesRequests{ - gentype.NewClientWithList[*kubebindv1alpha2.BindableResourcesRequest, *kubebindv1alpha2.BindableResourcesRequestList]( - "bindableresourcesrequests", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.BindableResourcesRequest { return &kubebindv1alpha2.BindableResourcesRequest{} }, - func() *kubebindv1alpha2.BindableResourcesRequestList { - return &kubebindv1alpha2.BindableResourcesRequestList{} - }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/boundschema.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/boundschema.go deleted file mode 100644 index b45c30d06..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/boundschema.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// BoundSchemasGetter has a method to return a BoundSchemaInterface. -// A group's client should implement this interface. -type BoundSchemasGetter interface { - BoundSchemas(namespace string) BoundSchemaInterface -} - -// BoundSchemaInterface has methods to work with BoundSchema resources. -type BoundSchemaInterface interface { - Create(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema, opts v1.CreateOptions) (*kubebindv1alpha2.BoundSchema, error) - Update(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema, opts v1.UpdateOptions) (*kubebindv1alpha2.BoundSchema, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, boundSchema *kubebindv1alpha2.BoundSchema, opts v1.UpdateOptions) (*kubebindv1alpha2.BoundSchema, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.BoundSchema, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.BoundSchemaList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.BoundSchema, err error) - BoundSchemaExpansion -} - -// boundSchemas implements BoundSchemaInterface -type boundSchemas struct { - *gentype.ClientWithList[*kubebindv1alpha2.BoundSchema, *kubebindv1alpha2.BoundSchemaList] -} - -// newBoundSchemas returns a BoundSchemas -func newBoundSchemas(c *KubeBindV1alpha2Client, namespace string) *boundSchemas { - return &boundSchemas{ - gentype.NewClientWithList[*kubebindv1alpha2.BoundSchema, *kubebindv1alpha2.BoundSchemaList]( - "boundschemas", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.BoundSchema { return &kubebindv1alpha2.BoundSchema{} }, - func() *kubebindv1alpha2.BoundSchemaList { return &kubebindv1alpha2.BoundSchemaList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/cluster.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/cluster.go deleted file mode 100644 index 9a61c664b..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/cluster.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// ClustersGetter has a method to return a ClusterInterface. -// A group's client should implement this interface. -type ClustersGetter interface { - Clusters(namespace string) ClusterInterface -} - -// ClusterInterface has methods to work with Cluster resources. -type ClusterInterface interface { - Create(ctx context.Context, cluster *kubebindv1alpha2.Cluster, opts v1.CreateOptions) (*kubebindv1alpha2.Cluster, error) - Update(ctx context.Context, cluster *kubebindv1alpha2.Cluster, opts v1.UpdateOptions) (*kubebindv1alpha2.Cluster, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, cluster *kubebindv1alpha2.Cluster, opts v1.UpdateOptions) (*kubebindv1alpha2.Cluster, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.Cluster, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.ClusterList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.Cluster, err error) - ClusterExpansion -} - -// clusters implements ClusterInterface -type clusters struct { - *gentype.ClientWithList[*kubebindv1alpha2.Cluster, *kubebindv1alpha2.ClusterList] -} - -// newClusters returns a Clusters -func newClusters(c *KubeBindV1alpha2Client, namespace string) *clusters { - return &clusters{ - gentype.NewClientWithList[*kubebindv1alpha2.Cluster, *kubebindv1alpha2.ClusterList]( - "clusters", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.Cluster { return &kubebindv1alpha2.Cluster{} }, - func() *kubebindv1alpha2.ClusterList { return &kubebindv1alpha2.ClusterList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/clusterbinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/clusterbinding.go deleted file mode 100644 index 081ba264d..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/clusterbinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// ClusterBindingsGetter has a method to return a ClusterBindingInterface. -// A group's client should implement this interface. -type ClusterBindingsGetter interface { - ClusterBindings(namespace string) ClusterBindingInterface -} - -// ClusterBindingInterface has methods to work with ClusterBinding resources. -type ClusterBindingInterface interface { - Create(ctx context.Context, clusterBinding *kubebindv1alpha2.ClusterBinding, opts v1.CreateOptions) (*kubebindv1alpha2.ClusterBinding, error) - Update(ctx context.Context, clusterBinding *kubebindv1alpha2.ClusterBinding, opts v1.UpdateOptions) (*kubebindv1alpha2.ClusterBinding, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, clusterBinding *kubebindv1alpha2.ClusterBinding, opts v1.UpdateOptions) (*kubebindv1alpha2.ClusterBinding, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.ClusterBinding, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.ClusterBindingList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.ClusterBinding, err error) - ClusterBindingExpansion -} - -// clusterBindings implements ClusterBindingInterface -type clusterBindings struct { - *gentype.ClientWithList[*kubebindv1alpha2.ClusterBinding, *kubebindv1alpha2.ClusterBindingList] -} - -// newClusterBindings returns a ClusterBindings -func newClusterBindings(c *KubeBindV1alpha2Client, namespace string) *clusterBindings { - return &clusterBindings{ - gentype.NewClientWithList[*kubebindv1alpha2.ClusterBinding, *kubebindv1alpha2.ClusterBindingList]( - "clusterbindings", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.ClusterBinding { return &kubebindv1alpha2.ClusterBinding{} }, - func() *kubebindv1alpha2.ClusterBindingList { return &kubebindv1alpha2.ClusterBindingList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/collection.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/collection.go deleted file mode 100644 index 4da65a827..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/collection.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - gentype "k8s.io/client-go/gentype" -) - -// CollectionsGetter has a method to return a CollectionInterface. -// A group's client should implement this interface. -type CollectionsGetter interface { - Collections(namespace string) CollectionInterface -} - -// CollectionInterface has methods to work with Collection resources. -type CollectionInterface interface { - Create(ctx context.Context, collection *kubebindv1alpha2.Collection, opts v1.CreateOptions) (*kubebindv1alpha2.Collection, error) - Update(ctx context.Context, collection *kubebindv1alpha2.Collection, opts v1.UpdateOptions) (*kubebindv1alpha2.Collection, error) - // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - UpdateStatus(ctx context.Context, collection *kubebindv1alpha2.Collection, opts v1.UpdateOptions) (*kubebindv1alpha2.Collection, error) - Delete(ctx context.Context, name string, opts v1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error - Get(ctx context.Context, name string, opts v1.GetOptions) (*kubebindv1alpha2.Collection, error) - List(ctx context.Context, opts v1.ListOptions) (*kubebindv1alpha2.CollectionList, error) - Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubebindv1alpha2.Collection, err error) - CollectionExpansion -} - -// collections implements CollectionInterface -type collections struct { - *gentype.ClientWithList[*kubebindv1alpha2.Collection, *kubebindv1alpha2.CollectionList] -} - -// newCollections returns a Collections -func newCollections(c *KubeBindV1alpha2Client, namespace string) *collections { - return &collections{ - gentype.NewClientWithList[*kubebindv1alpha2.Collection, *kubebindv1alpha2.CollectionList]( - "collections", - c.RESTClient(), - scheme.ParameterCodec, - namespace, - func() *kubebindv1alpha2.Collection { return &kubebindv1alpha2.Collection{} }, - func() *kubebindv1alpha2.CollectionList { return &kubebindv1alpha2.CollectionList{} }, - ), - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/doc.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/doc.go deleted file mode 100644 index 5c1216263..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha2 diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/doc.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/doc.go deleted file mode 100644 index a0ee34800..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebinding.go deleted file mode 100644 index b66334e64..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebinding.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceBindings implements APIServiceBindingInterface -type fakeAPIServiceBindings struct { - *gentype.FakeClientWithList[*v1alpha2.APIServiceBinding, *v1alpha2.APIServiceBindingList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeAPIServiceBindings(fake *FakeKubeBindV1alpha2) kubebindv1alpha2.APIServiceBindingInterface { - return &fakeAPIServiceBindings{ - gentype.NewFakeClientWithList[*v1alpha2.APIServiceBinding, *v1alpha2.APIServiceBindingList]( - fake.Fake, - "", - v1alpha2.SchemeGroupVersion.WithResource("apiservicebindings"), - v1alpha2.SchemeGroupVersion.WithKind("APIServiceBinding"), - func() *v1alpha2.APIServiceBinding { return &v1alpha2.APIServiceBinding{} }, - func() *v1alpha2.APIServiceBindingList { return &v1alpha2.APIServiceBindingList{} }, - func(dst, src *v1alpha2.APIServiceBindingList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.APIServiceBindingList) []*v1alpha2.APIServiceBinding { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.APIServiceBindingList, items []*v1alpha2.APIServiceBinding) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebindingbundle.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebindingbundle.go deleted file mode 100644 index 94fc38350..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicebindingbundle.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceBindingBundles implements APIServiceBindingBundleInterface -type fakeAPIServiceBindingBundles struct { - *gentype.FakeClientWithList[*v1alpha2.APIServiceBindingBundle, *v1alpha2.APIServiceBindingBundleList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeAPIServiceBindingBundles(fake *FakeKubeBindV1alpha2) kubebindv1alpha2.APIServiceBindingBundleInterface { - return &fakeAPIServiceBindingBundles{ - gentype.NewFakeClientWithList[*v1alpha2.APIServiceBindingBundle, *v1alpha2.APIServiceBindingBundleList]( - fake.Fake, - "", - v1alpha2.SchemeGroupVersion.WithResource("apiservicebindingbundles"), - v1alpha2.SchemeGroupVersion.WithKind("APIServiceBindingBundle"), - func() *v1alpha2.APIServiceBindingBundle { return &v1alpha2.APIServiceBindingBundle{} }, - func() *v1alpha2.APIServiceBindingBundleList { return &v1alpha2.APIServiceBindingBundleList{} }, - func(dst, src *v1alpha2.APIServiceBindingBundleList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.APIServiceBindingBundleList) []*v1alpha2.APIServiceBindingBundle { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.APIServiceBindingBundleList, items []*v1alpha2.APIServiceBindingBundle) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexport.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexport.go deleted file mode 100644 index f05d6d20c..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexport.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceExports implements APIServiceExportInterface -type fakeAPIServiceExports struct { - *gentype.FakeClientWithList[*v1alpha2.APIServiceExport, *v1alpha2.APIServiceExportList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeAPIServiceExports(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.APIServiceExportInterface { - return &fakeAPIServiceExports{ - gentype.NewFakeClientWithList[*v1alpha2.APIServiceExport, *v1alpha2.APIServiceExportList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("apiserviceexports"), - v1alpha2.SchemeGroupVersion.WithKind("APIServiceExport"), - func() *v1alpha2.APIServiceExport { return &v1alpha2.APIServiceExport{} }, - func() *v1alpha2.APIServiceExportList { return &v1alpha2.APIServiceExportList{} }, - func(dst, src *v1alpha2.APIServiceExportList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.APIServiceExportList) []*v1alpha2.APIServiceExport { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.APIServiceExportList, items []*v1alpha2.APIServiceExport) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexportrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexportrequest.go deleted file mode 100644 index ae8930dd8..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiserviceexportrequest.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceExportRequests implements APIServiceExportRequestInterface -type fakeAPIServiceExportRequests struct { - *gentype.FakeClientWithList[*v1alpha2.APIServiceExportRequest, *v1alpha2.APIServiceExportRequestList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeAPIServiceExportRequests(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.APIServiceExportRequestInterface { - return &fakeAPIServiceExportRequests{ - gentype.NewFakeClientWithList[*v1alpha2.APIServiceExportRequest, *v1alpha2.APIServiceExportRequestList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("apiserviceexportrequests"), - v1alpha2.SchemeGroupVersion.WithKind("APIServiceExportRequest"), - func() *v1alpha2.APIServiceExportRequest { return &v1alpha2.APIServiceExportRequest{} }, - func() *v1alpha2.APIServiceExportRequestList { return &v1alpha2.APIServiceExportRequestList{} }, - func(dst, src *v1alpha2.APIServiceExportRequestList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.APIServiceExportRequestList) []*v1alpha2.APIServiceExportRequest { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.APIServiceExportRequestList, items []*v1alpha2.APIServiceExportRequest) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicenamespace.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicenamespace.go deleted file mode 100644 index ea6ffa95f..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_apiservicenamespace.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeAPIServiceNamespaces implements APIServiceNamespaceInterface -type fakeAPIServiceNamespaces struct { - *gentype.FakeClientWithList[*v1alpha2.APIServiceNamespace, *v1alpha2.APIServiceNamespaceList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeAPIServiceNamespaces(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.APIServiceNamespaceInterface { - return &fakeAPIServiceNamespaces{ - gentype.NewFakeClientWithList[*v1alpha2.APIServiceNamespace, *v1alpha2.APIServiceNamespaceList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("apiservicenamespaces"), - v1alpha2.SchemeGroupVersion.WithKind("APIServiceNamespace"), - func() *v1alpha2.APIServiceNamespace { return &v1alpha2.APIServiceNamespace{} }, - func() *v1alpha2.APIServiceNamespaceList { return &v1alpha2.APIServiceNamespaceList{} }, - func(dst, src *v1alpha2.APIServiceNamespaceList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.APIServiceNamespaceList) []*v1alpha2.APIServiceNamespace { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.APIServiceNamespaceList, items []*v1alpha2.APIServiceNamespace) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_bindableresourcesrequest.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_bindableresourcesrequest.go deleted file mode 100644 index 7e8e304e0..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_bindableresourcesrequest.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeBindableResourcesRequests implements BindableResourcesRequestInterface -type fakeBindableResourcesRequests struct { - *gentype.FakeClientWithList[*v1alpha2.BindableResourcesRequest, *v1alpha2.BindableResourcesRequestList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeBindableResourcesRequests(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.BindableResourcesRequestInterface { - return &fakeBindableResourcesRequests{ - gentype.NewFakeClientWithList[*v1alpha2.BindableResourcesRequest, *v1alpha2.BindableResourcesRequestList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("bindableresourcesrequests"), - v1alpha2.SchemeGroupVersion.WithKind("BindableResourcesRequest"), - func() *v1alpha2.BindableResourcesRequest { return &v1alpha2.BindableResourcesRequest{} }, - func() *v1alpha2.BindableResourcesRequestList { return &v1alpha2.BindableResourcesRequestList{} }, - func(dst, src *v1alpha2.BindableResourcesRequestList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.BindableResourcesRequestList) []*v1alpha2.BindableResourcesRequest { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.BindableResourcesRequestList, items []*v1alpha2.BindableResourcesRequest) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_boundschema.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_boundschema.go deleted file mode 100644 index a50559ca6..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_boundschema.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeBoundSchemas implements BoundSchemaInterface -type fakeBoundSchemas struct { - *gentype.FakeClientWithList[*v1alpha2.BoundSchema, *v1alpha2.BoundSchemaList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeBoundSchemas(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.BoundSchemaInterface { - return &fakeBoundSchemas{ - gentype.NewFakeClientWithList[*v1alpha2.BoundSchema, *v1alpha2.BoundSchemaList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("boundschemas"), - v1alpha2.SchemeGroupVersion.WithKind("BoundSchema"), - func() *v1alpha2.BoundSchema { return &v1alpha2.BoundSchema{} }, - func() *v1alpha2.BoundSchemaList { return &v1alpha2.BoundSchemaList{} }, - func(dst, src *v1alpha2.BoundSchemaList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.BoundSchemaList) []*v1alpha2.BoundSchema { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.BoundSchemaList, items []*v1alpha2.BoundSchema) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_cluster.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_cluster.go deleted file mode 100644 index 43e366d24..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_cluster.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeClusters implements ClusterInterface -type fakeClusters struct { - *gentype.FakeClientWithList[*v1alpha2.Cluster, *v1alpha2.ClusterList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeClusters(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.ClusterInterface { - return &fakeClusters{ - gentype.NewFakeClientWithList[*v1alpha2.Cluster, *v1alpha2.ClusterList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("clusters"), - v1alpha2.SchemeGroupVersion.WithKind("Cluster"), - func() *v1alpha2.Cluster { return &v1alpha2.Cluster{} }, - func() *v1alpha2.ClusterList { return &v1alpha2.ClusterList{} }, - func(dst, src *v1alpha2.ClusterList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.ClusterList) []*v1alpha2.Cluster { return gentype.ToPointerSlice(list.Items) }, - func(list *v1alpha2.ClusterList, items []*v1alpha2.Cluster) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_clusterbinding.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_clusterbinding.go deleted file mode 100644 index d1f5a1fb8..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_clusterbinding.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeClusterBindings implements ClusterBindingInterface -type fakeClusterBindings struct { - *gentype.FakeClientWithList[*v1alpha2.ClusterBinding, *v1alpha2.ClusterBindingList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeClusterBindings(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.ClusterBindingInterface { - return &fakeClusterBindings{ - gentype.NewFakeClientWithList[*v1alpha2.ClusterBinding, *v1alpha2.ClusterBindingList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("clusterbindings"), - v1alpha2.SchemeGroupVersion.WithKind("ClusterBinding"), - func() *v1alpha2.ClusterBinding { return &v1alpha2.ClusterBinding{} }, - func() *v1alpha2.ClusterBindingList { return &v1alpha2.ClusterBindingList{} }, - func(dst, src *v1alpha2.ClusterBindingList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.ClusterBindingList) []*v1alpha2.ClusterBinding { - return gentype.ToPointerSlice(list.Items) - }, - func(list *v1alpha2.ClusterBindingList, items []*v1alpha2.ClusterBinding) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_collection.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_collection.go deleted file mode 100644 index eb75906c7..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_collection.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - gentype "k8s.io/client-go/gentype" -) - -// fakeCollections implements CollectionInterface -type fakeCollections struct { - *gentype.FakeClientWithList[*v1alpha2.Collection, *v1alpha2.CollectionList] - Fake *FakeKubeBindV1alpha2 -} - -func newFakeCollections(fake *FakeKubeBindV1alpha2, namespace string) kubebindv1alpha2.CollectionInterface { - return &fakeCollections{ - gentype.NewFakeClientWithList[*v1alpha2.Collection, *v1alpha2.CollectionList]( - fake.Fake, - namespace, - v1alpha2.SchemeGroupVersion.WithResource("collections"), - v1alpha2.SchemeGroupVersion.WithKind("Collection"), - func() *v1alpha2.Collection { return &v1alpha2.Collection{} }, - func() *v1alpha2.CollectionList { return &v1alpha2.CollectionList{} }, - func(dst, src *v1alpha2.CollectionList) { dst.ListMeta = src.ListMeta }, - func(list *v1alpha2.CollectionList) []*v1alpha2.Collection { return gentype.ToPointerSlice(list.Items) }, - func(list *v1alpha2.CollectionList, items []*v1alpha2.Collection) { - list.Items = gentype.FromPointerSlice(items) - }, - ), - fake, - } -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_kubebind_client.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_kubebind_client.go deleted file mode 100644 index 8c773e01b..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/fake/fake_kubebind_client.go +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha2 "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/typed/kubebind/v1alpha2" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeKubeBindV1alpha2 struct { - *testing.Fake -} - -func (c *FakeKubeBindV1alpha2) APIServiceBindings() v1alpha2.APIServiceBindingInterface { - return newFakeAPIServiceBindings(c) -} - -func (c *FakeKubeBindV1alpha2) APIServiceBindingBundles() v1alpha2.APIServiceBindingBundleInterface { - return newFakeAPIServiceBindingBundles(c) -} - -func (c *FakeKubeBindV1alpha2) APIServiceExports(namespace string) v1alpha2.APIServiceExportInterface { - return newFakeAPIServiceExports(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) APIServiceExportRequests(namespace string) v1alpha2.APIServiceExportRequestInterface { - return newFakeAPIServiceExportRequests(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) APIServiceNamespaces(namespace string) v1alpha2.APIServiceNamespaceInterface { - return newFakeAPIServiceNamespaces(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) BindableResourcesRequests(namespace string) v1alpha2.BindableResourcesRequestInterface { - return newFakeBindableResourcesRequests(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) BoundSchemas(namespace string) v1alpha2.BoundSchemaInterface { - return newFakeBoundSchemas(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) Clusters(namespace string) v1alpha2.ClusterInterface { - return newFakeClusters(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) ClusterBindings(namespace string) v1alpha2.ClusterBindingInterface { - return newFakeClusterBindings(c, namespace) -} - -func (c *FakeKubeBindV1alpha2) Collections(namespace string) v1alpha2.CollectionInterface { - return newFakeCollections(c, namespace) -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeKubeBindV1alpha2) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/generated_expansion.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/generated_expansion.go deleted file mode 100644 index 3c86f5c52..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/generated_expansion.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -type APIServiceBindingExpansion interface{} - -type APIServiceBindingBundleExpansion interface{} - -type APIServiceExportExpansion interface{} - -type APIServiceExportRequestExpansion interface{} - -type APIServiceNamespaceExpansion interface{} - -type BindableResourcesRequestExpansion interface{} - -type BoundSchemaExpansion interface{} - -type ClusterExpansion interface{} - -type ClusterBindingExpansion interface{} - -type CollectionExpansion interface{} diff --git a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/kubebind_client.go b/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/kubebind_client.go deleted file mode 100644 index e59c85f49..000000000 --- a/sdk/client/clientset/versioned/typed/kubebind/v1alpha2/kubebind_client.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - http "net/http" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - scheme "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type KubeBindV1alpha2Interface interface { - RESTClient() rest.Interface - APIServiceBindingsGetter - APIServiceBindingBundlesGetter - APIServiceExportsGetter - APIServiceExportRequestsGetter - APIServiceNamespacesGetter - BindableResourcesRequestsGetter - BoundSchemasGetter - ClustersGetter - ClusterBindingsGetter - CollectionsGetter -} - -// KubeBindV1alpha2Client is used to interact with features provided by the kube-bind.io group. -type KubeBindV1alpha2Client struct { - restClient rest.Interface -} - -func (c *KubeBindV1alpha2Client) APIServiceBindings() APIServiceBindingInterface { - return newAPIServiceBindings(c) -} - -func (c *KubeBindV1alpha2Client) APIServiceBindingBundles() APIServiceBindingBundleInterface { - return newAPIServiceBindingBundles(c) -} - -func (c *KubeBindV1alpha2Client) APIServiceExports(namespace string) APIServiceExportInterface { - return newAPIServiceExports(c, namespace) -} - -func (c *KubeBindV1alpha2Client) APIServiceExportRequests(namespace string) APIServiceExportRequestInterface { - return newAPIServiceExportRequests(c, namespace) -} - -func (c *KubeBindV1alpha2Client) APIServiceNamespaces(namespace string) APIServiceNamespaceInterface { - return newAPIServiceNamespaces(c, namespace) -} - -func (c *KubeBindV1alpha2Client) BindableResourcesRequests(namespace string) BindableResourcesRequestInterface { - return newBindableResourcesRequests(c, namespace) -} - -func (c *KubeBindV1alpha2Client) BoundSchemas(namespace string) BoundSchemaInterface { - return newBoundSchemas(c, namespace) -} - -func (c *KubeBindV1alpha2Client) Clusters(namespace string) ClusterInterface { - return newClusters(c, namespace) -} - -func (c *KubeBindV1alpha2Client) ClusterBindings(namespace string) ClusterBindingInterface { - return newClusterBindings(c, namespace) -} - -func (c *KubeBindV1alpha2Client) Collections(namespace string) CollectionInterface { - return newCollections(c, namespace) -} - -// NewForConfig creates a new KubeBindV1alpha2Client for the given config. -// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), -// where httpClient was generated with rest.HTTPClientFor(c). -func NewForConfig(c *rest.Config) (*KubeBindV1alpha2Client, error) { - config := *c - setConfigDefaults(&config) - httpClient, err := rest.HTTPClientFor(&config) - if err != nil { - return nil, err - } - return NewForConfigAndClient(&config, httpClient) -} - -// NewForConfigAndClient creates a new KubeBindV1alpha2Client for the given config and http client. -// Note the http client provided takes precedence over the configured transport values. -func NewForConfigAndClient(c *rest.Config, h *http.Client) (*KubeBindV1alpha2Client, error) { - config := *c - setConfigDefaults(&config) - client, err := rest.RESTClientForConfigAndClient(&config, h) - if err != nil { - return nil, err - } - return &KubeBindV1alpha2Client{client}, nil -} - -// NewForConfigOrDie creates a new KubeBindV1alpha2Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *KubeBindV1alpha2Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new KubeBindV1alpha2Client for the given RESTClient. -func New(c rest.Interface) *KubeBindV1alpha2Client { - return &KubeBindV1alpha2Client{c} -} - -func setConfigDefaults(config *rest.Config) { - gv := kubebindv1alpha2.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = rest.CodecFactoryForGeneratedClient(scheme.Scheme, scheme.Codecs).WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *KubeBindV1alpha2Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/sdk/client/informers/externalversions/factory.go b/sdk/client/informers/externalversions/factory.go deleted file mode 100644 index 0605f8ca6..000000000 --- a/sdk/client/informers/externalversions/factory.go +++ /dev/null @@ -1,263 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebind "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - transform cache.TransformFunc - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool - // wg tracks how many goroutines were started. - wg sync.WaitGroup - // shuttingDown is true when Shutdown has been called. It may still be running - // because it needs to wait for goroutines. - shuttingDown bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// WithTransform sets a transform on all informers. -func WithTransform(transform cache.TransformFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.transform = transform - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.shuttingDown { - return - } - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - f.wg.Add(1) - // We need a new variable in each loop iteration, - // otherwise the goroutine would use the loop variable - // and that keeps changing. - informer := informer - go func() { - defer f.wg.Done() - informer.Run(stopCh) - }() - f.startedInformers[informerType] = true - } - } -} - -func (f *sharedInformerFactory) Shutdown() { - f.lock.Lock() - f.shuttingDown = true - f.lock.Unlock() - - // Will return immediately if there is nothing to wait for. - f.wg.Wait() -} - -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - informer.SetTransform(f.transform) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -// -// It is typically used like this: -// -// ctx, cancel := context.WithCancel(context.Background()) -// defer cancel() -// factory := NewSharedInformerFactory(client, resyncPeriod) -// defer factory.WaitForStop() // Returns immediately if nothing was started. -// genericInformer := factory.ForResource(resource) -// typedInformer := factory.SomeAPIGroup().V1().SomeType() -// factory.Start(ctx.Done()) // Start processing these informers. -// synced := factory.WaitForCacheSync(ctx.Done()) -// for v, ok := range synced { -// if !ok { -// fmt.Fprintf(os.Stderr, "caches failed to sync: %v", v) -// return -// } -// } -// -// // Creating informers can also be created after Start, but then -// // Start must be called again: -// anotherGenericInformer := factory.ForResource(resource) -// factory.Start(ctx.Done()) -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - - // Start initializes all requested informers. They are handled in goroutines - // which run until the stop channel gets closed. - // Warning: Start does not block. When run in a go-routine, it will race with a later WaitForCacheSync. - Start(stopCh <-chan struct{}) - - // Shutdown marks a factory as shutting down. At that point no new - // informers can be started anymore and Start will return without - // doing anything. - // - // In addition, Shutdown blocks until all goroutines have terminated. For that - // to happen, the close channel(s) that they were started with must be closed, - // either before Shutdown gets called or while it is waiting. - // - // Shutdown may be called multiple times, even concurrently. All such calls will - // block until all goroutines have terminated. - Shutdown() - - // WaitForCacheSync blocks until all started informers' caches were synced - // or the stop channel gets closed. - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - // ForResource gives generic access to a shared informer of the matching type. - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - - // InformerFor returns the SharedIndexInformer for obj using an internal - // client. - InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer - - KubeBind() kubebind.Interface -} - -func (f *sharedInformerFactory) KubeBind() kubebind.Interface { - return kubebind.New(f, f.namespace, f.tweakListOptions) -} diff --git a/sdk/client/informers/externalversions/generic.go b/sdk/client/informers/externalversions/generic.go deleted file mode 100644 index a5ec5b5c6..000000000 --- a/sdk/client/informers/externalversions/generic.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package externalversions - -import ( - fmt "fmt" - - v1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - v1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=kube-bind.io, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("apiservicebindings"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha1().APIServiceBindings().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("apiserviceexports"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha1().APIServiceExports().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("apiserviceexportrequests"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha1().APIServiceExportRequests().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("apiservicenamespaces"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha1().APIServiceNamespaces().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("clusterbindings"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha1().ClusterBindings().Informer()}, nil - - // Group=kube-bind.io, Version=v1alpha2 - case v1alpha2.SchemeGroupVersion.WithResource("apiservicebindings"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().APIServiceBindings().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("apiservicebindingbundles"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().APIServiceBindingBundles().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("apiserviceexports"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().APIServiceExports().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("apiserviceexportrequests"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().APIServiceExportRequests().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("apiservicenamespaces"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().APIServiceNamespaces().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("bindableresourcesrequests"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().BindableResourcesRequests().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("boundschemas"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().BoundSchemas().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("clusters"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().Clusters().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("clusterbindings"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().ClusterBindings().Informer()}, nil - case v1alpha2.SchemeGroupVersion.WithResource("collections"): - return &genericInformer{resource: resource.GroupResource(), informer: f.KubeBind().V1alpha2().Collections().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/sdk/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/sdk/client/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index d807af268..000000000 --- a/sdk/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package internalinterfaces - -import ( - time "time" - - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/sdk/client/informers/externalversions/kubebind/interface.go b/sdk/client/informers/externalversions/kubebind/interface.go deleted file mode 100644 index 2a3f534d3..000000000 --- a/sdk/client/informers/externalversions/kubebind/interface.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package kubebind - -import ( - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha1" - v1alpha2 "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/kubebind/v1alpha2" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface - // V1alpha2 provides access to shared informers for resources in V1alpha2. - V1alpha2() v1alpha2.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} - -// V1alpha2 returns a new v1alpha2.Interface. -func (g *group) V1alpha2() v1alpha2.Interface { - return v1alpha2.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicebinding.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicebinding.go deleted file mode 100644 index e7cd2afaa..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicebinding.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apiskubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingInformer provides access to a shared informer and lister for -// APIServiceBindings. -type APIServiceBindingInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha1.APIServiceBindingLister -} - -type aPIServiceBindingInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewAPIServiceBindingInformer constructs a new informer for APIServiceBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceBindingInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceBindingInformer constructs a new informer for APIServiceBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceBindingInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceBindings().List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceBindings().Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceBindings().List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceBindings().Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha1.APIServiceBinding{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha1.APIServiceBinding{}, f.defaultInformer) -} - -func (f *aPIServiceBindingInformer) Lister() kubebindv1alpha1.APIServiceBindingLister { - return kubebindv1alpha1.NewAPIServiceBindingLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexport.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexport.go deleted file mode 100644 index f2c9fee0c..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexport.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apiskubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportInformer provides access to a shared informer and lister for -// APIServiceExports. -type APIServiceExportInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha1.APIServiceExportLister -} - -type aPIServiceExportInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceExportInformer constructs a new informer for APIServiceExport type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceExportInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceExportInformer constructs a new informer for APIServiceExport type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceExportInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExports(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExports(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExports(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExports(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha1.APIServiceExport{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceExportInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceExportInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha1.APIServiceExport{}, f.defaultInformer) -} - -func (f *aPIServiceExportInformer) Lister() kubebindv1alpha1.APIServiceExportLister { - return kubebindv1alpha1.NewAPIServiceExportLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexportrequest.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexportrequest.go deleted file mode 100644 index d4e1f38e5..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiserviceexportrequest.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apiskubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportRequestInformer provides access to a shared informer and lister for -// APIServiceExportRequests. -type APIServiceExportRequestInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha1.APIServiceExportRequestLister -} - -type aPIServiceExportRequestInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceExportRequestInformer constructs a new informer for APIServiceExportRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceExportRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportRequestInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceExportRequestInformer constructs a new informer for APIServiceExportRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceExportRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExportRequests(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExportRequests(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExportRequests(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceExportRequests(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha1.APIServiceExportRequest{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceExportRequestInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportRequestInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceExportRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha1.APIServiceExportRequest{}, f.defaultInformer) -} - -func (f *aPIServiceExportRequestInformer) Lister() kubebindv1alpha1.APIServiceExportRequestLister { - return kubebindv1alpha1.NewAPIServiceExportRequestLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicenamespace.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicenamespace.go deleted file mode 100644 index dd2623a0d..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/apiservicenamespace.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apiskubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceNamespaceInformer provides access to a shared informer and lister for -// APIServiceNamespaces. -type APIServiceNamespaceInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha1.APIServiceNamespaceLister -} - -type aPIServiceNamespaceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceNamespaceInformer constructs a new informer for APIServiceNamespace type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceNamespaceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceNamespaceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceNamespaceInformer constructs a new informer for APIServiceNamespace type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceNamespaceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceNamespaces(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceNamespaces(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceNamespaces(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().APIServiceNamespaces(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha1.APIServiceNamespace{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceNamespaceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceNamespaceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceNamespaceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha1.APIServiceNamespace{}, f.defaultInformer) -} - -func (f *aPIServiceNamespaceInformer) Lister() kubebindv1alpha1.APIServiceNamespaceLister { - return kubebindv1alpha1.NewAPIServiceNamespaceLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/clusterbinding.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/clusterbinding.go deleted file mode 100644 index 43cc4e072..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/clusterbinding.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - context "context" - time "time" - - apiskubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterBindingInformer provides access to a shared informer and lister for -// ClusterBindings. -type ClusterBindingInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha1.ClusterBindingLister -} - -type clusterBindingInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewClusterBindingInformer constructs a new informer for ClusterBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterBindingInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterBindingInformer constructs a new informer for ClusterBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().ClusterBindings(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().ClusterBindings(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().ClusterBindings(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha1().ClusterBindings(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha1.ClusterBinding{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha1.ClusterBinding{}, f.defaultInformer) -} - -func (f *clusterBindingInformer) Lister() kubebindv1alpha1.ClusterBindingLister { - return kubebindv1alpha1.NewClusterBindingLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha1/interface.go b/sdk/client/informers/externalversions/kubebind/v1alpha1/interface.go deleted file mode 100644 index e815f1978..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha1/interface.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // APIServiceBindings returns a APIServiceBindingInformer. - APIServiceBindings() APIServiceBindingInformer - // APIServiceExports returns a APIServiceExportInformer. - APIServiceExports() APIServiceExportInformer - // APIServiceExportRequests returns a APIServiceExportRequestInformer. - APIServiceExportRequests() APIServiceExportRequestInformer - // APIServiceNamespaces returns a APIServiceNamespaceInformer. - APIServiceNamespaces() APIServiceNamespaceInformer - // ClusterBindings returns a ClusterBindingInformer. - ClusterBindings() ClusterBindingInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// APIServiceBindings returns a APIServiceBindingInformer. -func (v *version) APIServiceBindings() APIServiceBindingInformer { - return &aPIServiceBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// APIServiceExports returns a APIServiceExportInformer. -func (v *version) APIServiceExports() APIServiceExportInformer { - return &aPIServiceExportInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// APIServiceExportRequests returns a APIServiceExportRequestInformer. -func (v *version) APIServiceExportRequests() APIServiceExportRequestInformer { - return &aPIServiceExportRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// APIServiceNamespaces returns a APIServiceNamespaceInformer. -func (v *version) APIServiceNamespaces() APIServiceNamespaceInformer { - return &aPIServiceNamespaceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// ClusterBindings returns a ClusterBindingInformer. -func (v *version) ClusterBindings() ClusterBindingInformer { - return &clusterBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebinding.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebinding.go deleted file mode 100644 index eb50688a3..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebinding.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingInformer provides access to a shared informer and lister for -// APIServiceBindings. -type APIServiceBindingInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.APIServiceBindingLister -} - -type aPIServiceBindingInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewAPIServiceBindingInformer constructs a new informer for APIServiceBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceBindingInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceBindingInformer constructs a new informer for APIServiceBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceBindingInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindings().List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindings().Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindings().List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindings().Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.APIServiceBinding{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.APIServiceBinding{}, f.defaultInformer) -} - -func (f *aPIServiceBindingInformer) Lister() kubebindv1alpha2.APIServiceBindingLister { - return kubebindv1alpha2.NewAPIServiceBindingLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebindingbundle.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebindingbundle.go deleted file mode 100644 index 1b5bcd699..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicebindingbundle.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingBundleInformer provides access to a shared informer and lister for -// APIServiceBindingBundles. -type APIServiceBindingBundleInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.APIServiceBindingBundleLister -} - -type aPIServiceBindingBundleInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// NewAPIServiceBindingBundleInformer constructs a new informer for APIServiceBindingBundle type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceBindingBundleInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingBundleInformer(client, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceBindingBundleInformer constructs a new informer for APIServiceBindingBundle type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceBindingBundleInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindingBundles().List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindingBundles().Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindingBundles().List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceBindingBundles().Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.APIServiceBindingBundle{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceBindingBundleInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceBindingBundleInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceBindingBundleInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.APIServiceBindingBundle{}, f.defaultInformer) -} - -func (f *aPIServiceBindingBundleInformer) Lister() kubebindv1alpha2.APIServiceBindingBundleLister { - return kubebindv1alpha2.NewAPIServiceBindingBundleLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexport.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexport.go deleted file mode 100644 index 8927a8cf1..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexport.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportInformer provides access to a shared informer and lister for -// APIServiceExports. -type APIServiceExportInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.APIServiceExportLister -} - -type aPIServiceExportInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceExportInformer constructs a new informer for APIServiceExport type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceExportInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceExportInformer constructs a new informer for APIServiceExport type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceExportInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExports(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExports(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExports(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExports(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.APIServiceExport{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceExportInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceExportInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.APIServiceExport{}, f.defaultInformer) -} - -func (f *aPIServiceExportInformer) Lister() kubebindv1alpha2.APIServiceExportLister { - return kubebindv1alpha2.NewAPIServiceExportLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexportrequest.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexportrequest.go deleted file mode 100644 index d73feec14..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiserviceexportrequest.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportRequestInformer provides access to a shared informer and lister for -// APIServiceExportRequests. -type APIServiceExportRequestInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.APIServiceExportRequestLister -} - -type aPIServiceExportRequestInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceExportRequestInformer constructs a new informer for APIServiceExportRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceExportRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportRequestInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceExportRequestInformer constructs a new informer for APIServiceExportRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceExportRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExportRequests(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExportRequests(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExportRequests(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceExportRequests(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.APIServiceExportRequest{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceExportRequestInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceExportRequestInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceExportRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.APIServiceExportRequest{}, f.defaultInformer) -} - -func (f *aPIServiceExportRequestInformer) Lister() kubebindv1alpha2.APIServiceExportRequestLister { - return kubebindv1alpha2.NewAPIServiceExportRequestLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicenamespace.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicenamespace.go deleted file mode 100644 index 02e113305..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/apiservicenamespace.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceNamespaceInformer provides access to a shared informer and lister for -// APIServiceNamespaces. -type APIServiceNamespaceInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.APIServiceNamespaceLister -} - -type aPIServiceNamespaceInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAPIServiceNamespaceInformer constructs a new informer for APIServiceNamespace type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAPIServiceNamespaceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAPIServiceNamespaceInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAPIServiceNamespaceInformer constructs a new informer for APIServiceNamespace type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAPIServiceNamespaceInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceNamespaces(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceNamespaces(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceNamespaces(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().APIServiceNamespaces(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.APIServiceNamespace{}, - resyncPeriod, - indexers, - ) -} - -func (f *aPIServiceNamespaceInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAPIServiceNamespaceInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *aPIServiceNamespaceInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.APIServiceNamespace{}, f.defaultInformer) -} - -func (f *aPIServiceNamespaceInformer) Lister() kubebindv1alpha2.APIServiceNamespaceLister { - return kubebindv1alpha2.NewAPIServiceNamespaceLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/bindableresourcesrequest.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/bindableresourcesrequest.go deleted file mode 100644 index 836690fba..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/bindableresourcesrequest.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// BindableResourcesRequestInformer provides access to a shared informer and lister for -// BindableResourcesRequests. -type BindableResourcesRequestInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.BindableResourcesRequestLister -} - -type bindableResourcesRequestInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewBindableResourcesRequestInformer constructs a new informer for BindableResourcesRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewBindableResourcesRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredBindableResourcesRequestInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredBindableResourcesRequestInformer constructs a new informer for BindableResourcesRequest type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredBindableResourcesRequestInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BindableResourcesRequests(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BindableResourcesRequests(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BindableResourcesRequests(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BindableResourcesRequests(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.BindableResourcesRequest{}, - resyncPeriod, - indexers, - ) -} - -func (f *bindableResourcesRequestInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredBindableResourcesRequestInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *bindableResourcesRequestInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.BindableResourcesRequest{}, f.defaultInformer) -} - -func (f *bindableResourcesRequestInformer) Lister() kubebindv1alpha2.BindableResourcesRequestLister { - return kubebindv1alpha2.NewBindableResourcesRequestLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/boundschema.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/boundschema.go deleted file mode 100644 index 4f0d0e30e..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/boundschema.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// BoundSchemaInformer provides access to a shared informer and lister for -// BoundSchemas. -type BoundSchemaInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.BoundSchemaLister -} - -type boundSchemaInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewBoundSchemaInformer constructs a new informer for BoundSchema type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewBoundSchemaInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredBoundSchemaInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredBoundSchemaInformer constructs a new informer for BoundSchema type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredBoundSchemaInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BoundSchemas(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BoundSchemas(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BoundSchemas(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().BoundSchemas(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.BoundSchema{}, - resyncPeriod, - indexers, - ) -} - -func (f *boundSchemaInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredBoundSchemaInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *boundSchemaInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.BoundSchema{}, f.defaultInformer) -} - -func (f *boundSchemaInformer) Lister() kubebindv1alpha2.BoundSchemaLister { - return kubebindv1alpha2.NewBoundSchemaLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/cluster.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/cluster.go deleted file mode 100644 index 87f178169..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/cluster.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterInformer provides access to a shared informer and lister for -// Clusters. -type ClusterInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.ClusterLister -} - -type clusterInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewClusterInformer constructs a new informer for Cluster type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterInformer constructs a new informer for Cluster type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Clusters(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Clusters(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Clusters(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Clusters(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.Cluster{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.Cluster{}, f.defaultInformer) -} - -func (f *clusterInformer) Lister() kubebindv1alpha2.ClusterLister { - return kubebindv1alpha2.NewClusterLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/clusterbinding.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/clusterbinding.go deleted file mode 100644 index 4b7b22842..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/clusterbinding.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterBindingInformer provides access to a shared informer and lister for -// ClusterBindings. -type ClusterBindingInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.ClusterBindingLister -} - -type clusterBindingInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewClusterBindingInformer constructs a new informer for ClusterBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewClusterBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredClusterBindingInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredClusterBindingInformer constructs a new informer for ClusterBinding type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredClusterBindingInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().ClusterBindings(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().ClusterBindings(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().ClusterBindings(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().ClusterBindings(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.ClusterBinding{}, - resyncPeriod, - indexers, - ) -} - -func (f *clusterBindingInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredClusterBindingInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *clusterBindingInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.ClusterBinding{}, f.defaultInformer) -} - -func (f *clusterBindingInformer) Lister() kubebindv1alpha2.ClusterBindingLister { - return kubebindv1alpha2.NewClusterBindingLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/collection.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/collection.go deleted file mode 100644 index f264a96c4..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/collection.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - context "context" - time "time" - - apiskubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - versioned "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/client/listers/kubebind/v1alpha2" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// CollectionInformer provides access to a shared informer and lister for -// Collections. -type CollectionInformer interface { - Informer() cache.SharedIndexInformer - Lister() kubebindv1alpha2.CollectionLister -} - -type collectionInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewCollectionInformer constructs a new informer for Collection type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewCollectionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredCollectionInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredCollectionInformer constructs a new informer for Collection type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredCollectionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - cache.ToListWatcherWithWatchListSemantics(&cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Collections(namespace).List(context.Background(), options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Collections(namespace).Watch(context.Background(), options) - }, - ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Collections(namespace).List(ctx, options) - }, - WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.KubeBindV1alpha2().Collections(namespace).Watch(ctx, options) - }, - }, client), - &apiskubebindv1alpha2.Collection{}, - resyncPeriod, - indexers, - ) -} - -func (f *collectionInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredCollectionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *collectionInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&apiskubebindv1alpha2.Collection{}, f.defaultInformer) -} - -func (f *collectionInformer) Lister() kubebindv1alpha2.CollectionLister { - return kubebindv1alpha2.NewCollectionLister(f.Informer().GetIndexer()) -} diff --git a/sdk/client/informers/externalversions/kubebind/v1alpha2/interface.go b/sdk/client/informers/externalversions/kubebind/v1alpha2/interface.go deleted file mode 100644 index 337fcf5fb..000000000 --- a/sdk/client/informers/externalversions/kubebind/v1alpha2/interface.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by informer-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - internalinterfaces "github.com/kube-bind/kube-bind/sdk/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // APIServiceBindings returns a APIServiceBindingInformer. - APIServiceBindings() APIServiceBindingInformer - // APIServiceBindingBundles returns a APIServiceBindingBundleInformer. - APIServiceBindingBundles() APIServiceBindingBundleInformer - // APIServiceExports returns a APIServiceExportInformer. - APIServiceExports() APIServiceExportInformer - // APIServiceExportRequests returns a APIServiceExportRequestInformer. - APIServiceExportRequests() APIServiceExportRequestInformer - // APIServiceNamespaces returns a APIServiceNamespaceInformer. - APIServiceNamespaces() APIServiceNamespaceInformer - // BindableResourcesRequests returns a BindableResourcesRequestInformer. - BindableResourcesRequests() BindableResourcesRequestInformer - // BoundSchemas returns a BoundSchemaInformer. - BoundSchemas() BoundSchemaInformer - // Clusters returns a ClusterInformer. - Clusters() ClusterInformer - // ClusterBindings returns a ClusterBindingInformer. - ClusterBindings() ClusterBindingInformer - // Collections returns a CollectionInformer. - Collections() CollectionInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// APIServiceBindings returns a APIServiceBindingInformer. -func (v *version) APIServiceBindings() APIServiceBindingInformer { - return &aPIServiceBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// APIServiceBindingBundles returns a APIServiceBindingBundleInformer. -func (v *version) APIServiceBindingBundles() APIServiceBindingBundleInformer { - return &aPIServiceBindingBundleInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} -} - -// APIServiceExports returns a APIServiceExportInformer. -func (v *version) APIServiceExports() APIServiceExportInformer { - return &aPIServiceExportInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// APIServiceExportRequests returns a APIServiceExportRequestInformer. -func (v *version) APIServiceExportRequests() APIServiceExportRequestInformer { - return &aPIServiceExportRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// APIServiceNamespaces returns a APIServiceNamespaceInformer. -func (v *version) APIServiceNamespaces() APIServiceNamespaceInformer { - return &aPIServiceNamespaceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// BindableResourcesRequests returns a BindableResourcesRequestInformer. -func (v *version) BindableResourcesRequests() BindableResourcesRequestInformer { - return &bindableResourcesRequestInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// BoundSchemas returns a BoundSchemaInformer. -func (v *version) BoundSchemas() BoundSchemaInformer { - return &boundSchemaInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// Clusters returns a ClusterInformer. -func (v *version) Clusters() ClusterInformer { - return &clusterInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// ClusterBindings returns a ClusterBindingInformer. -func (v *version) ClusterBindings() ClusterBindingInformer { - return &clusterBindingInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// Collections returns a CollectionInformer. -func (v *version) Collections() CollectionInformer { - return &collectionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/sdk/client/listers/kubebind/v1alpha1/apiservicebinding.go b/sdk/client/listers/kubebind/v1alpha1/apiservicebinding.go deleted file mode 100644 index c38dca7ea..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/apiservicebinding.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingLister helps list APIServiceBindings. -// All objects returned here must be treated as read-only. -type APIServiceBindingLister interface { - // List lists all APIServiceBindings in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceBinding, err error) - // Get retrieves the APIServiceBinding from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha1.APIServiceBinding, error) - APIServiceBindingListerExpansion -} - -// aPIServiceBindingLister implements the APIServiceBindingLister interface. -type aPIServiceBindingLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceBinding] -} - -// NewAPIServiceBindingLister returns a new APIServiceBindingLister. -func NewAPIServiceBindingLister(indexer cache.Indexer) APIServiceBindingLister { - return &aPIServiceBindingLister{listers.New[*kubebindv1alpha1.APIServiceBinding](indexer, kubebindv1alpha1.Resource("apiservicebinding"))} -} diff --git a/sdk/client/listers/kubebind/v1alpha1/apiserviceexport.go b/sdk/client/listers/kubebind/v1alpha1/apiserviceexport.go deleted file mode 100644 index ab7330da2..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/apiserviceexport.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportLister helps list APIServiceExports. -// All objects returned here must be treated as read-only. -type APIServiceExportLister interface { - // List lists all APIServiceExports in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceExport, err error) - // APIServiceExports returns an object that can list and get APIServiceExports. - APIServiceExports(namespace string) APIServiceExportNamespaceLister - APIServiceExportListerExpansion -} - -// aPIServiceExportLister implements the APIServiceExportLister interface. -type aPIServiceExportLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceExport] -} - -// NewAPIServiceExportLister returns a new APIServiceExportLister. -func NewAPIServiceExportLister(indexer cache.Indexer) APIServiceExportLister { - return &aPIServiceExportLister{listers.New[*kubebindv1alpha1.APIServiceExport](indexer, kubebindv1alpha1.Resource("apiserviceexport"))} -} - -// APIServiceExports returns an object that can list and get APIServiceExports. -func (s *aPIServiceExportLister) APIServiceExports(namespace string) APIServiceExportNamespaceLister { - return aPIServiceExportNamespaceLister{listers.NewNamespaced[*kubebindv1alpha1.APIServiceExport](s.ResourceIndexer, namespace)} -} - -// APIServiceExportNamespaceLister helps list and get APIServiceExports. -// All objects returned here must be treated as read-only. -type APIServiceExportNamespaceLister interface { - // List lists all APIServiceExports in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceExport, err error) - // Get retrieves the APIServiceExport from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha1.APIServiceExport, error) - APIServiceExportNamespaceListerExpansion -} - -// aPIServiceExportNamespaceLister implements the APIServiceExportNamespaceLister -// interface. -type aPIServiceExportNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceExport] -} diff --git a/sdk/client/listers/kubebind/v1alpha1/apiserviceexportrequest.go b/sdk/client/listers/kubebind/v1alpha1/apiserviceexportrequest.go deleted file mode 100644 index b302c52ca..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/apiserviceexportrequest.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportRequestLister helps list APIServiceExportRequests. -// All objects returned here must be treated as read-only. -type APIServiceExportRequestLister interface { - // List lists all APIServiceExportRequests in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceExportRequest, err error) - // APIServiceExportRequests returns an object that can list and get APIServiceExportRequests. - APIServiceExportRequests(namespace string) APIServiceExportRequestNamespaceLister - APIServiceExportRequestListerExpansion -} - -// aPIServiceExportRequestLister implements the APIServiceExportRequestLister interface. -type aPIServiceExportRequestLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceExportRequest] -} - -// NewAPIServiceExportRequestLister returns a new APIServiceExportRequestLister. -func NewAPIServiceExportRequestLister(indexer cache.Indexer) APIServiceExportRequestLister { - return &aPIServiceExportRequestLister{listers.New[*kubebindv1alpha1.APIServiceExportRequest](indexer, kubebindv1alpha1.Resource("apiserviceexportrequest"))} -} - -// APIServiceExportRequests returns an object that can list and get APIServiceExportRequests. -func (s *aPIServiceExportRequestLister) APIServiceExportRequests(namespace string) APIServiceExportRequestNamespaceLister { - return aPIServiceExportRequestNamespaceLister{listers.NewNamespaced[*kubebindv1alpha1.APIServiceExportRequest](s.ResourceIndexer, namespace)} -} - -// APIServiceExportRequestNamespaceLister helps list and get APIServiceExportRequests. -// All objects returned here must be treated as read-only. -type APIServiceExportRequestNamespaceLister interface { - // List lists all APIServiceExportRequests in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceExportRequest, err error) - // Get retrieves the APIServiceExportRequest from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha1.APIServiceExportRequest, error) - APIServiceExportRequestNamespaceListerExpansion -} - -// aPIServiceExportRequestNamespaceLister implements the APIServiceExportRequestNamespaceLister -// interface. -type aPIServiceExportRequestNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceExportRequest] -} diff --git a/sdk/client/listers/kubebind/v1alpha1/apiservicenamespace.go b/sdk/client/listers/kubebind/v1alpha1/apiservicenamespace.go deleted file mode 100644 index d0db5e300..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/apiservicenamespace.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceNamespaceLister helps list APIServiceNamespaces. -// All objects returned here must be treated as read-only. -type APIServiceNamespaceLister interface { - // List lists all APIServiceNamespaces in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceNamespace, err error) - // APIServiceNamespaces returns an object that can list and get APIServiceNamespaces. - APIServiceNamespaces(namespace string) APIServiceNamespaceNamespaceLister - APIServiceNamespaceListerExpansion -} - -// aPIServiceNamespaceLister implements the APIServiceNamespaceLister interface. -type aPIServiceNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceNamespace] -} - -// NewAPIServiceNamespaceLister returns a new APIServiceNamespaceLister. -func NewAPIServiceNamespaceLister(indexer cache.Indexer) APIServiceNamespaceLister { - return &aPIServiceNamespaceLister{listers.New[*kubebindv1alpha1.APIServiceNamespace](indexer, kubebindv1alpha1.Resource("apiservicenamespace"))} -} - -// APIServiceNamespaces returns an object that can list and get APIServiceNamespaces. -func (s *aPIServiceNamespaceLister) APIServiceNamespaces(namespace string) APIServiceNamespaceNamespaceLister { - return aPIServiceNamespaceNamespaceLister{listers.NewNamespaced[*kubebindv1alpha1.APIServiceNamespace](s.ResourceIndexer, namespace)} -} - -// APIServiceNamespaceNamespaceLister helps list and get APIServiceNamespaces. -// All objects returned here must be treated as read-only. -type APIServiceNamespaceNamespaceLister interface { - // List lists all APIServiceNamespaces in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.APIServiceNamespace, err error) - // Get retrieves the APIServiceNamespace from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha1.APIServiceNamespace, error) - APIServiceNamespaceNamespaceListerExpansion -} - -// aPIServiceNamespaceNamespaceLister implements the APIServiceNamespaceNamespaceLister -// interface. -type aPIServiceNamespaceNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.APIServiceNamespace] -} diff --git a/sdk/client/listers/kubebind/v1alpha1/clusterbinding.go b/sdk/client/listers/kubebind/v1alpha1/clusterbinding.go deleted file mode 100644 index 60f2f8630..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/clusterbinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterBindingLister helps list ClusterBindings. -// All objects returned here must be treated as read-only. -type ClusterBindingLister interface { - // List lists all ClusterBindings in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.ClusterBinding, err error) - // ClusterBindings returns an object that can list and get ClusterBindings. - ClusterBindings(namespace string) ClusterBindingNamespaceLister - ClusterBindingListerExpansion -} - -// clusterBindingLister implements the ClusterBindingLister interface. -type clusterBindingLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.ClusterBinding] -} - -// NewClusterBindingLister returns a new ClusterBindingLister. -func NewClusterBindingLister(indexer cache.Indexer) ClusterBindingLister { - return &clusterBindingLister{listers.New[*kubebindv1alpha1.ClusterBinding](indexer, kubebindv1alpha1.Resource("clusterbinding"))} -} - -// ClusterBindings returns an object that can list and get ClusterBindings. -func (s *clusterBindingLister) ClusterBindings(namespace string) ClusterBindingNamespaceLister { - return clusterBindingNamespaceLister{listers.NewNamespaced[*kubebindv1alpha1.ClusterBinding](s.ResourceIndexer, namespace)} -} - -// ClusterBindingNamespaceLister helps list and get ClusterBindings. -// All objects returned here must be treated as read-only. -type ClusterBindingNamespaceLister interface { - // List lists all ClusterBindings in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha1.ClusterBinding, err error) - // Get retrieves the ClusterBinding from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha1.ClusterBinding, error) - ClusterBindingNamespaceListerExpansion -} - -// clusterBindingNamespaceLister implements the ClusterBindingNamespaceLister -// interface. -type clusterBindingNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha1.ClusterBinding] -} diff --git a/sdk/client/listers/kubebind/v1alpha1/expansion_generated.go b/sdk/client/listers/kubebind/v1alpha1/expansion_generated.go deleted file mode 100644 index 3cdf7aed8..000000000 --- a/sdk/client/listers/kubebind/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha1 - -// APIServiceBindingListerExpansion allows custom methods to be added to -// APIServiceBindingLister. -type APIServiceBindingListerExpansion interface{} - -// APIServiceExportListerExpansion allows custom methods to be added to -// APIServiceExportLister. -type APIServiceExportListerExpansion interface{} - -// APIServiceExportNamespaceListerExpansion allows custom methods to be added to -// APIServiceExportNamespaceLister. -type APIServiceExportNamespaceListerExpansion interface{} - -// APIServiceExportRequestListerExpansion allows custom methods to be added to -// APIServiceExportRequestLister. -type APIServiceExportRequestListerExpansion interface{} - -// APIServiceExportRequestNamespaceListerExpansion allows custom methods to be added to -// APIServiceExportRequestNamespaceLister. -type APIServiceExportRequestNamespaceListerExpansion interface{} - -// APIServiceNamespaceListerExpansion allows custom methods to be added to -// APIServiceNamespaceLister. -type APIServiceNamespaceListerExpansion interface{} - -// APIServiceNamespaceNamespaceListerExpansion allows custom methods to be added to -// APIServiceNamespaceNamespaceLister. -type APIServiceNamespaceNamespaceListerExpansion interface{} - -// ClusterBindingListerExpansion allows custom methods to be added to -// ClusterBindingLister. -type ClusterBindingListerExpansion interface{} - -// ClusterBindingNamespaceListerExpansion allows custom methods to be added to -// ClusterBindingNamespaceLister. -type ClusterBindingNamespaceListerExpansion interface{} diff --git a/sdk/client/listers/kubebind/v1alpha2/apiservicebinding.go b/sdk/client/listers/kubebind/v1alpha2/apiservicebinding.go deleted file mode 100644 index e8d20e756..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/apiservicebinding.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingLister helps list APIServiceBindings. -// All objects returned here must be treated as read-only. -type APIServiceBindingLister interface { - // List lists all APIServiceBindings in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceBinding, err error) - // Get retrieves the APIServiceBinding from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.APIServiceBinding, error) - APIServiceBindingListerExpansion -} - -// aPIServiceBindingLister implements the APIServiceBindingLister interface. -type aPIServiceBindingLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceBinding] -} - -// NewAPIServiceBindingLister returns a new APIServiceBindingLister. -func NewAPIServiceBindingLister(indexer cache.Indexer) APIServiceBindingLister { - return &aPIServiceBindingLister{listers.New[*kubebindv1alpha2.APIServiceBinding](indexer, kubebindv1alpha2.Resource("apiservicebinding"))} -} diff --git a/sdk/client/listers/kubebind/v1alpha2/apiservicebindingbundle.go b/sdk/client/listers/kubebind/v1alpha2/apiservicebindingbundle.go deleted file mode 100644 index cffa0c89c..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/apiservicebindingbundle.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceBindingBundleLister helps list APIServiceBindingBundles. -// All objects returned here must be treated as read-only. -type APIServiceBindingBundleLister interface { - // List lists all APIServiceBindingBundles in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceBindingBundle, err error) - // Get retrieves the APIServiceBindingBundle from the index for a given name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.APIServiceBindingBundle, error) - APIServiceBindingBundleListerExpansion -} - -// aPIServiceBindingBundleLister implements the APIServiceBindingBundleLister interface. -type aPIServiceBindingBundleLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceBindingBundle] -} - -// NewAPIServiceBindingBundleLister returns a new APIServiceBindingBundleLister. -func NewAPIServiceBindingBundleLister(indexer cache.Indexer) APIServiceBindingBundleLister { - return &aPIServiceBindingBundleLister{listers.New[*kubebindv1alpha2.APIServiceBindingBundle](indexer, kubebindv1alpha2.Resource("apiservicebindingbundle"))} -} diff --git a/sdk/client/listers/kubebind/v1alpha2/apiserviceexport.go b/sdk/client/listers/kubebind/v1alpha2/apiserviceexport.go deleted file mode 100644 index 6dc873ec9..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/apiserviceexport.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportLister helps list APIServiceExports. -// All objects returned here must be treated as read-only. -type APIServiceExportLister interface { - // List lists all APIServiceExports in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceExport, err error) - // APIServiceExports returns an object that can list and get APIServiceExports. - APIServiceExports(namespace string) APIServiceExportNamespaceLister - APIServiceExportListerExpansion -} - -// aPIServiceExportLister implements the APIServiceExportLister interface. -type aPIServiceExportLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceExport] -} - -// NewAPIServiceExportLister returns a new APIServiceExportLister. -func NewAPIServiceExportLister(indexer cache.Indexer) APIServiceExportLister { - return &aPIServiceExportLister{listers.New[*kubebindv1alpha2.APIServiceExport](indexer, kubebindv1alpha2.Resource("apiserviceexport"))} -} - -// APIServiceExports returns an object that can list and get APIServiceExports. -func (s *aPIServiceExportLister) APIServiceExports(namespace string) APIServiceExportNamespaceLister { - return aPIServiceExportNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.APIServiceExport](s.ResourceIndexer, namespace)} -} - -// APIServiceExportNamespaceLister helps list and get APIServiceExports. -// All objects returned here must be treated as read-only. -type APIServiceExportNamespaceLister interface { - // List lists all APIServiceExports in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceExport, err error) - // Get retrieves the APIServiceExport from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.APIServiceExport, error) - APIServiceExportNamespaceListerExpansion -} - -// aPIServiceExportNamespaceLister implements the APIServiceExportNamespaceLister -// interface. -type aPIServiceExportNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceExport] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/apiserviceexportrequest.go b/sdk/client/listers/kubebind/v1alpha2/apiserviceexportrequest.go deleted file mode 100644 index 8788df35e..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/apiserviceexportrequest.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceExportRequestLister helps list APIServiceExportRequests. -// All objects returned here must be treated as read-only. -type APIServiceExportRequestLister interface { - // List lists all APIServiceExportRequests in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceExportRequest, err error) - // APIServiceExportRequests returns an object that can list and get APIServiceExportRequests. - APIServiceExportRequests(namespace string) APIServiceExportRequestNamespaceLister - APIServiceExportRequestListerExpansion -} - -// aPIServiceExportRequestLister implements the APIServiceExportRequestLister interface. -type aPIServiceExportRequestLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceExportRequest] -} - -// NewAPIServiceExportRequestLister returns a new APIServiceExportRequestLister. -func NewAPIServiceExportRequestLister(indexer cache.Indexer) APIServiceExportRequestLister { - return &aPIServiceExportRequestLister{listers.New[*kubebindv1alpha2.APIServiceExportRequest](indexer, kubebindv1alpha2.Resource("apiserviceexportrequest"))} -} - -// APIServiceExportRequests returns an object that can list and get APIServiceExportRequests. -func (s *aPIServiceExportRequestLister) APIServiceExportRequests(namespace string) APIServiceExportRequestNamespaceLister { - return aPIServiceExportRequestNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.APIServiceExportRequest](s.ResourceIndexer, namespace)} -} - -// APIServiceExportRequestNamespaceLister helps list and get APIServiceExportRequests. -// All objects returned here must be treated as read-only. -type APIServiceExportRequestNamespaceLister interface { - // List lists all APIServiceExportRequests in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceExportRequest, err error) - // Get retrieves the APIServiceExportRequest from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.APIServiceExportRequest, error) - APIServiceExportRequestNamespaceListerExpansion -} - -// aPIServiceExportRequestNamespaceLister implements the APIServiceExportRequestNamespaceLister -// interface. -type aPIServiceExportRequestNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceExportRequest] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/apiservicenamespace.go b/sdk/client/listers/kubebind/v1alpha2/apiservicenamespace.go deleted file mode 100644 index f90fadef1..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/apiservicenamespace.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// APIServiceNamespaceLister helps list APIServiceNamespaces. -// All objects returned here must be treated as read-only. -type APIServiceNamespaceLister interface { - // List lists all APIServiceNamespaces in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceNamespace, err error) - // APIServiceNamespaces returns an object that can list and get APIServiceNamespaces. - APIServiceNamespaces(namespace string) APIServiceNamespaceNamespaceLister - APIServiceNamespaceListerExpansion -} - -// aPIServiceNamespaceLister implements the APIServiceNamespaceLister interface. -type aPIServiceNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceNamespace] -} - -// NewAPIServiceNamespaceLister returns a new APIServiceNamespaceLister. -func NewAPIServiceNamespaceLister(indexer cache.Indexer) APIServiceNamespaceLister { - return &aPIServiceNamespaceLister{listers.New[*kubebindv1alpha2.APIServiceNamespace](indexer, kubebindv1alpha2.Resource("apiservicenamespace"))} -} - -// APIServiceNamespaces returns an object that can list and get APIServiceNamespaces. -func (s *aPIServiceNamespaceLister) APIServiceNamespaces(namespace string) APIServiceNamespaceNamespaceLister { - return aPIServiceNamespaceNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.APIServiceNamespace](s.ResourceIndexer, namespace)} -} - -// APIServiceNamespaceNamespaceLister helps list and get APIServiceNamespaces. -// All objects returned here must be treated as read-only. -type APIServiceNamespaceNamespaceLister interface { - // List lists all APIServiceNamespaces in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.APIServiceNamespace, err error) - // Get retrieves the APIServiceNamespace from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.APIServiceNamespace, error) - APIServiceNamespaceNamespaceListerExpansion -} - -// aPIServiceNamespaceNamespaceLister implements the APIServiceNamespaceNamespaceLister -// interface. -type aPIServiceNamespaceNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.APIServiceNamespace] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/bindableresourcesrequest.go b/sdk/client/listers/kubebind/v1alpha2/bindableresourcesrequest.go deleted file mode 100644 index d7432ca33..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/bindableresourcesrequest.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// BindableResourcesRequestLister helps list BindableResourcesRequests. -// All objects returned here must be treated as read-only. -type BindableResourcesRequestLister interface { - // List lists all BindableResourcesRequests in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.BindableResourcesRequest, err error) - // BindableResourcesRequests returns an object that can list and get BindableResourcesRequests. - BindableResourcesRequests(namespace string) BindableResourcesRequestNamespaceLister - BindableResourcesRequestListerExpansion -} - -// bindableResourcesRequestLister implements the BindableResourcesRequestLister interface. -type bindableResourcesRequestLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.BindableResourcesRequest] -} - -// NewBindableResourcesRequestLister returns a new BindableResourcesRequestLister. -func NewBindableResourcesRequestLister(indexer cache.Indexer) BindableResourcesRequestLister { - return &bindableResourcesRequestLister{listers.New[*kubebindv1alpha2.BindableResourcesRequest](indexer, kubebindv1alpha2.Resource("bindableresourcesrequest"))} -} - -// BindableResourcesRequests returns an object that can list and get BindableResourcesRequests. -func (s *bindableResourcesRequestLister) BindableResourcesRequests(namespace string) BindableResourcesRequestNamespaceLister { - return bindableResourcesRequestNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.BindableResourcesRequest](s.ResourceIndexer, namespace)} -} - -// BindableResourcesRequestNamespaceLister helps list and get BindableResourcesRequests. -// All objects returned here must be treated as read-only. -type BindableResourcesRequestNamespaceLister interface { - // List lists all BindableResourcesRequests in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.BindableResourcesRequest, err error) - // Get retrieves the BindableResourcesRequest from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.BindableResourcesRequest, error) - BindableResourcesRequestNamespaceListerExpansion -} - -// bindableResourcesRequestNamespaceLister implements the BindableResourcesRequestNamespaceLister -// interface. -type bindableResourcesRequestNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.BindableResourcesRequest] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/boundschema.go b/sdk/client/listers/kubebind/v1alpha2/boundschema.go deleted file mode 100644 index 06bad3889..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/boundschema.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// BoundSchemaLister helps list BoundSchemas. -// All objects returned here must be treated as read-only. -type BoundSchemaLister interface { - // List lists all BoundSchemas in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.BoundSchema, err error) - // BoundSchemas returns an object that can list and get BoundSchemas. - BoundSchemas(namespace string) BoundSchemaNamespaceLister - BoundSchemaListerExpansion -} - -// boundSchemaLister implements the BoundSchemaLister interface. -type boundSchemaLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.BoundSchema] -} - -// NewBoundSchemaLister returns a new BoundSchemaLister. -func NewBoundSchemaLister(indexer cache.Indexer) BoundSchemaLister { - return &boundSchemaLister{listers.New[*kubebindv1alpha2.BoundSchema](indexer, kubebindv1alpha2.Resource("boundschema"))} -} - -// BoundSchemas returns an object that can list and get BoundSchemas. -func (s *boundSchemaLister) BoundSchemas(namespace string) BoundSchemaNamespaceLister { - return boundSchemaNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.BoundSchema](s.ResourceIndexer, namespace)} -} - -// BoundSchemaNamespaceLister helps list and get BoundSchemas. -// All objects returned here must be treated as read-only. -type BoundSchemaNamespaceLister interface { - // List lists all BoundSchemas in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.BoundSchema, err error) - // Get retrieves the BoundSchema from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.BoundSchema, error) - BoundSchemaNamespaceListerExpansion -} - -// boundSchemaNamespaceLister implements the BoundSchemaNamespaceLister -// interface. -type boundSchemaNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.BoundSchema] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/cluster.go b/sdk/client/listers/kubebind/v1alpha2/cluster.go deleted file mode 100644 index 6bba81e5a..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/cluster.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterLister helps list Clusters. -// All objects returned here must be treated as read-only. -type ClusterLister interface { - // List lists all Clusters in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.Cluster, err error) - // Clusters returns an object that can list and get Clusters. - Clusters(namespace string) ClusterNamespaceLister - ClusterListerExpansion -} - -// clusterLister implements the ClusterLister interface. -type clusterLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.Cluster] -} - -// NewClusterLister returns a new ClusterLister. -func NewClusterLister(indexer cache.Indexer) ClusterLister { - return &clusterLister{listers.New[*kubebindv1alpha2.Cluster](indexer, kubebindv1alpha2.Resource("cluster"))} -} - -// Clusters returns an object that can list and get Clusters. -func (s *clusterLister) Clusters(namespace string) ClusterNamespaceLister { - return clusterNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.Cluster](s.ResourceIndexer, namespace)} -} - -// ClusterNamespaceLister helps list and get Clusters. -// All objects returned here must be treated as read-only. -type ClusterNamespaceLister interface { - // List lists all Clusters in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.Cluster, err error) - // Get retrieves the Cluster from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.Cluster, error) - ClusterNamespaceListerExpansion -} - -// clusterNamespaceLister implements the ClusterNamespaceLister -// interface. -type clusterNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.Cluster] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/clusterbinding.go b/sdk/client/listers/kubebind/v1alpha2/clusterbinding.go deleted file mode 100644 index b735eade2..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/clusterbinding.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// ClusterBindingLister helps list ClusterBindings. -// All objects returned here must be treated as read-only. -type ClusterBindingLister interface { - // List lists all ClusterBindings in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.ClusterBinding, err error) - // ClusterBindings returns an object that can list and get ClusterBindings. - ClusterBindings(namespace string) ClusterBindingNamespaceLister - ClusterBindingListerExpansion -} - -// clusterBindingLister implements the ClusterBindingLister interface. -type clusterBindingLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.ClusterBinding] -} - -// NewClusterBindingLister returns a new ClusterBindingLister. -func NewClusterBindingLister(indexer cache.Indexer) ClusterBindingLister { - return &clusterBindingLister{listers.New[*kubebindv1alpha2.ClusterBinding](indexer, kubebindv1alpha2.Resource("clusterbinding"))} -} - -// ClusterBindings returns an object that can list and get ClusterBindings. -func (s *clusterBindingLister) ClusterBindings(namespace string) ClusterBindingNamespaceLister { - return clusterBindingNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.ClusterBinding](s.ResourceIndexer, namespace)} -} - -// ClusterBindingNamespaceLister helps list and get ClusterBindings. -// All objects returned here must be treated as read-only. -type ClusterBindingNamespaceLister interface { - // List lists all ClusterBindings in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.ClusterBinding, err error) - // Get retrieves the ClusterBinding from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.ClusterBinding, error) - ClusterBindingNamespaceListerExpansion -} - -// clusterBindingNamespaceLister implements the ClusterBindingNamespaceLister -// interface. -type clusterBindingNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.ClusterBinding] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/collection.go b/sdk/client/listers/kubebind/v1alpha2/collection.go deleted file mode 100644 index 6ff8440be..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/collection.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -import ( - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - labels "k8s.io/apimachinery/pkg/labels" - listers "k8s.io/client-go/listers" - cache "k8s.io/client-go/tools/cache" -) - -// CollectionLister helps list Collections. -// All objects returned here must be treated as read-only. -type CollectionLister interface { - // List lists all Collections in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.Collection, err error) - // Collections returns an object that can list and get Collections. - Collections(namespace string) CollectionNamespaceLister - CollectionListerExpansion -} - -// collectionLister implements the CollectionLister interface. -type collectionLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.Collection] -} - -// NewCollectionLister returns a new CollectionLister. -func NewCollectionLister(indexer cache.Indexer) CollectionLister { - return &collectionLister{listers.New[*kubebindv1alpha2.Collection](indexer, kubebindv1alpha2.Resource("collection"))} -} - -// Collections returns an object that can list and get Collections. -func (s *collectionLister) Collections(namespace string) CollectionNamespaceLister { - return collectionNamespaceLister{listers.NewNamespaced[*kubebindv1alpha2.Collection](s.ResourceIndexer, namespace)} -} - -// CollectionNamespaceLister helps list and get Collections. -// All objects returned here must be treated as read-only. -type CollectionNamespaceLister interface { - // List lists all Collections in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*kubebindv1alpha2.Collection, err error) - // Get retrieves the Collection from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*kubebindv1alpha2.Collection, error) - CollectionNamespaceListerExpansion -} - -// collectionNamespaceLister implements the CollectionNamespaceLister -// interface. -type collectionNamespaceLister struct { - listers.ResourceIndexer[*kubebindv1alpha2.Collection] -} diff --git a/sdk/client/listers/kubebind/v1alpha2/expansion_generated.go b/sdk/client/listers/kubebind/v1alpha2/expansion_generated.go deleted file mode 100644 index dee68fbb5..000000000 --- a/sdk/client/listers/kubebind/v1alpha2/expansion_generated.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright The Kube Bind 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. -*/ - -// Code generated by lister-gen. DO NOT EDIT. - -package v1alpha2 - -// APIServiceBindingListerExpansion allows custom methods to be added to -// APIServiceBindingLister. -type APIServiceBindingListerExpansion interface{} - -// APIServiceBindingBundleListerExpansion allows custom methods to be added to -// APIServiceBindingBundleLister. -type APIServiceBindingBundleListerExpansion interface{} - -// APIServiceExportListerExpansion allows custom methods to be added to -// APIServiceExportLister. -type APIServiceExportListerExpansion interface{} - -// APIServiceExportNamespaceListerExpansion allows custom methods to be added to -// APIServiceExportNamespaceLister. -type APIServiceExportNamespaceListerExpansion interface{} - -// APIServiceExportRequestListerExpansion allows custom methods to be added to -// APIServiceExportRequestLister. -type APIServiceExportRequestListerExpansion interface{} - -// APIServiceExportRequestNamespaceListerExpansion allows custom methods to be added to -// APIServiceExportRequestNamespaceLister. -type APIServiceExportRequestNamespaceListerExpansion interface{} - -// APIServiceNamespaceListerExpansion allows custom methods to be added to -// APIServiceNamespaceLister. -type APIServiceNamespaceListerExpansion interface{} - -// APIServiceNamespaceNamespaceListerExpansion allows custom methods to be added to -// APIServiceNamespaceNamespaceLister. -type APIServiceNamespaceNamespaceListerExpansion interface{} - -// BindableResourcesRequestListerExpansion allows custom methods to be added to -// BindableResourcesRequestLister. -type BindableResourcesRequestListerExpansion interface{} - -// BindableResourcesRequestNamespaceListerExpansion allows custom methods to be added to -// BindableResourcesRequestNamespaceLister. -type BindableResourcesRequestNamespaceListerExpansion interface{} - -// BoundSchemaListerExpansion allows custom methods to be added to -// BoundSchemaLister. -type BoundSchemaListerExpansion interface{} - -// BoundSchemaNamespaceListerExpansion allows custom methods to be added to -// BoundSchemaNamespaceLister. -type BoundSchemaNamespaceListerExpansion interface{} - -// ClusterListerExpansion allows custom methods to be added to -// ClusterLister. -type ClusterListerExpansion interface{} - -// ClusterNamespaceListerExpansion allows custom methods to be added to -// ClusterNamespaceLister. -type ClusterNamespaceListerExpansion interface{} - -// ClusterBindingListerExpansion allows custom methods to be added to -// ClusterBindingLister. -type ClusterBindingListerExpansion interface{} - -// ClusterBindingNamespaceListerExpansion allows custom methods to be added to -// ClusterBindingNamespaceLister. -type ClusterBindingNamespaceListerExpansion interface{} - -// CollectionListerExpansion allows custom methods to be added to -// CollectionLister. -type CollectionListerExpansion interface{} - -// CollectionNamespaceListerExpansion allows custom methods to be added to -// CollectionNamespaceLister. -type CollectionNamespaceListerExpansion interface{} diff --git a/sdk/config/crd/catalog.kbind.io_collections.yaml b/sdk/config/crd/catalog.kbind.io_collections.yaml new file mode 100644 index 000000000..16752498c --- /dev/null +++ b/sdk/config/crd/catalog.kbind.io_collections.yaml @@ -0,0 +1,86 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: collections.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Collection + listKind: CollectionList + plural: collections + singular: collection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Collection groups Exports for UI/CLI browsing. Pure presentation; nothing + binds to a Collection. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: CollectionSpec is a titled grouping of Exports. + properties: + description: + description: description explains the grouping. + type: string + exports: + description: exports lists the member Exports by name. + items: + description: ExportRef references an Export by name. + properties: + name: + description: name of the Export. + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + title: + description: title is the human-facing name of the group. + minLength: 1 + type: string + required: + - exports + - title + type: object + required: + - spec + type: object + served: true + storage: true + subresources: {} diff --git a/sdk/config/crd/catalog.kbind.io_exports.yaml b/sdk/config/crd/catalog.kbind.io_exports.yaml new file mode 100644 index 000000000..6717d76b2 --- /dev/null +++ b/sdk/config/crd/catalog.kbind.io_exports.yaml @@ -0,0 +1,287 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: exports.catalog.kbind.io +spec: + group: catalog.kbind.io + names: + categories: + - kbind + kind: Export + listKind: ExportList + plural: exports + singular: export + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.title + name: Title + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Export is one curated offering in the provider's catalog: human-facing + metadata plus defaults on top of one or more exported APIs. The catalog is + derived-from-core-truth: an Export listing an API that is not actually + exported (label/boundary) gets a condition and is hidden by the gateway — + the export label remains the source of truth, the catalog is presentation + and defaults. Lives on the provider; the konnector never sees it. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ExportSpec describes one offering. + properties: + apis: + description: |- + apis lists the exported APIs a binding to this offering syncs, by CRD + name on the provider ("."). + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + defaults: + description: |- + defaults are copied into the generated ClusterBinding of the one-apply + bundle. + properties: + conflictPolicy: + description: |- + conflictPolicy is the default conflict behavior for the generated + ClusterBinding. + enum: + - Fail + - Adopt + type: string + relatedResources: + description: |- + relatedResources are the related-resource selectors for the generated + ClusterBinding. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string + for the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by + label. + properties: + matchExpressions: + description: matchExpressions is a list of label + selector requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the + selector applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact + name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + type: object + description: + description: description explains the offering to a human choosing + it. + type: string + docs: + description: docs optionally links to the offering's documentation. + type: string + icon: + description: icon optionally points at an icon for UIs. + properties: + url: + description: url of the icon image. + minLength: 1 + type: string + required: + - url + type: object + title: + description: title is the human-facing name of the offering. + minLength: 1 + type: string + required: + - apis + - title + type: object + status: + description: ExportStatus is the observed state of an Export. + properties: + conditions: + description: 'conditions: Ready (all listed APIs are actually exported).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/sdk/config/crd/core.kbind.io_bindings.yaml b/sdk/config/crd/core.kbind.io_bindings.yaml new file mode 100644 index 000000000..54687fe19 --- /dev/null +++ b/sdk/config/crd/core.kbind.io_bindings.yaml @@ -0,0 +1,297 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: bindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Binding + listKind: BindingList + plural: bindings + singular: binding + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Binding activates instance sync for one or more exported APIs within its own + namespace. Namespaced, following the Role convention. It is the v2 answer to + v1's informerScope: Namespaced. Where a ClusterBinding and a Binding cover the + same API on the same connection, the ClusterBinding wins. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict; + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. Not yet synced in the alpha POC. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object detail lives on each object's own condition, not here. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/sdk/config/crd/core.kbind.io_clusterbindings.yaml b/sdk/config/crd/core.kbind.io_clusterbindings.yaml new file mode 100644 index 000000000..9f68aaf51 --- /dev/null +++ b/sdk/config/crd/core.kbind.io_clusterbindings.yaml @@ -0,0 +1,295 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: clusterbindings.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: ClusterBinding + listKind: ClusterBindingList + plural: clusterbindings + singular: clusterbinding + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.connectionRef.name + name: Connection + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClusterBinding activates instance sync for one or more exported APIs + cluster-wide. Cluster-scoped, following the ClusterRole convention. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BindingSpec is the spec shared by ClusterBinding and Binding. The only + difference between the two kinds is scope (cluster-wide vs. one namespace), + which is expressed by the kind, not by a field. + properties: + apis: + description: apis lists one or more exported CRDs to sync, by CRD + name on the provider. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + conflictPolicy: + default: Fail + description: |- + conflictPolicy controls what happens when a target object already exists. + Fail (default) leaves a foreign object untouched and records a conflict; + Adopt takes ownership of an un-owned object. Adopt never steals an object + already carrying another binding's/consumer's markers. + enum: + - Fail + - Adopt + type: string + connectionRef: + description: |- + connectionRef points at the Connection that provides the provider link + and credentials for the listed APIs. + properties: + name: + description: name of the Connection. + minLength: 1 + type: string + required: + - name + type: object + relatedResources: + description: |- + relatedResources are Secrets/ConfigMaps synced alongside instances of the + bound APIs. Not yet synced in the alpha POC. + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - connectionRef + type: object + status: + description: BindingStatus is the observed state shared by ClusterBinding + and Binding. + properties: + boundAPIs: + description: boundAPIs is per-API observed state. + items: + description: BoundAPI is the per-API observed state recorded on + a binding's status. + properties: + conflictCount: + description: |- + conflictCount is the number of objects skipped due to foreign ownership. + Per-object detail lives on each object's own condition, not here. + format: int32 + type: integer + crdHash: + description: |- + crdHash is a hash of the schema currently applied on the consumer for + this API. Empty until the schema has been installed. + type: string + name: + description: name is the CRD name of the bound API, ".". + type: string + required: + - name + type: object + type: array + x-kubernetes-list-type: atomic + conditions: + description: 'conditions: Connected, Synced, Conflicts, PermissionDenied, + Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/sdk/config/crd/core.kbind.io_connections.yaml b/sdk/config/crd/core.kbind.io_connections.yaml new file mode 100644 index 000000000..d222a5bde --- /dev/null +++ b/sdk/config/crd/core.kbind.io_connections.yaml @@ -0,0 +1,259 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: connections.core.kbind.io +spec: + group: core.kbind.io + names: + categories: + - kbind + kind: Connection + listKind: ConnectionList + plural: connections + singular: connection + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .spec.kubeconfigSecretRef.name + name: Secret + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Connection is the link to one provider cluster. It owns the credentials and + schema delivery, and surfaces what the provider exports. Cluster-scoped. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ConnectionSpec defines the desired provider link. + properties: + autoBind: + default: false + description: |- + autoBind, when true, makes the konnector maintain a managed ClusterBinding + (named after this Connection) covering all exported APIs. + type: boolean + kubeconfigSecretRef: + description: |- + kubeconfigSecretRef points at the Secret holding the provider kubeconfig. + Immutable. The only credential reference in the core. + properties: + key: + default: kubeconfig + description: key within the Secret holding the kubeconfig. + type: string + name: + description: name of the Secret. + minLength: 1 + type: string + namespace: + description: namespace of the Secret. Must be the konnector's + designated namespace. + minLength: 1 + type: string + required: + - name + - namespace + type: object + x-kubernetes-validations: + - message: kubeconfigSecretRef is immutable + rule: self == oldSelf + schema: + default: {} + description: schema controls how exported APIs reach the consumer. + properties: + pullPolicy: + default: Bound + description: |- + pullPolicy selects which exported APIs are installed: + Bound - only APIs referenced by a Binding/ClusterBinding (default). + All - every exported API readable by the credentials. + None - never install CRDs (user/extension manages them). + enum: + - Bound + - All + - None + type: string + source: + default: Auto + description: |- + source selects how schemas are obtained: + Auto - CRD if readable on the provider, else OpenAPI (default). + CRD - read apiextensions CRDs verbatim. + OpenAPI - synthesize CRDs from discovery + /openapi/v3. + enum: + - Auto + - CRD + - OpenAPI + type: string + updatePolicy: + default: Always + description: |- + updatePolicy selects whether installed schemas follow provider changes: + Always - follow provider schema changes (default). + Once - pin at first pull. + enum: + - Always + - Once + type: string + type: object + required: + - kubeconfigSecretRef + type: object + status: + description: ConnectionStatus is the observed state of a Connection. + properties: + activeSchemaSource: + description: |- + activeSchemaSource is the schema source actually in effect after resolving + "Auto" (CRD or OpenAPI). The binding uses it to decide whether the + Connection already installed the CRDs (OpenAPI) or it should pull them (CRD). + type: string + conditions: + description: 'conditions: SecretValid, Connected, SchemaInSync, Ready.' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + exportedAPIs: + description: 'exportedAPIs is the discovery result: APIs exported + to these credentials.' + items: + description: ExportedAPI describes one API the provider exports + to these credentials. + properties: + group: + description: group of the exported API. + type: string + name: + description: name is the CRD name of the exported API, ".". + type: string + resource: + description: resource is the plural resource name of the exported + API. + type: string + scope: + description: scope is whether the API is Namespaced or Cluster + scoped. + type: string + versions: + description: versions are the served versions of the exported + API. + items: + type: string + type: array + x-kubernetes-list-type: set + required: + - group + - name + - resource + - scope + - versions + type: object + type: array + x-kubernetes-list-type: atomic + localClusterUID: + description: |- + localClusterUID is the identity of the consumer cluster, pinned on first + connect and immutable thereafter. + type: string + x-kubernetes-validations: + - message: localClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + remoteClusterUID: + description: |- + remoteClusterUID is the identity of the provider cluster, pinned on first + connect and immutable thereafter. A Secret later pointing at a different + cluster is rejected rather than silently re-homing synced objects. + type: string + x-kubernetes-validations: + - message: remoteClusterUID is immutable once set + rule: oldSelf == '' || self == oldSelf + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/sdk/config/crd/iam.kbind.io_grants.yaml b/sdk/config/crd/iam.kbind.io_grants.yaml new file mode 100644 index 000000000..12651a0e1 --- /dev/null +++ b/sdk/config/crd/iam.kbind.io_grants.yaml @@ -0,0 +1,308 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.17.2 + name: grants.iam.kbind.io +spec: + group: iam.kbind.io + names: + categories: + - kbind + kind: Grant + listKind: GrantList + plural: grants + singular: grant + scope: Cluster + versions: + - additionalPrinterColumns: + - jsonPath: .spec.identity.subject + name: Subject + type: string + - jsonPath: .spec.exportName + name: Export + type: string + - jsonPath: .status.namespace + name: Namespace + type: string + - jsonPath: .status.conditions[?(@.type=="Ready")].status + name: Ready + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + Grant records that an identity was issued credentials for an export. The + gateway creates it with the export's API list and defaults resolved in + (issuance is a stable record even if the catalog entry changes later); the + issuer controller provisions the tenancy boundary, ServiceAccount, RBAC and + token from the spec and reports the artifacts in status. Deleting the Grant + revokes: the issuer's cleanup finalizer unwinds everything it provisioned. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: GrantSpec is the issuance request/record. + properties: + apis: + description: |- + apis is the export's API list resolved at issuance time, by CRD name on + the provider ("."). The issuer scopes RBAC to exactly + these. + items: + description: |- + APIRef identifies an exported API by its CRD name on the provider, + i.e. "." (for example "mangodbs.mangodb.io"). Under the + OpenAPI schema source there is no CRD object behind the name; it is still + just resource + group. + properties: + name: + description: name is the CRD name of the exported API, ".". + minLength: 1 + type: string + required: + - name + type: object + minItems: 1 + type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map + conflictPolicy: + description: |- + conflictPolicy is the export's default conflict policy resolved at + issuance time, copied into the generated bundle's ClusterBinding. + enum: + - Fail + - Adopt + type: string + exportName: + description: exportName records which catalog Export this Grant was + issued for. + minLength: 1 + type: string + identity: + description: identity is who the credentials were issued to. + properties: + displayName: + description: displayName is a human-facing name (e.g. email), + informational only. + type: string + groups: + description: groups the identity carried at issuance, informational + only. + items: + type: string + type: array + x-kubernetes-list-type: atomic + subject: + description: subject is the stable identity key, "#" + for OIDC. + minLength: 1 + type: string + required: + - subject + type: object + relatedResources: + description: |- + relatedResources are the export's related-resource selectors resolved at + issuance time. They flow into the bundle's ClusterBinding and widen the + issued RBAC (secrets/configmaps in the declared direction). + items: + description: |- + RelatedResource selects auxiliary objects (Secrets/ConfigMaps) to sync + alongside the bound instances. + properties: + direction: + description: direction the related resource flows. + enum: + - FromProvider + - FromConsumer + type: string + group: + default: "" + description: group of the related resource. Empty string for + the core group. + type: string + resource: + description: |- + resource is the plural resource name. Only "secrets" and "configmaps" + are permitted in core. + enum: + - secrets + - configmaps + type: string + selector: + description: |- + selector restricts which objects are synced. Only labelSelector and + named selectors are supported in core (no JSONPath reference-following). + properties: + labelSelector: + description: labelSelector selects related objects by label. + properties: + matchExpressions: + description: matchExpressions is a list of label selector + requirements. The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector + applies to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + names: + description: names selects related objects by exact name. + items: + type: string + type: array + x-kubernetes-list-type: set + type: object + required: + - direction + - group + - resource + type: object + type: array + x-kubernetes-list-type: atomic + required: + - apis + - exportName + - identity + type: object + status: + description: GrantStatus reports what the issuer provisioned. + properties: + conditions: + description: 'conditions: Ready (credentials provisioned and token + populated).' + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + namespace: + description: namespace is the per-consumer tenancy boundary on the + provider. + type: string + serviceAccount: + description: serviceAccount is the name of the issued ServiceAccount + (in namespace). + type: string + tokenSecret: + description: |- + tokenSecret is the name of the long-lived SA token Secret (in + namespace). The gateway reads it to assemble the bundle's kubeconfig. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/sdk/go.mod b/sdk/go.mod index 9106ff165..ed3ac32e1 100644 --- a/sdk/go.mod +++ b/sdk/go.mod @@ -1,62 +1,30 @@ -module github.com/kube-bind/kube-bind/sdk +module github.com/kbind/kbind/sdk -go 1.26.9 +go 1.26.2 require ( - github.com/google/go-cmp v0.7.0 - github.com/onsi/gomega v1.39.1 - github.com/stretchr/testify v1.11.1 - k8s.io/api v0.35.1 - k8s.io/apiextensions-apiserver v0.35.1 - k8s.io/apimachinery v0.35.1 - k8s.io/client-go v0.35.1 - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 - sigs.k8s.io/yaml v1.6.0 + k8s.io/apiextensions-apiserver v0.33.4 + k8s.io/apimachinery v0.33.4 + sigs.k8s.io/controller-runtime v0.21.0 ) require ( - github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect - github.com/go-logr/logr v1.4.4 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.5 // indirect - github.com/go-openapi/swag v0.26.0 // indirect - github.com/go-openapi/swag/cmdutils v0.26.0 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.26.0 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect - github.com/google/gnostic-models v0.7.1 // indirect - github.com/google/uuid v1.6.0 // indirect + github.com/fxamacker/cbor/v2 v2.7.0 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/gogo/protobuf v1.3.2 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/kr/text v0.2.0 // indirect + github.com/kr/pretty v0.3.1 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/x448/float16 v0.8.4 // indirect - go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // 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/time v0.15.0 // indirect - google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect - gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect + golang.org/x/net v0.38.0 // indirect + golang.org/x/text v0.23.0 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/inf.v0 v0.9.1 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f // indirect - sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect + k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 // indirect + sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.0 // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.6.0 // indirect + sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/sdk/go.sum b/sdk/go.sum index 7bba906e4..89ad74c6c 100644 --- a/sdk/go.sum +++ b/sdk/go.sum @@ -1,148 +1,115 @@ -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= -github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.5 h1:6uCGVXU/aNF13AQNggxfysJ+5ZcU4nEAe+pJyVWRdiE= -github.com/go-openapi/jsonreference v0.21.5/go.mod h1:u25Bw85sX4E2jzFodh1FOKMTZLcfifd1Q+iKKOUxExw= -github.com/go-openapi/swag v0.26.0 h1:GVDXCmfvhfu1BxiHo8/FA+BbKmhecHnG3varjON5/RI= -github.com/go-openapi/swag v0.26.0/go.mod h1:82g3193sZJRbocs7bNCqGfIgq8pkuwVwCfhKIRlEQF0= -github.com/go-openapi/swag/cmdutils v0.26.0 h1:iowihOcvq7y4egO8cOq0dmfohz6wfeQ63U1EnuhO2TU= -github.com/go-openapi/swag/cmdutils v0.26.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.26.0 h1:CmZp+ZT7HrmFwrC3GdGsXBq2+42T1bjKBapcqVpIs3c= -github.com/go-openapi/swag/netutils v0.26.0/go.mod h1:5iK+Ok3ZohWWex1C50BFTPexi03UaPwjW4Oj8kgrpwo= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4= -github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= -github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= -github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo= +github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/onsi/ginkgo/v2 v2.28.0 h1:Rrf+lVLmtlBIKv6KrIGJCjyY8N36vDVcutbGJkyqjJc= -github.com/onsi/ginkgo/v2 v2.28.0/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= -github.com/onsi/gomega v1.39.1 h1:1IJLAad4zjPn2PsnhH70V4DKRFlrCzGBNrNaru+Vf28= -github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2lcfg= +github.com/onsi/ginkgo/v2 v2.22.0 h1:Yed107/8DjTr0lKCNt7Dn8yQ6ybuDRQoMGrNFKzMfHg= +github.com/onsi/ginkgo/v2 v2.22.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo= +github.com/onsi/gomega v1.36.1 h1:bJDPBO7ibjxcbHMgSCoo4Yj18UWbKDlLwX1x9sybDcw= +github.com/onsi/gomega v1.36.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/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/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= -github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= -go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= -go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -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/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -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/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= -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/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af h1:+5/Sw3GsDNlEmu7TfklWKPdQ0Ykja5VEmq2i817+jbI= -google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +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.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= -gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.35.1 h1:0PO/1FhlK/EQNVK5+txc4FuhQibV25VLSdLMmGpDE/Q= -k8s.io/api v0.35.1/go.mod h1:28uR9xlXWml9eT0uaGo6y71xK86JBELShLy4wR1XtxM= -k8s.io/apiextensions-apiserver v0.35.1 h1:p5vvALkknlOcAqARwjS20kJffgzHqwyQRM8vHLwgU7w= -k8s.io/apiextensions-apiserver v0.35.1/go.mod h1:2CN4fe1GZ3HMe4wBr25qXyJnJyZaquy4nNlNmb3R7AQ= -k8s.io/apimachinery v0.35.1 h1:yxO6gV555P1YV0SANtnTjXYfiivaTPvCTKX6w6qdDsU= -k8s.io/apimachinery v0.35.1/go.mod h1:jQCgFZFR1F4Ik7hvr2g84RTJSZegBc8yHgFWKn//hns= -k8s.io/client-go v0.35.1 h1:+eSfZHwuo/I19PaSxqumjqZ9l5XiTEKbIaJ+j1wLcLM= -k8s.io/client-go v0.35.1/go.mod h1:1p1KxDt3a0ruRfc/pG4qT/3oHmUj1AhSHEcxNSGg+OA= -k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= -k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f h1:4Qiq0YAoQATdgmHALJWz9rJ4fj20pB3xebpB4CFNhYM= -k8s.io/kube-openapi v0.0.0-20260414162039-ec9c827d403f/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= -sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= +k8s.io/api v0.33.4 h1:oTzrFVNPXBjMu0IlpA2eDDIU49jsuEorGHB4cvKupkk= +k8s.io/api v0.33.4/go.mod h1:VHQZ4cuxQ9sCUMESJV5+Fe8bGnqAARZ08tSTdHWfeAc= +k8s.io/apiextensions-apiserver v0.33.4 h1:rtq5SeXiDbXmSwxsF0MLe2Mtv3SwprA6wp+5qh/CrOU= +k8s.io/apiextensions-apiserver v0.33.4/go.mod h1:mWXcZQkQV1GQyxeIjYApuqsn/081hhXPZwZ2URuJeSs= +k8s.io/apimachinery v0.33.4 h1:SOf/JW33TP0eppJMkIgQ+L6atlDiP/090oaX0y9pd9s= +k8s.io/apimachinery v0.33.4/go.mod h1:BHW0YOu7n22fFv/JkYOEfkUYNRN0fj0BlvMFWA7b+SM= +k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= +k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738 h1:M3sRQVHv7vB20Xc2ybTt7ODCeFj6JSWYFzOFnYeS6Ro= +k8s.io/utils v0.0.0-20241104100929-3ea5e8cea738/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +sigs.k8s.io/controller-runtime v0.21.0 h1:CYfjpEuicjUecRk+KAeyYh+ouUBn4llGyDYytIGcJS8= +sigs.k8s.io/controller-runtime v0.21.0/go.mod h1:OSg14+F65eWqIu4DceX7k/+QRAbTTvxeQSNSOQpukWM= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8= +sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo= +sigs.k8s.io/randfill v0.0.0-20250304075658-069ef1bbf016/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0 h1:qmp2e3ZfFi1/jJbDGpD4mt3wyp6PE1NfKHCYLqgNQJo= -sigs.k8s.io/structured-merge-diff/v6 v6.4.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= -sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= -sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0 h1:IUA9nvMmnKWcj5jl84xn+T5MnlZKThmUW1TdblaLVAc= +sigs.k8s.io/structured-merge-diff/v4 v4.6.0/go.mod h1:dDy58f92j70zLsuZVuUX5Wp9vtxXpaZnkPGWeqDfCps= +sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= +sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/test/README.md b/test/README.md new file mode 100644 index 000000000..907e5f1ad --- /dev/null +++ b/test/README.md @@ -0,0 +1,22 @@ +# Tests + +This is the test catalog for the kbind slim core: every scenario, what it +asserts, and what is **not** covered yet. Keep it in sync when adding tests. + +## How the tests run + +- **e2e** (`test/e2e/`) run on **envtest** — real `kube-apiserver` + `etcd` + binaries as local processes (no kind, no Docker, no kubelet/nodes). Each test + starts **two** control planes: a *consumer* (pre-loaded with the core CRDs) and + a *provider*, and runs the real engine reconcilers in-process against the + consumer. See [e2e/framework/framework.go](e2e/framework/framework.go). +- **unit** tests live next to the code under `engine/*/` and need no cluster. + +```sh +make test # unit tests only (no external setup) +make test-e2e # downloads envtest assets and runs the e2e suite + +# one e2e test, verbose: +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@release-0.21 use 1.34.1 -p path)" \ + go test -v ./test/e2e -run TestSlimCoreHappyCase +``` diff --git a/test/e2e/backend_test.go b/test/e2e/backend_test.go new file mode 100644 index 000000000..29d9125f9 --- /dev/null +++ b/test/e2e/backend_test.go @@ -0,0 +1,484 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/require" + authenticationv1 "k8s.io/api/authentication/v1" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + apimachineryruntime "k8s.io/apimachinery/pkg/runtime" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/kubernetes" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + + "github.com/kbind/kbind/backend/auth" + "github.com/kbind/kbind/backend/gateway" + "github.com/kbind/kbind/backend/issuer" + "github.com/kbind/kbind/backend/reaper" + "github.com/kbind/kbind/cli" + "github.com/kbind/kbind/pkg/kubeapply" + "github.com/kbind/kbind/pkg/servicecrds" + catalogv1alpha1 "github.com/kbind/kbind/sdk/apis/catalog/v1alpha1" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + iamv1alpha1 "github.com/kbind/kbind/sdk/apis/iam/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// staticAuth is a test Authenticator: fixed bearer tokens map to identities. +type staticAuth struct{ tokens map[string]*auth.Identity } + +func (s *staticAuth) Name() string { return "test" } +func (s *staticAuth) RegisterRoutes(_ *http.ServeMux) {} +func (s *staticAuth) Authenticate(r *http.Request) (*auth.Identity, error) { + if id, ok := s.tokens[auth.TokenFromRequest(r)]; ok { + return id, nil + } + return nil, auth.ErrUnauthenticated +} + +// TestBackendFullLoop exercises the whole extended layer against the real +// core: catalog → gateway bind → issuer-provisioned credentials → one-apply +// bundle → konnector sync through the issued RBAC-fenced ServiceAccount → +// heartbeat in the boundary namespace → revocation, plus the reaper on a +// grant whose bundle was never applied. +func TestBackendFullLoop(t *testing.T) { + env := framework.Start(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + backendScheme := apimachineryruntime.NewScheme() + utilruntime.Must(clientgoscheme.AddToScheme(backendScheme)) + utilruntime.Must(apiextensionsv1.AddToScheme(backendScheme)) + utilruntime.Must(corev1alpha1.AddToScheme(backendScheme)) + utilruntime.Must(catalogv1alpha1.AddToScheme(backendScheme)) + utilruntime.Must(iamv1alpha1.AddToScheme(backendScheme)) + + // The provider serves the service-layer CRDs — via the backend's own + // startup self-install path (what --install-crds runs). + require.NoError(t, servicecrds.Install(ctx, env.ProviderCfg), + "installing catalog/iam CRDs on the provider") + + providerClient, err := client.New(env.ProviderCfg, client.Options{Scheme: backendScheme}) + require.NoError(t, err) + + env.InstallExportedWidgetCRD(t) + + startProviderControllers(t, ctx, env, backendScheme) + startFakeTokenController(t, ctx, env, providerClient) + + // Curate the catalog: one Export over the widget API, in one Collection. + require.NoError(t, providerClient.Create(ctx, &catalogv1alpha1.Export{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: catalogv1alpha1.ExportSpec{ + Title: "Widgets", + Description: "Managed widgets with automated pointiness.", + APIs: []corev1alpha1.APIRef{{Name: "widgets.example.org"}}, + Defaults: catalogv1alpha1.BindingDefaults{ + RelatedResources: []corev1alpha1.RelatedResource{{ + Resource: "secrets", + Direction: corev1alpha1.FromProvider, + Selector: &corev1alpha1.RelatedResourceSelector{ + LabelSelector: &metav1.LabelSelector{ + MatchLabels: map[string]string{"widgets.example.org/related": "true"}, + }, + }, + }}, + }, + }, + })) + require.NoError(t, providerClient.Create(ctx, &catalogv1alpha1.Collection{ + ObjectMeta: metav1.ObjectMeta{Name: "hardware"}, + Spec: catalogv1alpha1.CollectionSpec{ + Title: "Hardware", + Exports: []catalogv1alpha1.ExportRef{{Name: "widgets"}}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + var e catalogv1alpha1.Export + if err := providerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, &e); err != nil { + return nil, err + } + return e.Status.Conditions, nil + }, catalogv1alpha1.ConditionReady) + + // The gateway, fronting exactly this provider. + alice := &auth.Identity{Subject: "https://sso.example.com#alice", DisplayName: "alice@example.com"} + bob := &auth.Identity{Subject: "https://sso.example.com#bob", DisplayName: "bob@example.com"} + gw := gateway.New(gateway.Config{ + ProviderName: "e2e-provider", + BindTimeout: time.Minute, + }, providerClient, &issuer.BundleBuilder{ + Client: providerClient, + ExternalAddress: env.ProviderCfg.Host, + ExternalCA: env.ProviderCfg.CAData, + }, []auth.Authenticator{ + &staticAuth{tokens: map[string]*auth.Identity{ + "token-alice": alice, + "token-bob": bob, + }}, + mustKubernetesAuth(t, env), + }, nil) + server := httptest.NewServer(gw.Handler()) + t.Cleanup(server.Close) + + aliceClient := cli.NewClient(server.URL, "token-alice") + + t.Run("provider metadata and catalog", func(t *testing.T) { + provider, err := aliceClient.Provider(ctx) + require.NoError(t, err) + require.Equal(t, "e2e-provider", provider.Name) + require.Equal(t, []string{"test", "kubernetes"}, provider.AuthMethods) + require.False(t, provider.ApplyEnabled) + + _, err = cli.NewClient(server.URL, "").Catalog(ctx) + require.ErrorIs(t, err, cli.ErrLoginRequired, "catalog requires auth") + + catalog, err := aliceClient.Catalog(ctx) + require.NoError(t, err) + require.Len(t, catalog.Exports, 1) + require.Equal(t, "widgets", catalog.Exports[0].Name) + require.Len(t, catalog.Collections, 1) + + // Related resources (a core concept) surface on the offering. + require.Len(t, catalog.Exports[0].RelatedResources, 1) + rr := catalog.Exports[0].RelatedResources[0] + require.Equal(t, "secrets", rr.Resource) + require.Equal(t, "FromProvider", rr.Direction) + require.Equal(t, "widgets.example.org/related=true", rr.Selector) + }) + + t.Run("konnector install manifest is served for connecting clusters", func(t *testing.T) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/konnector", nil) + require.NoError(t, err) + res, err := http.DefaultClient.Do(req) // no auth: curl|kubectl is a complete client + require.NoError(t, err) + defer func() { _ = res.Body.Close() }() + require.Equal(t, http.StatusOK, res.StatusCode) + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + manifest := string(body) + require.Contains(t, manifest, "kind: CustomResourceDefinition") + require.Contains(t, manifest, "kind: Deployment") + require.Contains(t, manifest, "name: konnector") + }) + + t.Run("kubernetes authenticator accepts a provider-cluster token", func(t *testing.T) { + // An in-platform caller that already holds a provider identity: a + // ServiceAccount token minted on the provider, verified by the + // gateway via TokenReview — no SSO round trip. + clientset, err := kubernetes.NewForConfig(env.ProviderCfg) + require.NoError(t, err) + _, err = clientset.CoreV1().ServiceAccounts("default").Create(ctx, + &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "portal"}}, metav1.CreateOptions{}) + require.NoError(t, err) + tr, err := clientset.CoreV1().ServiceAccounts("default").CreateToken(ctx, "portal", + &authenticationv1.TokenRequest{Spec: authenticationv1.TokenRequestSpec{ + ExpirationSeconds: ptr.To(int64(3600)), + }}, metav1.CreateOptions{}) + require.NoError(t, err) + + catalog, err := cli.NewClient(server.URL, tr.Status.Token).Catalog(ctx) + require.NoError(t, err) + require.Len(t, catalog.Exports, 1) + }) + + var bundle []byte + grantName := issuer.GrantName("widgets", alice.Subject) + boundaryNS := issuer.BoundaryNamespace(alice.Subject) + + t.Run("bind provisions credentials and delivers a single-use bundle", func(t *testing.T) { + res, err := aliceClient.Bind(ctx, "widgets") + require.NoError(t, err) + require.Equal(t, grantName, res.Grant) + + bundle, err = aliceClient.Pickup(ctx, res.PickupURL) + require.NoError(t, err) + require.Contains(t, string(bundle), "kind: Connection") + require.Contains(t, string(bundle), "kind: ClusterBinding") + + _, err = aliceClient.Pickup(ctx, res.PickupURL) + require.Error(t, err, "pickup is single-use") + + // The issuer's artifacts exist: SA, token, RBAC, in the boundary. + var sa corev1.ServiceAccount + require.NoError(t, providerClient.Get(ctx, client.ObjectKey{Namespace: boundaryNS, Name: grantName}, &sa)) + var role rbacv1.Role + require.NoError(t, providerClient.Get(ctx, client.ObjectKey{Namespace: boundaryNS, Name: grantName}, &role)) + }) + + t.Run("one apply of the bundle syncs through issued credentials", func(t *testing.T) { + applier, err := kubeapply.New(env.ConsumerCfg, "e2e") + require.NoError(t, err) + objs, err := kubeapply.DecodeYAML(bundle) + require.NoError(t, err) + _, err = applier.Apply(ctx, objs) + require.NoError(t, err) + + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + var conn corev1alpha1.Connection + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: grantName}, &conn); err != nil { + return nil, err + } + return conn.Status.Conditions, nil + }, corev1alpha1.ConditionReady) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + var cb corev1alpha1.ClusterBinding + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: grantName}, &cb); err != nil { + return nil, err + } + return cb.Status.Conditions, nil + }, corev1alpha1.ConditionReady) + + // Spec up: a consumer widget materializes on the provider — written by + // the issued ServiceAccount, fenced by the issued RBAC. + widget := &unstructured.Unstructured{} + widget.SetGroupVersionKind(framework.WidgetGVK()) + widget.SetNamespace("default") + widget.SetName("w-backend") + require.NoError(t, unstructured.SetNestedField(widget.Object, "pointy", "spec", "shape")) + require.NoError(t, env.ConsumerClient.Create(ctx, widget)) + + require.Eventually(t, func() bool { + got := &unstructured.Unstructured{} + got.SetGroupVersionKind(framework.WidgetGVK()) + return env.ProviderClient.Get(ctx, client.ObjectKey{Namespace: "default", Name: "w-backend"}, got) == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "widget should sync to the provider") + + // The heartbeat Lease lands in the boundary namespace (the issued + // kubeconfig pins its context namespace there) — the reaper's signal. + require.Eventually(t, func() bool { + var leases coordinationv1.LeaseList + if err := providerClient.List(ctx, &leases, client.InNamespace(boundaryNS), + client.MatchingLabels{corev1alpha1.LabelManaged: "true"}); err != nil { + return false + } + return len(leases.Items) > 0 + }, wait.ForeverTestTimeout, 200*time.Millisecond, "heartbeat Lease in the boundary namespace") + }) + + t.Run("clusters view shows the consumer cluster and what it syncs", func(t *testing.T) { + // Bob binds but never applies his bundle: he must show up as + // pending, not as a cluster. + _, err := cli.NewClient(server.URL, "token-bob").Bind(ctx, "widgets") + require.NoError(t, err) + + require.Eventually(t, func() bool { + clusters, err := aliceClient.Clusters(ctx) + if err != nil || len(clusters.Clusters) != 1 { + return false + } + cluster := clusters.Clusters[0] + if !cluster.Live || len(cluster.Bindings) != 1 { + return false + } + binding := cluster.Bindings[0] + if binding.Grant != grantName || binding.Export != "widgets" || + binding.Identity != alice.DisplayName || !binding.Live { + return false + } + // The synced widget from the previous subtest is attributed to + // this cluster. + if len(binding.APIs) != 1 || binding.APIs[0].Name != "widgets.example.org" || + binding.APIs[0].SyncedCount < 1 { + return false + } + // Bob: bound, never connected. + for _, p := range clusters.Pending { + if p.Export == "widgets" && p.Identity == bob.DisplayName { + return true + } + } + return false + }, wait.ForeverTestTimeout, 200*time.Millisecond, + "clusters view should show alice's live cluster with a synced widget and bob as pending") + }) + + t.Run("catalog instances view lists synced objects per export", func(t *testing.T) { + // A provider original matching the export's FromProvider related rule + // shows up as a related row ("delivered with this service"). + require.NoError(t, providerClient.Create(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "widgets-connection", + Namespace: "default", + Labels: map[string]string{"widgets.example.org/related": "true"}, + }, + StringData: map[string]string{"endpoint": "https://widgets.internal"}, + })) + + require.Eventually(t, func() bool { + res, err := aliceClient.Instances(ctx, "widgets") + if err != nil || len(res.Instances) != 2 { + return false + } + widget, related := res.Instances[0], res.Instances[1] + if widget.API != "widgets.example.org" || widget.Related || + widget.Namespace != "default" || widget.Name != "w-backend" || + widget.ClusterUID == "" || widget.Identity != alice.DisplayName { + return false + } + return related.API == "secrets" && related.Related && + related.Direction == "FromProvider" && + related.Namespace == "default" && related.Name == "widgets-connection" && + related.ClusterUID == "" + }, wait.ForeverTestTimeout, 200*time.Millisecond, + "the synced widget and the related secret original should both be listed") + + _, err := aliceClient.Instances(ctx, "no-such-export") + require.Error(t, err, "unknown export is an error") + }) + + t.Run("reaper reaps a grant whose bundle was never applied", func(t *testing.T) { + bobClient := cli.NewClient(server.URL, "token-bob") + res, err := bobClient.Bind(ctx, "widgets") + require.NoError(t, err) + bobGrant := res.Grant + require.NotEqual(t, grantName, bobGrant) + + kubeIssuer := &issuer.KubeIssuer{Client: providerClient} + go (&reaper.Reaper{ + Client: providerClient, + Issuer: kubeIssuer, + TTL: 3 * time.Second, + Revoke: true, + Interval: 500 * time.Millisecond, + }).Start(ctx) //nolint:errcheck + + require.Eventually(t, func() bool { + var g iamv1alpha1.Grant + return apierrors.IsNotFound(providerClient.Get(ctx, client.ObjectKey{Name: bobGrant}, &g)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "stale grant should be revoked") + + // Bob's credentials are gone with it. + var sa corev1.ServiceAccount + require.Eventually(t, func() bool { + return apierrors.IsNotFound(providerClient.Get(ctx, + client.ObjectKey{Namespace: issuer.BoundaryNamespace(bob.Subject), Name: bobGrant}, &sa)) + }, wait.ForeverTestTimeout, 200*time.Millisecond) + + // Alice keeps heartbeating; her grant survives the same reaper. + var g iamv1alpha1.Grant + require.NoError(t, providerClient.Get(ctx, client.ObjectKey{Name: grantName}, &g)) + }) + + t.Run("deleting the grant revokes the credentials", func(t *testing.T) { + var g iamv1alpha1.Grant + require.NoError(t, providerClient.Get(ctx, client.ObjectKey{Name: grantName}, &g)) + require.NoError(t, providerClient.Delete(ctx, &g)) + + require.Eventually(t, func() bool { + var sa corev1.ServiceAccount + return apierrors.IsNotFound(providerClient.Get(ctx, client.ObjectKey{Namespace: boundaryNS, Name: grantName}, &sa)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "revocation removes the ServiceAccount") + + // The boundary namespace (and the synced objects) survive plain + // revocation — destructive cleanup is the reaper's explicit opt-in. + var ns corev1.Namespace + require.NoError(t, providerClient.Get(ctx, client.ObjectKey{Name: boundaryNS}, &ns)) + }) +} + +func mustKubernetesAuth(t *testing.T, env *framework.Env) *auth.Kubernetes { + t.Helper() + k, err := auth.NewKubernetes(env.ProviderCfg) + require.NoError(t, err) + return k +} + +// startProviderControllers runs the issuer's Grant + Export reconcilers +// against the provider, the way cmd/backend does. +func startProviderControllers(t *testing.T, ctx context.Context, env *framework.Env, scheme *apimachineryruntime.Scheme) { + t.Helper() + mgr, err := ctrl.NewManager(env.ProviderCfg, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + Controller: ctrlconfig.Controller{SkipNameValidation: ptr.To(true)}, + }) + require.NoError(t, err) + require.NoError(t, (&issuer.GrantReconciler{Issuer: &issuer.KubeIssuer{Client: mgr.GetClient()}}).SetupWithManager(mgr)) + require.NoError(t, (&issuer.ExportReconciler{}).SetupWithManager(mgr)) + go func() { + if err := mgr.Start(ctx); err != nil { + t.Logf("provider manager stopped: %v", err) + } + }() + require.True(t, mgr.GetCache().WaitForCacheSync(ctx), "provider controller cache sync") +} + +// startFakeTokenController plays kube-controller-manager's token controller, +// which envtest does not run: it populates service-account-token Secrets with +// a real TokenRequest token (accepted by the envtest API server) and the CA. +func startFakeTokenController(t *testing.T, ctx context.Context, env *framework.Env, providerClient client.Client) { + t.Helper() + clientset, err := kubernetes.NewForConfig(env.ProviderCfg) + require.NoError(t, err) + go func() { + for { + select { + case <-ctx.Done(): + return + case <-time.After(200 * time.Millisecond): + } + var secrets corev1.SecretList + if err := providerClient.List(ctx, &secrets); err != nil { + continue + } + for i := range secrets.Items { + secret := &secrets.Items[i] + if secret.Type != corev1.SecretTypeServiceAccountToken || len(secret.Data[corev1.ServiceAccountTokenKey]) > 0 { + continue + } + saName := secret.Annotations[corev1.ServiceAccountNameKey] + if saName == "" { + continue + } + tr, err := clientset.CoreV1().ServiceAccounts(secret.Namespace).CreateToken(ctx, saName, + &authenticationv1.TokenRequest{Spec: authenticationv1.TokenRequestSpec{ + ExpirationSeconds: ptr.To(int64(24 * 3600)), + }}, metav1.CreateOptions{}) + if err != nil { + continue + } + if secret.Data == nil { + secret.Data = map[string][]byte{} + } + secret.Data[corev1.ServiceAccountTokenKey] = []byte(tr.Status.Token) + secret.Data[corev1.ServiceAccountRootCAKey] = env.ProviderCfg.CAData + secret.Data["namespace"] = []byte(secret.Namespace) + _ = providerClient.Update(ctx, secret) + } + } + }() +} diff --git a/test/e2e/bind/happy-case_test.go b/test/e2e/bind/happy-case_test.go deleted file mode 100644 index df6c8f68f..000000000 --- a/test/e2e/bind/happy-case_test.go +++ /dev/null @@ -1,928 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 bind - -import ( - "context" - "fmt" - "path" - "slices" - "strings" - "testing" - "time" - - "github.com/google/uuid" - "github.com/stretchr/testify/require" - apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/cli-runtime/pkg/genericclioptions" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/rest" - "k8s.io/client-go/util/retry" - "sigs.k8s.io/yaml" - - kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources" - bindapiservice "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-apiservice/plugin" - examples "github.com/kube-bind/kube-bind/deploy/examples" - "github.com/kube-bind/kube-bind/pkg/konnector/types" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" - "github.com/kube-bind/kube-bind/test/e2e/framework" -) - -// TestClusterScoped tests scenarios where consumer-side resources are cluster-scoped (Sheriffs). -// Uses: template-sheriffs.yaml (scope=Cluster) & cr-sheriff.yaml -// -// This test validates three isolation strategies for cluster-scoped resources: -// - IsolationPrefixed: Sheriff name is prefixed with consumer ID, secrets isolated -// - IsolationNone: Same names and namespaces on both sides (⚠️ no isolation!) -// - IsolationNamespaced: CRD toggled to NamespaceScoped on provider, secrets isolated -// -// For detailed architecture diagrams and explanations, see: -// docs/content/developers/architecture.md#cluster-scoped-resources -func TestClusterScoped(t *testing.T) { - // name & test type defined by letters - cc - cluster-cluster so its easier to identify failures in the logs. - testHappyCase(t, "cc-prefixed", apiextensionsv1.ClusterScoped, apiextensionsv1.ClusterScoped, kubebindv1alpha2.ClusterScope, kubebindv1alpha2.IsolationPrefixed) - testHappyCase(t, "cc-none", apiextensionsv1.ClusterScoped, apiextensionsv1.ClusterScoped, kubebindv1alpha2.ClusterScope, kubebindv1alpha2.IsolationNone) - testHappyCase(t, "cc-namespaced", apiextensionsv1.ClusterScoped, apiextensionsv1.NamespaceScoped, kubebindv1alpha2.ClusterScope, kubebindv1alpha2.IsolationNamespaced) -} - -// TestNamespacedScoped tests scenarios where consumer-side resources are namespaced (Cowboys). -// Uses: template-cowboys.yaml (scope=Namespaced) & cr-cowboy.yaml -// -// This test validates two informerScope configurations for namespaced resources: -// - NamespacedScope (nn): Konnector watches only its own namespace on provider -// - ClusterScope (nc): Konnector watches cluster-wide on provider -// -// Note: Namespaced resources ALWAYS use ServiceNamespaced isolation strategy, -// regardless of the isolation parameter. Namespace mapping is always: -// wild-west → kube-bind--wild-west -// -// For detailed architecture diagrams and explanations, see: -// docs/content/developers/architecture.md#namespaced-resources -func TestNamespacedScoped(t *testing.T) { - testHappyCase(t, "nn", apiextensionsv1.NamespaceScoped, apiextensionsv1.NamespaceScoped, kubebindv1alpha2.NamespacedScope, "") - testHappyCase(t, "nc", apiextensionsv1.NamespaceScoped, apiextensionsv1.NamespaceScoped, kubebindv1alpha2.ClusterScope, "") -} - -// testHappyCase is the main test function that validates end-to-end kube-bind functionality. -// It tests the complete lifecycle of binding, syncing, and managing resources between -// consumer and provider clusters. -// -// TEST EXECUTION FLOW (with 2 consumers for isolation verification): -// -// SETUP PHASE -// =========== -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 1. Create provider workspace (kcp) │ -// │ - Install kube-bind CRDs │ -// │ - Start backend server (HTTP API for binding) │ -// │ - Bootstrap example CRDs (Cowboys/Sheriffs) via examples.Bootstrap() │ -// │ - Apply templates (template-cowboys.yaml / template-sheriffs.yaml) │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 2. Create consumer workspaces (consumer1, consumer2) │ -// │ - Start konnector on each consumer (watches APIServiceBinding) │ -// └──────────────────────────────────────────────────────────────────────────┘ -// -// BINDING PHASE (executed for each consumer) -// ============= -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 3. Login to provider │ -// │ - Simulate browser auth flow │ -// │ - Save credentials to kube-bind-config.yaml │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 4. List templates & collections │ -// │ - Verify backend returns 2 templates (cowboys, sheriffs) │ -// │ - Verify 1 collection exists │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 5. Bind API (consumer.Bind()) │ -// │ - Send BindableResourcesRequest with: │ -// │ • templateRef: "cowboys" or "sheriffs" │ -// │ • clusterIdentity: │ -// │ - Backend creates on provider: │ -// │ • Contract namespace: kube-bind- │ -// │ • APIServiceExportRequest │ -// │ • APIServiceNamespace: wild-west → kube-bind--wild-west │ -// │ • RBAC resources for secret access │ -// │ - Backend returns BindingResourceResponse with CRDs, RBAC manifests │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 6. Apply binding on consumer (BindFromResponse()) │ -// │ - Create APIServiceBinding (watched by konnector) │ -// │ - Apply CRDs (Cowboys.wildwest.dev or Sheriffs.wildwest.dev) │ -// │ - Wait for CRD to be established │ -// └──────────────────────────────────────────────────────────────────────────┘ -// -// SYNCHRONIZATION & VERIFICATION PHASE (per consumer) -// =================================== -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 7. Create instance on consumer (from cr-cowboy.yaml / cr-sheriff.yaml) │ -// │ - Namespace: wild-west │ -// │ - Resource: billy-the-kid (Cowboy) or wyatt-earp (Sheriff) │ -// │ - Secrets: colt-45-permit, cowboy-gang-affiliation, etc. │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 8. Verify sync to provider │ -// │ ✓ Instance created on provider (with ClusterNamespaceAnnotation) │ -// │ ✓ providerContractNamespace extracted from annotation │ -// │ ✓ providerObjectNamespace captured (may be empty for cluster-scoped) │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 9. Verify namespace pre-seeding & RBAC │ -// │ ✓ APIServiceNamespace created with .status.namespace populated │ -// │ ✓ Actual provider namespace exists (kube-bind--wild-west) │ -// │ ✓ RBAC created (ClusterRole/Role + Bindings) for secret access │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 10. Test bi-directional sync │ -// │ ✓ Update spec on consumer → synced to provider │ -// │ ✓ Update status on provider → synced to consumer │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 11. Verify secret sync (from permissionClaims in template) │ -// │ ✓ Referenced secret (spec.secretRefs) synced to provider namespace │ -// │ ✓ Label-selected secret (app=cowboy/sheriff) synced │ -// │ Location: kube-bind--wild-west/ │ -// └──────────────────────────────────────────────────────────────────────────┘ -// ▼ -// ┌──────────────────────────────────────────────────────────────────────────┐ -// │ 12. Test deletion │ -// │ ✓ Delete on consumer → deleted on provider │ -// └──────────────────────────────────────────────────────────────────────────┘ -// -// MULTI-CONSUMER ISOLATION VERIFICATION: -// ====================================== -// Running with 2 consumers validates that: -// - Each consumer gets isolated contract namespace (kube-bind-, kube-bind-) -// - Each consumer gets isolated provider namespace (kube-bind--wild-west, etc.) -// - Secrets are fully isolated between consumers -// - For cluster-scoped resources with IsolationNone, last-write-wins (both write to same Sheriff name) -// - For cluster-scoped resources with IsolationPrefixed, resources are name-prefixed -// - For cluster-scoped resources with IsolationNamespaced, provider CRD is toggled to NamespaceScoped -func testHappyCase( - t *testing.T, - name string, - consumerResourceScope apiextensionsv1.ResourceScope, - providerResourceScope apiextensionsv1.ResourceScope, - informerScope kubebindv1alpha2.InformerScope, - isolationStrategy kubebindv1alpha2.Isolation, -) { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) // Commented out to prevent cleanup of kcp assets - - suffix := framework.RandomString(4) - - t.Logf("Creating provider workspace") - providerConfig, providerKubeconfig := framework.NewWorkspace(t, framework.ClientConfig(t), framework.WithName("%s-provider-%s", name, suffix)) - - t.Logf("Installing kubebind CRDs") - framework.InstallKubeBindCRDs(t, providerConfig) - - t.Logf("Starting backend with random port") - addr, _ := framework.StartBackend(t, - "--kubeconfig="+providerKubeconfig, - "--listen-address=:0", - "--consumer-scope="+string(informerScope), - "--isolation="+string(isolationStrategy), - ) - - t.Logf("Creating CRD on provider side") - examples.Bootstrap(t, framework.DiscoveryClient(t, providerConfig), framework.DynamicClient(t, providerConfig), nil) - - // For namespaced-isolated cluster-scoped objects, the CRD needs to be namespaced on the provider side, - // but cluster-scoped on the consumer side. To make this setup possible without introducing another CRD, - // we will simply "hack" the CRD here on the providerside to make it work. - if providerResourceScope == apiextensionsv1.NamespaceScoped && consumerResourceScope == apiextensionsv1.ClusterScoped { - t.Logf("Changing sheriff CRD scope to namespaced on the provider side") - toggleCRDScope(t, ctx, providerConfig, "sheriffs.wildwest.dev", apiextensionsv1.NamespaceScoped) - } - - t.Logf("Creating consumer workspace and starting konnector") - consumer1Config, consumer1Kubeconfig := framework.NewWorkspace(t, framework.ClientConfig(t), - framework.WithGenerateName("%s-consumer-%s-", name, suffix)) - consumer2Config, consumer2Kubeconfig := framework.NewWorkspace(t, framework.ClientConfig(t), - framework.WithGenerateName("%s-consumer-%s-", name, suffix)) - framework.StartKonnector(t, consumer1Config, "--kubeconfig="+consumer1Kubeconfig, "--server-address=:0") - framework.StartKonnector(t, consumer2Config, "--kubeconfig="+consumer2Kubeconfig, "--server-address=:0") - - serviceGVR := schema.GroupVersionResource{Group: "wildwest.dev", Version: "v1alpha1", Resource: "cowboys"} - templateRef := "cowboys" - - if consumerResourceScope == apiextensionsv1.ClusterScoped { - serviceGVR = schema.GroupVersionResource{Group: "wildwest.dev", Version: "v1alpha1", Resource: "sheriffs"} - templateRef = "sheriffs" - } - - consumer1Client := framework.DynamicClient(t, consumer1Config).Resource(serviceGVR) - consumer2Client := framework.DynamicClient(t, consumer2Config).Resource(serviceGVR) - providerClient := framework.DynamicClient(t, providerConfig).Resource(serviceGVR) - - providerCoreClient := framework.KubeClient(t, providerConfig).CoreV1() - providerBindClient := framework.BindClient(t, providerConfig) - - kubeBindConfig := path.Join(framework.WorkDir(t), "kube-bind-config.yaml") - - // Secrets from the actual examples: - // For cowboys: colt-45-permit (referenced), cowboy-gang-affiliation (label selector) - // For sheriffs: sheriff-badge-credentials (referenced), sheriff-jurisdiction-config (label selector) - var referencedSecretName, labelSelectedSecretName string - var filename string - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - referencedSecretName = "colt-45-permit" - labelSelectedSecretName = "cowboy-gang-affiliation" - filename = "cr-cowboy.yaml" - } else { - referencedSecretName = "sheriff-badge-credentials" - labelSelectedSecretName = "sheriff-jurisdiction-config" - filename = "cr-sheriff.yaml" - } - - // Initial setup steps - for _, tc := range []struct { - name string - step func(t *testing.T) - }{ - { - name: "Login to provider", - step: func(t *testing.T) { - iostreams, _, _, _ := genericclioptions.NewTestIOStreams() - authURLDryRunCh := make(chan string, 1) - go framework.SimulateBrowser(t, authURLDryRunCh) - framework.Login(t, iostreams, authURLDryRunCh, kubeBindConfig, fmt.Sprintf("http://%s/api/exports", addr.String()), "") - }, - }, - { - name: "List templates", - step: func(t *testing.T) { - c := framework.GetKubeBindRestClient(t, kubeBindConfig) - result, err := c.GetTemplates(ctx) - require.NoError(t, err) - require.NotNil(t, result) - require.Len(t, result.Items, 2) - }, - }, - { - name: "List collections", - step: func(t *testing.T) { - c := framework.GetKubeBindRestClient(t, kubeBindConfig) - result, err := c.GetCollections(ctx) - require.NoError(t, err) - require.NotNil(t, result) - require.Len(t, result.Items, 1) - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - tc.step(t) - }) - } - - // Consumer-specific test loops - for _, consumer := range []struct { - // name is unique name usined in naming instances - name string - // clusterIdentity is unique UUID representing the consumer cluster identity. - clusterIdentity uuid.UUID - // consumerConfig is the REST config for the consumer cluster. - consumerConfig *rest.Config - // consumerKubeconfig is the kubeconfig path for the consumer cluster. - consumerKubeconfig string - // consumerClient is the dynamic client for the main resource on the consumer side. - consumerClient dynamic.NamespaceableResourceInterface - - // Bellow are runtime values populated during the test run and stored in the same struct - // for easier access. - - // providerContractNamespace is the namespace representing the binding contract on the backend side. - // YOu can get it from every synced object annotation. - providerContractNamespace string - // providerObjectNamespace is the namespace on the provider side where the synced object resides. Might be empty for cluster-scoped. - providerObjectNamespace string - // consumerObjectNamespace is the namespace on the consumer side where the main object resides. - consumerObjectNamespace string - // bindResponse is the response from the bind API call for this consumer. This contains dedicated provider - // resources for this consumer. - bindResponse *kubebindv1alpha2.BindingResourceResponse - }{ - { - name: "consumer1", - clusterIdentity: uuid.Must(uuid.NewUUID()), - consumerConfig: consumer1Config, - consumerKubeconfig: consumer1Kubeconfig, - consumerClient: consumer1Client, - - providerContractNamespace: "unknown", - providerObjectNamespace: "unknown", - consumerObjectNamespace: "wild-west", // This is part of binding contract and should be honored - bindResponse: nil, - }, - { - name: "consumer2", - clusterIdentity: uuid.Must(uuid.NewUUID()), - consumerConfig: consumer2Config, - consumerKubeconfig: consumer2Kubeconfig, - consumerClient: consumer2Client, - - providerContractNamespace: "unknown", - providerObjectNamespace: "unknown", - consumerObjectNamespace: "wild-west", - bindResponse: nil, - }, - } { - t.Run(consumer.name, func(t *testing.T) { - for _, tc := range []struct { - name string - step func(t *testing.T) - }{ - { - name: "Get bind APIServiceExportRequest from server", - step: func(t *testing.T) { - c := framework.GetKubeBindRestClient(t, kubeBindConfig) - var err error - - consumer.bindResponse, err = c.Bind(ctx, &kubebindv1alpha2.BindableResourcesRequest{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-binding", - }, - Spec: kubebindv1alpha2.BindableResourcesRequestSpec{ - TemplateRef: kubebindv1alpha2.APIServiceExportTemplateRef{ - Name: templateRef, - }, - ClusterIdentity: kubebindv1alpha2.ClusterIdentity{ - Identity: consumer.clusterIdentity.String(), - }, - }, - }) - require.NoError(t, err) - require.NotNil(t, *consumer.bindResponse) - }, - }, - { - name: "Bind the payload on consumer side", - step: func(t *testing.T) { - iostreams, _, _, _ := genericclioptions.NewTestIOStreams() - binderOpts := &bindapiservice.BinderOptions{ - IOStreams: iostreams, - SkipKonnector: true, - } - - binder := bindapiservice.NewBinder(consumer.consumerConfig, binderOpts) - result, err := binder.BindFromResponse(ctx, consumer.bindResponse) - require.NoError(t, err) - require.Len(t, result, 1) - - t.Logf("Waiting for %s CRD to be created on consumer side", serviceGVR.Resource) - crdClient := framework.ApiextensionsClient(t, consumer.consumerConfig).ApiextensionsV1().CustomResourceDefinitions() - require.Eventually(t, func() bool { - if serviceGVR.Group == "" { - serviceGVR.Group = "core" - } - _, err := crdClient.Get(ctx, serviceGVR.Resource+"."+serviceGVR.Group, metav1.GetOptions{}) - return err == nil - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for %s CRD to be created on consumer side", serviceGVR.Resource) - }, - }, - { - name: "instances are synced", - step: func(t *testing.T) { - instanceName := fmt.Sprintf("test-%s", consumer.name) - t.Logf("Seeding example objects on consumer side for %s with instance name %s", serviceGVR.Resource, instanceName) - - err := seedSpecificCRExample(t, framework.DynamicClient(t, consumer.consumerConfig), filename, instanceName) - require.NoError(t, err) - - t.Logf("Trying to create %s on consumer side", serviceGVR.Resource) - - t.Logf("Waiting for the %s instance to be created on provider side", serviceGVR.Resource) - var instances *unstructured.UnstructuredList - require.Eventually(t, func() bool { - var err error - instances, err = providerClient.List(ctx, metav1.ListOptions{}) - return err == nil && len(instances.Items) >= 1 - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for the %s instance to be created on provider side", serviceGVR.Resource) - - // Find our specific instance - var ourInstance *unstructured.Unstructured - for _, item := range instances.Items { - if strings.Contains(item.GetName(), instanceName) { - ourInstance = &item - break - } - } - require.NotNil(t, ourInstance, "should find instance for consumer %s", consumer.name) - - // providerNs is the namespaced where the synced object lives; this might be empty - // for cluster-scoped objects on the provider side. - consumer.providerObjectNamespace = ourInstance.GetNamespace() - // Cluster namespace represent binding contract namespace, and is stored on every object. - consumer.providerContractNamespace = ourInstance.GetAnnotations()[types.ClusterNamespaceAnnotationKey] - require.NotEmpty(t, consumer.providerContractNamespace, "cluster namespace annotation must always exist") - require.NotEqual(t, consumer.providerContractNamespace, "unknown") - - // Verify consumer source metadata annotations are set on the provider-side object. - annotations := ourInstance.GetAnnotations() - _, hasConsumerNS := annotations[types.ConsumerNamespaceAnnotationKey] - require.True(t, hasConsumerNS, "consumer-namespace annotation must exist on provider object") - consumerUID := annotations[types.ConsumerUIDAnnotationKey] - require.NotEmpty(t, consumerUID, "consumer-uid annotation must exist on provider object") - }, - }, - { - name: "verify BoundSchemas have owner references to APIServiceExport", - step: func(t *testing.T) { - t.Logf("Verifying BoundSchemas have owner references to APIServiceExport") - export, err := providerBindClient.KubeBindV1alpha2().APIServiceExports(consumer.providerContractNamespace).Get(ctx, "test-binding", metav1.GetOptions{}) - if errors.IsNotFound(err) && consumer.name != "consumer1" { - t.Skip("APIServiceExport already deleted by another consumer") - } - require.NoError(t, err, "APIServiceExport should exist") - - boundSchemas, err := providerBindClient.KubeBindV1alpha2().BoundSchemas(consumer.providerContractNamespace).List(ctx, metav1.ListOptions{}) - require.NoError(t, err, "should be able to list BoundSchemas") - require.NotEmpty(t, boundSchemas.Items, "should have at least one BoundSchema") - - // Verify each BoundSchema has an owner reference to the APIServiceExport - for _, boundSchema := range boundSchemas.Items { - t.Logf("Checking owner reference for BoundSchema %s", boundSchema.Name) - - var hasOwnerRef bool - for _, ownerRef := range boundSchema.OwnerReferences { - if ownerRef.Kind == "APIServiceExport" && - ownerRef.Name == export.Name && - ownerRef.UID == export.UID && - ownerRef.Controller != nil && - *ownerRef.Controller { - hasOwnerRef = true - break - } - } - - require.True(t, hasOwnerRef, - "BoundSchema %s should have controller owner reference to APIServiceExport %s", - boundSchema.Name, export.Name) - } - - t.Logf("All BoundSchemas have proper owner references") - }, - }, - // Request included namespace, so we check it first - { - name: "verify provider side namespace pre-seeding and RBAC management", - step: func(t *testing.T) { - t.Logf("Verifying APIServiceNamespace was created from pre-seeded namespace spec") - var foundPreSeededNamespace bool - var actualProviderNamespace string - require.Eventually(t, func() bool { - // If we are operating namespaced resources - namespace will be set, if cluster - we need to use - // extracted one from the cluster-scoped object. - namespaces, err := providerBindClient.KubeBindV1alpha2().APIServiceNamespaces(consumer.providerContractNamespace).List(ctx, metav1.ListOptions{}) - if err != nil { - return false - } - - for _, ns := range namespaces.Items { - if ns.Name == "wild-west" && ns.Status.Namespace != "" { - actualProviderNamespace = ns.Status.Namespace - foundPreSeededNamespace = true - return true - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for pre-seeded APIServiceNamespace to be created on provider side") - require.True(t, foundPreSeededNamespace, "Pre-seeded namespace 'wild-west' should be created via APIServiceExportRequest.Spec.Namespaces") - - providerCoreClient := framework.KubeClient(t, providerConfig).CoreV1() - _, err := providerCoreClient.Namespaces().Get(ctx, actualProviderNamespace, metav1.GetOptions{}) - require.NoError(t, err, "Actual provider side namespace object should exist") - - expectedVerbs := []string{"get", "list", "watch", "create", "update", "patch", "delete"} - slices.Sort(expectedVerbs) - - switch informerScope { - case kubebindv1alpha2.ClusterScope: - t.Logf("Verifying RBAC resources were created for secret management in cluster scope") - rbacClient := framework.KubeClient(t, providerConfig).RbacV1() - - require.Eventually(t, func() bool { - clusterRoles, err := rbacClient.ClusterRoles().List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, clusterRole := range clusterRoles.Items { - if !strings.HasPrefix(clusterRole.Name, "kube-binder-claims-") { - continue - } - for _, rule := range clusterRole.Rules { - if !slices.Contains(rule.Resources, "secrets") || !slices.Contains(rule.APIGroups, "") { - continue - } - slices.Sort(rule.Verbs) - if slices.Equal(expectedVerbs, rule.Verbs) { - return true - } - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for ClusterRole for claimed secrets resource to be ready on provider side") - - t.Logf("Verifying ClusterRole for secrets claim has been aggregated into kube-binder-exports ClusterRole") - - require.Eventually(t, func() bool { - aggregatingClusterRole, err := rbacClient.ClusterRoles().Get(ctx, "kube-binder-exports", metav1.GetOptions{}) - require.NoError(t, err) // kube-binder-exports must already exist: it is created before kube-binder-claims-* ClusterRole. - for _, rule := range aggregatingClusterRole.Rules { - if !slices.Contains(rule.Resources, "secrets") || !slices.Contains(rule.APIGroups, "") { - continue - } - slices.Sort(rule.Verbs) - if slices.Equal(expectedVerbs, rule.Verbs) { - return true - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for ClusterRoleBinding to be ready on provider side") - - t.Logf("Verifying ClusterRoleBinding for kube-binder-exports ClusterRole was created") - - require.Eventually(t, func() bool { - aggregatingCRB, err := rbacClient.ClusterRoleBindings().Get(ctx, "kube-binder-exports", metav1.GetOptions{}) - require.NoError(t, err) - for _, subject := range aggregatingCRB.Subjects { - if subject.Kind == "ServiceAccount" && subject.Name == kuberesources.ServiceAccountName { - return true - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for ClusterRoleBinding kube-binder-exports to be ready on provider side") - case kubebindv1alpha2.NamespacedScope: - t.Logf("Verifying RBAC resources were created for secret management in namespace scope") - rbacClient := framework.KubeClient(t, providerConfig).RbacV1() - - require.Eventually(t, func() bool { - roles, err := rbacClient.Roles(consumer.providerObjectNamespace).List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, cr := range roles.Items { - if !strings.HasPrefix(cr.Name, "kube-binder-claims-") { - continue - } - for _, rule := range cr.Rules { - if !slices.Contains(rule.Resources, "secrets") || !slices.Contains(rule.APIGroups, "") { - continue - } - slices.Sort(rule.Verbs) - if slices.Equal(expectedVerbs, rule.Verbs) { - return true - } - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for RoleBinding for claimed secrets resource to be ready on provider side") - - t.Logf("Verifying RoleBinding was created for pre-seeded namespace secret access") - - require.Eventually(t, func() bool { - roleBindings, err := rbacClient.RoleBindings(consumer.providerObjectNamespace).List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, rb := range roleBindings.Items { - if !strings.HasPrefix(rb.Name, "kube-binder-claims-") { - continue - } - for _, subject := range rb.Subjects { - if subject.Kind == "ServiceAccount" && subject.Name == kuberesources.ServiceAccountName { - return true - } - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for RoleBinding for claimed secrets resource to be ready on provider side") - } - - t.Logf("Provider side namespace pre-seeding and secret management RBAC verified successfully") - }, - }, - { - name: "instance spec updated downstream is updated upstream", - step: func(t *testing.T) { - instanceName := fmt.Sprintf("test-%s", consumer.name) - err := retry.RetryOnConflict(retry.DefaultRetry, func() error { - var obj *unstructured.Unstructured - var err error - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - obj, err = consumer.consumerClient.Namespace(consumer.consumerObjectNamespace).Get(ctx, instanceName, metav1.GetOptions{}) - } else { - obj, err = consumer.consumerClient.Get(ctx, instanceName, metav1.GetOptions{}) - } - require.NoError(t, err) - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - unstructured.SetNestedField(obj.Object, fmt.Sprintf("Updated cowboy intent from %s", consumer.name), "spec", "intent") //nolint:errcheck - _, err = consumer.consumerClient.Namespace(consumer.consumerObjectNamespace).Update(ctx, obj, metav1.UpdateOptions{}) - } else { - unstructured.SetNestedField(obj.Object, fmt.Sprintf("Updated sheriff intent from %s", consumer.name), "spec", "intent") //nolint:errcheck - _, err = consumer.consumerClient.Update(ctx, obj, metav1.UpdateOptions{}) - } - return err - }) - require.NoError(t, err) - - // Find our instance on provider side - require.Eventually(t, func() bool { - instances, err := providerClient.List(ctx, metav1.ListOptions{}) - if err != nil { - return false - } - for _, item := range instances.Items { - if !strings.Contains(item.GetName(), instanceName) { - continue - } - var obj *unstructured.Unstructured - if providerResourceScope == apiextensionsv1.NamespaceScoped { - obj, err = providerClient.Namespace(item.GetNamespace()).Get(ctx, instanceName, metav1.GetOptions{}) - } else { - obj, err = providerClient.Get(ctx, item.GetName(), metav1.GetOptions{}) - } - if err != nil { - return false - } - value, _, err := unstructured.NestedString(obj.Object, "spec", "intent") - require.NoError(t, err) - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - return value == fmt.Sprintf("Updated cowboy intent from %s", consumer.name) - } else { - return value == fmt.Sprintf("Updated sheriff intent from %s", consumer.name) - } - } - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for the %s instance to be updated upstream for %s", serviceGVR.Resource, consumer.name) - }, - }, - { - name: "instance status updated upstream is updated downstream", - step: func(t *testing.T) { - instanceName := fmt.Sprintf("test-%s", consumer.name) - // Find our instance on provider side first - var providerInstanceName string - var providerInstanceNs string - instances, err := providerClient.List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, item := range instances.Items { - if strings.Contains(item.GetName(), instanceName) { - providerInstanceName = item.GetName() - providerInstanceNs = item.GetNamespace() - break - } - } - require.NotEmpty(t, providerInstanceName, "should find provider instance for %s", consumer.name) - - err = retry.RetryOnConflict(retry.DefaultRetry, func() error { - var obj *unstructured.Unstructured - var err error - if providerResourceScope == apiextensionsv1.NamespaceScoped { - obj, err = providerClient.Namespace(providerInstanceNs).Get(ctx, instanceName, metav1.GetOptions{}) - } else { - obj, err = providerClient.Get(ctx, providerInstanceName, metav1.GetOptions{}) - } - require.NoError(t, err) - unstructured.SetNestedField(obj.Object, fmt.Sprintf("Ready to ride from %s", consumer.name), "status", "result") //nolint:errcheck - if providerResourceScope == apiextensionsv1.NamespaceScoped { - _, err = providerClient.Namespace(providerInstanceNs).UpdateStatus(ctx, obj, metav1.UpdateOptions{}) - } else { - _, err = providerClient.UpdateStatus(ctx, obj, metav1.UpdateOptions{}) - } - return err - }) - require.NoError(t, err) - - var consumerObj *unstructured.Unstructured - require.Eventually(t, func() bool { - var err error - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - consumerObj, err = consumer.consumerClient.Namespace(consumer.consumerObjectNamespace).Get(ctx, instanceName, metav1.GetOptions{}) - } else { - consumerObj, err = consumer.consumerClient.Get(ctx, instanceName, metav1.GetOptions{}) - } - require.NoError(t, err) - value, _, err := unstructured.NestedString(consumerObj.Object, "status", "result") - require.NoError(t, err) - return value == fmt.Sprintf("Ready to ride from %s", consumer.name) - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for the %s instance to be updated downstream for %s", serviceGVR.Resource, consumer.name) - - // Verify provider source metadata annotations are set on the consumer-side object. - consumerAnnotations := consumerObj.GetAnnotations() - _, hasProviderNS := consumerAnnotations[types.ProviderNamespaceAnnotationKey] - require.True(t, hasProviderNS, "provider-namespace annotation must exist on consumer object") - providerUID := consumerAnnotations[types.ProviderUIDAnnotationKey] - require.NotEmpty(t, providerUID, "provider-uid annotation must exist on consumer object") - }, - }, - - { - name: "verify secrets from examples are synced to provider", - step: func(t *testing.T) { - // Determine which permission namespace to use for this consumer - var consumerPermClaimNs string - if informerScope == kubebindv1alpha2.ClusterScope && - consumerResourceScope == apiextensionsv1.ClusterScoped { - // Find the specific permission claim namespace for this consumer - namespaces, err := providerBindClient.KubeBindV1alpha2().APIServiceNamespaces(consumer.providerContractNamespace).List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, namespace := range namespaces.Items { - if strings.Contains(namespace.Name, consumer.consumerObjectNamespace) && namespace.Status.Namespace != "" { - consumerPermClaimNs = namespace.Status.Namespace - break - } - } - require.NotEmpty(t, consumerPermClaimNs, "Should find permission claim namespace for %s", consumer.name) - } else { - consumerPermClaimNs = consumer.providerObjectNamespace - } - - t.Logf("Waiting for referenced secret to be synced to provider side for %s in namespace %s", consumer.name, consumerPermClaimNs) - require.Eventually(t, func() bool { - _, err := providerCoreClient.Secrets(consumerPermClaimNs).Get(ctx, referencedSecretName, metav1.GetOptions{}) - return err == nil - }, time.Minute*2, time.Millisecond*100, "waiting for referenced secret to be synced to provider side for %s", consumer.name) - - t.Logf("Waiting for label-selected secret to be synced to provider side for %s", consumer.name) - require.Eventually(t, func() bool { - _, err := providerCoreClient.Secrets(consumerPermClaimNs).Get(ctx, labelSelectedSecretName, metav1.GetOptions{}) - return err == nil - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for label-selected secret to be synced to provider side for %s", consumer.name) - - t.Logf("Secrets from examples are properly synced to provider for %s", consumer.name) - }, - }, - { - name: "instances deleted downstream are deleted upstream", - step: func(t *testing.T) { - instanceName := fmt.Sprintf("test-%s", consumer.name) - // Find our instance on provider side first - var providerInstanceName string - instances, err := providerClient.List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - for _, item := range instances.Items { - if strings.Contains(item.GetName(), instanceName) { - providerInstanceName = item.GetName() - break - } - } - require.NotEmpty(t, providerInstanceName, "should find provider instance for %s", consumer.name) - - if consumerResourceScope == apiextensionsv1.NamespaceScoped { - err = consumer.consumerClient.Namespace(consumer.consumerObjectNamespace).Delete(ctx, instanceName, metav1.DeleteOptions{}) - } else { - err = consumer.consumerClient.Delete(ctx, instanceName, metav1.DeleteOptions{}) - } - require.NoError(t, err) - - require.Eventually(t, func() bool { - var err error - if providerResourceScope == apiextensionsv1.NamespaceScoped { - _, err = providerClient.Namespace(consumer.providerObjectNamespace).Get(ctx, instanceName, metav1.GetOptions{}) - } else { - _, err = providerClient.Get(ctx, providerInstanceName, metav1.GetOptions{}) - } - return errors.IsNotFound(err) - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for the %s instance to be deleted on provider side for %s", serviceGVR.Resource, consumer.name) - }, - }, - } { - t.Run(tc.name, tc.step) - } - }) - } -} - -func seedSpecificCRExample(t *testing.T, dynamicClient dynamic.Interface, filename, instanceName string) error { - t.Helper() - - ctx := t.Context() - - // Read and apply all objects from the specified CR example file - bytes, err := examples.CRExamples.ReadFile(filename) - if err != nil { - return err - } - - // Replace the main resource name with the test name - yamlContent := string(bytes) - if strings.Contains(filename, "cowboy") { - yamlContent = strings.ReplaceAll(yamlContent, "name: billy-the-kid", "name: "+instanceName) - } else if strings.Contains(filename, "sheriff") { - yamlContent = strings.ReplaceAll(yamlContent, "name: wyatt-earp", "name: "+instanceName) - } - - return applyMultiDocYAML(ctx, t, dynamicClient, yamlContent) -} - -func applyMultiDocYAML(ctx context.Context, t *testing.T, dynamicClient dynamic.Interface, yamlContent string) error { - t.Helper() - - // Split YAML documents - documents := strings.Split(yamlContent, "---") - - for _, doc := range documents { - doc = strings.TrimSpace(doc) - if doc == "" || strings.HasPrefix(doc, "#") { - continue - } - - obj := &unstructured.Unstructured{} - if err := yaml.Unmarshal([]byte(doc), obj); err != nil { - continue // Skip invalid documents - } - - if obj.GetKind() == "" { - continue // Skip empty documents - } - - gvk := obj.GroupVersionKind() - gvr := schema.GroupVersionResource{ - Group: gvk.Group, - Version: gvk.Version, - // Resources is handled below. - } - - // Handle special cases for pluralization - switch gvk.Kind { - case "Namespace": - gvr.Resource = "namespaces" - case "Secret": - gvr.Resource = "secrets" - case "Cowboy": - gvr.Resource = "cowboys" - case "Sheriff": - gvr.Resource = "sheriffs" - } - - client := dynamicClient.Resource(gvr) - - // Apply based on namespace scope - if obj.GetNamespace() != "" { - _, err := client.Namespace(obj.GetNamespace()).Create(ctx, obj, metav1.CreateOptions{}) - if err != nil && !errors.IsAlreadyExists(err) { - return err - } - } else { - _, err := client.Create(ctx, obj, metav1.CreateOptions{}) - if err != nil && !errors.IsAlreadyExists(err) { - return err - } - } - } - - return nil -} - -func toggleCRDScope(t *testing.T, ctx context.Context, config *rest.Config, name string, scope apiextensionsv1.ResourceScope) { - clientset, err := apiextensionsclient.NewForConfig(config) - require.NoError(t, err) - - crdClient := clientset.ApiextensionsV1().CustomResourceDefinitions() - - // copy existing CRD - crd, err := crdClient.Get(ctx, name, metav1.GetOptions{}) - require.NoError(t, err) - - // delete it - require.NoError(t, crdClient.Delete(ctx, name, metav1.DeleteOptions{})) - - require.Eventually(t, func() bool { - _, err := crdClient.Get(ctx, name, metav1.GetOptions{}) - return errors.IsNotFound(err) - }, wait.ForeverTestTimeout, time.Millisecond*100, "waiting for the CRD to be deleted") - - // re-create it - crd.Spec.Scope = scope - crd.ObjectMeta.ResourceVersion = "" - crd.ObjectMeta.UID = "" - crd.ObjectMeta.Generation = 0 - _, err = crdClient.Create(ctx, crd, metav1.CreateOptions{}) - require.NoError(t, err) -} diff --git a/test/e2e/dex_test.go b/test/e2e/dex_test.go new file mode 100644 index 000000000..95196c18e --- /dev/null +++ b/test/e2e/dex_test.go @@ -0,0 +1,254 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/cookiejar" + "net/url" + "os" + "os/exec" + "path/filepath" + goruntime "runtime" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +const dexImage = "ghcr.io/dexidp/dex:v2.41.1" + +// TestBackendWithDex boots the REAL backend binary (cmd/backend) against a +// real OIDC issuer — Dex in docker — and an envtest provider, then drives the +// full authorization-code login through Dex's password form: proof that the +// kube-style OIDC flags, discovery, PKCE exchange and session issuance work +// against an actual IdP, not just the embedded mock. Skips without docker. +func TestBackendWithDex(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + if err := exec.CommandContext(ctx, "docker", "info").Run(); err != nil { + t.Skip("docker not available; skipping Dex e2e") + } + + // A provider API server for the backend to run against (the backend + // self-installs the catalog/iam CRDs at startup). + providerEnv := &envtest.Environment{} + providerCfg, err := providerEnv.Start() + require.NoError(t, err, "starting provider envtest") + t.Cleanup(func() { _ = providerEnv.Stop() }) + + kubeconfigPath := filepath.Join(t.TempDir(), "provider.kubeconfig") + require.NoError(t, os.WriteFile(kubeconfigPath, kubeconfigBytes(t, providerCfg), 0o600)) + + gatewayPort := freePort(t) + dexPort := freePort(t) + gatewayURL := fmt.Sprintf("http://127.0.0.1:%d", gatewayPort) + dexIssuer := fmt.Sprintf("http://127.0.0.1:%d/dex", dexPort) + + startDex(t, ctx, dexPort, gatewayURL+"/api/auth/oidc/callback", dexIssuer) + startBackendBinary(t, ctx, kubeconfigPath, gatewayPort, dexIssuer) + + // The gateway is up and advertises OIDC. + var provider struct { + AuthMethods []string `json:"authMethods"` + } + require.Eventually(t, func() bool { + res, err := http.Get(gatewayURL + "/api/provider") //nolint:noctx // poll helper + if err != nil { + return false + } + defer func() { _ = res.Body.Close() }() + return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(&provider) == nil + }, 60*time.Second, 500*time.Millisecond, "backend gateway should come up") + require.Equal(t, []string{"oidc"}, provider.AuthMethods) + + // The browser dance, through Dex's real login form. + jar, err := cookiejar.New(nil) + require.NoError(t, err) + browser := &http.Client{Jar: jar} + + loginReq, err := http.NewRequestWithContext(ctx, http.MethodGet, gatewayURL+"/api/auth/oidc/login?redirect=/", nil) + require.NoError(t, err) + res, err := browser.Do(loginReq) + require.NoError(t, err) + defer func() { _ = res.Body.Close() }() + require.Equal(t, http.StatusOK, res.StatusCode) + require.Contains(t, res.Request.URL.String(), "/dex/auth", "should land on Dex's login form") + + // Submit the password form to the page Dex served (its URL carries the + // request id); skipApprovalScreen then bounces straight back to the + // gateway callback, which issues the session and redirects home. + form := url.Values{"login": {"admin@example.com"}, "password": {"password"}} + postReq, err := http.NewRequestWithContext(ctx, http.MethodPost, res.Request.URL.String(), + strings.NewReader(form.Encode())) + require.NoError(t, err) + postReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") + res2, err := browser.Do(postReq) + require.NoError(t, err) + defer func() { _ = res2.Body.Close() }() + require.Equal(t, http.StatusOK, res2.StatusCode, "login should end back on the gateway") + require.Equal(t, fmt.Sprintf("127.0.0.1:%d", gatewayPort), res2.Request.URL.Host, + "final redirect should land on the gateway, got %s", res2.Request.URL) + + // The session works: /api/me knows who we are, via the email claim. + meReq, err := http.NewRequestWithContext(ctx, http.MethodGet, gatewayURL+"/api/me", nil) + require.NoError(t, err) + res3, err := browser.Do(meReq) + require.NoError(t, err) + defer func() { _ = res3.Body.Close() }() + require.Equal(t, http.StatusOK, res3.StatusCode) + var me struct { + Subject string `json:"subject"` + DisplayName string `json:"displayName"` + } + require.NoError(t, json.NewDecoder(res3.Body).Decode(&me)) + require.Equal(t, dexIssuer+"#admin@example.com", me.Subject) + require.Equal(t, "admin@example.com", me.DisplayName) +} + +// startDex runs Dex in docker with memory storage, one static client (the +// gateway) and one static password user. +func startDex(t *testing.T, ctx context.Context, port int, redirectURI, issuer string) { + t.Helper() + + // bcrypt of "password" (the canonical hash from Dex's own examples). + config := fmt.Sprintf(`issuer: %s +storage: + type: memory +web: + http: 0.0.0.0:5556 +staticClients: + - id: kbind + secret: kbind-secret + name: kbind + redirectURIs: + - %s +oauth2: + skipApprovalScreen: true +enablePasswordDB: true +staticPasswords: + - email: admin@example.com + hash: "$2a$10$2b2cU8CPhOTaGrs1HRQuAueS7JTT5ZHsHSzYiFPm1leZck7Mc8T4W" + username: admin + userID: 08a8684b-db88-4b73-90a9-3cd1661f5466 +`, issuer, redirectURI) + configPath := filepath.Join(t.TempDir(), "dex.yaml") + // 0644: the file is bind-mounted into the Dex container, whose user must + // read it (0600 would be root-only inside the container). + require.NoError(t, os.WriteFile(configPath, []byte(config), 0o644)) //nolint:gosec // see above + + name := fmt.Sprintf("kbind-e2e-dex-%d", port) + run := exec.CommandContext(ctx, "docker", "run", "--rm", "-d", + "--name", name, + "-p", fmt.Sprintf("127.0.0.1:%d:5556", port), + "-v", configPath+":/etc/dex/config.yaml:ro", + dexImage, "dex", "serve", "/etc/dex/config.yaml") + out, err := run.CombinedOutput() + require.NoError(t, err, "starting dex: %s", out) + t.Cleanup(func() { _ = exec.CommandContext(context.Background(), "docker", "rm", "-f", name).Run() }) + + require.Eventually(t, func() bool { + res, err := http.Get(issuer + "/.well-known/openid-configuration") //nolint:noctx // poll helper + if err != nil { + return false + } + defer func() { _ = res.Body.Close() }() + return res.StatusCode == http.StatusOK + }, 60*time.Second, 500*time.Millisecond, "dex discovery should come up") +} + +// startBackendBinary builds and runs the real cmd/backend with kube-style +// OIDC flags pointing at Dex. +func startBackendBinary(t *testing.T, ctx context.Context, kubeconfig string, gatewayPort int, dexIssuer string) { + t.Helper() + + bin := filepath.Join(t.TempDir(), "backend") + build := exec.CommandContext(ctx, "go", "build", "-o", bin, "./cmd/backend") + build.Dir = repoRoot(t) + out, err := build.CombinedOutput() + require.NoError(t, err, "building backend: %s", out) + + backend := exec.CommandContext(ctx, bin, + fmt.Sprintf("--listen-address=127.0.0.1:%d", gatewayPort), + fmt.Sprintf("--external-url=http://127.0.0.1:%d", gatewayPort), + "--oidc-issuer-url="+dexIssuer, + "--oidc-client-id=kbind", + "--oidc-client-secret=kbind-secret", + "--oidc-username-claim=email", + "--metrics-bind-address=0", + "--health-probe-bind-address=127.0.0.1:0", + ) + backend.Env = append(os.Environ(), "KUBECONFIG="+kubeconfig) + var logs bytes.Buffer + backend.Stdout = &logs + backend.Stderr = &logs + require.NoError(t, backend.Start()) + t.Cleanup(func() { + _ = backend.Process.Kill() + _, _ = backend.Process.Wait() + if t.Failed() { + t.Logf("backend logs:\n%s", logs.String()) + } + }) +} + +func freePort(t *testing.T) int { + t.Helper() + ln, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0") + require.NoError(t, err) + defer func() { _ = ln.Close() }() + return ln.Addr().(*net.TCPAddr).Port +} + +func repoRoot(t *testing.T) string { + t.Helper() + _, thisFile, _, ok := goruntime.Caller(0) + require.True(t, ok) + root, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..")) + require.NoError(t, err) + return root +} + +// kubeconfigBytes serializes an envtest rest.Config into a kubeconfig file +// the backend binary can load via KUBECONFIG. +func kubeconfigBytes(t *testing.T, cfg *rest.Config) []byte { + t.Helper() + c := clientcmdapi.NewConfig() + c.Clusters["provider"] = &clientcmdapi.Cluster{ + Server: cfg.Host, + CertificateAuthorityData: cfg.CAData, + } + c.AuthInfos["provider"] = &clientcmdapi.AuthInfo{ + ClientCertificateData: cfg.CertData, + ClientKeyData: cfg.KeyData, + } + c.Contexts["provider"] = &clientcmdapi.Context{Cluster: "provider", AuthInfo: "provider"} + c.CurrentContext = "provider" + data, err := clientcmd.Write(*c) + require.NoError(t, err) + return data +} diff --git a/test/e2e/disengage_test.go b/test/e2e/disengage_test.go new file mode 100644 index 000000000..a76602191 --- /dev/null +++ b/test/e2e/disengage_test.go @@ -0,0 +1,119 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// TestSlimCoreStopOnDisengage verifies the syncer lifecycle around a Connection +// losing and regaining readiness: when the Connection stops being Ready the +// provider disengages and the per-GVR syncer is torn down; when it becomes Ready +// again the syncer is rebuilt against the freshly engaged provider cluster +// (rather than left pointing at a dead one), so sync resumes. +func TestSlimCoreStopOnDisengage(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + gvr := env.InstallExportedWidgetCRD(t) + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + waitBindingReady(t, env, ctx) + + consumerWidgets := env.ConsumerDyn.Resource(gvr).Namespace(instanceNS) + providerWidgets := env.ProviderDyn.Resource(gvr).Namespace(instanceNS) + + // Baseline: the syncer is running — an instance syncs to the provider. + _, err := consumerWidgets.Create(ctx, widget("w1", "small"), metav1.CreateOptions{}) + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, "w1", metav1.GetOptions{}) + return err == nil + }, 30*time.Second, 200*time.Millisecond, "baseline instance should sync while the Connection is engaged") + + secretKey := client.ObjectKey{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig"} + good := &corev1.Secret{} + require.NoError(t, env.ConsumerClient.Get(ctx, secretKey, good)) + goodKubeconfig := good.Data["kubeconfig"] + + t.Run("a Connection that loses readiness disengages", func(t *testing.T) { + // Corrupt the kubeconfig so the konnector can no longer build a provider + // client → the Connection goes not-Ready → the provider disengages. + bad := good.DeepCopy() + bad.Data["kubeconfig"] = []byte("not-a-kubeconfig") + require.NoError(t, env.ConsumerClient.Update(ctx, bad)) + + require.Eventually(t, func() bool { + conn := &corev1alpha1.Connection{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn); err != nil { + return false + } + return !apimeta.IsStatusConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) + }, 30*time.Second, 200*time.Millisecond, "Connection should go not-Ready once its kubeconfig is broken") + }) + + t.Run("re-engage rebuilds the syncer and sync resumes", func(t *testing.T) { + // Restore the good kubeconfig → the Connection becomes Ready again and the + // provider re-engages as a fresh cluster. + cur := &corev1.Secret{} + require.NoError(t, env.ConsumerClient.Get(ctx, secretKey, cur)) + cur.Data["kubeconfig"] = goodKubeconfig + require.NoError(t, env.ConsumerClient.Update(ctx, cur)) + waitBindingReady(t, env, ctx) + + // A NEW instance created after re-engage must sync — proving the syncer was + // rebuilt against the live cluster rather than left pointing at the dead one. + _, err := consumerWidgets.Create(ctx, widget("w2", "large"), metav1.CreateOptions{}) + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, "w2", metav1.GetOptions{}) + return err == nil + }, 60*time.Second, 200*time.Millisecond, "a post-re-engage instance should sync through the rebuilt syncer") + }) +} + +func waitBindingReady(t *testing.T, env *framework.Env, ctx context.Context) { + t.Helper() + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) +} diff --git a/test/e2e/framework/apply.go b/test/e2e/framework/apply.go deleted file mode 100644 index fe8165c0e..000000000 --- a/test/e2e/framework/apply.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 framework - -import ( - "errors" - "io" - "os" - "testing" - "time" - - "github.com/stretchr/testify/require" - "gopkg.in/yaml.v3" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/discovery/cached/memory" - "k8s.io/client-go/rest" - "k8s.io/client-go/restmapper" -) - -func ignoreEof(err error) error { - if errors.Is(err, io.EOF) { - return nil - } - return err -} - -// ApplyFiles reads the given file paths and applies the manifests -// contained in them to the cluster specified by config. -// This is equivalent to `kubectl apply -f `. -func ApplyFiles(t testing.TB, config *rest.Config, filePaths ...string) { - t.Helper() - t.Logf("Reading manifests from files: %v", filePaths) - - manifests := []any{} - for _, filePath := range filePaths { - f, err := os.Open(filePath) - require.NoError(t, err, "Failed to open file %s", filePath) - defer f.Close() - - dec := yaml.NewDecoder(f) - for { - var node yaml.Node - err := dec.Decode(&node) - require.NoError(t, ignoreEof(err), "Failed to decode YAML from file %s", filePath) - if errors.Is(err, io.EOF) { - break - } - manifests = append(manifests, node) - } - } - - ApplyManifest(t, config, manifests...) -} - -// ApplyManifest applies the given manifests to the cluster specified by config. -func ApplyManifest(t testing.TB, config *rest.Config, manifests ...any) { - t.Helper() - t.Logf("Applying %d manifests", len(manifests)) - - dynamicClient := DynamicClient(t, config) - discoveryClient := DiscoveryClient(t, config) - mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(discoveryClient)) - - for _, manifest := range manifests { - var u unstructured.Unstructured - - switch m := manifest.(type) { - case unstructured.Unstructured: - u = m - case string: - obj := map[string]any{} - err := yaml.Unmarshal([]byte(m), &obj) - require.NoError(t, err, "Failed to unmarshal manifest") - u.Object = obj - case []byte: - obj := map[string]any{} - err := yaml.Unmarshal(m, &obj) - require.NoError(t, err, "Failed to unmarshal manifest") - u.Object = obj - case yaml.Node: - obj := map[string]any{} - err := m.Decode(&obj) - require.NoError(t, err, "Failed to decode YAML node") - u.Object = obj - default: - require.Fail(t, "Unsupported manifest type %T", m) - } - - gvk := u.GroupVersionKind() - - t.Logf("Creating resource %s/%s of type %s", u.GetNamespace(), u.GetName(), gvk.String()) - require.Eventually(t, func() bool { - t.Logf("Finding REST mapping for GVK %#v", gvk) - mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) - if err != nil { - t.Logf("Error finding REST mapping for GVK %s: %v", gvk.String(), err) - return false - } - - _, err = dynamicClient.Resource(mapping.Resource). - Namespace(u.GetNamespace()). - Apply(t.Context(), u.GetName(), &u, metav1.ApplyOptions{FieldManager: "kube-bind-test-framework"}) - if err != nil { - t.Logf("Error creating resource %s/%s of type %s: %v", u.GetNamespace(), u.GetName(), gvk.String(), err) - return false - } - return true - }, wait.ForeverTestTimeout, time.Millisecond*100) - } -} diff --git a/test/e2e/framework/backend.go b/test/e2e/framework/backend.go deleted file mode 100644 index 856f18936..000000000 --- a/test/e2e/framework/backend.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "context" - "fmt" - "net" - "testing" - - "github.com/spf13/pflag" - "github.com/stretchr/testify/require" - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - - backend "github.com/kube-bind/kube-bind/backend" - "github.com/kube-bind/kube-bind/backend/options" - "github.com/kube-bind/kube-bind/deploy/crd" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func InstallKubeBindCRDs(t testing.TB, clientConfig *rest.Config) { - crdClient, err := apiextensionsclient.NewForConfig(clientConfig) - require.NoError(t, err) - err = crd.Create(t.Context(), - crdClient.ApiextensionsV1().CustomResourceDefinitions(), - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "clusterbindings"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiserviceexports"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiservicenamespaces"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiserviceexportrequests"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "boundschemas"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiserviceexporttemplates"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "collections"}, - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "clusters"}, - ) - require.NoError(t, err) -} - -func StartBackend(t testing.TB, args ...string) (net.Addr, *backend.Server) { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - fs := pflag.NewFlagSet("backend", pflag.ContinueOnError) - opts := options.NewOptions() - opts.AddFlags(fs) - err := fs.Parse(args) - require.NoError(t, err) - - // use a random port via an explicit listener. Then add a kube-bind- client to dex - // with the callback URL set to the listener's address. - listenConfig := net.ListenConfig{} - opts.Serve.Listener, err = listenConfig.Listen(context.Background(), "tcp", "localhost:0") - require.NoError(t, err) - addr := opts.Serve.Listener.Addr() - - opts.OIDC.Type = string(kubebindv1alpha2.OIDCProviderTypeEmbedded) - opts.OIDC.IssuerURL = fmt.Sprintf("http://%s/oidc", addr.String()) - opts.OIDC.CallbackURL = fmt.Sprintf("http://%s/api/callback", addr.String()) - - // Skip name conflict validation - when run in-process with multiple - // controllers they all will register the same metric names, which - // causes subsequent controllers to fail. - opts.ExtraOptions.TestingSkipNameValidation = true - - completed, err := opts.Complete() - require.NoError(t, err) - require.NoError(t, completed.Validate()) - - config, err := backend.NewConfig(completed) - require.NoError(t, err) - - server, err := backend.NewServer(ctx, config) - require.NoError(t, err) - - err = server.Run(ctx) - require.NoError(t, err) - t.Logf("backend listening on %s", addr) - - return addr, server -} diff --git a/test/e2e/framework/bind.go b/test/e2e/framework/bind.go deleted file mode 100644 index d864f5ca5..000000000 --- a/test/e2e/framework/bind.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "context" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/require" - "k8s.io/cli-runtime/pkg/genericclioptions" - - "github.com/kube-bind/kube-bind/cli/pkg/client" - "github.com/kube-bind/kube-bind/cli/pkg/config" - loginplugin "github.com/kube-bind/kube-bind/cli/pkg/kubectl/bind-login/plugin" -) - -func GetKubeBindRestClient(t *testing.T, configFile string) client.Client { - t.Helper() - - c, err := config.LoadConfigFromFile(configFile) - require.NoError(t, err) - - server, _, err := c.GetCurrentServer() - require.NoError(t, err) - require.NotNil(t, server, "no current server configured in %s", configFile) - - client, err := client.NewClient(*server, client.WithInsecure(true)) - require.NoError(t, err) - - return client -} - -func Login(t *testing.T, iostreams genericclioptions.IOStreams, authURLCh chan<- string, configFile, serverURL, clusterID string) { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - t.Logf("kubectl login %s --skip-browser --config-file=%s --cluster=%s", serverURL, configFile, clusterID) - - opts := loginplugin.NewLoginOptions(iostreams) - cmd := &cobra.Command{} - opts.AddCmdFlags(cmd) - args := []string{serverURL} - if clusterID != "" { - args = append(args, "--cluster="+clusterID) - } - if configFile != "" { - args = append(args, "--config-file="+configFile) - } - err := cmd.Flags().Parse(args) - require.NoError(t, err) - - err = opts.Complete(args) - require.NoError(t, err) - - err = opts.Validate() - require.NoError(t, err) - err = opts.Run(ctx, authURLCh) - require.NoError(t, err) -} diff --git a/test/e2e/framework/browser.go b/test/e2e/framework/browser.go deleted file mode 100644 index f71c5a47f..000000000 --- a/test/e2e/framework/browser.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "strings" - "testing" - "time" - - "github.com/headzoo/surf" - "github.com/headzoo/surf/browser" - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/util/wait" -) - -func BrowserEventuallyAtPath(t *testing.T, browser *browser.Browser, path string) { - require.Eventuallyf(t, func() bool { - if strings.Contains(browser.Url().Path, path) { - t.Logf("Browser is at %s, waiting for path %s", browser.Url(), path) - return true - } - t.Logf("Waiting for browser to be at %s, current URL: %s", path, browser.Url()) - return false - }, wait.ForeverTestTimeout, time.Millisecond*100, "Browser is not at path %s", path) -} - -func SimulateBrowser(t *testing.T, authURLCh chan string) { - browser := surf.NewBrowser() - authURL := <-authURLCh - - t.Logf("Browsing to auth URL: %s", authURL) - err := browser.Open(authURL) - require.NoError(t, err) -} diff --git a/test/e2e/framework/clients.go b/test/e2e/framework/clients.go deleted file mode 100644 index 088ea53f3..000000000 --- a/test/e2e/framework/clients.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "testing" - - "github.com/stretchr/testify/require" - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - "k8s.io/client-go/discovery" - "k8s.io/client-go/dynamic" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - - bindclientset "github.com/kube-bind/kube-bind/sdk/client/clientset/versioned" -) - -func DynamicClient(t testing.TB, config *rest.Config) dynamic.Interface { - c, err := dynamic.NewForConfig(config) - require.NoError(t, err) - return c -} - -func KubeClient(t testing.TB, config *rest.Config) kubernetes.Interface { - c, err := kubernetes.NewForConfig(config) - require.NoError(t, err) - return c -} - -func ApiextensionsClient(t testing.TB, config *rest.Config) apiextensionsclient.Interface { - c, err := apiextensionsclient.NewForConfig(config) - require.NoError(t, err) - return c -} - -func DiscoveryClient(t testing.TB, config *rest.Config) discovery.DiscoveryInterface { - c, err := discovery.NewDiscoveryClientForConfig(config) - require.NoError(t, err) - return c -} - -func BindClient(t *testing.T, config *rest.Config) bindclientset.Interface { - c, err := bindclientset.NewForConfig(config) - require.NoError(t, err) - return c -} - -func NewRESTConfig(t *testing.T, kubeconfig string) *rest.Config { - config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) - require.NoError(t, err, "Failed to build config from kubeconfig file") - return config -} diff --git a/test/e2e/framework/dex.go b/test/e2e/framework/dex.go deleted file mode 100644 index f14baedb3..000000000 --- a/test/e2e/framework/dex.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 framework - -import ( - "context" - "crypto/rand" - "fmt" - "net" - "net/http" - "os" - "os/exec" - "path/filepath" - "sync" - "syscall" - "testing" - "time" - - dexapi "github.com/dexidp/dex/api/v2" - "github.com/stretchr/testify/require" - "google.golang.org/grpc" - grpcinsecure "google.golang.org/grpc/credentials/insecure" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" -) - -var dexOnce sync.Once - -var dexKill = func(t testing.TB, cmd *exec.Cmd) { - t.Helper() - // Do nothing. Without a suite setup and teardown we cannot - // determine when to kill dex and Pdeathsig is only supported on - // Linux. - // On macOS (and Windows) the process will continue to run. - // Which per se isn't a problem for development. - cmd.SysProcAttr = &syscall.SysProcAttr{} -} - -func StartDex(t testing.TB) { - t.Helper() - - dexOnce.Do(func() { - dexConfig := os.Getenv("DEX_CONFIG") - if dexConfig == "" { - dexConfig = filepath.Clean(filepath.Join(RepoRoot(), "hack", "dex-config-dev.yaml")) - } - - t.Logf("Starting dex with config %q", dexConfig) - - dexBinary := os.Getenv("DEX_BINARY") - if dexBinary == "" { - dexBinary = "dex" - } - - //nolint:gosec // test helper intentionally allows overriding dex binary/config via environment for local e2e runs. - // Use context.Background() instead of t.Context() because dexOnce.Do - // ties the process to the first test that calls StartDex. If we used - // t.Context(), Dex would be killed when that test finishes, but - // dexOnce prevents restarting it for subsequent tests. - // The Dex process will be cleaned up when the test binary exits. - dexCmd := exec.CommandContext( - context.Background(), - dexBinary, - "serve", - dexConfig, - ) - - // Set os-dependent killing - dexKill(t, dexCmd) - - require.NoError(t, dexCmd.Start()) - }) - - t.Log("Wait for Dex to be ready") - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://127.0.0.1:5556/dex/.well-known/openid-configuration", nil) - require.NoError(t, err) - require.Eventually(t, func() bool { - resp, err := http.DefaultClient.Do(req) - if err != nil { - return false - } - defer resp.Body.Close() - return resp.StatusCode == http.StatusOK - }, wait.ForeverTestTimeout, time.Millisecond*100) - t.Log("Dex is ready") -} - -func CreateDexClient(t testing.TB, addr net.Addr) (string, string) { - t.Helper() - - _, port, err := net.SplitHostPort(addr.String()) - require.NoError(t, err) - conn, err := grpc.NewClient("127.0.0.1:5557", grpc.WithTransportCredentials(grpcinsecure.NewCredentials())) - require.NoError(t, err) - defer conn.Close() - client := dexapi.NewDexClient(conn) - - secret := rand.Text() - id := "kube-bind-" + port - - _, err = client.CreateClient(t.Context(), &dexapi.CreateClientReq{ - Client: &dexapi.Client{ - Id: id, - Secret: secret, - RedirectUris: []string{fmt.Sprintf("http://%s/api/callback", addr)}, - Public: true, - Name: "kube-bind on port " + port, - }, - }) - require.NoError(t, err) - - t.Cleanup(func() { - ctx, cancel := context.WithDeadline(t.Context(), metav1.Now().Add(10*time.Second)) - defer cancel() - conn, err := grpc.NewClient("127.0.0.1:5557", grpc.WithTransportCredentials(grpcinsecure.NewCredentials())) - require.NoError(t, err) - _, err = dexapi.NewDexClient(conn).DeleteClient(ctx, &dexapi.DeleteClientReq{Id: id}) - require.NoError(t, err) - }) - - return id, secret -} diff --git a/test/e2e/framework/dex_linux.go b/test/e2e/framework/dex_linux.go deleted file mode 100644 index 29088bd1a..000000000 --- a/test/e2e/framework/dex_linux.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright 2025 The Kube Bind 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 framework - -import ( - "os/exec" - "syscall" - "testing" -) - -func init() { - dexKill = func(t testing.TB, cmd *exec.Cmd) { - t.Helper() - cmd.SysProcAttr = &syscall.SysProcAttr{ - Pdeathsig: syscall.SIGKILL, - } - } -} diff --git a/test/e2e/framework/env.go b/test/e2e/framework/env.go deleted file mode 100644 index 3864dc41e..000000000 --- a/test/e2e/framework/env.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "os" - "path/filepath" - "runtime" - "strings" - "testing" -) - -var ( - repoRoot string -) - -func init() { - _, f, _, _ := runtime.Caller(0) - repoRoot = filepath.Clean(filepath.Join(f, "..", "..", "..", "..")) -} - -// WorkDir returns a test-specific working directory. Each test gets its own subdirectory -// based on the test name, allowing parallel tests to avoid file conflicts. -func WorkDir(t testing.TB) string { - workDir := os.Getenv("WORK_DIR") - if workDir == "" { - workDir = filepath.Join(RepoRoot(), ".kube-bind") - } - - return filepath.Join(workDir, sanitizeTestName(t.Name())) -} - -// RepoRoot returns the root directory of the repository -func RepoRoot() string { - return repoRoot -} - -// sanitizeTestName converts a test name to a valid directory name by replacing -// path separators and other problematic characters. -func sanitizeTestName(name string) string { - name = strings.ReplaceAll(name, "/", "_") - name = strings.ReplaceAll(name, "\\", "_") - - return name -} diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go new file mode 100644 index 000000000..221f4744e --- /dev/null +++ b/test/e2e/framework/framework.go @@ -0,0 +1,397 @@ +/* +Copyright 2026 The kbind 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 framework provides an envtest-based harness for v2 slim-core e2e +// tests: a provider API server and a consumer API server, with the konnector +// engine reconcilers running in-process against the consumer. +// +// Unlike the v1 framework (kcp + backend + browser auth), the v2 core has no +// backend, so the harness only needs two API servers, a kubeconfig Secret, and +// the one-apply bundle. +package framework + +import ( + "context" + "path/filepath" + "runtime" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + apimachineryruntime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/dynamic" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/config" + "sigs.k8s.io/controller-runtime/pkg/envtest" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" + + "github.com/kbind/kbind/engine/binding" + "github.com/kbind/kbind/engine/connection" + "github.com/kbind/kbind/engine/provider" + syncengine "github.com/kbind/kbind/engine/sync" + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" +) + +// KbindNamespace is the konnector's designated namespace on the consumer. +const KbindNamespace = "kbind" + +// Env is a running provider+consumer test environment with the engine wired up. +type Env struct { + Scheme *apimachineryruntime.Scheme + + ProviderCfg *rest.Config + ConsumerCfg *rest.Config + ProviderClient client.Client + ConsumerClient client.Client + ProviderDyn dynamic.Interface + ConsumerDyn dynamic.Interface + + providerEnv *envtest.Environment +} + +// RestrictedProviderSecret creates a Secret on the consumer holding a kubeconfig +// for a provider user with no RBAC, so the konnector's provider operations are +// forbidden. Used to exercise the PermissionDenied path. +func (e *Env) RestrictedProviderSecret(t *testing.T, name string) *corev1.Secret { + t.Helper() + au, err := e.providerEnv.AddUser(envtest.User{Name: "restricted-konnector"}, nil) + require.NoError(t, err, "adding restricted provider user") + kubeconfig, err := kubeconfigFromRestConfig(au.Config()) + require.NoError(t, err) + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: KbindNamespace}, + Data: map[string][]byte{"kubeconfig": kubeconfig}, + } +} + +// Start brings up two envtest API servers, installs the core CRDs on the +// consumer, creates the kube-system namespaces (for cluster identity) and the +// kbind namespace, stores the provider kubeconfig as a Secret on the +// consumer, and starts the engine reconcilers in-process against the consumer. +var setLoggerOnce sync.Once + +func Start(t *testing.T) *Env { + t.Helper() + setLoggerOnce.Do(func() { ctrl.SetLogger(zap.New(zap.UseDevMode(true))) }) + + scheme := apimachineryruntime.NewScheme() + utilruntime.Must(clientgoscheme.AddToScheme(scheme)) + utilruntime.Must(apiextensionsv1.AddToScheme(scheme)) + utilruntime.Must(corev1alpha1.AddToScheme(scheme)) + + // Consumer API server, pre-loaded with the core CRDs. + consumerEnv := &envtest.Environment{ + CRDDirectoryPaths: []string{coreCRDDir(t)}, + ErrorIfCRDPathMissing: true, + Scheme: scheme, + } + consumerCfg, err := consumerEnv.Start() + require.NoError(t, err, "starting consumer envtest") + t.Cleanup(func() { _ = consumerEnv.Stop() }) + + // Provider API server (plain). + providerEnv := &envtest.Environment{Scheme: scheme} + providerCfg, err := providerEnv.Start() + require.NoError(t, err, "starting provider envtest") + t.Cleanup(func() { _ = providerEnv.Stop() }) + + consumerClient, err := client.New(consumerCfg, client.Options{Scheme: scheme}) + require.NoError(t, err) + providerClient, err := client.New(providerCfg, client.Options{Scheme: scheme}) + require.NoError(t, err) + consumerDyn, err := dynamic.NewForConfig(consumerCfg) + require.NoError(t, err) + providerDyn, err := dynamic.NewForConfig(providerCfg) + require.NoError(t, err) + + ctx := context.Background() + + // kube-system in both clusters → stable cluster identity for ownership markers + // (envtest may already seed it, so tolerate AlreadyExists). + ensureNamespace(t, consumerClient, "kube-system") + ensureNamespace(t, providerClient, "kube-system") + ensureNamespace(t, consumerClient, KbindNamespace) + + // Store the provider kubeconfig as a Secret on the consumer (the credential + // the Connection references). + kubeconfig, err := kubeconfigFromRestConfig(providerCfg) + require.NoError(t, err) + require.NoError(t, consumerClient.Create(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider-kubeconfig", Namespace: KbindNamespace}, + Data: map[string][]byte{"kubeconfig": kubeconfig}, + })) + + startEngine(t, consumerCfg, scheme) + + return &Env{ + Scheme: scheme, + ProviderCfg: providerCfg, + ConsumerCfg: consumerCfg, + ProviderClient: providerClient, + ConsumerClient: consumerClient, + ProviderDyn: providerDyn, + ConsumerDyn: consumerDyn, + providerEnv: providerEnv, + } +} + +// startEngine wires the full engine the way main.go does: a local (consumer) +// manager, the mcr ConnectionProvider (each Connection -> engaged provider +// cluster), the multicluster manager, and the reconcilers — including the +// sync engine using the engaged cluster (Option B). +func startEngine(t *testing.T, consumerCfg *rest.Config, scheme *apimachineryruntime.Scheme) { + t.Helper() + localMgr, err := ctrl.NewManager(consumerCfg, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + // Multiple test envs run in one process; skip the global controller-name + // uniqueness check. + Controller: config.Controller{SkipNameValidation: ptr.To(true)}, + }) + require.NoError(t, err) + + connProvider, err := provider.New(localMgr, provider.Options{}) + require.NoError(t, err) + + mcMgr, err := mcmanager.New(consumerCfg, connProvider, mcmanager.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + }) + require.NoError(t, err) + + // Short resync intervals so re-discovery and conflictCount refresh fast in tests. + require.NoError(t, (&connection.Reconciler{DiscoveryResync: time.Second}).SetupWithManager(localMgr)) + require.NoError(t, (&binding.ClusterReconciler{Resync: time.Second}).SetupWithManager(localMgr)) + require.NoError(t, (&binding.NamespacedReconciler{Resync: time.Second}).SetupWithManager(localMgr)) + require.NoError(t, syncengine.SetupWithManager(localMgr, connProvider)) + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go func() { + if err := localMgr.Start(ctx); err != nil { + t.Logf("local manager stopped: %v", err) + } + }() + go func() { + if err := connProvider.Run(ctx, mcMgr); err != nil { + t.Logf("connection provider stopped: %v", err) + } + }() + go func() { + if err := mcMgr.Start(ctx); err != nil { + t.Logf("mc manager stopped: %v", err) + } + }() + require.True(t, localMgr.GetCache().WaitForCacheSync(ctx), "engine cache sync") +} + +// CopyProviderSecret returns a new Secret named `name` in the kbind +// namespace carrying the same provider kubeconfig as the one created by Start. +// Used to test Connection-before-Secret ordering. +func (e *Env) CopyProviderSecret(t *testing.T, name string) *corev1.Secret { + t.Helper() + var src corev1.Secret + require.NoError(t, e.ConsumerClient.Get(context.Background(), + client.ObjectKey{Namespace: KbindNamespace, Name: "demo-provider-kubeconfig"}, &src)) + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: KbindNamespace}, + Data: src.Data, + } +} + +// MakeProviderKCPLike turns the provider into a kcp-shaped cluster: it installs +// a LogicalCluster CRD + the singleton "cluster" object (the kcp per-workspace +// identity object). On a real kcp workspace there is no kube-system namespace, +// so identity comes from the LogicalCluster; the konnector prefers it whenever +// it is present (which only a kcp-shaped cluster serves), so we don't need to +// remove kube-system here (envtest has no namespace controller to finalize it +// away anyway). Returns the LogicalCluster's UID. +func (e *Env) MakeProviderKCPLike(t *testing.T, ctx context.Context) string { + t.Helper() + + require.NoError(t, e.ProviderClient.Create(ctx, logicalClusterCRD())) + lcGVR := schema.GroupVersionResource{Group: "core.kcp.io", Version: "v1alpha1", Resource: "logicalclusters"} + require.Eventually(t, func() bool { + _, err := e.ProviderDyn.Resource(lcGVR).List(ctx, metav1.ListOptions{}) + return err == nil + }, 30*time.Second, 200*time.Millisecond, "provider should serve LogicalCluster") + + lc := &unstructured.Unstructured{} + lc.SetGroupVersionKind(schema.GroupVersionKind{Group: "core.kcp.io", Version: "v1alpha1", Kind: "LogicalCluster"}) + lc.SetName("cluster") + require.NoError(t, e.ProviderClient.Create(ctx, lc)) + require.NoError(t, e.ProviderClient.Get(ctx, client.ObjectKey{Name: "cluster"}, lc)) + uid := string(lc.GetUID()) + require.NotEmpty(t, uid) + return uid +} + +func logicalClusterCRD() *apiextensionsv1.CustomResourceDefinition { + preserve := true + return &apiextensionsv1.CustomResourceDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "logicalclusters.core.kcp.io"}, + Spec: apiextensionsv1.CustomResourceDefinitionSpec{ + Group: "core.kcp.io", + Names: apiextensionsv1.CustomResourceDefinitionNames{ + Plural: "logicalclusters", Singular: "logicalcluster", Kind: "LogicalCluster", ListKind: "LogicalClusterList", + }, + Scope: apiextensionsv1.ClusterScoped, + Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{ + Name: "v1alpha1", Served: true, Storage: true, + Schema: &apiextensionsv1.CustomResourceValidation{ + OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "spec": {Type: "object", XPreserveUnknownFields: &preserve}, + }, + }, + }, + }}, + }, + } +} + +// InstallExportedWidgetCRD installs the demo Widget CRD on the provider, labeled +// as exported. +func (e *Env) InstallExportedWidgetCRD(t *testing.T) schema.GroupVersionResource { + return e.InstallExportedCRD(t, "example.org", "widgets", "widget", "Widget") +} + +// InstallExportedCRD installs a namespaced CRD on the provider labeled as +// exported, and waits for the provider to serve it. +func (e *Env) InstallExportedCRD(t *testing.T, group, plural, singular, kind string) schema.GroupVersionResource { + t.Helper() + require.NoError(t, e.ProviderClient.Create(context.Background(), exportedCRD(group, plural, singular, kind))) + gvr := schema.GroupVersionResource{Group: group, Version: "v1", Resource: plural} + require.Eventually(t, func() bool { + _, err := e.ProviderDyn.Resource(gvr).Namespace("default").List(context.Background(), metav1.ListOptions{}) + return err == nil + }, 30*time.Second, 200*time.Millisecond, "provider should serve the %s API", kind) + return gvr +} + +// WidgetGVK returns the demo Widget GVK. +func WidgetGVK() schema.GroupVersionKind { + return schema.GroupVersionKind{Group: "example.org", Version: "v1", Kind: "Widget"} +} + +func exportedCRD(group, plural, singular, kind string) *apiextensionsv1.CustomResourceDefinition { + preserve := true + return &apiextensionsv1.CustomResourceDefinition{ + ObjectMeta: metav1.ObjectMeta{ + Name: plural + "." + group, + Labels: map[string]string{corev1alpha1.LabelExported: "true"}, + }, + Spec: apiextensionsv1.CustomResourceDefinitionSpec{ + Group: group, + Names: apiextensionsv1.CustomResourceDefinitionNames{ + Plural: plural, + Singular: singular, + Kind: kind, + ListKind: kind + "List", + }, + Scope: apiextensionsv1.NamespaceScoped, + Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{ + Name: "v1", + Served: true, + Storage: true, + Subresources: &apiextensionsv1.CustomResourceSubresources{ + Status: &apiextensionsv1.CustomResourceSubresourceStatus{}, + }, + Schema: &apiextensionsv1.CustomResourceValidation{ + OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "spec": {Type: "object", XPreserveUnknownFields: &preserve}, + "status": {Type: "object", XPreserveUnknownFields: &preserve}, + }, + }, + }, + }}, + }, + } +} + +// kubeconfigFromRestConfig serializes an envtest rest.Config (client-cert auth) +// into a kubeconfig the konnector can load from a Secret. +func kubeconfigFromRestConfig(cfg *rest.Config) ([]byte, error) { + const name = "provider" + c := clientcmdapi.NewConfig() + c.Clusters[name] = &clientcmdapi.Cluster{ + Server: cfg.Host, + CertificateAuthorityData: cfg.CAData, + } + c.AuthInfos[name] = &clientcmdapi.AuthInfo{ + ClientCertificateData: cfg.CertData, + ClientKeyData: cfg.KeyData, + } + c.Contexts[name] = &clientcmdapi.Context{Cluster: name, AuthInfo: name} + c.CurrentContext = name + return clientcmd.Write(*c) +} + +func ensureNamespace(t *testing.T, c client.Client, name string) { + t.Helper() + err := c.Create(context.Background(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}) + if err != nil && !apierrors.IsAlreadyExists(err) { + require.NoError(t, err, "creating namespace %s", name) + } +} + +func coreCRDDir(t *testing.T) string { + t.Helper() + _, thisFile, _, ok := runtime.Caller(0) + require.True(t, ok, "runtime.Caller") + // .../test/e2e/framework/framework.go -> .../sdk/config/crd + dir := filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "sdk", "config", "crd") + abs, err := filepath.Abs(dir) + require.NoError(t, err) + return abs +} + +// WaitForConditionTrue polls until the named condition on the object is True. +func WaitForConditionTrue(t *testing.T, get func() ([]metav1.Condition, error), condType string) { + t.Helper() + require.Eventually(t, func() bool { + conds, err := get() + if err != nil { + return false + } + for _, c := range conds { + if c.Type == condType { + return c.Status == metav1.ConditionTrue + } + } + return false + }, wait.ForeverTestTimeout, 200*time.Millisecond, "waiting for condition %s=True", condType) +} diff --git a/test/e2e/framework/kcp.go b/test/e2e/framework/kcp.go deleted file mode 100644 index 9a5e04906..000000000 --- a/test/e2e/framework/kcp.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "context" - "crypto/rand" - "fmt" - "os" - "path/filepath" - "strings" - "testing" - "time" - - corev1alpha1 "github.com/kcp-dev/sdk/apis/core/v1alpha1" - tenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1" - "github.com/martinlindhe/base36" - "github.com/stretchr/testify/require" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/apiutil" - - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -type ( - ClusterWorkspaceOption func(ws *tenancyv1alpha1.Workspace) -) - -var ( - kcpScheme = runtime.NewScheme() -) - -func init() { - utilruntime.Must(tenancyv1alpha1.AddToScheme(kcpScheme)) - utilruntime.Must(kubebindv1alpha2.AddToScheme(kcpScheme)) -} - -func WithName(s string, formatArgs ...any) ClusterWorkspaceOption { - return func(ws *tenancyv1alpha1.Workspace) { - ws.Name = fmt.Sprintf(s, formatArgs...) - ws.GenerateName = "" - } -} - -func WithStaticName(s string) ClusterWorkspaceOption { - return func(ws *tenancyv1alpha1.Workspace) { - ws.Name = s - ws.GenerateName = "" - } -} - -func RandomString(length int) string { - token := make([]byte, length) - rand.Read(token) - base36hash := strings.ToLower(base36.EncodeBytes(token)) - return base36hash[:length+1] -} - -func WithGenerateName(s string, formatArgs ...any) ClusterWorkspaceOption { - return func(ws *tenancyv1alpha1.Workspace) { - s = fmt.Sprintf(s, formatArgs...) - // Workspace.ObjectMeta.GenerateName is broken in kcp: https://github.com/kcp-dev/kcp/pull/2193 - // - // ws.GenerateName = fmt.Sprintf(s, formatArgs...) - // if !strings.HasSuffix(ws.GenerateName, "-") { - // ws.GenerateName += "-" - // } - if !strings.HasSuffix(s, "-") { - s += "-" - } - - token := make([]byte, 4) - rand.Read(token) - base36hash := strings.ToLower(base36.EncodeBytes(token)) - ws.Name = s + base36hash[:5] - ws.GenerateName = "" - } -} - -func NewWorkspace(t testing.TB, config *rest.Config, options ...ClusterWorkspaceOption) (*rest.Config, string) { - ctx, cancelFunc := context.WithCancel(context.Background()) - t.Cleanup(cancelFunc) - - httpClient, err := rest.HTTPClientFor(config) - require.NoError(t, err) - mapper, err := apiutil.NewDynamicRESTMapper(config, httpClient) - require.NoError(t, err) - tenancyClient, err := client.New(config, client.Options{Scheme: kcpScheme, Mapper: mapper}) - require.NoError(t, err) - - ws := &tenancyv1alpha1.Workspace{ - ObjectMeta: metav1.ObjectMeta{ - GenerateName: "e2e-workspace-", - }, - } - - // workaround broken GenerateName for workspaces: https://github.com/kcp-dev/kcp/pull/2193 - ws.Name = ws.GenerateName - ws.GenerateName = "" - token := make([]byte, 4) - rand.Read(token) - base36hash := strings.ToLower(base36.EncodeBytes(token)) - ws.Name += base36hash[:5] - - for _, opt := range options { - opt(ws) - } - // retry as on startup kcp might be busy - require.Eventually(t, func() bool { - err = tenancyClient.Create(ctx, ws) - if err != nil && !errors.IsAlreadyExists(err) { - return false - } - return true - }, wait.ForeverTestTimeout, time.Millisecond*100, "failed to create workspace %s", ws.Name) - - ret := rest.CopyConfig(config) - ret.Host += ":" + ws.Name - - wsKubeconfigPath := filepath.Join(WorkDir(t), ws.Name+".kubeconfig") - err = clientcmd.WriteToFile(RestToKubeconfig(ret, ""), wsKubeconfigPath) - require.NoError(t, err) - - t.Cleanup(func() { - ctx, cancelFn := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30)) - defer cancelFn() - - err := tenancyClient.Get(ctx, client.ObjectKey{Name: ws.Name}, ws) - if errors.IsNotFound(err) { - return - } - require.NoError(t, err) - tenancyClient.Delete(ctx, ws) //nolint:errcheck - os.Remove(wsKubeconfigPath) - }) - - require.Eventually(t, func() bool { - background, cancel := context.WithDeadline(context.Background(), metav1.Now().Add(10*time.Second)) - defer cancel() - err := tenancyClient.Get(background, client.ObjectKey{Name: ws.Name}, ws) - require.NoError(t, err) - return ws.Status.Phase == corev1alpha1.LogicalClusterPhaseReady - }, wait.ForeverTestTimeout, time.Millisecond*100, "failed to wait for workspace %s to become ready", ws.Name) - t.Logf("Created %s workspace %s", ws.Spec.Type, ws.Name) - - return ret, wsKubeconfigPath -} diff --git a/test/e2e/framework/konnector.go b/test/e2e/framework/konnector.go deleted file mode 100644 index d55db7dd9..000000000 --- a/test/e2e/framework/konnector.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "context" - "testing" - - "github.com/spf13/pflag" - "github.com/stretchr/testify/require" - apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - - "github.com/kube-bind/kube-bind/deploy/crd" - "github.com/kube-bind/kube-bind/pkg/konnector" - "github.com/kube-bind/kube-bind/pkg/konnector/options" - kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" -) - -func StartKonnector(t *testing.T, clientConfig *rest.Config, args ...string) *konnector.Server { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - crdClient, err := apiextensionsclient.NewForConfig(clientConfig) - require.NoError(t, err) - err = crd.Create(ctx, - crdClient.ApiextensionsV1().CustomResourceDefinitions(), - metav1.GroupResource{Group: kubebindv1alpha2.GroupName, Resource: "apiservicebindings"}, - ) - require.NoError(t, err) - - fs := pflag.NewFlagSet("konnector", pflag.ContinueOnError) - options := options.NewOptions() - options.AddFlags(fs) - err = fs.Parse(args) - require.NoError(t, err) - - completed, err := options.Complete() - require.NoError(t, err) - - config, err := konnector.NewConfig(completed) - require.NoError(t, err) - - server, err := konnector.NewServer(config) - require.NoError(t, err) - prepared, err := server.PrepareRun(ctx) - require.NoError(t, err) - - prepared.OptionallyStartInformers(ctx) - go func() { - err := prepared.Run(ctx) - select { - case <-ctx.Done(): - default: - require.NoError(t, err) - } - }() - - return server -} diff --git a/test/e2e/framework/kubeconfig.go b/test/e2e/framework/kubeconfig.go deleted file mode 100644 index f369f71e3..000000000 --- a/test/e2e/framework/kubeconfig.go +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -func ClientConfig(t *testing.T) *rest.Config { - rules := clientcmd.NewDefaultClientConfigLoadingRules() - rules.ExplicitPath = os.Getenv("KUBECONFIG") - clientcmdConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, nil) - config, err := clientcmdConfig.ClientConfig() - require.NoError(t, err) - - return config -} - -func RestToKubeconfig(config *rest.Config, namespace string) clientcmdapi.Config { - return clientcmdapi.Config{ - Kind: "Config", - APIVersion: "v1", - Clusters: map[string]*clientcmdapi.Cluster{ - "default": { - Server: config.Host, - CertificateAuthorityData: config.CAData, - }, - }, - Contexts: map[string]*clientcmdapi.Context{ - "default": { - Cluster: "default", - Namespace: namespace, - AuthInfo: "default", - }, - }, - CurrentContext: "default", - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "default": { - Token: config.BearerToken, - }, - }, - } -} - -func WriteKubeconfig(t testing.TB, config clientcmdapi.Config, name string) string { - t.Helper() - - return WriteKubeconfigToPath(t, config, filepath.Join(t.TempDir(), name)) -} - -func WriteKubeconfigToPath(t testing.TB, config clientcmdapi.Config, path string) string { - t.Helper() - err := clientcmd.WriteToFile(config, path) - require.NoError(t, err, "error writing kubeconfig to %q", path) - return path -} diff --git a/test/e2e/framework/logs.go b/test/e2e/framework/logs.go deleted file mode 100644 index 6a26c3089..000000000 --- a/test/e2e/framework/logs.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2022 The Kube Bind 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 framework - -import ( - "os" - - "github.com/spf13/pflag" - "k8s.io/component-base/logs" - logsv1 "k8s.io/component-base/logs/api/v1" - "sigs.k8s.io/controller-runtime/pkg/log" - "sigs.k8s.io/controller-runtime/pkg/log/zap" -) - -func init() { - logs := logs.NewOptions() - logs.Verbosity = logsv1.VerbosityLevel(2) - logsv1.AddFlags(logs, pflag.CommandLine) - if err := pflag.CommandLine.Parse(os.Args); err != nil { - panic(err) - } - if err := logsv1.ValidateAndApply(logs, nil); err != nil { - panic(err) - } - - // prevent warnings from controller-runtime about loggers not being - // configured - log.SetLogger(zap.New(zap.UseDevMode(true))) -} diff --git a/test/e2e/namespaced_binding_test.go b/test/e2e/namespaced_binding_test.go new file mode 100644 index 000000000..c6eb2412b --- /dev/null +++ b/test/e2e/namespaced_binding_test.go @@ -0,0 +1,101 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/wait" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// TestSlimCoreNamespacedBinding exercises the namespaced Binding kind (the +// happy case uses ClusterBinding): it becomes Ready and pulls the CRD, and the +// syncer scopes instance sync to the Binding's namespace — instances elsewhere +// are not synced (ResolveConnection: a namespaced Binding covers only its own +// namespace). +func TestSlimCoreNamespacedBinding(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + gvr := env.InstallExportedWidgetCRD(t) + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + // A namespaced Binding scoped to "default". + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Binding{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + + t.Run("the namespaced Binding becomes Ready and pulls the CRD", func(t *testing.T) { + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + b := &corev1alpha1.Binding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Namespace: "default", Name: "widgets"}, b) + return b.Status.Conditions, err + }, corev1alpha1.ConditionReady) + require.Eventually(t, func() bool { + crd := &apiextensionsv1.CustomResourceDefinition{} + return env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd) == nil + }, 30*time.Second, 200*time.Millisecond, "the bound CRD should be pulled onto the consumer") + }) + + t.Run("an instance in the bound namespace syncs to the provider", func(t *testing.T) { + _, err := env.ConsumerDyn.Resource(gvr).Namespace("default").Create(ctx, nsWidget("default", "in-scope"), metav1.CreateOptions{}) + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := env.ProviderDyn.Resource(gvr).Namespace("default").Get(ctx, "in-scope", metav1.GetOptions{}) + return err == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "an instance in the bound namespace should sync to the provider") + }) + + t.Run("an instance in another namespace is not synced", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other"}})) + _, err := env.ConsumerDyn.Resource(gvr).Namespace("other").Create(ctx, nsWidget("other", "out-of-scope"), metav1.CreateOptions{}) + require.NoError(t, err) + require.Never(t, func() bool { + _, err := env.ProviderDyn.Resource(gvr).Namespace("other").Get(ctx, "out-of-scope", metav1.GetOptions{}) + return err == nil + }, 4*time.Second, 300*time.Millisecond, "an instance outside the bound namespace must not sync") + }) +} + +func nsWidget(ns, name string) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(framework.WidgetGVK()) + u.SetNamespace(ns) + u.SetName(name) + _ = unstructured.SetNestedField(u.Object, "small", "spec", "size") + return u +} diff --git a/test/e2e/policies_test.go b/test/e2e/policies_test.go new file mode 100644 index 000000000..c2a492e66 --- /dev/null +++ b/test/e2e/policies_test.go @@ -0,0 +1,176 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// TestSlimCorePolicies exercises the binding/connection policy knobs. It shares +// one envtest pair (spinning a fresh one per case exhausts envtest resources): +// deletion-policy Orphan, updatePolicy Always, autoBind, pullPolicy All, and +// PermissionDenied. The widgets-dependent cases run first, before the extra +// Connections (autoBind/All) re-stamp the widgets CRD. +func TestSlimCorePolicies(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + gvr := env.InstallExportedWidgetCRD(t) + consumerWidgets := env.ConsumerDyn.Resource(gvr).Namespace(instanceNS) + providerWidgets := env.ProviderDyn.Resource(gvr).Namespace(instanceNS) + + // Base bundle: demo-provider Connection + widgets ClusterBinding. + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + t.Run("deletion-policy Orphan keeps the provider copy", func(t *testing.T) { + w := widget("orphan-widget", "keep") + w.SetAnnotations(map[string]string{corev1alpha1.AnnotationDeletionPolicy: corev1alpha1.DeletionPolicyOrphan}) + _, err := consumerWidgets.Create(ctx, w, metav1.CreateOptions{}) + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, "orphan-widget", metav1.GetOptions{}) + return err == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "orphan-widget should sync to the provider") + + require.NoError(t, consumerWidgets.Delete(ctx, "orphan-widget", metav1.DeleteOptions{})) + require.Eventually(t, func() bool { + _, err := consumerWidgets.Get(ctx, "orphan-widget", metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer object should finalize despite Orphan") + require.Never(t, func() bool { + _, err := providerWidgets.Get(ctx, "orphan-widget", metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, 3*time.Second, 500*time.Millisecond, "Orphan must keep the provider copy") + }) + + t.Run("updatePolicy Always follows provider CRD changes", func(t *testing.T) { + require.NoError(t, retry.RetryOnConflict(retry.DefaultRetry, func() error { + crd := &apiextensionsv1.CustomResourceDefinition{} + if err := env.ProviderClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd); err != nil { + return err + } + crd.Spec.Versions[0].AdditionalPrinterColumns = append(crd.Spec.Versions[0].AdditionalPrinterColumns, + apiextensionsv1.CustomResourceColumnDefinition{Name: "colour", Type: "string", JSONPath: ".spec.colour"}) + return env.ProviderClient.Update(ctx, crd) + })) + require.Eventually(t, func() bool { + crd := &apiextensionsv1.CustomResourceDefinition{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd); err != nil { + return false + } + for _, v := range crd.Spec.Versions { + for _, col := range v.AdditionalPrinterColumns { + if col.Name == "colour" { + return true + } + } + } + return false + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer CRD should follow the provider schema change (updatePolicy: Always)") + }) + + t.Run("autoBind maintains a managed ClusterBinding", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "auto-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + AutoBind: true, + }, + })) + require.Eventually(t, func() bool { + cb := &corev1alpha1.ClusterBinding{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "auto-provider"}, cb); err != nil { + return false + } + if cb.Labels[corev1alpha1.LabelManaged] != "true" || len(cb.OwnerReferences) == 0 { + return false + } + for _, a := range cb.Spec.APIs { + if a.Name == widgetCRDName { + return true + } + } + return false + }, 30*time.Second, 200*time.Millisecond, "autoBind should maintain a managed ClusterBinding mirroring exportedAPIs") + }) + + t.Run("pullPolicy All installs CRDs without a binding", func(t *testing.T) { + env.InstallExportedCRD(t, "doodad.io", "doodads", "doodad", "Doodad") + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "all-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD, PullPolicy: corev1alpha1.PullPolicyAll}, + }, + })) + require.Eventually(t, func() bool { + crd := &apiextensionsv1.CustomResourceDefinition{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "doodads.doodad.io"}, crd) + return err == nil && crd.Labels[corev1alpha1.LabelManaged] == "true" + }, 30*time.Second, 200*time.Millisecond, "pullPolicy: All should install the CRD without a binding") + }) + + t.Run("PermissionDenied surfaces on a restricted Connection", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, env.RestrictedProviderSecret(t, "restricted-secret"))) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "restricted-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "restricted-secret", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.Eventually(t, func() bool { + conn := &corev1alpha1.Connection{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "restricted-provider"}, conn); err != nil { + return false + } + return isConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionPermissionDenied) && + !isConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) + }, 30*time.Second, 200*time.Millisecond, "a restricted Connection should report PermissionDenied and not be Ready") + }) +} diff --git a/test/e2e/related_resources_more_test.go b/test/e2e/related_resources_more_test.go new file mode 100644 index 000000000..3bd650845 --- /dev/null +++ b/test/e2e/related_resources_more_test.go @@ -0,0 +1,225 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// setupWidgetRelatedBinding creates the demo Connection (CRD schema source) and a +// Ready ClusterBinding for the Widget API carrying the given relatedResources +// rules. The Widget CRD must already be installed on the provider. +func setupWidgetRelatedBinding(t *testing.T, env *framework.Env, ctx context.Context, name string, rr []corev1alpha1.RelatedResource) { + t.Helper() + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + RelatedResources: rr, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: name}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) +} + +// TestSlimCoreRelatedConfigMaps covers ConfigMaps as a related resource +// (FromProvider): sync, GC on stop-matching, and the foreign-object guard. +func TestSlimCoreRelatedConfigMaps(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + env.InstallExportedWidgetCRD(t) + setupWidgetRelatedBinding(t, env, ctx, "widgets", []corev1alpha1.RelatedResource{{ + Resource: "configmaps", + Direction: corev1alpha1.FromProvider, + Selector: &corev1alpha1.RelatedResourceSelector{LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "widget"}}}, + }}) + + key := client.ObjectKey{Namespace: "default", Name: "widget-config"} + + t.Run("a label-selected provider ConfigMap syncs to the consumer", func(t *testing.T) { + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "widget-config", Labels: map[string]string{"app": "widget"}}, + Data: map[string]string{"region": "eu"}, + })) + require.Eventually(t, func() bool { + cm := &corev1.ConfigMap{} + if err := env.ConsumerClient.Get(ctx, key, cm); err != nil { + return false + } + return cm.Data["region"] == "eu" && + cm.Labels[corev1alpha1.LabelManaged] == "true" && + cm.Annotations[corev1alpha1.AnnotationRelatedBinding] != "" + }, 30*time.Second, 200*time.Millisecond, "the label-selected provider ConfigMap should sync to the consumer") + }) + + t.Run("the synced ConfigMap is GC'd when it stops matching", func(t *testing.T) { + cm := &corev1.ConfigMap{} + require.NoError(t, env.ProviderClient.Get(ctx, key, cm)) + delete(cm.Labels, "app") + require.NoError(t, env.ProviderClient.Update(ctx, cm)) + require.Eventually(t, func() bool { + c := &corev1.ConfigMap{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, key, c)) + }, 30*time.Second, 200*time.Millisecond, "the consumer copy should be GC'd once the ConfigMap stops matching") + }) + + t.Run("a foreign ConfigMap of the same name is not overwritten", func(t *testing.T) { + foreignKey := client.ObjectKey{Namespace: "default", Name: "foreign-config"} + // A pre-existing, unmanaged consumer ConfigMap. + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "foreign-config"}, + Data: map[string]string{"region": "FOREIGN"}, + })) + // The provider exports a same-named, matching ConfigMap. + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "foreign-config", Labels: map[string]string{"app": "widget"}}, + Data: map[string]string{"region": "PROVIDER"}, + })) + require.Never(t, func() bool { + cm := &corev1.ConfigMap{} + if err := env.ConsumerClient.Get(ctx, foreignKey, cm); err != nil { + return false + } + return cm.Data["region"] == "PROVIDER" || cm.Labels[corev1alpha1.LabelManaged] == "true" + }, 3*time.Second, 300*time.Millisecond, "the foreign consumer ConfigMap must not be overwritten or marked managed") + }) +} + +// TestSlimCoreRelatedReverseDirection covers FromConsumer (consumer -> provider): +// a consumer Secret is synced UP to the provider and GC'd when it stops matching. +func TestSlimCoreRelatedReverseDirection(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + env.InstallExportedWidgetCRD(t) + setupWidgetRelatedBinding(t, env, ctx, "widgets", []corev1alpha1.RelatedResource{{ + Resource: "secrets", + Direction: corev1alpha1.FromConsumer, + Selector: &corev1alpha1.RelatedResourceSelector{LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "widget"}}}, + }}) + + key := client.ObjectKey{Namespace: "default", Name: "consumer-creds"} + + t.Run("a label-selected consumer Secret syncs up to the provider", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "consumer-creds", Labels: map[string]string{"app": "widget"}}, + StringData: map[string]string{"token": "up3cr3t"}, + })) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + if err := env.ProviderClient.Get(ctx, key, s); err != nil { + return false + } + return string(s.Data["token"]) == "up3cr3t" && + s.Labels[corev1alpha1.LabelManaged] == "true" && + s.Annotations[corev1alpha1.AnnotationRelatedBinding] != "" + }, 30*time.Second, 200*time.Millisecond, "the consumer Secret should sync up to the provider") + }) + + t.Run("the provider copy is GC'd when the consumer Secret stops matching", func(t *testing.T) { + s := &corev1.Secret{} + require.NoError(t, env.ConsumerClient.Get(ctx, key, s)) + delete(s.Labels, "app") + require.NoError(t, env.ConsumerClient.Update(ctx, s)) + require.Eventually(t, func() bool { + c := &corev1.Secret{} + return apierrors.IsNotFound(env.ProviderClient.Get(ctx, key, c)) + }, 30*time.Second, 200*time.Millisecond, "the provider copy should be GC'd once the consumer Secret stops matching") + }) +} + +// TestSlimCoreRelatedNamedSelector covers the named selector: only the listed +// objects are synced; others are left alone. +func TestSlimCoreRelatedNamedSelector(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + env.InstallExportedWidgetCRD(t) + setupWidgetRelatedBinding(t, env, ctx, "widgets", []corev1alpha1.RelatedResource{{ + Resource: "configmaps", + Direction: corev1alpha1.FromProvider, + Selector: &corev1alpha1.RelatedResourceSelector{Names: []string{"wanted"}}, + }}) + + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "wanted"}, Data: map[string]string{"k": "v"}, + })) + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "unwanted"}, Data: map[string]string{"k": "v"}, + })) + + require.Eventually(t, func() bool { + cm := &corev1.ConfigMap{} + return env.ConsumerClient.Get(ctx, client.ObjectKey{Namespace: "default", Name: "wanted"}, cm) == nil + }, 30*time.Second, 200*time.Millisecond, "the named ConfigMap should sync") + + // Once "wanted" has synced the reconcile loop has run, so a non-named object + // would already have synced if names were ignored. + require.Never(t, func() bool { + cm := &corev1.ConfigMap{} + return env.ConsumerClient.Get(ctx, client.ObjectKey{Namespace: "default", Name: "unwanted"}, cm) == nil + }, 3*time.Second, 300*time.Millisecond, "the non-named ConfigMap must not sync") +} + +// TestSlimCoreRelatedCleanupOnUnbind verifies that deleting the binding removes +// the related copies it created (cleanupRelated on the unbind finalizer). +func TestSlimCoreRelatedCleanupOnUnbind(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + env.InstallExportedWidgetCRD(t) + setupWidgetRelatedBinding(t, env, ctx, "widgets", []corev1alpha1.RelatedResource{{ + Resource: "secrets", + Direction: corev1alpha1.FromProvider, + Selector: &corev1alpha1.RelatedResourceSelector{LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "widget"}}}, + }}) + + key := client.ObjectKey{Namespace: "default", Name: "widget-creds"} + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "widget-creds", Labels: map[string]string{"app": "widget"}}, + StringData: map[string]string{"token": "s3cr3t"}, + })) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + return env.ConsumerClient.Get(ctx, key, s) == nil + }, 30*time.Second, 200*time.Millisecond, "the related Secret should sync before unbind") + + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1alpha1.ClusterBinding{ObjectMeta: metav1.ObjectMeta{Name: "widgets"}})) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, key, s)) + }, 30*time.Second, 200*time.Millisecond, "the related copy should be cleaned up on unbind") +} diff --git a/test/e2e/related_resources_test.go b/test/e2e/related_resources_test.go new file mode 100644 index 000000000..547876bd4 --- /dev/null +++ b/test/e2e/related_resources_test.go @@ -0,0 +1,98 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// TestSlimCoreRelatedResources binds the Widget API with a relatedResources rule +// that syncs label-selected Secrets FromProvider, and verifies sync + GC. +func TestSlimCoreRelatedResources(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + env.InstallExportedWidgetCRD(t) + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + RelatedResources: []corev1alpha1.RelatedResource{{ + Group: "", + Resource: "secrets", + Direction: corev1alpha1.FromProvider, + Selector: &corev1alpha1.RelatedResourceSelector{ + LabelSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "widget"}}, + }, + }}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + secretKey := client.ObjectKey{Namespace: "default", Name: "widget-creds"} + + t.Run("a label-selected provider Secret syncs to the consumer", func(t *testing.T) { + require.NoError(t, env.ProviderClient.Create(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: "widget-creds", Labels: map[string]string{"app": "widget"}}, + StringData: map[string]string{"token": "s3cr3t"}, + })) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + if err := env.ConsumerClient.Get(ctx, secretKey, s); err != nil { + return false + } + return string(s.Data["token"]) == "s3cr3t" && + s.Labels[corev1alpha1.LabelManaged] == "true" && + s.Annotations[corev1alpha1.AnnotationRelatedBinding] != "" + }, 30*time.Second, 200*time.Millisecond, "the label-selected provider Secret should sync to the consumer") + }) + + t.Run("the synced copy is GC'd when it stops matching", func(t *testing.T) { + s := &corev1.Secret{} + require.NoError(t, env.ProviderClient.Get(ctx, secretKey, s)) + delete(s.Labels, "app") + require.NoError(t, env.ProviderClient.Update(ctx, s)) + + require.Eventually(t, func() bool { + c := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, secretKey, c)) + }, 30*time.Second, 200*time.Millisecond, "the consumer copy should be GC'd once the Secret stops matching the selector") + }) +} diff --git a/test/e2e/schema_source_test.go b/test/e2e/schema_source_test.go new file mode 100644 index 000000000..4c4e2744c --- /dev/null +++ b/test/e2e/schema_source_test.go @@ -0,0 +1,170 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +// TestSlimCoreOpenAPISource exercises schema.source: OpenAPI — the Connection +// synthesizes the consumer CRD from the provider's discovery + /openapi/v3 +// (no provider CRD read), then a binding syncs instances. +func TestSlimCoreOpenAPISource(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + gvr := env.InstallExportedWidgetCRD(t) // provider serves Widget; the label is ignored by OpenAPI + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceOpenAPI}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + conn := &corev1alpha1.Connection{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn) + return conn.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + t.Run("Connection discovers via OpenAPI but installs no unbound CRD (pullPolicy: Bound)", func(t *testing.T) { + conn := &corev1alpha1.Connection{} + require.NoError(t, env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn)) + require.Equal(t, corev1alpha1.SchemaSourceOpenAPI, conn.Status.ActiveSchemaSource) + _, ok := conn.Status.ExportsAPI(widgetCRDName) + require.True(t, ok, "OpenAPI discovery should export %s", widgetCRDName) + + // Under the default pullPolicy: Bound the Connection populates + // exportedAPIs but installs nothing — install is deferred to a binding. + // (This keeps a provider's built-in groups, e.g. kcp's *.kcp.io, off the + // consumer unless a binding references them.) + crd := &apiextensionsv1.CustomResourceDefinition{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd) + require.True(t, apierrors.IsNotFound(err), "the synthesized CRD must not be installed before a binding references it") + }) + + t.Run("a binding installs the synthesized CRD and syncs an instance", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + // The binding installed the synthesized CRD on demand (pullPolicy: Bound). + crd := &apiextensionsv1.CustomResourceDefinition{} + require.Eventually(t, func() bool { + return env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd) == nil + }, 30*time.Second, 200*time.Millisecond, "the binding should install the synthesized CRD") + require.Equal(t, "true", crd.Labels[corev1alpha1.LabelManaged]) + + consumerWidgets := env.ConsumerDyn.Resource(gvr).Namespace(instanceNS) + providerWidgets := env.ProviderDyn.Resource(gvr).Namespace(instanceNS) + require.Eventually(t, func() bool { + _, err := consumerWidgets.Create(ctx, widget("openapi-widget", "large"), metav1.CreateOptions{}) + return err == nil || apierrors.IsAlreadyExists(err) + }, 30*time.Second, 200*time.Millisecond, "the synthesized Widget CRD should become creatable") + require.Eventually(t, func() bool { + o, err := providerWidgets.Get(ctx, "openapi-widget", metav1.GetOptions{}) + if err != nil { + return false + } + size, _, _ := unstructured.NestedString(o.Object, "spec", "size") + return size == "large" + }, 30*time.Second, 200*time.Millisecond, "the instance should sync to the provider") + }) +} + +// TestSlimCoreKCPLikeProvider runs the full OpenAPI flow against a kcp-shaped +// provider (a LogicalCluster object is present, as on a kcp workspace; identity +// is taken from it rather than kube-system) and verifies the pinned remote +// identity + sync. +func TestSlimCoreKCPLikeProvider(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + lcUID := env.MakeProviderKCPLike(t, ctx) + gvr := env.InstallExportedWidgetCRD(t) + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "kcp-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{Namespace: framework.KbindNamespace, Name: "demo-provider-kubeconfig", Key: "kubeconfig"}, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceOpenAPI}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + conn := &corev1alpha1.Connection{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "kcp-provider"}, conn) + return conn.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + t.Run("identity is pinned from the LogicalCluster", func(t *testing.T) { + conn := &corev1alpha1.Connection{} + require.NoError(t, env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "kcp-provider"}, conn)) + require.Equal(t, lcUID, conn.Status.RemoteClusterUID, "remote identity must come from the LogicalCluster on a kcp-like provider") + _, ok := conn.Status.ExportsAPI(widgetCRDName) + require.True(t, ok) + }) + + t.Run("instances sync against the kcp-like provider", func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "kcp-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + consumerWidgets := env.ConsumerDyn.Resource(gvr).Namespace(instanceNS) + providerWidgets := env.ProviderDyn.Resource(gvr).Namespace(instanceNS) + require.Eventually(t, func() bool { + _, err := consumerWidgets.Create(ctx, widget("kcp-widget", "large"), metav1.CreateOptions{}) + return err == nil || apierrors.IsAlreadyExists(err) + }, 30*time.Second, 200*time.Millisecond, "the synthesized Widget CRD should become creatable") + require.Eventually(t, func() bool { + o, err := providerWidgets.Get(ctx, "kcp-widget", metav1.GetOptions{}) + if err != nil { + return false + } + // The provider copy carries our consumer markers. + return o.GetAnnotations()[corev1alpha1.AnnotationConsumerObjectUID] != "" + }, 30*time.Second, 200*time.Millisecond, "the instance should sync to the kcp-like provider") + }) +} diff --git a/test/e2e/sync_test.go b/test/e2e/sync_test.go new file mode 100644 index 000000000..e437e8dae --- /dev/null +++ b/test/e2e/sync_test.go @@ -0,0 +1,562 @@ +/* +Copyright 2026 The kbind 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 e2e + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + coordinationv1 "k8s.io/api/coordination/v1" + corev1 "k8s.io/api/core/v1" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + corev1alpha1 "github.com/kbind/kbind/sdk/apis/core/v1alpha1" + "github.com/kbind/kbind/test/e2e/framework" +) + +const ( + widgetCRDName = "widgets.example.org" + instanceNS = "default" + instanceName = "my-widget" +) + +// TestSlimCoreHappyCase exercises the full v2 slim-core flow against two +// envtest API servers, mirroring the v1 happy-case step pattern: the one-apply +// bundle (Secret + Connection + ClusterBinding) drives CRD delivery and +// bidirectional instance sync, with conflict and deletion behavior verified. +func TestSlimCoreHappyCase(t *testing.T) { + env := framework.Start(t) + ctx := context.Background() + + gvr := env.InstallExportedWidgetCRD(t) + consumerWidgets := env.ConsumerDyn.Resource(gvr).Namespace(instanceNS) + providerWidgets := env.ProviderDyn.Resource(gvr).Namespace(instanceNS) + + // The "one apply" bundle: Connection + ClusterBinding on the consumer. + // (The kubeconfig Secret was created by the framework.) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "demo-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{ + Namespace: framework.KbindNamespace, + Name: "demo-provider-kubeconfig", + Key: "kubeconfig", + }, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: widgetCRDName}}, + }, + })) + + for _, tc := range []struct { + name string + step func(t *testing.T) + }{ + { + name: "Connection becomes Ready and discovers the exported API", + step: func(t *testing.T) { + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + conn := &corev1alpha1.Connection{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn) + return conn.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + conn := &corev1alpha1.Connection{} + require.NoError(t, env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn)) + require.NotEmpty(t, conn.Status.RemoteClusterUID, "remote cluster UID must be pinned") + require.NotEmpty(t, conn.Status.LocalClusterUID, "local cluster UID must be pinned") + _, ok := conn.Status.ExportsAPI(widgetCRDName) + require.True(t, ok, "Connection must export %s", widgetCRDName) + }, + }, + { + name: "provider heartbeat Lease is maintained and renewed", + step: func(t *testing.T) { + leaseFor := func() (*coordinationv1.Lease, bool) { + conn := &corev1alpha1.Connection{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn); err != nil || conn.Status.LocalClusterUID == "" { + return nil, false + } + l := &coordinationv1.Lease{} + key := client.ObjectKey{Namespace: framework.KbindNamespace, Name: "demo-provider-" + conn.Status.LocalClusterUID[:10]} + if err := env.ProviderClient.Get(ctx, key, l); err != nil { + return nil, false + } + if l.Annotations[corev1alpha1.AnnotationConnection] != "demo-provider" { + return nil, false + } + return l, l.Spec.HolderIdentity != nil && *l.Spec.HolderIdentity == conn.Status.LocalClusterUID + } + + var renew1 metav1.MicroTime + require.Eventually(t, func() bool { + l, ok := leaseFor() + if !ok || l.Labels[corev1alpha1.LabelManaged] != "true" || l.Spec.RenewTime == nil { + return false + } + renew1 = *l.Spec.RenewTime + return true + }, 30*time.Second, 200*time.Millisecond, "a heartbeat Lease should appear on the provider") + + require.Eventually(t, func() bool { + l, ok := leaseFor() + return ok && l.Spec.RenewTime != nil && l.Spec.RenewTime.After(renew1.Time) + }, 30*time.Second, 200*time.Millisecond, "the heartbeat Lease should be renewed") + }, + }, + { + name: "ClusterBinding becomes Ready and the CRD is pulled onto the consumer", + step: func(t *testing.T) { + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + crd := &apiextensionsv1.CustomResourceDefinition{} + require.Eventually(t, func() bool { + return env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd) == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Widget CRD should be pulled onto the consumer") + require.Equal(t, "true", crd.GetLabels()[corev1alpha1.LabelManaged], "pulled CRD must be marked managed") + }, + }, + { + name: "instance spec syncs consumer -> provider with ownership markers and a finalizer", + step: func(t *testing.T) { + require.Eventually(t, func() bool { + _, err := consumerWidgets.Create(ctx, widget(instanceName, "large"), metav1.CreateOptions{}) + return err == nil || apierrors.IsAlreadyExists(err) + }, 30*time.Second, 200*time.Millisecond, "consumer Widget CRD should become creatable") + + var provObj *unstructured.Unstructured + require.Eventually(t, func() bool { + var err error + provObj, err = providerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + return err == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Widget should sync to the provider") + + size, _, _ := unstructured.NestedString(provObj.Object, "spec", "size") + require.Equal(t, "large", size) + require.Equal(t, "true", provObj.GetLabels()[corev1alpha1.LabelManaged]) + require.NotEmpty(t, provObj.GetAnnotations()[corev1alpha1.AnnotationConsumerClusterUID], "consumer-cluster-uid marker") + require.NotEmpty(t, provObj.GetAnnotations()[corev1alpha1.AnnotationConsumerObjectUID], "consumer-object-uid marker") + + require.Eventually(t, func() bool { + obj, err := consumerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + if err != nil { + return false + } + for _, f := range obj.GetFinalizers() { + if f == corev1alpha1.FinalizerSyncer { + return true + } + } + return false + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer object should carry the syncer finalizer") + }, + }, + { + name: "status syncs provider -> consumer", + step: func(t *testing.T) { + require.NoError(t, retry.RetryOnConflict(retry.DefaultRetry, func() error { + obj, err := providerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + if err != nil { + return err + } + _ = unstructured.SetNestedField(obj.Object, "Running", "status", "phase") + _, err = providerWidgets.UpdateStatus(ctx, obj, metav1.UpdateOptions{}) + return err + })) + require.Eventually(t, func() bool { + obj, err := consumerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + if err != nil { + return false + } + phase, _, _ := unstructured.NestedString(obj.Object, "status", "phase") + return phase == "Running" + }, wait.ForeverTestTimeout, 200*time.Millisecond, "provider status should flow to the consumer") + }, + }, + { + name: "spec update syncs consumer -> provider", + step: func(t *testing.T) { + require.NoError(t, retry.RetryOnConflict(retry.DefaultRetry, func() error { + obj, err := consumerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + if err != nil { + return err + } + _ = unstructured.SetNestedField(obj.Object, "xlarge", "spec", "size") + _, err = consumerWidgets.Update(ctx, obj, metav1.UpdateOptions{}) + return err + })) + require.Eventually(t, func() bool { + obj, err := providerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + if err != nil { + return false + } + size, _, _ := unstructured.NestedString(obj.Object, "spec", "size") + return size == "xlarge" + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer spec update should flow to the provider") + }, + }, + { + name: "conflict: a foreign provider object is not overwritten", + step: func(t *testing.T) { + // Pre-create a foreign object on the provider (no markers). + _, err := providerWidgets.Create(ctx, widget("conflict-widget", "PROVIDER-OWNED"), metav1.CreateOptions{}) + require.NoError(t, err) + // Create a same-named object on the consumer. + _, err = consumerWidgets.Create(ctx, widget("conflict-widget", "CONSUMER-WANTS"), metav1.CreateOptions{}) + require.NoError(t, err) + + // The provider object must stay foreign and untouched. + require.Never(t, func() bool { + obj, err := providerWidgets.Get(ctx, "conflict-widget", metav1.GetOptions{}) + if err != nil { + return false + } + size, _, _ := unstructured.NestedString(obj.Object, "spec", "size") + return size != "PROVIDER-OWNED" || obj.GetLabels()[corev1alpha1.LabelManaged] == "true" + }, 5*time.Second, 500*time.Millisecond, "foreign provider object must not be overwritten") + + // The consumer object is marked with the conflict annotation. + require.Eventually(t, func() bool { + o, err := consumerWidgets.Get(ctx, "conflict-widget", metav1.GetOptions{}) + return err == nil && o.GetAnnotations()[corev1alpha1.AnnotationConflict] != "" + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer object should carry the conflict annotation") + + // The ClusterBinding surfaces conflictCount + the Conflicts condition. + require.Eventually(t, func() bool { + cb := &corev1alpha1.ClusterBinding{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb); err != nil { + return false + } + var cnt int32 + for _, ba := range cb.Status.BoundAPIs { + if ba.Name == widgetCRDName { + cnt = ba.ConflictCount + } + } + return cnt == 1 && isConditionTrue(cb.Status.Conditions, corev1alpha1.ConditionConflicts) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "ClusterBinding should report conflictCount=1 and Conflicts=True") + }, + }, + { + name: "deletion: consumer delete removes the provider copy and releases the finalizer", + step: func(t *testing.T) { + require.NoError(t, consumerWidgets.Delete(ctx, instanceName, metav1.DeleteOptions{})) + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "provider copy should be deleted") + require.Eventually(t, func() bool { + _, err := consumerWidgets.Get(ctx, instanceName, metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer object should finalize and disappear") + }, + }, + { + name: "deletion of a conflicting consumer object leaves the foreign provider object intact", + step: func(t *testing.T) { + require.NoError(t, consumerWidgets.Delete(ctx, "conflict-widget", metav1.DeleteOptions{})) + require.Eventually(t, func() bool { + _, err := consumerWidgets.Get(ctx, "conflict-widget", metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "consumer conflict object should finalize") + // Foreign provider object must survive. + obj, err := providerWidgets.Get(ctx, "conflict-widget", metav1.GetOptions{}) + require.NoError(t, err, "foreign provider object must survive consumer deletion") + size, _, _ := unstructured.NestedString(obj.Object, "spec", "size") + require.Equal(t, "PROVIDER-OWNED", size) + }, + }, + { + // Re-discovery: a Connection already Ready picks up a CRD exported later. + name: "re-discovery: a CRD exported after connect is picked up", + step: func(t *testing.T) { + env.InstallExportedCRD(t, "gadget.io", "gadgets", "gadget", "Gadget") + require.Eventually(t, func() bool { + conn := &corev1alpha1.Connection{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "demo-provider"}, conn); err != nil { + return false + } + _, ok := conn.Status.ExportsAPI("gadgets.gadget.io") + return ok + }, 30*time.Second, 200*time.Millisecond, "Connection should re-discover the newly-exported gadgets API") + }, + }, + { + // conflictPolicy Adopt takes over an un-owned provider object. + name: "conflictPolicy Adopt takes over an un-owned provider object", + step: func(t *testing.T) { + gadgetGVR := schema.GroupVersionResource{Group: "gadget.io", Version: "v1", Resource: "gadgets"} + gadgetGVK := schema.GroupVersionKind{Group: "gadget.io", Version: "v1", Kind: "Gadget"} + consumerGadgets := env.ConsumerDyn.Resource(gadgetGVR).Namespace(instanceNS) + providerGadgets := env.ProviderDyn.Resource(gadgetGVR).Namespace(instanceNS) + gadget := func(name, size string) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(gadgetGVK) + u.SetNamespace(instanceNS) + u.SetName(name) + _ = unstructured.SetNestedField(u.Object, size, "spec", "size") + return u + } + + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "gadgets"}, + Spec: corev1alpha1.BindingSpec{ + ConnectionRef: corev1alpha1.ConnectionRef{Name: "demo-provider"}, + APIs: []corev1alpha1.APIRef{{Name: "gadgets.gadget.io"}}, + ConflictPolicy: corev1alpha1.ConflictPolicyAdopt, + }, + })) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + cb := &corev1alpha1.ClusterBinding{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "gadgets"}, cb) + return cb.Status.Conditions, err + }, corev1alpha1.ConditionReady) + + // Pre-create a FOREIGN gadget on the provider (no markers). + _, err := providerGadgets.Create(ctx, gadget("shared-gadget", "PROVIDER-OWNED"), metav1.CreateOptions{}) + require.NoError(t, err) + // Create the same-named gadget on the consumer (CRD now pulled). + require.Eventually(t, func() bool { + _, err := consumerGadgets.Create(ctx, gadget("shared-gadget", "ADOPTED"), metav1.CreateOptions{}) + return err == nil || apierrors.IsAlreadyExists(err) + }, 30*time.Second, 200*time.Millisecond, "consumer Gadget CRD should become creatable") + + // Adopt: the provider object gets our markers and its spec is + // overwritten to the consumer's value. + require.Eventually(t, func() bool { + o, err := providerGadgets.Get(ctx, "shared-gadget", metav1.GetOptions{}) + if err != nil { + return false + } + size, _, _ := unstructured.NestedString(o.Object, "spec", "size") + return size == "ADOPTED" && + o.GetLabels()[corev1alpha1.LabelManaged] == "true" && + o.GetAnnotations()[corev1alpha1.AnnotationConsumerObjectUID] != "" + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Adopt should take over the un-owned provider object") + }, + }, + { + // Gap 1: a Connection created before its Secret must resolve once the + // Secret arrives (order-independent "one apply"). + name: "Connection created before its Secret resolves when the Secret arrives", + step: func(t *testing.T) { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "late-provider"}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{ + Namespace: framework.KbindNamespace, + Name: "late-secret", + Key: "kubeconfig", + }, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + // It must be not-Ready while the Secret is missing. + require.Never(t, func() bool { + conn := &corev1alpha1.Connection{} + if err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "late-provider"}, conn); err != nil { + return false + } + return isConditionTrue(conn.Status.Conditions, corev1alpha1.ConditionReady) + }, 3*time.Second, 500*time.Millisecond, "must not be Ready without its Secret") + + // Now create the Secret (copy of the working one). + require.NoError(t, env.ConsumerClient.Create(ctx, env.CopyProviderSecret(t, "late-secret"))) + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + conn := &corev1alpha1.Connection{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "late-provider"}, conn) + return conn.Status.Conditions, err + }, corev1alpha1.ConditionReady) + }, + }, + { + // The Secret cannot be hard-deleted while its Connection exists (it + // carries a cleanup finalizer); updates stay allowed. It is released + // only when the Connection is deleted. + name: "Secret survives deletion while its Connection exists, released on Connection delete", + step: func(t *testing.T) { + secretKey := client.ObjectKey{Namespace: framework.KbindNamespace, Name: "late-secret"} + // The Connection reconcile should have stamped the finalizer. + require.Eventually(t, func() bool { + s := &corev1.Secret{} + if err := env.ConsumerClient.Get(ctx, secretKey, s); err != nil { + return false + } + for _, f := range s.Finalizers { + if f == corev1alpha1.FinalizerCleanup { + return true + } + } + return false + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Secret should carry the cleanup finalizer") + + // Deleting the Secret must NOT remove it while the Connection lives. + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: secretKey.Namespace, Name: secretKey.Name}, + })) + require.Never(t, func() bool { + s := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, secretKey, s)) + }, 3*time.Second, 500*time.Millisecond, "Secret must persist (Terminating) while its Connection exists") + + // Deleting the Connection releases the Secret. + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "late-provider"}, + })) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, secretKey, s)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Secret should be released once the Connection is deleted") + require.Eventually(t, func() bool { + c := &corev1alpha1.Connection{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "late-provider"}, c)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "Connection should finalize") + }, + }, + { + // A Secret shared by multiple Connections keeps its finalizer until + // the LAST Connection referencing it is gone. + name: "Secret shared by multiple Connections is released only when the last one is deleted", + step: func(t *testing.T) { + sharedKey := client.ObjectKey{Namespace: framework.KbindNamespace, Name: "shared-secret"} + require.NoError(t, env.ConsumerClient.Create(ctx, env.CopyProviderSecret(t, "shared-secret"))) + for _, name := range []string{"shared-a", "shared-b"} { + require.NoError(t, env.ConsumerClient.Create(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: corev1alpha1.ConnectionSpec{ + KubeconfigSecretRef: corev1alpha1.SecretKeyRef{ + Namespace: framework.KbindNamespace, Name: "shared-secret", Key: "kubeconfig", + }, + Schema: corev1alpha1.SchemaPolicy{Source: corev1alpha1.SchemaSourceCRD}, + }, + })) + } + for _, name := range []string{"shared-a", "shared-b"} { + framework.WaitForConditionTrue(t, func() ([]metav1.Condition, error) { + c := &corev1alpha1.Connection{} + err := env.ConsumerClient.Get(ctx, client.ObjectKey{Name: name}, c) + return c.Status.Conditions, err + }, corev1alpha1.ConditionReady) + } + + // Request deletion of the shared Secret — it must stay (finalizer). + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Namespace: sharedKey.Namespace, Name: sharedKey.Name}, + })) + + // Delete the first Connection — the Secret must survive (the second + // Connection still holds it). + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "shared-a"}, + })) + require.Eventually(t, func() bool { + c := &corev1alpha1.Connection{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "shared-a"}, c)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "shared-a should finalize") + require.Never(t, func() bool { + s := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, sharedKey, s)) + }, 3*time.Second, 500*time.Millisecond, "shared Secret must survive while shared-b still references it") + + // Delete the second (last) Connection — now the Secret is released + // and its pending deletion proceeds. + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1alpha1.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "shared-b"}, + })) + require.Eventually(t, func() bool { + s := &corev1.Secret{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, sharedKey, s)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "shared Secret should be released after the last Connection is deleted") + }, + }, + { + // Gap 2: deleting the ClusterBinding unbinds — provider copies gone, + // pulled CRD removed, consumer instances cascade away, finalizer freed. + name: "deleting the ClusterBinding unbinds and cleans up", + step: func(t *testing.T) { + // Seed a fresh synced instance. + _, err := consumerWidgets.Create(ctx, widget("unbind-widget", "small"), metav1.CreateOptions{}) + require.NoError(t, err) + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, "unbind-widget", metav1.GetOptions{}) + return err == nil + }, wait.ForeverTestTimeout, 200*time.Millisecond, "unbind-widget should sync to the provider") + + // Unbind. + require.NoError(t, env.ConsumerClient.Delete(ctx, &corev1alpha1.ClusterBinding{ + ObjectMeta: metav1.ObjectMeta{Name: "widgets"}, + })) + + // ClusterBinding finalizes and disappears. + require.Eventually(t, func() bool { + cb := &corev1alpha1.ClusterBinding{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, client.ObjectKey{Name: "widgets"}, cb)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "ClusterBinding should finalize") + + // Provider copy deleted. + require.Eventually(t, func() bool { + _, err := providerWidgets.Get(ctx, "unbind-widget", metav1.GetOptions{}) + return apierrors.IsNotFound(err) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "provider copy should be cleaned up on unbind") + + // Pulled CRD removed → consumer instances cascade away. + require.Eventually(t, func() bool { + crd := &apiextensionsv1.CustomResourceDefinition{} + return apierrors.IsNotFound(env.ConsumerClient.Get(ctx, client.ObjectKey{Name: widgetCRDName}, crd)) + }, wait.ForeverTestTimeout, 200*time.Millisecond, "pulled CRD should be removed on unbind") + }, + }, + } { + t.Run(tc.name, tc.step) + } +} + +func isConditionTrue(conds []metav1.Condition, t string) bool { + for _, c := range conds { + if c.Type == t { + return c.Status == metav1.ConditionTrue + } + } + return false +} + +func widget(name, size string) *unstructured.Unstructured { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(framework.WidgetGVK()) + u.SetNamespace(instanceNS) + u.SetName(name) + _ = unstructured.SetNestedField(u.Object, size, "spec", "size") + return u +} diff --git a/web/.eslintrc.cjs b/web/.eslintrc.cjs deleted file mode 100644 index 55117e7cc..000000000 --- a/web/.eslintrc.cjs +++ /dev/null @@ -1,17 +0,0 @@ -/* eslint-env node */ -require('@rushstack/eslint-patch/modern-module-resolution') - -module.exports = { - root: true, - 'extends': [ - 'plugin:vue/vue3-essential', - 'eslint:recommended', - '@vue/eslint-config-typescript' - ], - parserOptions: { - ecmaVersion: 'latest' - }, - rules: { - 'vue/multi-word-component-names': 'off' - } -} \ No newline at end of file diff --git a/web/.npmrc b/web/.npmrc deleted file mode 100644 index 1223b5c7d..000000000 --- a/web/.npmrc +++ /dev/null @@ -1,2 +0,0 @@ -fund=false -audit=false diff --git a/web/README.md b/web/README.md deleted file mode 100644 index 654c3b68c..000000000 --- a/web/README.md +++ /dev/null @@ -1,104 +0,0 @@ -# Kube Bind Frontend - -A Vue.js + TypeScript frontend application for the Kube Bind project that provides a web interface for binding Kubernetes resources across clusters with SSO authentication. - -## Features - -- **SSO Authentication**: OAuth2/OIDC-based authentication via `/api/authorize` endpoint -- **Resource Management**: Browse and bind available Kubernetes resources -- **Modern Stack**: Built with Vue.js 3, TypeScript, and Vite - -## Architecture - -The frontend integrates with the existing Go backend and provides compatibility for CLI clients through redirect handling: - -### API Endpoints - -- `/api/authorize` - SSO authentication endpoint -- `/api/callback` - OAuth2 callback handler -- `/api/resources` - Fetch available resources -- `/api/bind` - Bind resources to cluster -- `/api/clusters/{cluster}/resources` - Cluster-specific resources -- `/api/clusters/{cluster}/authorize` - Cluster-specific authentication -- `/api/exports` - Export binding configuration -- `/api/clusters/{cluster}/exports` - Cluster-specific exports - -### Redirect Handling - -For CLI compatibility, the following routes provide HTTP 302 redirects: - -- `/exports` → `/api/exports` -- `/clusters/{cluster}/exports` → `/api/clusters/{cluster}/exports` - -Frontend routes handle browser-based redirects for: - -- `/authorize` → `/api/authorize` -- `/clusters/{cluster}/authorize` → `/api/clusters/{cluster}/authorize` -- `/callback` → `/api/callback` - -## Development Setup - -### Prerequisites - -- Node.js 18+ and npm -- Go 1.19+ for running the backend server - -### Development Workflow - -#### Development with Hot Reload (Recommended) -```bash -# Terminal 1: Start Go backend -go run ./cmd/backend --listen-port=8080 --frontend http://localhost:3000 - -# Terminal 2: Start frontend dev server with hot reload -cd web -npm install -npm run dev - -### Available Scripts - -- `npm run dev` - Start development server -- `npm run build` - Build for production -- `npm run preview` - Preview production build -- `npm run lint` - Lint code -- `npm run type-check` - Run TypeScript type checking - -## Authentication Flow - -1. User clicks "Login" or accesses protected resource -2. Frontend redirects to `/api/authorize` with session parameters -3. Backend handles OAuth2 flow with configured OIDC provider -4. User is redirected back to frontend with authentication cookie -5. Frontend can now access protected endpoints - -## Project Structure - -```text -src/ -├── main.ts # Application entry point and routing -├── App.vue # Root component -├── services/ -│ └── auth.ts # Authentication and API service -└── views/ - └── Resources.vue # Resource management interface -``` - -## Configuration - -The frontend automatically detects the backend API through Vite proxy configuration. For production deployments, ensure the frontend is served from the same domain as the backend or configure CORS appropriately. - -## Building for Production - -### Integrated Build -```bash -# Use the build script (builds frontend + Go binary) -./scripts/build-frontend.sh -``` - -### Frontend Only -```bash -cd web -npm run build -``` - -The built files will be in the `web/dist/` directory and are automatically embedded into the container image and served from there. \ No newline at end of file diff --git a/web/dist/assets/favicon.D0IB_wPW.png b/web/dist/assets/favicon.D0IB_wPW.png deleted file mode 100644 index d2f7a52bc..000000000 Binary files a/web/dist/assets/favicon.D0IB_wPW.png and /dev/null differ diff --git a/web/dist/assets/index.BKHWhbRZ.js b/web/dist/assets/index.BKHWhbRZ.js deleted file mode 100644 index b4e613688..000000000 --- a/web/dist/assets/index.BKHWhbRZ.js +++ /dev/null @@ -1,12142 +0,0 @@ -//#region \0rolldown/runtime.js -var __defProp = Object.defineProperty; -var __exportAll = (all, no_symbols) => { - let target = {}; - for (var name in all) __defProp(target, name, { - get: all[name], - enumerable: true - }); - if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" }); - return target; -}; -//#endregion -//#region \0vite/modulepreload-polyfill.js -(function polyfill() { - const relList = document.createElement("link").relList; - if (relList && relList.supports && relList.supports("modulepreload")) return; - for (const link of document.querySelectorAll("link[rel=\"modulepreload\"]")) processPreload(link); - new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (mutation.type !== "childList") continue; - for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node); - } - }).observe(document, { - childList: true, - subtree: true - }); - function getFetchOpts(link) { - const fetchOpts = {}; - if (link.integrity) fetchOpts.integrity = link.integrity; - if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy; - if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include"; - else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; - else fetchOpts.credentials = "same-origin"; - return fetchOpts; - } - function processPreload(link) { - if (link.ep) return; - link.ep = true; - const fetchOpts = getFetchOpts(link); - fetch(link.href, fetchOpts); - } -})(); -//#endregion -//#region node_modules/@vue/shared/dist/shared.esm-bundler.js -/** -* @vue/shared v3.5.44 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -// @__NO_SIDE_EFFECTS__ -function makeMap(str) { - const map = /* @__PURE__ */ Object.create(null); - for (const key of str.split(",")) map[key] = 1; - return (val) => val in map; -} -var EMPTY_OBJ = {}; -var EMPTY_ARR = []; -var NOOP = () => {}; -var NO = () => false; -var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); -var isModelListener = (key) => key.startsWith("onUpdate:"); -var extend$1 = Object.assign; -var remove = (arr, el) => { - const i = arr.indexOf(el); - if (i > -1) arr.splice(i, 1); -}; -var hasOwnProperty$2 = Object.prototype.hasOwnProperty; -var hasOwn = (val, key) => hasOwnProperty$2.call(val, key); -var isArray$2 = Array.isArray; -var isMap = (val) => toTypeString(val) === "[object Map]"; -var isSet$1 = (val) => toTypeString(val) === "[object Set]"; -var isDate$1 = (val) => toTypeString(val) === "[object Date]"; -var isFunction$2 = (val) => typeof val === "function"; -var isString$1 = (val) => typeof val === "string"; -var isSymbol = (val) => typeof val === "symbol"; -var isObject$1 = (val) => val !== null && typeof val === "object"; -var isPromise = (val) => { - return (isObject$1(val) || isFunction$2(val)) && isFunction$2(val.then) && isFunction$2(val.catch); -}; -var objectToString = Object.prototype.toString; -var toTypeString = (value) => objectToString.call(value); -var toRawType = (value) => { - return toTypeString(value).slice(8, -1); -}; -var isPlainObject$1 = (val) => toTypeString(val) === "[object Object]"; -var isIntegerKey = (key) => isString$1(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; -var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"); -var cacheStringFunction = (fn) => { - const cache = /* @__PURE__ */ Object.create(null); - return ((str) => { - return cache[str] || (cache[str] = fn(str)); - }); -}; -var camelizeRE = /-\w/g; -var camelize = cacheStringFunction((str) => { - return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase()); -}); -var hyphenateRE = /\B([A-Z])/g; -var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); -var capitalize = cacheStringFunction((str) => { - return str.charAt(0).toUpperCase() + str.slice(1); -}); -var toHandlerKey = cacheStringFunction((str) => { - return str ? `on${capitalize(str)}` : ``; -}); -var hasChanged = (value, oldValue) => !Object.is(value, oldValue); -var invokeArrayFns = (fns, ...arg) => { - for (let i = 0; i < fns.length; i++) fns[i](...arg); -}; -var def = (obj, key, value, writable = false) => { - Object.defineProperty(obj, key, { - configurable: true, - enumerable: false, - writable, - value - }); -}; -var looseToNumber = (val) => { - const n = parseFloat(val); - return isNaN(n) ? val : n; -}; -var _globalThis; -var getGlobalThis = () => { - return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); -}; -function normalizeStyle(value) { - if (isArray$2(value)) { - const res = {}; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - const normalized = isString$1(item) ? parseStringStyle(item) : normalizeStyle(item); - if (normalized) for (const key in normalized) res[key] = normalized[key]; - } - return res; - } else if (isString$1(value) || isObject$1(value)) return value; -} -var listDelimiterRE = /;(?![^(]*\))/g; -var propertyDelimiterRE = /:([^]+)/; -var styleCommentRE = /"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g; -function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, (match) => match.startsWith("/*") ? "" : match).split(listDelimiterRE).forEach((item) => { - if (item) { - const tmp = item.split(propertyDelimiterRE); - tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); - } - }); - return ret; -} -function normalizeClass(value) { - let res = ""; - if (isString$1(value)) res = value; - else if (isArray$2(value)) for (let i = 0; i < value.length; i++) { - const normalized = normalizeClass(value[i]); - if (normalized) res += normalized + " "; - } - else if (isObject$1(value)) { - for (const name in value) if (value[name]) res += name + " "; - } - return res.trim(); -} -var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`; -var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); -specialBooleanAttrs + ""; -function includeBooleanAttr(value) { - return !!value || value === ""; -} -function looseCompareArrays(a, b, seen) { - if (a.length !== b.length) return false; - let equal = true; - for (let i = 0; equal && i < a.length; i++) equal = looseEqual(a[i], b[i], seen); - return equal; -} -function looseCompareCollections(a, b, seen) { - if (a.size !== b.size) return false; - const candidates = Array.from(b); - const matched = new Uint8Array(candidates.length); - for (const item of a) { - let index = -1; - for (let i = 0; i < candidates.length; i++) if (!matched[i] && looseEqual(item, candidates[i], seen)) { - index = i; - break; - } - if (index < 0) return false; - matched[index] = 1; - } - return true; -} -function looseCompareObjects(a, b, seen) { - let aValidType = isMap(a); - let bValidType = isMap(b); - if (aValidType || bValidType) return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - aValidType = isSet$1(a); - bValidType = isSet$1(b); - if (aValidType || bValidType) return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false; - if (Object.keys(a).length !== Object.keys(b).length) return false; - for (const key in a) { - const aHasKey = a.hasOwnProperty(key); - const bHasKey = b.hasOwnProperty(key); - if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key], seen)) return false; - } - return String(a) === String(b); -} -function looseCompareNested(a, b, seen, compare) { - if (!seen) seen = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()]; - const [seenA, seenB] = seen; - if (seenA.has(a) || seenB.has(b)) return seenA.get(a) === b && seenB.get(b) === a; - seenA.set(a, b); - seenB.set(b, a); - const equal = compare(a, b, seen); - seenA.delete(a); - seenB.delete(b); - return equal; -} -function looseEqual(a, b, seen) { - if (a === b) return true; - let aValidType = isDate$1(a); - let bValidType = isDate$1(b); - if (aValidType || bValidType) return aValidType && bValidType ? a.getTime() === b.getTime() : false; - aValidType = isSymbol(a); - bValidType = isSymbol(b); - if (aValidType || bValidType) return a === b; - aValidType = isArray$2(a); - bValidType = isArray$2(b); - if (aValidType || bValidType) return aValidType && bValidType ? looseCompareNested(a, b, seen, looseCompareArrays) : false; - aValidType = isObject$1(a); - bValidType = isObject$1(b); - if (aValidType || bValidType) { - if (!aValidType || !bValidType) return false; - return looseCompareNested(a, b, seen, looseCompareObjects); - } - return String(a) === String(b); -} -var isRef$1 = (val) => { - return !!(val && val["__v_isRef"] === true); -}; -var toDisplayString = (val) => { - return isString$1(val) ? val : val == null ? "" : isArray$2(val) || isObject$1(val) && (val.toString === objectToString || !isFunction$2(val.toString)) ? isRef$1(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val); -}; -var replacer = (_key, val) => { - if (isRef$1(val)) return replacer(_key, val.value); - else if (isMap(val)) return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2], i) => { - entries[stringifySymbol(key, i) + " =>"] = val2; - return entries; - }, {}) }; - else if (isSet$1(val)) return { [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) }; - else if (isSymbol(val)) return stringifySymbol(val); - else if (isObject$1(val) && !isArray$2(val) && !isPlainObject$1(val)) return String(val); - return val; -}; -var stringifySymbol = (v, i = "") => { - var _a; - return isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v; -}; -//#endregion -//#region node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js -/** -* @vue/reactivity v3.5.44 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -var activeEffectScope; -var EffectScope = class { - constructor(detached = false) { - this.detached = detached; - /** - * @internal - */ - this._active = true; - /** - * @internal track `on` calls, allow `on` call multiple times - */ - this._on = 0; - /** - * @internal - */ - this.effects = []; - /** - * @internal - */ - this.cleanups = []; - this._isPaused = false; - this._warnOnRun = true; - this.__v_skip = true; - if (!detached && activeEffectScope) if (activeEffectScope.active) { - this.parent = activeEffectScope; - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1; - } else { - this._active = false; - this._warnOnRun = false; - } - } - get active() { - return this._active; - } - pause() { - if (this._active) { - this._isPaused = true; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) scopes[i].pause(); - } - for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].pause(); - } - } - /** - * Resumes the effect scope, including all child scopes and effects. - */ - resume() { - if (this._active) { - if (this._isPaused) { - this._isPaused = false; - let i, l; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) scopes[i].resume(); - } - const effects = this.effects.slice(); - for (i = 0, l = effects.length; i < l; i++) effects[i].resume(); - } - } - } - run(fn) { - if (this._active) { - const currentEffectScope = activeEffectScope; - try { - activeEffectScope = this; - return fn(); - } finally { - activeEffectScope = currentEffectScope; - } - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - on() { - if (++this._on === 1) { - this.prevScope = activeEffectScope; - activeEffectScope = this; - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - off() { - if (this._on > 0 && --this._on === 0) { - if (activeEffectScope === this) activeEffectScope = this.prevScope; - else { - let current = activeEffectScope; - while (current) { - if (current.prevScope === this) { - current.prevScope = this.prevScope; - break; - } - current = current.prevScope; - } - } - this.prevScope = void 0; - } - } - stop(fromParent) { - if (this._active) { - this._active = false; - let i, l; - for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].stop(); - this.effects.length = 0; - for (i = 0, l = this.cleanups.length; i < l; i++) this.cleanups[i](); - this.cleanups.length = 0; - if (this.scopes) { - const scopes = this.scopes.slice(); - for (i = 0, l = scopes.length; i < l; i++) scopes[i].stop(true); - this.scopes.length = 0; - } - if (!this.detached && this.parent && !fromParent) { - const last = this.parent.scopes.pop(); - if (last && last !== this) { - this.parent.scopes[this.index] = last; - last.index = this.index; - } - } - this.parent = void 0; - } - } -}; -function getCurrentScope() { - return activeEffectScope; -} -var activeSub; -var pausedQueueEffects = /* @__PURE__ */ new WeakSet(); -var ReactiveEffect = class { - constructor(fn) { - this.fn = fn; - /** - * @internal - */ - this.deps = void 0; - /** - * @internal - */ - this.depsTail = void 0; - /** - * @internal - */ - this.flags = 5; - /** - * @internal - */ - this.next = void 0; - /** - * @internal - */ - this.cleanup = void 0; - this.scheduler = void 0; - if (activeEffectScope) if (activeEffectScope.active) activeEffectScope.effects.push(this); - else this.flags &= -2; - } - pause() { - this.flags |= 64; - } - resume() { - if (this.flags & 64) { - this.flags &= -65; - if (pausedQueueEffects.has(this)) { - pausedQueueEffects.delete(this); - this.trigger(); - } - } - } - /** - * @internal - */ - notify() { - if (this.flags & 2 && !(this.flags & 32)) return; - if (!(this.flags & 8)) batch(this); - } - run() { - if (!(this.flags & 1)) return this.fn(); - this.flags |= 2; - cleanupEffect(this); - prepareDeps(this); - const prevEffect = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = this; - shouldTrack = true; - try { - return this.fn(); - } finally { - cleanupDeps(this); - activeSub = prevEffect; - shouldTrack = prevShouldTrack; - this.flags &= -3; - } - } - stop() { - if (this.flags & 1) { - for (let link = this.deps; link; link = link.nextDep) removeSub(link); - this.deps = this.depsTail = void 0; - cleanupEffect(this); - this.onStop && this.onStop(); - this.flags &= -2; - } - } - trigger() { - if (this.flags & 64) pausedQueueEffects.add(this); - else if (this.scheduler) this.scheduler(); - else this.runIfDirty(); - } - /** - * @internal - */ - runIfDirty() { - if (isDirty(this)) this.run(); - } - get dirty() { - return isDirty(this); - } -}; -var batchDepth = 0; -var batchedSub; -var batchedComputed; -function batch(sub, isComputed = false) { - sub.flags |= 8; - if (isComputed) { - sub.next = batchedComputed; - batchedComputed = sub; - return; - } - sub.next = batchedSub; - batchedSub = sub; -} -function startBatch() { - batchDepth++; -} -function endBatch() { - if (--batchDepth > 0) return; - if (batchedComputed) { - let e = batchedComputed; - batchedComputed = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - e = next; - } - } - let error; - while (batchedSub) { - let e = batchedSub; - batchedSub = void 0; - while (e) { - const next = e.next; - e.next = void 0; - e.flags &= -9; - if (e.flags & 1) try { - e.trigger(); - } catch (err) { - if (!error) error = err; - } - e = next; - } - } - if (error) throw error; -} -function prepareDeps(sub) { - for (let link = sub.deps; link; link = link.nextDep) { - link.version = -1; - link.prevActiveLink = link.dep.activeLink; - link.dep.activeLink = link; - } -} -function cleanupDeps(sub) { - let head; - let tail = sub.depsTail; - let link = tail; - while (link) { - const prev = link.prevDep; - if (link.version === -1) { - if (link === tail) tail = prev; - removeSub(link); - removeDep(link); - } else head = link; - link.dep.activeLink = link.prevActiveLink; - link.prevActiveLink = void 0; - link = prev; - } - sub.deps = head; - sub.depsTail = tail; -} -function isDirty(sub) { - for (let link = sub.deps; link; link = link.nextDep) if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) return true; - if (sub._dirty) return true; - return false; -} -function refreshComputed(computed) { - if (computed.flags & 4 && !(computed.flags & 16)) return; - computed.flags &= -17; - if (computed.globalVersion === globalVersion) return; - computed.globalVersion = globalVersion; - if (!computed.isSSR && computed.flags & 128 && (!computed.deps && !computed._dirty || !isDirty(computed))) return; - computed.flags |= 2; - const dep = computed.dep; - const prevSub = activeSub; - const prevShouldTrack = shouldTrack; - activeSub = computed; - shouldTrack = true; - try { - prepareDeps(computed); - const value = computed.fn(computed._value); - if (dep.version === 0 || hasChanged(value, computed._value)) { - computed.flags |= 128; - computed._value = value; - dep.version++; - } - } catch (err) { - dep.version++; - throw err; - } finally { - activeSub = prevSub; - shouldTrack = prevShouldTrack; - cleanupDeps(computed); - computed.flags &= -3; - } -} -function removeSub(link, soft = false) { - const { dep, prevSub, nextSub } = link; - if (prevSub) { - prevSub.nextSub = nextSub; - link.prevSub = void 0; - } - if (nextSub) { - nextSub.prevSub = prevSub; - link.nextSub = void 0; - } - if (dep.subs === link) { - dep.subs = prevSub; - if (!prevSub && dep.computed) { - dep.computed.flags &= -5; - for (let l = dep.computed.deps; l; l = l.nextDep) removeSub(l, true); - } - } - if (!soft && !--dep.sc && dep.map) dep.map.delete(dep.key); -} -function removeDep(link) { - const { prevDep, nextDep } = link; - if (prevDep) { - prevDep.nextDep = nextDep; - link.prevDep = void 0; - } - if (nextDep) { - nextDep.prevDep = prevDep; - link.nextDep = void 0; - } -} -var shouldTrack = true; -var trackStack = []; -function pauseTracking() { - trackStack.push(shouldTrack); - shouldTrack = false; -} -function resetTracking() { - const last = trackStack.pop(); - shouldTrack = last === void 0 ? true : last; -} -function cleanupEffect(e) { - const { cleanup } = e; - e.cleanup = void 0; - if (cleanup) { - const prevSub = activeSub; - activeSub = void 0; - try { - cleanup(); - } finally { - activeSub = prevSub; - } - } -} -var globalVersion = 0; -var Link = class { - constructor(sub, dep) { - this.sub = sub; - this.dep = dep; - this.version = dep.version; - this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0; - } -}; -var Dep = class { - constructor(computed) { - this.computed = computed; - this.version = 0; - /** - * Link between this dep and the current active effect - */ - this.activeLink = void 0; - /** - * Doubly linked list representing the subscribing effects (tail) - */ - this.subs = void 0; - /** - * For object property deps cleanup - */ - this.map = void 0; - this.key = void 0; - /** - * Subscriber counter - */ - this.sc = 0; - /** - * @internal - */ - this.__v_skip = true; - } - track(debugInfo) { - if (!activeSub || !shouldTrack || activeSub === this.computed) return; - let link = this.activeLink; - if (link === void 0 || link.sub !== activeSub) { - link = this.activeLink = new Link(activeSub, this); - if (!activeSub.deps) activeSub.deps = activeSub.depsTail = link; - else { - link.prevDep = activeSub.depsTail; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - } - addSub(link); - } else if (link.version === -1) { - link.version = this.version; - if (link.nextDep) { - const next = link.nextDep; - next.prevDep = link.prevDep; - if (link.prevDep) link.prevDep.nextDep = next; - link.prevDep = activeSub.depsTail; - link.nextDep = void 0; - activeSub.depsTail.nextDep = link; - activeSub.depsTail = link; - if (activeSub.deps === link) activeSub.deps = next; - } - } - return link; - } - trigger(debugInfo) { - this.version++; - globalVersion++; - this.notify(debugInfo); - } - notify(debugInfo) { - startBatch(); - try { - for (let link = this.subs; link; link = link.prevSub) if (link.sub.notify()) link.sub.dep.notify(); - } finally { - endBatch(); - } - } -}; -function addSub(link) { - link.dep.sc++; - if (link.sub.flags & 4) { - const computed = link.dep.computed; - if (computed && !link.dep.subs) { - computed.flags |= 20; - for (let l = computed.deps; l; l = l.nextDep) addSub(l); - } - const currentTail = link.dep.subs; - if (currentTail !== link) { - link.prevSub = currentTail; - if (currentTail) currentTail.nextSub = link; - } - link.dep.subs = link; - } -} -var targetMap = /* @__PURE__ */ new WeakMap(); -var ITERATE_KEY = /* @__PURE__ */ Symbol(""); -var MAP_KEY_ITERATE_KEY = /* @__PURE__ */ Symbol(""); -var ARRAY_ITERATE_KEY = /* @__PURE__ */ Symbol(""); -function track(target, type, key) { - if (shouldTrack && activeSub) { - let depsMap = targetMap.get(target); - if (!depsMap) targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); - let dep = depsMap.get(key); - if (!dep) { - depsMap.set(key, dep = new Dep()); - dep.map = depsMap; - dep.key = key; - } - dep.track(); - } -} -function trigger(target, type, key, newValue, oldValue, oldTarget) { - const depsMap = targetMap.get(target); - if (!depsMap) { - globalVersion++; - return; - } - const run = (dep) => { - if (dep) dep.trigger(); - }; - startBatch(); - if (type === "clear") depsMap.forEach(run); - else { - const targetIsArray = isArray$2(target); - const isArrayIndex = targetIsArray && isIntegerKey(key); - if (targetIsArray && key === "length") { - const newLength = Number(newValue); - depsMap.forEach((dep, key2) => { - if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !isSymbol(key2) && key2 >= newLength) run(dep); - }); - } else { - if (key !== void 0 || depsMap.has(void 0)) run(depsMap.get(key)); - if (isArrayIndex) run(depsMap.get(ARRAY_ITERATE_KEY)); - switch (type) { - case "add": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } else if (isArrayIndex) run(depsMap.get("length")); - break; - case "delete": - if (!targetIsArray) { - run(depsMap.get(ITERATE_KEY)); - if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - break; - case "set": - if (isMap(target)) run(depsMap.get(ITERATE_KEY)); - break; - } - } - } - endBatch(); -} -function reactiveReadArray(array) { - const raw = /* @__PURE__ */ toRaw(array); - if (raw === array) return raw; - track(raw, "iterate", ARRAY_ITERATE_KEY); - if (/* @__PURE__ */ isShallow(array)) return raw; - if (!/* @__PURE__ */ isReadonly(array)) return raw.map(toReactive); - return /* @__PURE__ */ isReactive(array) ? raw.map((item) => toReadonly(toReactive(item))) : raw.map(toReadonly); -} -function shallowReadArray(arr) { - track(arr = /* @__PURE__ */ toRaw(arr), "iterate", ARRAY_ITERATE_KEY); - return arr; -} -function toWrapped(target, item) { - if (/* @__PURE__ */ isReadonly(target)) return /* @__PURE__ */ isReactive(target) ? toReadonly(toReactive(item)) : toReadonly(item); - return toReactive(item); -} -var arrayInstrumentations = { - __proto__: null, - [Symbol.iterator]() { - return iterator$1(this, Symbol.iterator, (item) => toWrapped(this, item)); - }, - concat(...args) { - return reactiveReadArray(this).concat(...args.map((x) => isArray$2(x) ? reactiveReadArray(x) : x)); - }, - entries() { - return iterator$1(this, "entries", (value) => { - value[1] = toWrapped(this, value[1]); - return value; - }); - }, - every(fn, thisArg) { - return apply(this, "every", fn, thisArg, void 0, arguments); - }, - filter(fn, thisArg) { - return apply(this, "filter", fn, thisArg, (v) => v.map((item) => toWrapped(this, item)), arguments); - }, - find(fn, thisArg) { - return apply(this, "find", fn, thisArg, (item) => toWrapped(this, item), arguments); - }, - findIndex(fn, thisArg) { - return apply(this, "findIndex", fn, thisArg, void 0, arguments); - }, - findLast(fn, thisArg) { - return apply(this, "findLast", fn, thisArg, (item) => toWrapped(this, item), arguments); - }, - findLastIndex(fn, thisArg) { - return apply(this, "findLastIndex", fn, thisArg, void 0, arguments); - }, - forEach(fn, thisArg) { - return apply(this, "forEach", fn, thisArg, void 0, arguments); - }, - includes(...args) { - return searchProxy(this, "includes", args); - }, - indexOf(...args) { - return searchProxy(this, "indexOf", args); - }, - join(separator) { - return reactiveReadArray(this).join(separator); - }, - lastIndexOf(...args) { - return searchProxy(this, "lastIndexOf", args); - }, - map(fn, thisArg) { - return apply(this, "map", fn, thisArg, void 0, arguments); - }, - pop() { - return noTracking(this, "pop"); - }, - push(...args) { - return noTracking(this, "push", args); - }, - reduce(fn, ...args) { - return reduce(this, "reduce", fn, args); - }, - reduceRight(fn, ...args) { - return reduce(this, "reduceRight", fn, args); - }, - shift() { - return noTracking(this, "shift"); - }, - some(fn, thisArg) { - return apply(this, "some", fn, thisArg, void 0, arguments); - }, - splice(...args) { - return noTracking(this, "splice", args); - }, - toReversed() { - return reactiveReadArray(this).toReversed(); - }, - toSorted(comparer) { - return reactiveReadArray(this).toSorted(comparer); - }, - toSpliced(...args) { - return reactiveReadArray(this).toSpliced(...args); - }, - unshift(...args) { - return noTracking(this, "unshift", args); - }, - values() { - return iterator$1(this, "values", (item) => toWrapped(this, item)); - } -}; -function iterator$1(self, method, wrapValue) { - const arr = shallowReadArray(self); - const methodFn = arr[method]; - const iter = methodFn.call(arr); - if (arr !== self && !/* @__PURE__ */ isShallow(self)) { - if (iter[Symbol.toStringTag] === "Array Iterator") { - const wrapped = Object.create(Object.getPrototypeOf(iter)); - wrapped.next = () => wrapResult(iter.next(), wrapValue); - if (methodFn !== arrayProto[method]) Object.defineProperties(wrapped, { - return: { get() { - const fn = iter.return; - return typeof fn === "function" ? fn.bind(iter) : fn; - } }, - throw: { get() { - const fn = iter.throw; - return typeof fn === "function" ? fn.bind(iter) : fn; - } } - }); - return wrapped; - } - iter._next = iter.next; - iter.next = () => wrapResult(iter._next(), wrapValue); - } - return iter; -} -function wrapResult(result, wrapValue) { - if (!result.done) result.value = wrapValue(result.value); - return result; -} -var arrayProto = Array.prototype; -function apply(self, method, fn, thisArg, wrappedRetFn, args) { - const arr = shallowReadArray(self); - const needsWrap = arr !== self && !/* @__PURE__ */ isShallow(self); - const methodFn = arr[method]; - if (methodFn !== arrayProto[method]) { - const result2 = methodFn.apply(self, args); - return needsWrap ? toReactive(result2) : result2; - } - let wrappedFn = fn; - if (arr !== self) { - if (needsWrap) wrappedFn = function(item, index) { - return fn.call(this, toWrapped(self, item), index, self); - }; - else if (fn.length > 2) wrappedFn = function(item, index) { - return fn.call(this, item, index, self); - }; - } - const result = methodFn.call(arr, wrappedFn, thisArg); - return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result; -} -function reduce(self, method, fn, args) { - const arr = shallowReadArray(self); - const needsWrap = arr !== self && !/* @__PURE__ */ isShallow(self); - let wrappedFn = fn; - let wrapInitialAccumulator = false; - if (arr !== self) { - if (needsWrap) { - wrapInitialAccumulator = args.length === 0; - wrappedFn = function(acc, item, index) { - if (wrapInitialAccumulator) { - wrapInitialAccumulator = false; - acc = toWrapped(self, acc); - } - return fn.call(this, acc, toWrapped(self, item), index, self); - }; - } else if (fn.length > 3) wrappedFn = function(acc, item, index) { - return fn.call(this, acc, item, index, self); - }; - } - const result = arr[method](wrappedFn, ...args); - return wrapInitialAccumulator ? toWrapped(self, result) : result; -} -function searchProxy(self, method, args) { - const arr = /* @__PURE__ */ toRaw(self); - track(arr, "iterate", ARRAY_ITERATE_KEY); - const res = arr[method](...args); - if ((res === -1 || res === false) && /* @__PURE__ */ isProxy(args[0])) { - args[0] = /* @__PURE__ */ toRaw(args[0]); - return arr[method](...args); - } - return res; -} -function noTracking(self, method, args = []) { - pauseTracking(); - startBatch(); - const res = (/* @__PURE__ */ toRaw(self))[method].apply(self, args); - endBatch(); - resetTracking(); - return res; -} -var isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); -var builtInSymbols = new Set(/* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol)); -function hasOwnProperty$1(key) { - if (!isSymbol(key)) key = String(key); - const obj = /* @__PURE__ */ toRaw(this); - track(obj, "has", key); - return obj.hasOwnProperty(key); -} -var BaseReactiveHandler = class { - constructor(_isReadonly = false, _isShallow = false) { - this._isReadonly = _isReadonly; - this._isShallow = _isShallow; - } - get(target, key, receiver) { - if (key === "__v_skip") return target["__v_skip"]; - const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; - if (key === "__v_isReactive") return !isReadonly2; - else if (key === "__v_isReadonly") return isReadonly2; - else if (key === "__v_isShallow") return isShallow2; - else if (key === "__v_raw") { - if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) return target; - return; - } - const targetIsArray = isArray$2(target); - if (!isReadonly2) { - let fn; - if (targetIsArray && (fn = arrayInstrumentations[key])) return fn; - if (key === "hasOwnProperty") return hasOwnProperty$1; - } - const res = Reflect.get(target, key, /* @__PURE__ */ isRef(target) ? target : receiver); - if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) return res; - if (!isReadonly2) track(target, "get", key); - if (isShallow2) return res; - if (/* @__PURE__ */ isRef(res)) { - const value = targetIsArray && isIntegerKey(key) ? res : res.value; - return isReadonly2 && isObject$1(value) ? /* @__PURE__ */ readonly(value) : value; - } - if (isObject$1(res)) return isReadonly2 ? /* @__PURE__ */ readonly(res) : /* @__PURE__ */ reactive(res); - return res; - } -}; -var MutableReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(false, isShallow2); - } - set(target, key, value, receiver) { - let oldValue = target[key]; - const isArrayWithIntegerKey = isArray$2(target) && isIntegerKey(key); - if (!this._isShallow) { - const isOldValueReadonly = /* @__PURE__ */ isReadonly(oldValue); - if (!/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) { - oldValue = /* @__PURE__ */ toRaw(oldValue); - value = /* @__PURE__ */ toRaw(value); - } - if (!isArrayWithIntegerKey && /* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) if (isOldValueReadonly) return true; - else { - oldValue.value = value; - return true; - } - } - const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : hasOwn(target, key); - const result = Reflect.set(target, key, value, /* @__PURE__ */ isRef(target) ? target : receiver); - if (target === /* @__PURE__ */ toRaw(receiver) && result) { - if (!hadKey) trigger(target, "add", key, value); - else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue); - } - return result; - } - deleteProperty(target, key) { - const hadKey = hasOwn(target, key); - const oldValue = target[key]; - const result = Reflect.deleteProperty(target, key); - if (result && hadKey) trigger(target, "delete", key, void 0, oldValue); - return result; - } - has(target, key) { - const result = Reflect.has(target, key); - if (!isSymbol(key) || !builtInSymbols.has(key)) track(target, "has", key); - return result; - } - ownKeys(target) { - track(target, "iterate", isArray$2(target) ? "length" : ITERATE_KEY); - return Reflect.ownKeys(target); - } -}; -var ReadonlyReactiveHandler = class extends BaseReactiveHandler { - constructor(isShallow2 = false) { - super(true, isShallow2); - } - set(target, key) { - return true; - } - deleteProperty(target, key) { - return true; - } -}; -var mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); -var readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); -var shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler(true); -var toShallow = (value) => value; -var getProto = (v) => Reflect.getPrototypeOf(v); -function createIterableMethod(method, isReadonly2, isShallow2) { - return function(...args) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const targetIsMap = isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; - const innerIterator = target[method](...args); - const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; - !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); - return extend$1(Object.create(innerIterator), { next() { - const { value, done } = innerIterator.next(); - return done ? { - value, - done - } : { - value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), - done - }; - } }); - }; -} -function createReadonlyMethod(type) { - return function(...args) { - return type === "delete" ? false : type === "clear" ? void 0 : this; - }; -} -function createInstrumentations(readonly, shallow) { - const instrumentations = { - get(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly) { - if (hasChanged(key, rawKey)) track(rawTarget, "get", key); - track(rawTarget, "get", rawKey); - } - const { has } = getProto(rawTarget); - const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive; - if (has.call(rawTarget, key)) return wrap(target.get(key)); - else if (has.call(rawTarget, rawKey)) return wrap(target.get(rawKey)); - else if (target !== rawTarget) target.get(key); - }, - get size() { - const target = this["__v_raw"]; - !readonly && track(/* @__PURE__ */ toRaw(target), "iterate", ITERATE_KEY); - return target.size; - }, - has(key) { - const target = this["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const rawKey = /* @__PURE__ */ toRaw(key); - if (!readonly) { - if (hasChanged(key, rawKey)) track(rawTarget, "has", key); - track(rawTarget, "has", rawKey); - } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); - }, - forEach(callback, thisArg) { - const observed = this; - const target = observed["__v_raw"]; - const rawTarget = /* @__PURE__ */ toRaw(target); - const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive; - !readonly && track(rawTarget, "iterate", ITERATE_KEY); - return target.forEach((value, key) => { - return callback.call(thisArg, wrap(value), wrap(key), observed); - }); - } - }; - extend$1(instrumentations, readonly ? { - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear") - } : { - add(value) { - const target = /* @__PURE__ */ toRaw(this); - const proto = getProto(target); - const rawValue = /* @__PURE__ */ toRaw(value); - const valueToAdd = !shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value) ? rawValue : value; - if (!(proto.has.call(target, valueToAdd) || hasChanged(value, valueToAdd) && proto.has.call(target, value) || hasChanged(rawValue, valueToAdd) && proto.has.call(target, rawValue))) { - target.add(valueToAdd); - trigger(target, "add", valueToAdd, valueToAdd); - } - return this; - }, - set(key, value) { - if (!shallow && !/* @__PURE__ */ isShallow(value) && !/* @__PURE__ */ isReadonly(value)) value = /* @__PURE__ */ toRaw(value); - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } - const oldValue = get.call(target, key); - target.set(key, value); - if (!hadKey) trigger(target, "add", key, value); - else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue); - return this; - }, - delete(key) { - const target = /* @__PURE__ */ toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = /* @__PURE__ */ toRaw(key); - hadKey = has.call(target, key); - } - const oldValue = get ? get.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) trigger(target, "delete", key, void 0, oldValue); - return result; - }, - clear() { - const target = /* @__PURE__ */ toRaw(this); - const hadItems = target.size !== 0; - const oldTarget = void 0; - const result = target.clear(); - if (hadItems) trigger(target, "clear", void 0, void 0, oldTarget); - return result; - } - }); - [ - "keys", - "values", - "entries", - Symbol.iterator - ].forEach((method) => { - instrumentations[method] = createIterableMethod(method, readonly, shallow); - }); - return instrumentations; -} -function createInstrumentationGetter(isReadonly2, shallow) { - const instrumentations = createInstrumentations(isReadonly2, shallow); - return (target, key, receiver) => { - if (key === "__v_isReactive") return !isReadonly2; - else if (key === "__v_isReadonly") return isReadonly2; - else if (key === "__v_isShallow") return shallow; - else if (key === "__v_raw") return target; - return Reflect.get(hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); - }; -} -var mutableCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, false) }; -var shallowCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(false, true) }; -var readonlyCollectionHandlers = { get: /* @__PURE__ */ createInstrumentationGetter(true, false) }; -var reactiveMap = /* @__PURE__ */ new WeakMap(); -var shallowReactiveMap = /* @__PURE__ */ new WeakMap(); -var readonlyMap = /* @__PURE__ */ new WeakMap(); -var shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); -function targetTypeMap(rawType) { - switch (rawType) { - case "Object": - case "Array": return 1; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": return 2; - default: return 0; - } -} -// @__NO_SIDE_EFFECTS__ -function reactive(target) { - if (/* @__PURE__ */ isReadonly(target)) return target; - return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); -} -// @__NO_SIDE_EFFECTS__ -function shallowReactive(target) { - return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); -} -// @__NO_SIDE_EFFECTS__ -function readonly(target) { - return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); -} -function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { - if (!isObject$1(target)) return target; - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) return target; - if (target["__v_skip"] || !Object.isExtensible(target)) return target; - const existingProxy = proxyMap.get(target); - if (existingProxy) return existingProxy; - const targetType = targetTypeMap(toRawType(target)); - if (targetType === 0) return target; - const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); - proxyMap.set(target, proxy); - return proxy; -} -// @__NO_SIDE_EFFECTS__ -function isReactive(value) { - if (/* @__PURE__ */ isReadonly(value)) return /* @__PURE__ */ isReactive(value["__v_raw"]); - return !!(value && value["__v_isReactive"]); -} -// @__NO_SIDE_EFFECTS__ -function isReadonly(value) { - return !!(value && value["__v_isReadonly"]); -} -// @__NO_SIDE_EFFECTS__ -function isShallow(value) { - return !!(value && value["__v_isShallow"]); -} -// @__NO_SIDE_EFFECTS__ -function isProxy(value) { - return value ? !!value["__v_raw"] : false; -} -// @__NO_SIDE_EFFECTS__ -function toRaw(observed) { - const raw = observed && observed["__v_raw"]; - return raw ? /* @__PURE__ */ toRaw(raw) : observed; -} -function markRaw(value) { - if (!hasOwn(value, "__v_skip") && Object.isExtensible(value)) def(value, "__v_skip", true); - return value; -} -var toReactive = (value) => isObject$1(value) ? /* @__PURE__ */ reactive(value) : value; -var toReadonly = (value) => isObject$1(value) ? /* @__PURE__ */ readonly(value) : value; -// @__NO_SIDE_EFFECTS__ -function isRef(r) { - return r ? r["__v_isRef"] === true : false; -} -// @__NO_SIDE_EFFECTS__ -function ref(value) { - return createRef(value, false); -} -// @__NO_SIDE_EFFECTS__ -function shallowRef(value) { - return createRef(value, true); -} -function createRef(rawValue, shallow) { - if (/* @__PURE__ */ isRef(rawValue)) return rawValue; - return new RefImpl(rawValue, shallow); -} -var RefImpl = class { - constructor(value, isShallow2) { - this.dep = new Dep(); - this["__v_isRef"] = true; - this["__v_isShallow"] = false; - this._rawValue = isShallow2 ? value : /* @__PURE__ */ toRaw(value); - this._value = isShallow2 ? value : toReactive(value); - this["__v_isShallow"] = isShallow2; - } - get value() { - this.dep.track(); - return this._value; - } - set value(newValue) { - const oldValue = this._rawValue; - const useDirectValue = this["__v_isShallow"] || /* @__PURE__ */ isShallow(newValue) || /* @__PURE__ */ isReadonly(newValue); - newValue = useDirectValue ? newValue : /* @__PURE__ */ toRaw(newValue); - if (hasChanged(newValue, oldValue)) { - this._rawValue = newValue; - this._value = useDirectValue ? newValue : toReactive(newValue); - this.dep.trigger(); - } - } -}; -function unref(ref2) { - return /* @__PURE__ */ isRef(ref2) ? ref2.value : ref2; -} -var shallowUnwrapHandlers = { - get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), - set: (target, key, value, receiver) => { - const oldValue = target[key]; - if (/* @__PURE__ */ isRef(oldValue) && !/* @__PURE__ */ isRef(value)) { - oldValue.value = value; - return true; - } else return Reflect.set(target, key, value, receiver); - } -}; -function proxyRefs(objectWithRefs) { - return /* @__PURE__ */ isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); -} -var ComputedRefImpl = class { - constructor(fn, setter, isSSR) { - this.fn = fn; - this.setter = setter; - /** - * @internal - */ - this._value = void 0; - /** - * @internal - */ - this.dep = new Dep(this); - /** - * @internal - */ - this.__v_isRef = true; - /** - * @internal - */ - this.deps = void 0; - /** - * @internal - */ - this.depsTail = void 0; - /** - * @internal - */ - this.flags = 16; - /** - * @internal - */ - this.globalVersion = globalVersion - 1; - /** - * @internal - */ - this.next = void 0; - this.effect = this; - this["__v_isReadonly"] = !setter; - this.isSSR = isSSR; - } - /** - * @internal - */ - notify() { - this.flags |= 16; - if (!(this.flags & 8) && activeSub !== this) { - batch(this, true); - return true; - } - } - get value() { - const link = this.dep.track(); - refreshComputed(this); - if (link) link.version = this.dep.version; - return this._value; - } - set value(newValue) { - if (this.setter) this.setter(newValue); - } -}; -// @__NO_SIDE_EFFECTS__ -function computed$1(getterOrOptions, debugOptions, isSSR = false) { - let getter; - let setter; - if (isFunction$2(getterOrOptions)) getter = getterOrOptions; - else { - getter = getterOrOptions.get; - setter = getterOrOptions.set; - } - return new ComputedRefImpl(getter, setter, isSSR); -} -var INITIAL_WATCHER_VALUE = {}; -var cleanupMap = /* @__PURE__ */ new WeakMap(); -var activeWatcher = void 0; -function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) { - if (owner) { - let cleanups = cleanupMap.get(owner); - if (!cleanups) cleanupMap.set(owner, cleanups = []); - cleanups.push(cleanupFn); - } -} -function watch$1(source, cb, options = EMPTY_OBJ) { - const { immediate, deep, once, scheduler, augmentJob, call } = options; - const reactiveGetter = (source2) => { - if (deep) return source2; - if (/* @__PURE__ */ isShallow(source2) || deep === false || deep === 0) return traverse(source2, 1); - return traverse(source2); - }; - let effect; - let getter; - let cleanup; - let boundCleanup; - let forceTrigger = false; - let isMultiSource = false; - if (/* @__PURE__ */ isRef(source)) { - getter = () => source.value; - forceTrigger = /* @__PURE__ */ isShallow(source); - } else if (/* @__PURE__ */ isReactive(source)) { - getter = () => reactiveGetter(source); - forceTrigger = true; - } else if (isArray$2(source)) { - isMultiSource = true; - forceTrigger = source.some((s) => /* @__PURE__ */ isReactive(s) || /* @__PURE__ */ isShallow(s)); - getter = () => source.map((s) => { - if (/* @__PURE__ */ isRef(s)) return s.value; - else if (/* @__PURE__ */ isReactive(s)) return reactiveGetter(s); - else if (isFunction$2(s)) return call ? call(s, 2) : s(); - }); - } else if (isFunction$2(source)) if (cb) getter = call ? () => call(source, 2) : source; - else getter = () => { - if (cleanup) { - pauseTracking(); - try { - cleanup(); - } finally { - resetTracking(); - } - } - const currentEffect = activeWatcher; - activeWatcher = effect; - try { - return call ? call(source, 3, [boundCleanup]) : source(boundCleanup); - } finally { - activeWatcher = currentEffect; - } - }; - else getter = NOOP; - if (cb && deep) { - const baseGetter = getter; - const depth = deep === true ? Infinity : deep; - getter = () => traverse(baseGetter(), depth); - } - const scope = getCurrentScope(); - const watchHandle = () => { - effect.stop(); - if (scope && scope.active) remove(scope.effects, effect); - }; - if (once && cb) { - const _cb = cb; - cb = (...args) => { - try { - return _cb(...args); - } finally { - watchHandle(); - } - }; - } - let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; - const job = (immediateFirstRun) => { - if (!(effect.flags & 1) || !effect.dirty && !immediateFirstRun) return; - if (cb) { - const newValue = effect.run(); - if (immediateFirstRun || deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue))) { - const currentWatcher = activeWatcher; - pauseTracking(); - try { - if (cleanup) cleanup(); - activeWatcher = effect; - const args = [ - newValue, - oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, - boundCleanup - ]; - oldValue = newValue; - call ? call(cb, 3, args) : cb(...args); - } finally { - activeWatcher = currentWatcher; - resetTracking(); - } - } - } else effect.run(); - }; - if (augmentJob) augmentJob(job); - effect = new ReactiveEffect(getter); - effect.scheduler = scheduler ? () => scheduler(job, false) : job; - boundCleanup = (fn) => onWatcherCleanup(fn, false, effect); - cleanup = effect.onStop = () => { - const cleanups = cleanupMap.get(effect); - if (cleanups) { - if (call) call(cleanups, 4); - else for (const cleanup2 of cleanups) cleanup2(); - cleanupMap.delete(effect); - } - }; - if (cb) if (immediate) job(true); - else oldValue = effect.run(); - else if (scheduler) scheduler(job.bind(null, true), true); - else effect.run(); - watchHandle.pause = effect.pause.bind(effect); - watchHandle.resume = effect.resume.bind(effect); - watchHandle.stop = watchHandle; - return watchHandle; -} -function traverse(value, depth = Infinity, seen) { - if (depth <= 0 || !isObject$1(value) || value["__v_skip"]) return value; - seen = seen || /* @__PURE__ */ new Map(); - if ((seen.get(value) || 0) >= depth) return value; - seen.set(value, depth); - depth--; - if (/* @__PURE__ */ isRef(value)) traverse(value.value, depth, seen); - else if (isArray$2(value)) for (let i = 0; i < value.length; i++) traverse(value[i], depth, seen); - else if (isSet$1(value) || isMap(value)) value.forEach((v) => { - traverse(v, depth, seen); - }); - else if (isPlainObject$1(value)) { - for (const key in value) traverse(value[key], depth, seen); - for (const key of Object.getOwnPropertySymbols(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) traverse(value[key], depth, seen); - } - return value; -} -//#endregion -//#region node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js -/** -* @vue/runtime-core v3.5.44 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -function callWithErrorHandling(fn, instance, type, args) { - try { - return args ? fn(...args) : fn(); - } catch (err) { - handleError(err, instance, type); - } -} -function callWithAsyncErrorHandling(fn, instance, type, args) { - if (isFunction$2(fn)) { - const res = callWithErrorHandling(fn, instance, type, args); - if (res && isPromise(res)) res.catch((err) => { - handleError(err, instance, type); - }); - return res; - } - if (isArray$2(fn)) { - const values = []; - for (let i = 0; i < fn.length; i++) values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); - return values; - } -} -function handleError(err, instance, type, throwInDev = true) { - const contextVNode = instance ? instance.vnode : null; - const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || EMPTY_OBJ; - if (instance) { - let cur = instance.parent; - const exposedInstance = instance.proxy; - const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`; - while (cur) { - const errorCapturedHooks = cur.ec; - if (errorCapturedHooks) { - for (let i = 0; i < errorCapturedHooks.length; i++) if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) return; - } - cur = cur.parent; - } - if (errorHandler) { - pauseTracking(); - callWithErrorHandling(errorHandler, null, 10, [ - err, - exposedInstance, - errorInfo - ]); - resetTracking(); - return; - } - } - logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction); -} -function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) { - if (throwInProd) throw err; - else console.error(err); -} -var queue = []; -var flushIndex = -1; -var pendingPostFlushCbs = []; -var activePostFlushCbs = null; -var postFlushIndex = 0; -var resolvedPromise = /* @__PURE__ */ Promise.resolve(); -var currentFlushPromise = null; -function nextTick(fn) { - const p = currentFlushPromise || resolvedPromise; - return fn ? p.then(this ? fn.bind(this) : fn) : p; -} -function findInsertionIndex$1(id) { - let start = flushIndex + 1; - let end = queue.length; - while (start < end) { - const middle = start + end >>> 1; - const middleJob = queue[middle]; - const middleJobId = getId(middleJob); - if (middleJobId < id || middleJobId === id && middleJob.flags & 2) start = middle + 1; - else end = middle; - } - return start; -} -function queueJob(job) { - if (!(job.flags & 1)) { - const jobId = getId(job); - const lastJob = queue[queue.length - 1]; - if (!lastJob || !(job.flags & 2) && jobId >= getId(lastJob)) queue.push(job); - else queue.splice(findInsertionIndex$1(jobId), 0, job); - job.flags |= 1; - queueFlush(); - } -} -function queueFlush() { - if (!currentFlushPromise) currentFlushPromise = resolvedPromise.then(flushJobs); -} -function queuePostFlushCb(cb) { - if (!isArray$2(cb)) { - if (activePostFlushCbs && cb.id === -1) activePostFlushCbs.splice(postFlushIndex + 1, 0, cb); - else if (!(cb.flags & 1)) { - pendingPostFlushCbs.push(cb); - cb.flags |= 1; - } - } else for (let i = 0; i < cb.length; i++) pendingPostFlushCbs.push(cb[i]); - queueFlush(); -} -function flushPreFlushCbs(instance, minUid, seen, i = flushIndex + 1) { - for (; i < queue.length; i++) { - const cb = queue[i]; - if (cb && cb.flags & 2) { - if (instance && cb.id !== instance.uid || minUid !== void 0 && !(cb.id >= minUid)) continue; - queue.splice(i, 1); - i = instance ? i - 1 : flushIndex; - if (cb.flags & 4) cb.flags &= -2; - cb(); - if (!(cb.flags & 4)) cb.flags &= -2; - } - } -} -function flushPostFlushCbs(seen, skip, minUid = 0) { - if (pendingPostFlushCbs.length) { - let cbs = pendingPostFlushCbs; - let kept = 0; - if (skip) { - cbs = []; - for (let i = 0; i < pendingPostFlushCbs.length; i++) { - const cb = pendingPostFlushCbs[i]; - if (cb.i !== void 0 ? !cb.i || cb.i.uid < minUid : skip.has(cb)) pendingPostFlushCbs[kept++] = cb; - else cbs.push(cb); - } - } - const deduped = [...new Set(cbs)].sort((a, b) => getId(a) - getId(b)); - pendingPostFlushCbs.length = kept; - if (activePostFlushCbs) { - for (let i = 0; i < deduped.length; i++) activePostFlushCbs.push(deduped[i]); - return; - } - activePostFlushCbs = deduped; - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - const cb = activePostFlushCbs[postFlushIndex]; - if (cb.flags & 4) cb.flags &= -2; - if (!(cb.flags & 8)) cb(); - cb.flags &= -2; - } - activePostFlushCbs = null; - postFlushIndex = 0; - } -} -var isFlushing = false; -function flushOnAppMount(fn, minUid) { - if (isFlushing) { - fn(); - return; - } - const queued = minUid === void 0 ? void 0 : new Set(pendingPostFlushCbs); - fn(); - isFlushing = true; - try { - flushPreFlushCbs(void 0, minUid); - flushPostFlushCbs(void 0, queued, minUid); - } finally { - isFlushing = false; - } -} -var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id; -function flushJobs(seen) { - try { - for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job && !(job.flags & 8)) { - if (job.flags & 4) job.flags &= -2; - callWithErrorHandling(job, job.i, job.i ? 15 : 14); - if (!(job.flags & 4)) job.flags &= -2; - } - } - } finally { - for (; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job) job.flags &= -2; - } - flushIndex = -1; - queue.length = 0; - flushPostFlushCbs(seen); - currentFlushPromise = null; - if (queue.length || pendingPostFlushCbs.length) flushJobs(seen); - } -} -var currentRenderingInstance = null; -var currentScopeId = null; -function setCurrentRenderingInstance(instance) { - const prev = currentRenderingInstance; - currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; - return prev; -} -function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { - if (!ctx) return fn; - if (fn._n) return fn; - const renderFnWithContext = (...args) => { - if (renderFnWithContext._d) setBlockTracking(-1); - const prevInstance = setCurrentRenderingInstance(ctx); - const prevStackSize = blockStack.length; - let res; - try { - res = fn(...args); - } finally { - for (let i = blockStack.length; i > prevStackSize; i--) closeBlock(); - setCurrentRenderingInstance(prevInstance); - if (renderFnWithContext._d) setBlockTracking(1); - } - return res; - }; - renderFnWithContext._n = true; - renderFnWithContext._c = true; - renderFnWithContext._d = true; - return renderFnWithContext; -} -function withDirectives(vnode, directives) { - if (currentRenderingInstance === null) return vnode; - const instance = getComponentPublicInstance(currentRenderingInstance); - const bindings = vnode.dirs || (vnode.dirs = []); - for (let i = 0; i < directives.length; i++) { - let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; - if (dir) { - if (isFunction$2(dir)) dir = { - mounted: dir, - updated: dir - }; - if (dir.deep) traverse(value); - bindings.push({ - dir, - instance, - value, - oldValue: void 0, - arg, - modifiers - }); - } - } - return vnode; -} -function invokeDirectiveHook(vnode, prevVNode, instance, name) { - const bindings = vnode.dirs; - const oldBindings = prevVNode && prevVNode.dirs; - for (let i = 0; i < bindings.length; i++) { - const binding = bindings[i]; - if (oldBindings) binding.oldValue = oldBindings[i].value; - let hook = binding.dir[name]; - if (hook) { - pauseTracking(); - callWithAsyncErrorHandling(hook, instance, 8, [ - vnode.el, - binding, - vnode, - prevVNode - ]); - resetTracking(); - } - } -} -function provide(key, value) { - if (currentInstance) { - let provides = currentInstance.provides; - const parentProvides = currentInstance.parent && currentInstance.parent.provides; - if (parentProvides === provides) provides = currentInstance.provides = Object.create(parentProvides); - provides[key] = value; - } -} -function inject(key, defaultValue, treatDefaultAsFactory = false) { - const instance = getCurrentInstance(); - if (instance || currentApp) { - let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0; - if (provides && key in provides) return provides[key]; - else if (arguments.length > 1) return treatDefaultAsFactory && isFunction$2(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue; - } -} -var ssrContextKey = /* @__PURE__ */ Symbol.for("v-scx"); -var useSSRContext = () => { - { - const ctx = inject(ssrContextKey); - if (!ctx) {} - return ctx; - } -}; -function watch(source, cb, options) { - return doWatch(source, cb, options); -} -function doWatch(source, cb, options = EMPTY_OBJ) { - const { immediate, deep, flush, once } = options; - const baseWatchOptions = extend$1({}, options); - const runsImmediately = cb && immediate || !cb && flush !== "post"; - let ssrCleanup; - if (isInSSRComponentSetup) { - if (flush === "sync") { - const ctx = useSSRContext(); - ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); - } else if (!runsImmediately) { - const watchStopHandle = () => {}; - watchStopHandle.stop = NOOP; - watchStopHandle.resume = NOOP; - watchStopHandle.pause = NOOP; - return watchStopHandle; - } - } - const instance = currentInstance; - baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args); - let isPre = false; - if (flush === "post") baseWatchOptions.scheduler = (job) => { - job.i = instance; - queuePostRenderEffect(job, instance && instance.suspense); - }; - else if (flush !== "sync") { - isPre = true; - baseWatchOptions.scheduler = (job, isFirstRun) => { - if (isFirstRun) job(); - else queueJob(job); - }; - } - baseWatchOptions.augmentJob = (job) => { - if (cb) job.flags |= 4; - if (isPre) { - job.flags |= 2; - if (instance) { - job.id = instance.uid; - job.i = instance; - } - } - }; - const watchHandle = watch$1(source, cb, baseWatchOptions); - if (isInSSRComponentSetup) { - if (ssrCleanup) ssrCleanup.push(watchHandle); - else if (runsImmediately) watchHandle(); - } - return watchHandle; -} -function instanceWatch(source, value, options) { - const publicThis = this.proxy; - const getter = isString$1(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); - let cb; - if (isFunction$2(value)) cb = value; - else { - cb = value.handler; - options = value; - } - const reset = setCurrentInstance(this); - const res = doWatch(getter, cb.bind(publicThis), options); - reset(); - return res; -} -function createPathGetter(ctx, path) { - const segments = path.split("."); - return () => { - let cur = ctx; - for (let i = 0; i < segments.length && cur; i++) cur = cur[segments[i]]; - return cur; - }; -} -var TeleportEndKey = /* @__PURE__ */ Symbol("_vte"); -var isTeleport = (type) => type.__isTeleport; -var leaveCbKey = /* @__PURE__ */ Symbol("_leaveCb"); -function findNonCommentChild(children) { - let child = children[0]; - if (children.length > 1) { - for (const c of children) if (c.type !== Comment) { - child = c; - break; - } - } - return child; -} -function getInnerChild$1(vnode) { - if (!isKeepAlive(vnode)) { - if (isTeleport(vnode.type) && vnode.children) return findNonCommentChild(vnode.children); - return vnode; - } - if (vnode.component) return vnode.component.subTree; - const { shapeFlag, children } = vnode; - if (children) { - if (shapeFlag & 16) return children[0]; - if (shapeFlag & 32 && isFunction$2(children.default)) return children.default(); - } -} -function setTransitionHooks(vnode, hooks) { - if (vnode.shapeFlag & 6 && vnode.component) { - vnode.transition = hooks; - const subTree = vnode.component.subTree; - setTransitionHooks(isTeleport(subTree.type) ? getInnerChild$1(subTree) || subTree : subTree, hooks); - } else if (vnode.shapeFlag & 128) { - vnode.ssContent.transition = hooks.clone(vnode.ssContent); - vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); - } else { - vnode.transition = hooks; - if (vnode.type === Fragment && isArray$2(vnode.children)) { - const child = filterSingleRoot(vnode.children, false); - if (child) setTransitionHooks(child, hooks); - } - } -} -function getTransitionRoot(vnode) { - if (vnode.component) return getTransitionRoot(vnode.component.subTree); - if (vnode.type === Fragment) { - const child = isArray$2(vnode.children) && filterSingleRoot(vnode.children, false); - return child ? getTransitionRoot(child) : void 0; - } - if (vnode.type !== Comment) return vnode; -} -// @__NO_SIDE_EFFECTS__ -function defineComponent(options, extraOptions) { - return isFunction$2(options) ? /* @__PURE__ */ (() => extend$1({ name: options.name }, extraOptions, { setup: options }))() : options; -} -function markAsyncBoundary(instance) { - instance.ids = [ - instance.ids[0] + instance.ids[2]++ + "-", - 0, - 0 - ]; -} -function isTemplateRefKey(refs, key) { - let desc; - return !!((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable); -} -var pendingSetRefMap = /* @__PURE__ */ new WeakMap(); -function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { - if (isArray$2(rawRef)) { - rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray$2(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount)); - return; - } - if (isAsyncWrapper(vnode) && !isUnmount) { - if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree); - return; - } - const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el; - const value = isUnmount ? null : refValue; - const { i: owner, r: ref } = rawRef; - const oldRef = oldRawRef && oldRawRef.r; - const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs; - const setupState = owner.setupState; - const rawSetupState = /* @__PURE__ */ toRaw(setupState); - const canSetSetupRef = setupState === EMPTY_OBJ ? NO : (key) => { - if (isTemplateRefKey(refs, key)) return false; - return hasOwn(rawSetupState, key); - }; - const canSetRef = (ref2, key) => { - if (key && isTemplateRefKey(refs, key)) return false; - return true; - }; - if (oldRef != null && oldRef !== ref) { - invalidatePendingSetRef(oldRawRef); - if (isString$1(oldRef)) { - refs[oldRef] = null; - if (canSetSetupRef(oldRef)) setupState[oldRef] = null; - } else if (/* @__PURE__ */ isRef(oldRef)) { - const oldRawRefAtom = oldRawRef; - if (canSetRef(oldRef, oldRawRefAtom.k)) oldRef.value = null; - if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null; - } - } - if (isFunction$2(ref)) callWithErrorHandling(ref, owner, 12, [value, refs]); - else { - const _isString = isString$1(ref); - const _isRef = /* @__PURE__ */ isRef(ref); - if (_isString || _isRef) { - const doSet = () => { - if (rawRef.f) { - const existing = _isString ? canSetSetupRef(ref) ? setupState[ref] : refs[ref] : canSetRef(ref) || !rawRef.k ? ref.value : refs[rawRef.k]; - if (isUnmount) isArray$2(existing) && remove(existing, refValue); - else if (!isArray$2(existing)) if (_isString) { - refs[ref] = [refValue]; - if (canSetSetupRef(ref)) setupState[ref] = refs[ref]; - } else { - const newVal = [refValue]; - if (canSetRef(ref, rawRef.k)) ref.value = newVal; - if (rawRef.k) refs[rawRef.k] = newVal; - } - else if (!existing.includes(refValue)) existing.push(refValue); - } else if (_isString) { - refs[ref] = value; - if (canSetSetupRef(ref)) setupState[ref] = value; - } else if (_isRef) { - if (canSetRef(ref, rawRef.k)) ref.value = value; - if (rawRef.k) refs[rawRef.k] = value; - } - }; - if (value) { - const job = () => { - doSet(); - pendingSetRefMap.delete(rawRef); - }; - job.id = -1; - pendingSetRefMap.set(rawRef, job); - queuePostRenderEffect(job, parentSuspense); - } else { - invalidatePendingSetRef(rawRef); - doSet(); - } - } - } -} -function invalidatePendingSetRef(rawRef) { - const pendingSetRef = pendingSetRefMap.get(rawRef); - if (pendingSetRef) { - pendingSetRef.flags |= 8; - pendingSetRefMap.delete(rawRef); - } -} -getGlobalThis().requestIdleCallback; -getGlobalThis().cancelIdleCallback; -var isAsyncWrapper = (i) => !!i.type.__asyncLoader; -var isKeepAlive = (vnode) => vnode.type.__isKeepAlive; -function onActivated(hook, target) { - registerKeepAliveHook(hook, "a", target); -} -function onDeactivated(hook, target) { - registerKeepAliveHook(hook, "da", target); -} -function registerKeepAliveHook(hook, type, target = currentInstance) { - const wrappedHook = hook.__wdc || (hook.__wdc = () => { - let current = target; - while (current) { - if (current.isDeactivated) return; - current = current.parent; - } - return hook(); - }); - injectHook(type, wrappedHook, target); - if (target) { - let current = target.parent; - while (current && current.parent) { - if (isKeepAlive(current.parent.vnode)) injectToKeepAliveRoot(wrappedHook, type, target, current); - current = current.parent; - } - } -} -function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { - const injected = injectHook(type, hook, keepAliveRoot, true); - onUnmounted(() => { - remove(keepAliveRoot[type], injected); - }, target); -} -function injectHook(type, hook, target = currentInstance, prepend = false) { - if (target) { - const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - pauseTracking(); - const reset = setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - reset(); - resetTracking(); - return res; - }); - if (prepend) hooks.unshift(wrappedHook); - else hooks.push(wrappedHook); - return wrappedHook; - } -} -var createHook = (lifecycle) => (hook, target = currentInstance) => { - if (!isInSSRComponentSetup || lifecycle === "sp") injectHook(lifecycle, (...args) => hook(...args), target); -}; -var onBeforeMount = createHook("bm"); -var onMounted = createHook("m"); -var onBeforeUpdate = createHook("bu"); -var onUpdated = createHook("u"); -var onBeforeUnmount = createHook("bum"); -var onUnmounted = createHook("um"); -var onServerPrefetch = createHook("sp"); -var onRenderTriggered = createHook("rtg"); -var onRenderTracked = createHook("rtc"); -function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); -} -var COMPONENTS = "components"; -function resolveComponent(name, maybeSelfReference) { - return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; -} -var NULL_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol.for("v-ndc"); -function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { - const instance = currentRenderingInstance || currentInstance; - if (instance) { - const Component = instance.type; - if (type === COMPONENTS) { - const selfName = getComponentName(Component, false); - if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) return Component; - } - const res = resolve(instance[type] || Component[type], name) || resolve(instance.appContext[type], name); - if (!res && maybeSelfReference) return Component; - return res; - } -} -function resolve(registry, name) { - return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]); -} -function renderList(source, renderItem, cache, index) { - let ret; - const cached = cache && cache[index]; - const sourceIsArray = isArray$2(source); - if (sourceIsArray || isString$1(source)) { - const sourceIsReactiveArray = sourceIsArray && /* @__PURE__ */ isReactive(source); - let needsWrap = false; - let isReadonlySource = false; - if (sourceIsReactiveArray) { - needsWrap = !/* @__PURE__ */ isShallow(source); - isReadonlySource = /* @__PURE__ */ isReadonly(source); - source = shallowReadArray(source); - } - ret = new Array(source.length); - for (let i = 0, l = source.length; i < l; i++) ret[i] = renderItem(needsWrap ? isReadonlySource ? toReadonly(toReactive(source[i])) : toReactive(source[i]) : source[i], i, void 0, cached && cached[i]); - } else if (typeof source === "number") if (!Number.isInteger(source) || source < 0) ret = []; - else { - ret = new Array(source); - for (let i = 0; i < source; i++) ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); - } - else if (isObject$1(source)) if (source[Symbol.iterator]) ret = Array.from(source, (item, i) => renderItem(item, i, void 0, cached && cached[i])); - else { - const keys = Object.keys(source); - ret = new Array(keys.length); - for (let i = 0, l = keys.length; i < l; i++) { - const key = keys[i]; - ret[i] = renderItem(source[key], key, i, cached && cached[i]); - } - } - else ret = []; - if (cache) cache[index] = ret; - return ret; -} -var getPublicInstance = (i) => { - if (!i) return null; - if (isStatefulComponent(i)) return getComponentPublicInstance(i); - return getPublicInstance(i.parent); -}; -var publicPropertiesMap = /* @__PURE__ */ extend$1(/* @__PURE__ */ Object.create(null), { - $: (i) => i, - $el: (i) => i.vnode.el, - $data: (i) => i.data, - $props: (i) => i.props, - $attrs: (i) => i.attrs, - $slots: (i) => i.slots, - $refs: (i) => i.refs, - $parent: (i) => getPublicInstance(i.parent), - $root: (i) => getPublicInstance(i.root), - $host: (i) => i.ce, - $emit: (i) => i.emit, - $options: (i) => resolveMergedOptions(i), - $forceUpdate: (i) => i.f || (i.f = () => { - queueJob(i.update); - }), - $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), - $watch: (i) => instanceWatch.bind(i) -}); -var hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key); -var PublicInstanceProxyHandlers = { - get({ _: instance }, key) { - if (key === "__v_skip") return true; - const { ctx, setupState, data, props, accessCache, type, appContext } = instance; - if (key[0] !== "$") { - const n = accessCache[key]; - if (n !== void 0) switch (n) { - case 1: return setupState[key]; - case 2: return data[key]; - case 4: return ctx[key]; - case 3: return props[key]; - } - else if (hasSetupBinding(setupState, key)) { - accessCache[key] = 1; - return setupState[key]; - } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { - accessCache[key] = 2; - return data[key]; - } else if (hasOwn(props, key)) { - accessCache[key] = 3; - return props[key]; - } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if (shouldCacheAccess) accessCache[key] = 0; - } - const publicGetter = publicPropertiesMap[key]; - let cssModule, globalProperties; - if (publicGetter) { - if (key === "$attrs") track(instance.attrs, "get", ""); - return publicGetter(instance); - } else if ((cssModule = type.__cssModules) && (cssModule = cssModule[key])) return cssModule; - else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { - accessCache[key] = 4; - return ctx[key]; - } else if (globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)) return globalProperties[key]; - }, - set({ _: instance }, key, value) { - const { data, setupState, ctx } = instance; - if (hasSetupBinding(setupState, key)) { - setupState[key] = value; - return true; - } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { - data[key] = value; - return true; - } else if (hasOwn(instance.props, key)) return false; - if (key[0] === "$" && key.slice(1) in instance) return false; - else ctx[key] = value; - return true; - }, - has({ _: { data, setupState, accessCache, ctx, appContext, props, type } }, key) { - let cssModules; - return !!(accessCache[key] || data !== EMPTY_OBJ && key[0] !== "$" && hasOwn(data, key) || hasSetupBinding(setupState, key) || hasOwn(props, key) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]); - }, - defineProperty(target, key, descriptor) { - if (descriptor.get != null) target._.accessCache[key] = 0; - else if (hasOwn(descriptor, "value")) this.set(target, key, descriptor.value, null); - return Reflect.defineProperty(target, key, descriptor); - } -}; -function normalizePropsOrEmits(props) { - return isArray$2(props) ? props.reduce((normalized, p) => (normalized[p] = null, normalized), {}) : props; -} -var shouldCacheAccess = true; -function applyOptions(instance) { - const options = resolveMergedOptions(instance); - const publicThis = instance.proxy; - const ctx = instance.ctx; - shouldCacheAccess = false; - if (options.beforeCreate) callHook(options.beforeCreate, instance, "bc"); - const { data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch, expose, inheritAttrs, components, directives, filters } = options; - const checkDuplicateProperties = null; - if (injectOptions) resolveInjections(injectOptions, ctx, checkDuplicateProperties); - if (methods) for (const key in methods) { - const methodHandler = methods[key]; - if (isFunction$2(methodHandler)) ctx[key] = methodHandler.bind(publicThis); - } - if (dataOptions) { - const data = dataOptions.call(publicThis, publicThis); - if (!isObject$1(data)) {} else instance.data = /* @__PURE__ */ reactive(data); - } - shouldCacheAccess = true; - if (computedOptions) for (const key in computedOptions) { - const opt = computedOptions[key]; - const c = computed({ - get: isFunction$2(opt) ? opt.bind(publicThis, publicThis) : isFunction$2(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP, - set: !isFunction$2(opt) && isFunction$2(opt.set) ? opt.set.bind(publicThis) : NOOP - }); - Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => c.value, - set: (v) => c.value = v - }); - } - if (watchOptions) for (const key in watchOptions) createWatcher(watchOptions[key], ctx, publicThis, key); - if (provideOptions) { - const provides = isFunction$2(provideOptions) ? provideOptions.call(publicThis) : provideOptions; - Reflect.ownKeys(provides).forEach((key) => { - provide(key, provides[key]); - }); - } - if (created) callHook(created, instance, "c"); - function registerLifecycleHook(register, hook) { - if (isArray$2(hook)) hook.forEach((_hook) => register(_hook.bind(publicThis))); - else if (hook) register(hook.bind(publicThis)); - } - registerLifecycleHook(onBeforeMount, beforeMount); - registerLifecycleHook(onMounted, mounted); - registerLifecycleHook(onBeforeUpdate, beforeUpdate); - registerLifecycleHook(onUpdated, updated); - registerLifecycleHook(onActivated, activated); - registerLifecycleHook(onDeactivated, deactivated); - registerLifecycleHook(onErrorCaptured, errorCaptured); - registerLifecycleHook(onRenderTracked, renderTracked); - registerLifecycleHook(onRenderTriggered, renderTriggered); - registerLifecycleHook(onBeforeUnmount, beforeUnmount); - registerLifecycleHook(onUnmounted, unmounted); - registerLifecycleHook(onServerPrefetch, serverPrefetch); - if (isArray$2(expose)) { - if (expose.length) { - const exposed = instance.exposed || (instance.exposed = {}); - expose.forEach((key) => { - Object.defineProperty(exposed, key, { - get: () => publicThis[key], - set: (val) => publicThis[key] = val, - enumerable: true - }); - }); - } else if (!instance.exposed) instance.exposed = {}; - } - if (render && instance.render === NOOP) instance.render = render; - if (inheritAttrs != null) instance.inheritAttrs = inheritAttrs; - if (components) instance.components = components; - if (directives) instance.directives = directives; - if (serverPrefetch) markAsyncBoundary(instance); -} -function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) { - if (isArray$2(injectOptions)) injectOptions = normalizeInject(injectOptions); - for (const key in injectOptions) { - const opt = injectOptions[key]; - let injected; - if (isObject$1(opt)) if ("default" in opt) injected = inject(opt.from || key, opt.default, true); - else injected = inject(opt.from || key); - else injected = inject(opt); - if (/* @__PURE__ */ isRef(injected)) Object.defineProperty(ctx, key, { - enumerable: true, - configurable: true, - get: () => injected.value, - set: (v) => injected.value = v - }); - else ctx[key] = injected; - } -} -function callHook(hook, instance, type) { - callWithAsyncErrorHandling(isArray$2(hook) ? hook.map((h) => h.bind(instance.proxy)) : hook.bind(instance.proxy), instance, type); -} -function createWatcher(raw, ctx, publicThis, key) { - let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key]; - if (isString$1(raw)) { - const handler = ctx[raw]; - if (isFunction$2(handler)) watch(getter, handler); - } else if (isFunction$2(raw)) watch(getter, raw.bind(publicThis)); - else if (isObject$1(raw)) if (isArray$2(raw)) raw.forEach((r) => createWatcher(r, ctx, publicThis, key)); - else { - const handler = isFunction$2(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler]; - if (isFunction$2(handler)) watch(getter, handler, raw); - } -} -function resolveMergedOptions(instance) { - const base = instance.type; - const { mixins, extends: extendsOptions } = base; - const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext; - const cached = cache.get(base); - let resolved; - if (cached) resolved = cached; - else if (!globalMixins.length && !mixins && !extendsOptions) resolved = base; - else { - resolved = {}; - if (globalMixins.length) globalMixins.forEach((m) => mergeOptions$1(resolved, m, optionMergeStrategies, true)); - mergeOptions$1(resolved, base, optionMergeStrategies); - } - if (isObject$1(base)) cache.set(base, resolved); - return resolved; -} -function mergeOptions$1(to, from, strats, asMixin = false) { - const { mixins, extends: extendsOptions } = from; - if (extendsOptions) mergeOptions$1(to, extendsOptions, strats, true); - if (mixins) mixins.forEach((m) => mergeOptions$1(to, m, strats, true)); - for (const key in from) if (asMixin && key === "expose") {} else { - const strat = internalOptionMergeStrats[key] || strats && strats[key]; - to[key] = strat ? strat(to[key], from[key]) : from[key]; - } - return to; -} -var internalOptionMergeStrats = { - data: mergeDataFn, - props: mergeEmitsOrPropsOptions, - emits: mergeEmitsOrPropsOptions, - methods: mergeObjectOptions, - computed: mergeObjectOptions, - beforeCreate: mergeAsArray, - created: mergeAsArray, - beforeMount: mergeAsArray, - mounted: mergeAsArray, - beforeUpdate: mergeAsArray, - updated: mergeAsArray, - beforeDestroy: mergeAsArray, - beforeUnmount: mergeAsArray, - destroyed: mergeAsArray, - unmounted: mergeAsArray, - activated: mergeAsArray, - deactivated: mergeAsArray, - errorCaptured: mergeAsArray, - serverPrefetch: mergeAsArray, - components: mergeObjectOptions, - directives: mergeObjectOptions, - watch: mergeWatchOptions, - provide: mergeDataFn, - inject: mergeInject -}; -function mergeDataFn(to, from) { - if (!from) return to; - if (!to) return from; - return function mergedDataFn() { - return extend$1(isFunction$2(to) ? to.call(this, this) : to, isFunction$2(from) ? from.call(this, this) : from); - }; -} -function mergeInject(to, from) { - return mergeObjectOptions(normalizeInject(to), normalizeInject(from)); -} -function normalizeInject(raw) { - if (isArray$2(raw)) { - const res = {}; - for (let i = 0; i < raw.length; i++) res[raw[i]] = raw[i]; - return res; - } - return raw; -} -function mergeAsArray(to, from) { - return to ? [...new Set([].concat(to, from))] : from; -} -function mergeObjectOptions(to, from) { - return to ? extend$1(/* @__PURE__ */ Object.create(null), to, from) : from; -} -function mergeEmitsOrPropsOptions(to, from) { - if (to) { - if (isArray$2(to) && isArray$2(from)) return [.../* @__PURE__ */ new Set([...to, ...from])]; - return extend$1(/* @__PURE__ */ Object.create(null), normalizePropsOrEmits(to), normalizePropsOrEmits(from != null ? from : {})); - } else return from; -} -function mergeWatchOptions(to, from) { - if (!to) return from; - if (!from) return to; - const merged = extend$1(/* @__PURE__ */ Object.create(null), to); - for (const key in from) merged[key] = mergeAsArray(to[key], from[key]); - return merged; -} -function createAppContext() { - return { - app: null, - config: { - isNativeTag: NO, - performance: false, - globalProperties: {}, - optionMergeStrategies: {}, - errorHandler: void 0, - warnHandler: void 0, - compilerOptions: {} - }, - mixins: [], - components: {}, - directives: {}, - provides: /* @__PURE__ */ Object.create(null), - optionsCache: /* @__PURE__ */ new WeakMap(), - propsCache: /* @__PURE__ */ new WeakMap(), - emitsCache: /* @__PURE__ */ new WeakMap() - }; -} -var uid$1 = 0; -function createAppAPI(render, hydrate) { - return function createApp(rootComponent, rootProps = null) { - if (!isFunction$2(rootComponent)) rootComponent = extend$1({}, rootComponent); - if (rootProps != null && !isObject$1(rootProps)) rootProps = null; - const context = createAppContext(); - const installedPlugins = /* @__PURE__ */ new WeakSet(); - const pluginCleanupFns = []; - let isMounted = false; - const app = context.app = { - _uid: uid$1++, - _component: rootComponent, - _props: rootProps, - _container: null, - _context: context, - _instance: null, - version, - get config() { - return context.config; - }, - set config(v) {}, - use(plugin, ...options) { - if (installedPlugins.has(plugin)) {} else if (plugin && isFunction$2(plugin.install)) { - installedPlugins.add(plugin); - plugin.install(app, ...options); - } else if (isFunction$2(plugin)) { - installedPlugins.add(plugin); - plugin(app, ...options); - } - return app; - }, - mixin(mixin) { - if (!context.mixins.includes(mixin)) context.mixins.push(mixin); - return app; - }, - component(name, component) { - if (!component) return context.components[name]; - context.components[name] = component; - return app; - }, - directive(name, directive) { - if (!directive) return context.directives[name]; - context.directives[name] = directive; - return app; - }, - mount(rootContainer, isHydrate, namespace) { - if (!isMounted) { - const vnode = app._ceVNode || createVNode(rootComponent, rootProps); - vnode.appContext = context; - if (namespace === true) namespace = "svg"; - else if (namespace === false) namespace = void 0; - if (isHydrate && hydrate) hydrate(vnode, rootContainer); - else render(vnode, rootContainer, namespace); - isMounted = true; - app._container = rootContainer; - rootContainer.__vue_app__ = app; - return getComponentPublicInstance(vnode.component); - } - }, - onUnmount(cleanupFn) { - pluginCleanupFns.push(cleanupFn); - }, - unmount() { - if (isMounted) { - callWithAsyncErrorHandling(pluginCleanupFns, app._instance, 16); - render(null, app._container); - delete app._container.__vue_app__; - } - }, - provide(key, value) { - context.provides[key] = value; - return app; - }, - runWithContext(fn) { - const lastApp = currentApp; - currentApp = app; - try { - return fn(); - } finally { - currentApp = lastApp; - } - } - }; - return app; - }; -} -var currentApp = null; -var getModelModifiers = (props, modelName) => { - return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${camelize(modelName)}Modifiers`] || props[`${hyphenate(modelName)}Modifiers`]; -}; -function emit(instance, event, ...rawArgs) { - if (instance.isUnmounted) return; - const props = instance.vnode.props || EMPTY_OBJ; - let args = rawArgs; - const isModelListener = event.startsWith("update:"); - const modifiers = isModelListener && getModelModifiers(props, event.slice(7)); - if (modifiers) { - if (modifiers.trim) args = rawArgs.map((a) => isString$1(a) ? a.trim() : a); - if (modifiers.number) args = args.map(looseToNumber); - } - let handlerName; - let handler = props[handlerName = toHandlerKey(event)] || props[handlerName = toHandlerKey(camelize(event))]; - if (!handler && isModelListener) handler = props[handlerName = toHandlerKey(hyphenate(event))]; - if (handler) callWithAsyncErrorHandling(handler, instance, 6, args); - const onceHandler = props[handlerName + `Once`]; - if (onceHandler) { - if (!instance.emitted) instance.emitted = {}; - else if (instance.emitted[handlerName]) return; - instance.emitted[handlerName] = true; - callWithAsyncErrorHandling(onceHandler, instance, 6, args); - } -} -var mixinEmitsCache = /* @__PURE__ */ new WeakMap(); -function normalizeEmitsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinEmitsCache : appContext.emitsCache; - const cached = cache.get(comp); - if (cached !== void 0) return cached; - const raw = comp.emits; - let normalized = {}; - let hasExtends = false; - if (!isFunction$2(comp)) { - const extendEmits = (raw2) => { - const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); - if (normalizedFromExtend) { - hasExtends = true; - extend$1(normalized, normalizedFromExtend); - } - }; - if (!asMixin && appContext.mixins.length) appContext.mixins.forEach(extendEmits); - if (comp.extends) extendEmits(comp.extends); - if (comp.mixins) comp.mixins.forEach(extendEmits); - } - if (!raw && !hasExtends) { - if (isObject$1(comp)) cache.set(comp, null); - return null; - } - if (isArray$2(raw)) raw.forEach((key) => normalized[key] = null); - else extend$1(normalized, raw); - if (isObject$1(comp)) cache.set(comp, normalized); - return normalized; -} -function isEmitListener(options, key) { - if (!options || !isOn(key)) return false; - key = key.slice(2); - key = key === "Once" ? key : key.replace(/Once$/, ""); - return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key); -} -function renderComponentRoot(instance) { - const { type: Component, vnode, proxy, withProxy, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, props, data, setupState, ctx, inheritAttrs } = instance; - const prev = setCurrentRenderingInstance(instance); - let result; - let fallthroughAttrs; - try { - if (vnode.shapeFlag & 4) { - const proxyToUse = withProxy || proxy; - const thisProxy = proxyToUse; - result = normalizeVNode(render.call(thisProxy, proxyToUse, renderCache, props, setupState, data, ctx)); - fallthroughAttrs = attrs; - } else { - const render2 = Component; - result = normalizeVNode(render2.length > 1 ? render2(props, { - attrs, - slots, - emit - }) : render2(props, null)); - fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); - } - } catch (err) { - blockStack.length = 0; - handleError(err, instance, 1); - result = createVNode(Comment); - } - let root = result; - if (fallthroughAttrs && inheritAttrs !== false) { - const keys = Object.keys(fallthroughAttrs); - const { shapeFlag } = root; - if (keys.length) { - if (shapeFlag & 7) { - if (propsOptions && keys.some(isModelListener)) fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions); - root = cloneVNode(root, fallthroughAttrs, false, true); - } - } - } - if (vnode.dirs) { - root = cloneVNode(root, null, false, true); - root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; - } - if (vnode.transition) setTransitionHooks(isTeleport(root.type) ? getInnerChild$1(root) || root : root, vnode.transition); - result = root; - setCurrentRenderingInstance(prev); - return result; -} -function filterSingleRoot(children, recurse = true) { - let singleRoot; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isVNode(child)) { - if (child.type !== Comment || child.children === "v-if") if (singleRoot) return; - else singleRoot = child; - } else return; - } - return singleRoot; -} -var getFunctionalFallthrough = (attrs) => { - let res; - for (const key in attrs) if (key === "class" || key === "style" || isOn(key)) (res || (res = {}))[key] = attrs[key]; - return res; -}; -var filterModelListeners = (attrs, props) => { - const res = {}; - for (const key in attrs) if (!isModelListener(key) || !(key.slice(9) in props)) res[key] = attrs[key]; - return res; -}; -function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - const { props: prevProps, children: prevChildren, component } = prevVNode; - const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; - const emits = component.emitsOptions; - if (nextVNode.dirs || nextVNode.transition) return true; - if (optimized && patchFlag >= 0) { - if (patchFlag & 1024) return true; - if (patchFlag & 16) { - if (!prevProps) return !!nextProps; - return hasPropsChanged(prevProps, nextProps, emits); - } else if (patchFlag & 8) { - const dynamicProps = nextVNode.dynamicProps; - for (let i = 0; i < dynamicProps.length; i++) { - const key = dynamicProps[i]; - if (hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emits, key)) return true; - } - } - } else { - if (prevChildren || nextChildren) { - if (!nextChildren || !nextChildren.$stable) return true; - } - if (prevProps === nextProps) return false; - if (!prevProps) return !!nextProps; - if (!nextProps) return true; - return hasPropsChanged(prevProps, nextProps, emits); - } - return false; -} -function hasPropsChanged(prevProps, nextProps, emitsOptions) { - const nextKeys = Object.keys(nextProps); - if (nextKeys.length !== Object.keys(prevProps).length) return true; - for (let i = 0; i < nextKeys.length; i++) { - const key = nextKeys[i]; - if (!hasOwn(prevProps, key) || hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emitsOptions, key)) return true; - } - return false; -} -function hasPropValueChanged(nextProps, prevProps, key) { - const nextProp = nextProps[key]; - const prevProp = prevProps[key]; - if (key === "style" && isObject$1(nextProp) && isObject$1(prevProp)) return !looseEqual(nextProp, prevProp); - return nextProp !== prevProp; -} -function updateHOCHostEl({ vnode, parent, suspense }, el) { - while (parent) { - const root = parent.subTree; - if (root.suspense && root.suspense.activeBranch === vnode) { - root.suspense.vnode.el = root.el = el; - vnode = root; - } - if (root === vnode) { - (vnode = parent.vnode).el = el; - parent = parent.parent; - } else break; - } - if (suspense && suspense.activeBranch === vnode) suspense.vnode.el = el; -} -var internalObjectProto = {}; -var createInternalObject = () => Object.create(internalObjectProto); -var isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto; -function initProps(instance, rawProps, isStateful, isSSR = false) { - const props = {}; - const attrs = createInternalObject(); - instance.propsDefaults = /* @__PURE__ */ Object.create(null); - setFullProps(instance, rawProps, props, attrs); - for (const key in instance.propsOptions[0]) if (!(key in props)) props[key] = void 0; - if (isStateful) instance.props = isSSR ? props : /* @__PURE__ */ shallowReactive(props); - else if (!instance.type.props) instance.props = attrs; - else instance.props = props; - instance.attrs = attrs; -} -function updateProps(instance, rawProps, rawPrevProps, optimized) { - const { props, attrs, vnode: { patchFlag } } = instance; - const rawCurrentProps = /* @__PURE__ */ toRaw(props); - const [options] = instance.propsOptions; - let hasAttrsChanged = false; - if ((optimized || patchFlag > 0) && !(patchFlag & 16)) { - if (patchFlag & 8) { - const propsToUpdate = instance.vnode.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - let key = propsToUpdate[i]; - if (isEmitListener(instance.emitsOptions, key)) continue; - const value = rawProps[key]; - if (options) if (hasOwn(attrs, key)) { - if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } else { - const camelizedKey = camelize(key); - props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false); - } - else if (value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - } else { - if (setFullProps(instance, rawProps, props, attrs)) hasAttrsChanged = true; - let kebabKey; - for (const key in rawCurrentProps) if (!rawProps || !hasOwn(rawProps, key) && ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey))) if (options) { - if (rawPrevProps && (rawPrevProps[key] !== void 0 || rawPrevProps[kebabKey] !== void 0)) props[key] = resolvePropValue(options, rawCurrentProps, key, void 0, instance, true); - } else delete props[key]; - if (attrs !== rawCurrentProps) { - for (const key in attrs) if (!rawProps || !hasOwn(rawProps, key) && true) { - delete attrs[key]; - hasAttrsChanged = true; - } - } - } - if (hasAttrsChanged) trigger(instance.attrs, "set", ""); -} -function setFullProps(instance, rawProps, props, attrs) { - const [options, needCastKeys] = instance.propsOptions; - let hasAttrsChanged = false; - let rawCastValues; - if (rawProps) for (let key in rawProps) { - if (isReservedProp(key)) continue; - const value = rawProps[key]; - let camelKey; - if (options && hasOwn(options, camelKey = camelize(key))) if (!needCastKeys || !needCastKeys.includes(camelKey)) props[camelKey] = value; - else (rawCastValues || (rawCastValues = {}))[camelKey] = value; - else if (!isEmitListener(instance.emitsOptions, key)) { - if (!(key in attrs) || value !== attrs[key]) { - attrs[key] = value; - hasAttrsChanged = true; - } - } - } - if (needCastKeys) { - const rawCurrentProps = /* @__PURE__ */ toRaw(props); - const castValues = rawCastValues || EMPTY_OBJ; - for (let i = 0; i < needCastKeys.length; i++) { - const key = needCastKeys[i]; - props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key)); - } - } - return hasAttrsChanged; -} -function resolvePropValue(options, props, key, value, instance, isAbsent) { - const opt = options[key]; - if (opt != null) { - const hasDefault = hasOwn(opt, "default"); - if (hasDefault && value === void 0) { - const defaultValue = opt.default; - if (opt.type !== Function && !opt.skipFactory && isFunction$2(defaultValue)) { - const { propsDefaults } = instance; - if (key in propsDefaults) value = propsDefaults[key]; - else { - const reset = setCurrentInstance(instance); - value = propsDefaults[key] = defaultValue.call(null, props); - reset(); - } - } else value = defaultValue; - if (instance.ce) instance.ce._setProp(key, value); - } - if (opt[0]) { - if (isAbsent && !hasDefault) value = false; - else if (opt[1] && (value === "" || value === hyphenate(key))) value = true; - } - } - return value; -} -var mixinPropsCache = /* @__PURE__ */ new WeakMap(); -function normalizePropsOptions(comp, appContext, asMixin = false) { - const cache = asMixin ? mixinPropsCache : appContext.propsCache; - const cached = cache.get(comp); - if (cached) return cached; - const raw = comp.props; - const normalized = {}; - const needCastKeys = []; - let hasExtends = false; - if (!isFunction$2(comp)) { - const extendProps = (raw2) => { - hasExtends = true; - const [props, keys] = normalizePropsOptions(raw2, appContext, true); - extend$1(normalized, props); - if (keys) needCastKeys.push(...keys); - }; - if (!asMixin && appContext.mixins.length) appContext.mixins.forEach(extendProps); - if (comp.extends) extendProps(comp.extends); - if (comp.mixins) comp.mixins.forEach(extendProps); - } - if (!raw && !hasExtends) { - if (isObject$1(comp)) cache.set(comp, EMPTY_ARR); - return EMPTY_ARR; - } - if (isArray$2(raw)) for (let i = 0; i < raw.length; i++) { - const normalizedKey = camelize(raw[i]); - if (validatePropName(normalizedKey)) normalized[normalizedKey] = EMPTY_OBJ; - } - else if (raw) for (const key in raw) { - const normalizedKey = camelize(key); - if (validatePropName(normalizedKey)) { - const opt = raw[key]; - const prop = normalized[normalizedKey] = isArray$2(opt) || isFunction$2(opt) ? { type: opt } : extend$1({}, opt); - const propType = prop.type; - let shouldCast = false; - let shouldCastTrue = true; - if (isArray$2(propType)) for (let index = 0; index < propType.length; ++index) { - const type = propType[index]; - const typeName = isFunction$2(type) && type.name; - if (typeName === "Boolean") { - shouldCast = true; - break; - } else if (typeName === "String") shouldCastTrue = false; - } - else shouldCast = isFunction$2(propType) && propType.name === "Boolean"; - prop[0] = shouldCast; - prop[1] = shouldCastTrue; - if (shouldCast || hasOwn(prop, "default")) needCastKeys.push(normalizedKey); - } - } - const res = [normalized, needCastKeys]; - if (isObject$1(comp)) cache.set(comp, res); - return res; -} -function validatePropName(key) { - if (key[0] !== "$" && !isReservedProp(key)) return true; - return false; -} -var isInternalKey = (key) => key === "_" || key === "_ctx" || key === "$stable"; -var normalizeSlotValue = (value) => isArray$2(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; -var normalizeSlot$1 = (key, rawSlot, ctx) => { - if (rawSlot._n) return rawSlot; - const normalized = withCtx((...args) => { - return normalizeSlotValue(rawSlot(...args)); - }, ctx); - normalized._c = false; - return normalized; -}; -var normalizeObjectSlots = (rawSlots, slots, instance) => { - const ctx = rawSlots._ctx; - for (const key in rawSlots) { - if (isInternalKey(key)) continue; - const value = rawSlots[key]; - if (isFunction$2(value)) slots[key] = normalizeSlot$1(key, value, ctx); - else if (value != null) { - const normalized = normalizeSlotValue(value); - slots[key] = () => normalized; - } - } -}; -var normalizeVNodeSlots = (instance, children) => { - const normalized = normalizeSlotValue(children); - instance.slots.default = () => normalized; -}; -var assignSlots = (slots, children, optimized) => { - for (const key in children) if (optimized || !isInternalKey(key)) slots[key] = children[key]; -}; -var initSlots = (instance, children, optimized) => { - const slots = instance.slots = createInternalObject(); - if (instance.vnode.shapeFlag & 32) { - const type = children._; - if (type) { - assignSlots(slots, children, optimized); - if (optimized) def(slots, "_", type, true); - } else normalizeObjectSlots(children, slots); - } else if (children) normalizeVNodeSlots(instance, children); -}; -var updateSlots = (instance, children, optimized) => { - const { vnode, slots } = instance; - let needDeletionCheck = true; - let deletionComparisonTarget = EMPTY_OBJ; - if (vnode.shapeFlag & 32) { - const type = children._; - if (type) if (optimized && type === 1) needDeletionCheck = false; - else assignSlots(slots, children, optimized); - else { - needDeletionCheck = !children.$stable; - normalizeObjectSlots(children, slots); - } - deletionComparisonTarget = children; - } else if (children) { - normalizeVNodeSlots(instance, children); - deletionComparisonTarget = { default: 1 }; - } - if (needDeletionCheck) { - for (const key in slots) if (!isInternalKey(key) && deletionComparisonTarget[key] == null) delete slots[key]; - } -}; -var queuePostRenderEffect = queueEffectWithSuspense; -function createRenderer(options) { - return baseCreateRenderer(options); -} -function baseCreateRenderer(options, createHydrationFns) { - const target = getGlobalThis(); - target.__VUE__ = true; - const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options; - const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => { - if (n1 === n2) return; - if (n1 && !isSameVNodeType(n1, n2)) { - anchor = getNextHostNode(n1); - unmount(n1, parentComponent, parentSuspense, true); - n1 = null; - } - if (n2.patchFlag === -2) { - optimized = false; - n2.dynamicChildren = null; - } - if (n2.dynamicChildren && n1 && n1.dynamicChildren && n1.dynamicChildren.hasOnce) { - if (n2.dynamicChildren === EMPTY_ARR) n2.dynamicChildren = []; - n2.dynamicChildren.hasOnce = true; - } - const { type, ref, shapeFlag } = n2; - switch (type) { - case Text: - processText(n1, n2, container, anchor); - break; - case Comment: - processCommentNode(n1, n2, container, anchor); - break; - case Static: - if (n1 == null) mountStaticNode(n2, container, anchor, namespace); - break; - case Fragment: - processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - break; - default: if (shapeFlag & 1) processElement(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else if (shapeFlag & 6) processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else if (shapeFlag & 64) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals); - else if (shapeFlag & 128) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals); - } - if (ref != null && parentComponent) setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2); - else if (ref == null && n1 && n1.ref != null) setRef(n1.ref, null, parentSuspense, n1, true); - }; - const processText = (n1, n2, container, anchor) => { - if (n1 == null) hostInsert(n2.el = hostCreateText(n2.children), container, anchor); - else { - const el = n2.el = n1.el; - if (n2.children !== n1.children) hostSetText(el, n2.children); - } - }; - const processCommentNode = (n1, n2, container, anchor) => { - if (n1 == null) hostInsert(n2.el = hostCreateComment(n2.children || ""), container, anchor); - else n2.el = n1.el; - }; - const mountStaticNode = (n2, container, anchor, namespace) => { - [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, namespace, n2.el, n2.anchor); - }; - const moveStaticNode = ({ el, anchor }, container, nextSibling) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostInsert(el, container, nextSibling); - el = next; - } - hostInsert(anchor, container, nextSibling); - }; - const removeStaticNode = ({ el, anchor }) => { - let next; - while (el && el !== anchor) { - next = hostNextSibling(el); - hostRemove(el); - el = next; - } - hostRemove(anchor); - }; - const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - if (n2.type === "svg") namespace = "svg"; - else if (n2.type === "math") namespace = "mathml"; - if (n1 == null) mountElement(n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else { - const customElement = n1.el && n1.el._isVueCE ? n1.el : null; - try { - if (customElement) customElement._beginPatch(); - patchElement(n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - } finally { - if (customElement) customElement._endPatch(); - } - } - }; - const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let el; - let vnodeHook; - const { props, shapeFlag, transition, dirs } = vnode; - el = vnode.el = hostCreateElement(vnode.type, namespace, props && props.is, props); - if (shapeFlag & 8) hostSetElementText(el, vnode.children); - else if (shapeFlag & 16) mountChildren(vnode.children, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(vnode, namespace), slotScopeIds, optimized); - if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "created"); - setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent); - if (props) { - for (const key in props) if (key !== "value" && !isReservedProp(key)) hostPatchProp(el, key, null, props[key], namespace, parentComponent); - if ("value" in props) hostPatchProp(el, "value", null, props.value, namespace); - if (vnodeHook = props.onVnodeBeforeMount) invokeVNodeHook(vnodeHook, parentComponent, vnode); - } - if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); - const needCallTransitionHooks = needTransition(parentSuspense, transition); - if (needCallTransitionHooks) transition.beforeEnter(el); - hostInsert(el, container, anchor); - if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) queuePostRenderEffect(() => { - try { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); - } finally {} - }, parentSuspense); - }; - const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => { - if (scopeId) hostSetScopeId(el, scopeId); - if (slotScopeIds) for (let i = 0; i < slotScopeIds.length; i++) hostSetScopeId(el, slotScopeIds[i]); - if (parentComponent) { - let subTree = parentComponent.subTree; - if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) { - const parentVNode = parentComponent.vnode; - setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent); - } - } - }; - const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => { - for (let i = start; i < children.length; i++) patch(null, children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - }; - const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const el = n2.el = n1.el; - let { patchFlag, dynamicChildren, dirs } = n2; - patchFlag |= n1.patchFlag & 16; - const oldProps = n1.props || EMPTY_OBJ; - const newProps = n2.props || EMPTY_OBJ; - let vnodeHook; - parentComponent && toggleRecurse(parentComponent, false); - if (vnodeHook = newProps.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - if (dirs) invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate"); - parentComponent && toggleRecurse(parentComponent, true); - if (dynamicChildren && (!n1.dynamicChildren || n1.dynamicChildren.length !== dynamicChildren.length)) { - patchFlag = 0; - optimized = false; - dynamicChildren = null; - } - if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) hostSetElementText(el, ""); - if (dynamicChildren) patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds); - else if (!optimized) patchChildren(n1, n2, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds, false); - if (patchFlag > 0) { - if (patchFlag & 16) patchProps(el, oldProps, newProps, parentComponent, namespace); - else { - if (patchFlag & 2) { - if (oldProps.class !== newProps.class) hostPatchProp(el, "class", null, newProps.class, namespace); - } - if (patchFlag & 4) hostPatchProp(el, "style", oldProps.style, newProps.style, namespace); - if (patchFlag & 8) { - const propsToUpdate = n2.dynamicProps; - for (let i = 0; i < propsToUpdate.length; i++) { - const key = propsToUpdate[i]; - const prev = oldProps[key]; - const next = newProps[key]; - if (next !== prev || key === "value") hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - } - } - if (patchFlag & 1) { - if (n1.children !== n2.children) hostSetElementText(el, n2.children); - } - } else if (!optimized && dynamicChildren == null) patchProps(el, oldProps, newProps, parentComponent, namespace); - if ((vnodeHook = newProps.onVnodeUpdated) || dirs) queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1); - dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated"); - }, parentSuspense); - }; - const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => { - for (let i = 0; i < newChildren.length; i++) { - const oldVNode = oldChildren[i]; - const newVNode = newChildren[i]; - const oldEl = oldVNode.el || resolveAsyncComponentPlaceholder(oldVNode); - patch(oldVNode, newVNode, oldEl && (oldVNode.type === Fragment || !isSameVNodeType(oldVNode, newVNode) || oldVNode.shapeFlag & 198) ? hostParentNode(oldEl) : fallbackContainer, null, parentComponent, parentSuspense, namespace, slotScopeIds, true); - } - }; - const patchProps = (el, oldProps, newProps, parentComponent, namespace) => { - if (oldProps !== newProps) { - if (oldProps !== EMPTY_OBJ) { - for (const key in oldProps) if (!isReservedProp(key) && !(key in newProps)) hostPatchProp(el, key, oldProps[key], null, namespace, parentComponent); - } - for (const key in newProps) { - if (isReservedProp(key)) continue; - const next = newProps[key]; - const prev = oldProps[key]; - if (next !== prev && key !== "value") hostPatchProp(el, key, prev, next, namespace, parentComponent); - } - if ("value" in newProps) hostPatchProp(el, "value", oldProps.value, newProps.value, namespace); - } - }; - const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText(""); - const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText(""); - let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2; - if (fragmentSlotScopeIds) slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; - if (n1 == null) { - hostInsert(fragmentStartAnchor, container, anchor); - hostInsert(fragmentEndAnchor, container, anchor); - mountChildren(n2.children || [], container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - } else if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && n1.dynamicChildren && n1.dynamicChildren.length === dynamicChildren.length) { - patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, namespace, slotScopeIds); - if (n2.key != null || parentComponent && n2 === parentComponent.subTree) traverseStaticChildren(n1, n2, true); - } else patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - }; - const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - n2.slotScopeIds = slotScopeIds; - if (n1 == null) if (n2.shapeFlag & 512) parentComponent.ctx.activate(n2, container, anchor, namespace, optimized); - else mountComponent(n2, container, anchor, parentComponent, parentSuspense, namespace, optimized); - else updateComponent(n1, n2, optimized); - }; - const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => { - const instance = initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense); - if (isKeepAlive(initialVNode)) instance.ctx.renderer = internals; - setupComponent(instance, false, optimized); - if (instance.asyncDep) { - parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized, namespace); - if (!initialVNode.el) { - const placeholder = instance.subTree = createVNode(Comment); - processCommentNode(null, placeholder, container, anchor); - initialVNode.placeholder = placeholder.el; - } - } else setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, namespace, optimized); - }; - const updateComponent = (n1, n2, optimized) => { - const instance = n2.component = n1.component; - if (shouldUpdateComponent(n1, n2, optimized)) if (instance.asyncDep && !instance.asyncResolved) { - n2.el = n1.el; - n2.placeholder = n1.placeholder; - updateComponentPreRender(instance, n2, optimized); - return; - } else { - instance.next = n2; - instance.update(); - } - else { - n2.el = n1.el; - n2.placeholder = n1.placeholder; - instance.vnode = n2; - } - }; - const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => { - const componentUpdateFn = () => { - if (!instance.isMounted) { - let vnodeHook; - const { el, props } = initialVNode; - const { bm, m, parent, root, type } = instance; - const isAsyncWrapperVNode = isAsyncWrapper(initialVNode); - toggleRecurse(instance, false); - if (bm) invokeArrayFns(bm); - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) invokeVNodeHook(vnodeHook, parent, initialVNode); - toggleRecurse(instance, true); - if (el && hydrateNode) { - const hydrateSubTree = () => { - instance.subTree = renderComponentRoot(instance); - hydrateNode(el, instance.subTree, instance, parentSuspense, null); - }; - if (isAsyncWrapperVNode && type.__asyncHydrate) type.__asyncHydrate(el, instance, hydrateSubTree); - else hydrateSubTree(); - } else { - if (root.ce && root.ce._hasShadowRoot()) root.ce._injectChildStyle(type, instance.parent ? instance.parent.type : void 0); - const subTree = instance.subTree = renderComponentRoot(instance); - patch(null, subTree, container, anchor, instance, parentSuspense, namespace); - initialVNode.el = subTree.el; - } - if (m) queuePostRenderEffect(m, parentSuspense); - if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) { - const scopedInitialVNode = initialVNode; - queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense); - } - if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) instance.a && queuePostRenderEffect(instance.a, parentSuspense); - instance.isMounted = true; - initialVNode = container = anchor = null; - } else { - let { next, bu, u, parent, vnode } = instance; - { - const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance); - if (nonHydratedAsyncRoot) { - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } - nonHydratedAsyncRoot.asyncDep.then(() => { - queuePostRenderEffect(() => { - if (!instance.isUnmounted) update(); - }, parentSuspense); - }); - return; - } - } - let originNext = next; - let vnodeHook; - toggleRecurse(instance, false); - if (next) { - next.el = vnode.el; - updateComponentPreRender(instance, next, optimized); - } else next = vnode; - if (bu) invokeArrayFns(bu); - if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parent, next, vnode); - toggleRecurse(instance, true); - const nextTree = renderComponentRoot(instance); - const prevTree = instance.subTree; - instance.subTree = nextTree; - patch(prevTree, nextTree, hostParentNode(prevTree.el), getNextHostNode(prevTree), instance, parentSuspense, namespace); - next.el = nextTree.el; - if (originNext === null) updateHOCHostEl(instance, nextTree.el); - if (u) queuePostRenderEffect(u, parentSuspense); - if (vnodeHook = next.props && next.props.onVnodeUpdated) queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense); - } - }; - instance.scope.on(); - const effect = instance.effect = new ReactiveEffect(componentUpdateFn); - instance.scope.off(); - const update = instance.update = effect.run.bind(effect); - const job = instance.job = effect.runIfDirty.bind(effect); - job.i = instance; - job.id = instance.uid; - effect.scheduler = () => queueJob(job); - toggleRecurse(instance, true); - update(); - }; - const updateComponentPreRender = (instance, nextVNode, optimized) => { - nextVNode.component = instance; - const prevProps = instance.vnode.props; - instance.vnode = nextVNode; - instance.next = null; - updateProps(instance, nextVNode.props, prevProps, optimized); - updateSlots(instance, nextVNode.children, optimized); - pauseTracking(); - flushPreFlushCbs(instance); - resetTracking(); - }; - const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => { - const c1 = n1 && n1.children; - const prevShapeFlag = n1 ? n1.shapeFlag : 0; - const c2 = n2.children; - const { patchFlag, shapeFlag } = n2; - if (patchFlag > 0) { - if (patchFlag & 128) { - patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - return; - } else if (patchFlag & 256) { - patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - return; - } - } - if (shapeFlag & 8) { - if (prevShapeFlag & 16) unmountChildren(c1, parentComponent, parentSuspense); - if (c2 !== c1) hostSetElementText(container, c2); - } else if (prevShapeFlag & 16) if (shapeFlag & 16) patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else unmountChildren(c1, parentComponent, parentSuspense, true); - else { - if (prevShapeFlag & 8) hostSetElementText(container, ""); - if (shapeFlag & 16) mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - } - }; - const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - c1 = c1 || EMPTY_ARR; - c2 = c2 || EMPTY_ARR; - const oldLength = c1.length; - const newLength = c2.length; - const commonLength = Math.min(oldLength, newLength); - let i; - for (i = 0; i < commonLength; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - } - if (oldLength > newLength) unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength); - else mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, commonLength); - }; - const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => { - let i = 0; - const l2 = c2.length; - let e1 = c1.length - 1; - let e2 = l2 - 1; - while (i <= e1 && i <= e2) { - const n1 = c1[i]; - const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else break; - i++; - } - while (i <= e1 && i <= e2) { - const n1 = c1[e1]; - const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]); - if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else break; - e1--; - e2--; - } - if (i > e1) { - if (i <= e2) { - const nextPos = e2 + 1; - const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor; - while (i <= e2) { - patch(null, c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - i++; - } - } - } else if (i > e2) while (i <= e1) { - unmount(c1[i], parentComponent, parentSuspense, true); - i++; - } - else { - const s1 = i; - const s2 = i; - const keyToNewIndexMap = /* @__PURE__ */ new Map(); - for (i = s2; i <= e2; i++) { - const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]); - if (nextChild.key != null) keyToNewIndexMap.set(nextChild.key, i); - } - let j; - let patched = 0; - const toBePatched = e2 - s2 + 1; - let moved = false; - let maxNewIndexSoFar = 0; - const newIndexToOldIndexMap = new Array(toBePatched); - for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0; - for (i = s1; i <= e1; i++) { - const prevChild = c1[i]; - if (patched >= toBePatched) { - unmount(prevChild, parentComponent, parentSuspense, true); - continue; - } - let newIndex; - if (prevChild.key != null) newIndex = keyToNewIndexMap.get(prevChild.key); - else for (j = s2; j <= e2; j++) if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) { - newIndex = j; - break; - } - if (newIndex === void 0) unmount(prevChild, parentComponent, parentSuspense, true); - else { - newIndexToOldIndexMap[newIndex - s2] = i + 1; - if (newIndex >= maxNewIndexSoFar) maxNewIndexSoFar = newIndex; - else moved = true; - patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - patched++; - } - } - const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR; - j = increasingNewIndexSequence.length - 1; - for (i = toBePatched - 1; i >= 0; i--) { - const nextIndex = s2 + i; - const nextChild = c2[nextIndex]; - const anchorVNode = c2[nextIndex + 1]; - const anchor = nextIndex + 1 < l2 ? anchorVNode.el || resolveAsyncComponentPlaceholder(anchorVNode) : parentAnchor; - if (newIndexToOldIndexMap[i] === 0) patch(null, nextChild, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized); - else if (moved) if (j < 0 || i !== increasingNewIndexSequence[j]) move(nextChild, container, anchor, 2); - else j--; - } - } - }; - const move = (vnode, container, anchor, moveType, parentSuspense = null) => { - const { el, type, transition, children, shapeFlag } = vnode; - if (shapeFlag & 6) { - move(vnode.component.subTree, container, anchor, moveType); - return; - } - if (shapeFlag & 128) { - vnode.suspense.move(container, anchor, moveType); - return; - } - if (shapeFlag & 64) { - type.move(vnode, container, anchor, internals); - return; - } - if (type === Fragment) { - hostInsert(el, container, anchor); - for (let i = 0; i < children.length; i++) move(children[i], container, anchor, moveType); - hostInsert(vnode.anchor, container, anchor); - return; - } - if (type === Static) { - moveStaticNode(vnode, container, anchor); - return; - } - if (moveType !== 2 && shapeFlag & 1 && transition) if (moveType === 0) if (transition.persisted && !el[leaveCbKey]) hostInsert(el, container, anchor); - else { - transition.beforeEnter(el); - hostInsert(el, container, anchor); - queuePostRenderEffect(() => transition.enter(el), parentSuspense); - } - else { - const { leave, delayLeave, afterLeave } = transition; - const remove2 = () => { - if (vnode.ctx.isUnmounted) hostRemove(el); - else hostInsert(el, container, anchor); - }; - const performLeave = () => { - const wasLeaving = el._isLeaving || !!el[leaveCbKey]; - if (el._isLeaving) el[leaveCbKey](true); - if (transition.persisted && !wasLeaving) remove2(); - else leave(el, () => { - remove2(); - afterLeave && afterLeave(); - }); - }; - if (delayLeave) delayLeave(el, remove2, performLeave); - else performLeave(); - } - else hostInsert(el, container, anchor); - }; - const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => { - const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs, cacheIndex, memo } = vnode; - if (patchFlag === -2 || dynamicChildren && dynamicChildren.hasOnce) optimized = false; - if (ref != null) { - pauseTracking(); - setRef(ref, null, parentSuspense, vnode, true); - resetTracking(); - } - if (cacheIndex != null && (!vnode.ctx || vnode.ctx === parentComponent)) parentComponent.renderCache[cacheIndex] = void 0; - if (shapeFlag & 256) { - parentComponent.ctx.deactivate(vnode); - return; - } - const shouldInvokeDirs = shapeFlag & 1 && dirs; - const shouldInvokeVnodeHook = !isAsyncWrapper(vnode); - let vnodeHook; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) invokeVNodeHook(vnodeHook, parentComponent, vnode); - if (shapeFlag & 6) unmountComponent(vnode.component, parentSuspense, doRemove); - else { - if (shapeFlag & 128) { - vnode.suspense.unmount(parentSuspense, doRemove); - return; - } - if (shouldInvokeDirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount"); - if (shapeFlag & 64) vnode.type.remove(vnode, parentComponent, parentSuspense, internals, doRemove); - else if (dynamicChildren && !dynamicChildren.hasOnce && (type !== Fragment || patchFlag > 0 && patchFlag & 64)) unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true); - else if (type === Fragment && patchFlag & 384 || !optimized && shapeFlag & 16) unmountChildren(children, parentComponent, parentSuspense); - if (doRemove) remove(vnode); - } - const shouldInvalidateMemo = memo != null && cacheIndex == null; - if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs || shouldInvalidateMemo) queuePostRenderEffect(() => { - vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode); - shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted"); - if (shouldInvalidateMemo) vnode.el = null; - }, parentSuspense); - }; - const remove = (vnode) => { - const { type, el, anchor, transition } = vnode; - const isFragment = type === Fragment; - if (isFragment && !transition) { - removeFragment(el, anchor); - return; - } - if (type === Static) { - removeStaticNode(vnode); - if (transition && !transition.persisted && transition.afterLeave) transition.afterLeave(); - return; - } - const leavingNode = isFragment ? getTransitionRoot(vnode) : vnode; - const performRemove = () => { - if (isFragment) { - if (hostParentNode(el)) removeFragment(el, anchor); - } else hostRemove(el); - if (transition && !transition.persisted && transition.afterLeave) transition.afterLeave(); - }; - if (leavingNode && leavingNode.shapeFlag & 1 && transition && !transition.persisted) { - const { leave, delayLeave } = transition; - const leavingEl = leavingNode.el; - const performLeave = () => leave(leavingEl, performRemove); - if (delayLeave) delayLeave(leavingEl, performRemove, performLeave); - else performLeave(); - } else performRemove(); - }; - const removeFragment = (cur, end) => { - let next; - while (cur !== end) { - next = hostNextSibling(cur); - hostRemove(cur); - cur = next; - } - hostRemove(end); - }; - const unmountComponent = (instance, parentSuspense, doRemove) => { - const { bum, scope, job, subTree, um, m, a } = instance; - invalidateMount(m); - invalidateMount(a); - if (bum) invokeArrayFns(bum); - scope.stop(); - if (job) { - job.flags |= 8; - unmount(subTree, instance, parentSuspense, doRemove); - } else if (instance.vnode.el && subTree) { - subTree.transition = instance.vnode.transition; - unmount(subTree, instance, parentSuspense, doRemove); - } - if (um) queuePostRenderEffect(um, parentSuspense); - queuePostRenderEffect(() => { - instance.isUnmounted = true; - }, parentSuspense); - }; - const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => { - for (let i = start; i < children.length; i++) unmount(children[i], parentComponent, parentSuspense, doRemove, optimized); - }; - const getNextHostNode = (vnode) => { - if (vnode.shapeFlag & 6) return getNextHostNode(vnode.component.subTree); - if (vnode.shapeFlag & 128) return vnode.suspense.next(); - const el = hostNextSibling(vnode.anchor || vnode.el); - const teleportEnd = el && el[TeleportEndKey]; - return teleportEnd ? hostNextSibling(teleportEnd) : el; - }; - const render = (vnode, container, namespace) => { - flushOnAppMount(() => { - if (vnode == null) { - if (container._vnode) unmount(container._vnode, null, null, true); - } else patch(container._vnode || null, vnode, container, null, null, null, namespace); - container._vnode = vnode; - }, vnode && container._vnode ? void 0 : vnode && vnode.component ? vnode.component.uid : getNextUid()); - }; - const internals = { - p: patch, - um: unmount, - m: move, - r: remove, - mt: mountComponent, - mc: mountChildren, - pc: patchChildren, - pbc: patchBlockChildren, - n: getNextHostNode, - o: options - }; - let hydrate; - let hydrateNode; - if (createHydrationFns) [hydrate, hydrateNode] = createHydrationFns(internals); - return { - render, - hydrate, - createApp: createAppAPI(render, hydrate) - }; -} -function resolveChildrenNamespace({ type, props }, currentNamespace) { - return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace; -} -function toggleRecurse({ effect, job }, allowed) { - if (allowed) { - effect.flags |= 32; - job.flags |= 4; - } else { - effect.flags &= -33; - job.flags &= -5; - } -} -function needTransition(parentSuspense, transition) { - return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted; -} -function traverseStaticChildren(n1, n2, shallow = false) { - const ch1 = n1.children; - const ch2 = n2.children; - if (isArray$2(ch1) && isArray$2(ch2)) for (let i = 0; i < ch1.length; i++) { - const c1 = ch1[i]; - let c2 = ch2[i]; - if (c2.shapeFlag & 1 && !c2.dynamicChildren) { - if (c2.patchFlag <= 0 || c2.patchFlag === 32) { - c2 = ch2[i] = cloneIfMounted(ch2[i]); - c2.el = c1.el; - } - if (!shallow && c2.patchFlag !== -2) traverseStaticChildren(c1, c2); - } - if (c2.type === Text) { - if (c2.patchFlag === -1) c2 = ch2[i] = cloneIfMounted(c2); - c2.el = c1.el; - } - if (c2.type === Comment && !c2.el) c2.el = c1.el; - } -} -function getSequence(arr) { - const p = arr.slice(); - const result = [0]; - let i, j, u, v, c; - const len = arr.length; - for (i = 0; i < len; i++) { - const arrI = arr[i]; - if (arrI !== 0) { - j = result[result.length - 1]; - if (arr[j] < arrI) { - p[i] = j; - result.push(i); - continue; - } - u = 0; - v = result.length - 1; - while (u < v) { - c = u + v >> 1; - if (arr[result[c]] < arrI) u = c + 1; - else v = c; - } - if (arrI < arr[result[u]]) { - if (u > 0) p[i] = result[u - 1]; - result[u] = i; - } - } - } - u = result.length; - v = result[u - 1]; - while (u-- > 0) { - result[u] = v; - v = p[v]; - } - return result; -} -function locateNonHydratedAsyncRoot(instance) { - const subComponent = instance.subTree.component; - if (subComponent) if (subComponent.asyncDep && !subComponent.asyncResolved) return subComponent; - else return locateNonHydratedAsyncRoot(subComponent); -} -function invalidateMount(hooks) { - if (hooks) for (let i = 0; i < hooks.length; i++) hooks[i].flags |= 8; -} -function resolveAsyncComponentPlaceholder(anchorVnode) { - if (anchorVnode.placeholder) return anchorVnode.placeholder; - const instance = anchorVnode.component; - if (instance) return resolveAsyncComponentPlaceholder(instance.subTree); - return null; -} -var isSuspense = (type) => type.__isSuspense; -function queueEffectWithSuspense(fn, suspense) { - if (suspense && suspense.pendingBranch) if (isArray$2(fn)) suspense.effects.push(...fn); - else suspense.effects.push(fn); - else queuePostFlushCb(fn); -} -var Fragment = /* @__PURE__ */ Symbol.for("v-fgt"); -var Text = /* @__PURE__ */ Symbol.for("v-txt"); -var Comment = /* @__PURE__ */ Symbol.for("v-cmt"); -var Static = /* @__PURE__ */ Symbol.for("v-stc"); -var blockStack = []; -var currentBlock = null; -function openBlock(disableTracking = false) { - blockStack.push(currentBlock = disableTracking ? null : []); -} -function closeBlock() { - blockStack.pop(); - currentBlock = blockStack[blockStack.length - 1] || null; -} -var isBlockTreeEnabled = 1; -function setBlockTracking(value, inVOnce = false) { - isBlockTreeEnabled += value; - if (value < 0 && currentBlock && inVOnce) currentBlock.hasOnce = true; -} -function setupBlock(vnode) { - vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null; - closeBlock(); - if (isBlockTreeEnabled > 0 && currentBlock) currentBlock.push(vnode); - return vnode; -} -function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) { - return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true)); -} -function createBlock(type, props, children, patchFlag, dynamicProps) { - return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true)); -} -function isVNode(value) { - return value ? value.__v_isVNode === true : false; -} -function isSameVNodeType(n1, n2) { - return n1.type === n2.type && n1.key === n2.key; -} -var normalizeKey = ({ key }) => key != null ? key : null; -var normalizeRef = ({ ref, ref_key, ref_for }) => { - if (typeof ref === "number") ref = "" + ref; - return ref != null ? isString$1(ref) || /* @__PURE__ */ isRef(ref) || isFunction$2(ref) ? { - i: currentRenderingInstance, - r: ref, - k: ref_key, - f: !!ref_for - } : ref : null; -}; -function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) { - const vnode = { - __v_isVNode: true, - __v_skip: true, - type, - props, - key: props && normalizeKey(props), - ref: props && normalizeRef(props), - scopeId: currentScopeId, - slotScopeIds: null, - children, - component: null, - suspense: null, - ssContent: null, - ssFallback: null, - dirs: null, - transition: null, - el: null, - anchor: null, - target: null, - targetStart: null, - targetAnchor: null, - staticCount: 0, - shapeFlag, - patchFlag, - dynamicProps, - dynamicChildren: null, - appContext: null, - ctx: currentRenderingInstance - }; - if (needFullChildrenNormalization) { - normalizeChildren(vnode, children); - if (shapeFlag & 128) type.normalize(vnode); - } else if (children) vnode.shapeFlag |= isString$1(children) ? 8 : 16; - if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock && (vnode.patchFlag > 0 || shapeFlag & 6) && vnode.patchFlag !== 32) currentBlock.push(vnode); - return vnode; -} -var createVNode = _createVNode; -function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) { - if (!type || type === NULL_DYNAMIC_COMPONENT) type = Comment; - if (isVNode(type)) { - const cloned = cloneVNode(type, props, true); - if (children) normalizeChildren(cloned, children); - if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) if (cloned.shapeFlag & 6) currentBlock[currentBlock.indexOf(type)] = cloned; - else currentBlock.push(cloned); - cloned.patchFlag = -2; - return cloned; - } - if (isClassComponent(type)) type = type.__vccOpts; - if (props) { - props = guardReactiveProps(props); - let { class: klass, style } = props; - if (klass && !isString$1(klass)) props.class = normalizeClass(klass); - if (isObject$1(style)) { - if (/* @__PURE__ */ isProxy(style) && !isArray$2(style)) style = extend$1({}, style); - props.style = normalizeStyle(style); - } - } - const shapeFlag = isString$1(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject$1(type) ? 4 : isFunction$2(type) ? 2 : 0; - return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true); -} -function guardReactiveProps(props) { - if (!props) return null; - return /* @__PURE__ */ isProxy(props) || isInternalObject(props) ? extend$1({}, props) : props; -} -function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) { - const { props, ref, patchFlag, children, transition } = vnode; - const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props; - const cloned = { - __v_isVNode: true, - __v_skip: true, - type: vnode.type, - props: mergedProps, - key: mergedProps && normalizeKey(mergedProps), - ref: extraProps && extraProps.ref ? mergeRef && ref ? isArray$2(ref) ? ref.concat(normalizeRef(extraProps)) : [ref, normalizeRef(extraProps)] : normalizeRef(extraProps) : ref, - scopeId: vnode.scopeId, - slotScopeIds: vnode.slotScopeIds, - children, - target: vnode.target, - targetStart: vnode.targetStart, - targetAnchor: vnode.targetAnchor, - staticCount: vnode.staticCount, - shapeFlag: vnode.shapeFlag, - patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag, - dynamicProps: vnode.dynamicProps, - dynamicChildren: vnode.dynamicChildren, - appContext: vnode.appContext, - dirs: vnode.dirs, - transition, - component: vnode.component, - suspense: vnode.suspense, - ssContent: vnode.ssContent && cloneVNode(vnode.ssContent), - ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback), - placeholder: vnode.placeholder, - el: vnode.el, - anchor: vnode.anchor, - ctx: vnode.ctx, - ce: vnode.ce, - cacheIndex: vnode.cacheIndex - }; - if (transition && cloneTransition) setTransitionHooks(cloned, transition.clone(cloned)); - return cloned; -} -function createTextVNode(text = " ", flag = 0) { - return createVNode(Text, null, text, flag); -} -function createCommentVNode(text = "", asBlock = false) { - return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text); -} -function normalizeVNode(child) { - if (child == null || typeof child === "boolean") return createVNode(Comment); - else if (isArray$2(child)) return createVNode(Fragment, null, child.slice()); - else if (isVNode(child)) return cloneIfMounted(child); - else return createVNode(Text, null, String(child)); -} -function cloneIfMounted(child) { - return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child); -} -function normalizeChildren(vnode, children) { - let type = 0; - const { shapeFlag } = vnode; - if (children == null) children = null; - else if (isArray$2(children)) type = 16; - else if (typeof children === "object") if (shapeFlag & 65) { - const slot = children.default; - if (slot) { - slot._c && (slot._d = false); - normalizeChildren(vnode, slot()); - slot._c && (slot._d = true); - } - return; - } else { - type = 32; - const slotFlag = children._; - if (!slotFlag && !isInternalObject(children)) children._ctx = currentRenderingInstance; - else if (slotFlag === 3 && currentRenderingInstance) if (currentRenderingInstance.slots._ === 1) children._ = 1; - else { - children._ = 2; - vnode.patchFlag |= 1024; - } - } - else if (isFunction$2(children)) { - if (shapeFlag & 65) { - normalizeChildren(vnode, { default: children }); - return; - } - children = { - default: children, - _ctx: currentRenderingInstance - }; - type = 32; - } else { - children = String(children); - if (shapeFlag & 64) { - type = 16; - children = [createTextVNode(children)]; - } else type = 8; - } - vnode.children = children; - vnode.shapeFlag |= type; -} -function mergeProps(...args) { - const ret = {}; - for (let i = 0; i < args.length; i++) { - const toMerge = args[i]; - for (const key in toMerge) if (key === "class") { - if (ret.class !== toMerge.class) ret.class = normalizeClass([ret.class, toMerge.class]); - } else if (key === "style") ret.style = normalizeStyle([ret.style, toMerge.style]); - else if (isOn(key)) { - const existing = ret[key]; - const incoming = toMerge[key]; - if (incoming && existing !== incoming && !(isArray$2(existing) && existing.includes(incoming))) ret[key] = existing ? [].concat(existing, incoming) : incoming; - else if (incoming == null && existing == null && !isModelListener(key)) ret[key] = incoming; - } else if (key !== "") ret[key] = toMerge[key]; - } - return ret; -} -function invokeVNodeHook(hook, instance, vnode, prevVNode = null) { - callWithAsyncErrorHandling(hook, instance, 7, [vnode, prevVNode]); -} -var emptyAppContext = createAppContext(); -var uid = 0; -function getNextUid() { - return uid; -} -function createComponentInstance(vnode, parent, suspense) { - const type = vnode.type; - const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext; - const instance = { - uid: uid++, - vnode, - type, - parent, - appContext, - root: null, - next: null, - subTree: null, - effect: null, - update: null, - job: null, - scope: new EffectScope(true), - render: null, - proxy: null, - exposed: null, - exposeProxy: null, - withProxy: null, - provides: parent ? parent.provides : Object.create(appContext.provides), - ids: parent ? parent.ids : [ - "", - 0, - 0 - ], - accessCache: null, - renderCache: [], - components: null, - directives: null, - propsOptions: normalizePropsOptions(type, appContext), - emitsOptions: normalizeEmitsOptions(type, appContext), - emit: null, - emitted: null, - propsDefaults: EMPTY_OBJ, - inheritAttrs: type.inheritAttrs, - ctx: EMPTY_OBJ, - data: EMPTY_OBJ, - props: EMPTY_OBJ, - attrs: EMPTY_OBJ, - slots: EMPTY_OBJ, - refs: EMPTY_OBJ, - setupState: EMPTY_OBJ, - setupContext: null, - suspense, - suspenseId: suspense ? suspense.pendingId : 0, - asyncDep: null, - asyncResolved: false, - isMounted: false, - isUnmounted: false, - isDeactivated: false, - bc: null, - c: null, - bm: null, - m: null, - bu: null, - u: null, - um: null, - bum: null, - da: null, - a: null, - rtg: null, - rtc: null, - ec: null, - sp: null - }; - instance.ctx = { _: instance }; - instance.root = parent ? parent.root : instance; - instance.emit = emit.bind(null, instance); - if (vnode.ce) vnode.ce(instance); - return instance; -} -var currentInstance = null; -var getCurrentInstance = () => currentInstance || currentRenderingInstance; -var internalSetCurrentInstance; -var setInSSRSetupState; -{ - const g = getGlobalThis(); - const registerGlobalSetter = (key, setter) => { - let setters; - if (!(setters = g[key])) setters = g[key] = []; - setters.push(setter); - return (v) => { - if (setters.length > 1) setters.forEach((set) => set(v)); - else setters[0](v); - }; - }; - internalSetCurrentInstance = registerGlobalSetter(`__VUE_INSTANCE_SETTERS__`, (v) => currentInstance = v); - setInSSRSetupState = registerGlobalSetter(`__VUE_SSR_SETTERS__`, (v) => isInSSRComponentSetup = v); -} -var setCurrentInstance = (instance) => { - const prev = currentInstance; - internalSetCurrentInstance(instance); - instance.scope.on(); - return () => { - instance.scope.off(); - internalSetCurrentInstance(prev); - }; -}; -var unsetCurrentInstance = () => { - currentInstance && currentInstance.scope.off(); - internalSetCurrentInstance(null); -}; -function isStatefulComponent(instance) { - return instance.vnode.shapeFlag & 4; -} -var isInSSRComponentSetup = false; -function setupComponent(instance, isSSR = false, optimized = false) { - isSSR && setInSSRSetupState(isSSR); - const { props, children } = instance.vnode; - const isStateful = isStatefulComponent(instance); - initProps(instance, props, isStateful, isSSR); - initSlots(instance, children, optimized || isSSR); - const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0; - isSSR && setInSSRSetupState(false); - return setupResult; -} -function setupStatefulComponent(instance, isSSR) { - const Component = instance.type; - instance.accessCache = /* @__PURE__ */ Object.create(null); - instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers); - const { setup } = Component; - if (setup) { - pauseTracking(); - const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null; - const reset = setCurrentInstance(instance); - const setupResult = callWithErrorHandling(setup, instance, 0, [instance.props, setupContext]); - const isAsyncSetup = isPromise(setupResult); - resetTracking(); - reset(); - if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) markAsyncBoundary(instance); - if (isAsyncSetup) { - setupResult.then(unsetCurrentInstance, unsetCurrentInstance); - if (isSSR) return setupResult.then((resolvedResult) => { - setInSSRSetupState(true); - try { - handleSetupResult(instance, resolvedResult, isSSR); - } finally { - setInSSRSetupState(false); - } - }).catch((e) => { - handleError(e, instance, 0); - }); - else instance.asyncDep = setupResult; - } else handleSetupResult(instance, setupResult, isSSR); - } else finishComponentSetup(instance, isSSR); -} -function handleSetupResult(instance, setupResult, isSSR) { - if (isFunction$2(setupResult)) if (instance.type.__ssrInlineRender) instance.ssrRender = setupResult; - else instance.render = setupResult; - else if (isObject$1(setupResult)) instance.setupState = proxyRefs(setupResult); - finishComponentSetup(instance, isSSR); -} -var compile; -var installWithProxy; -function finishComponentSetup(instance, isSSR, skipOptions) { - const Component = instance.type; - if (!instance.render) { - if (!isSSR && compile && !Component.render) { - const template = Component.template || resolveMergedOptions(instance).template; - if (template) { - const { isCustomElement, compilerOptions } = instance.appContext.config; - const { delimiters, compilerOptions: componentCompilerOptions } = Component; - Component.render = compile(template, extend$1(extend$1({ - isCustomElement, - delimiters - }, compilerOptions), componentCompilerOptions)); - } - } - instance.render = Component.render || NOOP; - if (installWithProxy) installWithProxy(instance); - } - { - const reset = setCurrentInstance(instance); - pauseTracking(); - try { - applyOptions(instance); - } finally { - resetTracking(); - reset(); - } - } -} -var attrsProxyHandlers = { get(target, key) { - track(target, "get", ""); - return target[key]; -} }; -function createSetupContext(instance) { - const expose = (exposed) => { - instance.exposed = exposed || {}; - }; - return { - attrs: new Proxy(instance.attrs, attrsProxyHandlers), - slots: instance.slots, - emit: instance.emit, - expose - }; -} -function getComponentPublicInstance(instance) { - if (instance.exposed) return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), { - get(target, key) { - if (key in target) return target[key]; - else if (key in publicPropertiesMap) return publicPropertiesMap[key](instance); - }, - has(target, key) { - return key in target || key in publicPropertiesMap; - } - })); - else return instance.proxy; -} -function getComponentName(Component, includeInferred = true) { - return isFunction$2(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name; -} -function isClassComponent(value) { - return isFunction$2(value) && "__vccOpts" in value; -} -var computed = (getterOrOptions, debugOptions) => { - return /* @__PURE__ */ computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup); -}; -function h(type, propsOrChildren, children) { - try { - setBlockTracking(-1); - const l = arguments.length; - if (l === 2) if (isObject$1(propsOrChildren) && !isArray$2(propsOrChildren)) { - if (isVNode(propsOrChildren)) return createVNode(type, null, [propsOrChildren]); - return createVNode(type, propsOrChildren); - } else return createVNode(type, null, propsOrChildren); - else { - if (l > 3) children = Array.prototype.slice.call(arguments, 2); - else if (l === 3 && isVNode(children)) children = [children]; - return createVNode(type, propsOrChildren, children); - } - } finally { - setBlockTracking(1); - } -} -var version = "3.5.44"; -//#endregion -//#region node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js -/** -* @vue/runtime-dom v3.5.44 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/ -var policy = void 0; -var tt = typeof window !== "undefined" && window.trustedTypes; -if (tt) try { - policy = /* @__PURE__ */ tt.createPolicy("vue", { createHTML: (val) => val }); -} catch (e) {} -var unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val; -var svgNS = "http://www.w3.org/2000/svg"; -var mathmlNS = "http://www.w3.org/1998/Math/MathML"; -var doc = typeof document !== "undefined" ? document : null; -var templateContainer = doc && /* @__PURE__ */ doc.createElement("template"); -var nodeOps = { - insert: (child, parent, anchor) => { - parent.insertBefore(child, anchor || null); - }, - remove: (child) => { - const parent = child.parentNode; - if (parent) parent.removeChild(child); - }, - createElement: (tag, namespace, is, props) => { - const el = namespace === "svg" ? doc.createElementNS(svgNS, tag) : namespace === "mathml" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag); - if (tag === "select" && props && props.multiple != null) el.setAttribute("multiple", props.multiple); - return el; - }, - createText: (text) => doc.createTextNode(text), - createComment: (text) => doc.createComment(text), - setText: (node, text) => { - node.nodeValue = text; - }, - setElementText: (el, text) => { - el.textContent = text; - }, - parentNode: (node) => node.parentNode, - nextSibling: (node) => node.nextSibling, - querySelector: (selector) => doc.querySelector(selector), - setScopeId(el, id) { - el.setAttribute(id, ""); - }, - insertStaticContent(content, parent, anchor, namespace, start, end) { - const before = anchor ? anchor.previousSibling : parent.lastChild; - if (start && (start === end || start.nextSibling)) while (true) { - parent.insertBefore(start.cloneNode(true), anchor); - if (start === end || !(start = start.nextSibling)) break; - } - else { - templateContainer.innerHTML = unsafeToTrustedHTML(namespace === "svg" ? `${content}` : namespace === "mathml" ? `${content}` : content); - const template = templateContainer.content; - if (namespace === "svg" || namespace === "mathml") { - const wrapper = template.firstChild; - while (wrapper.firstChild) template.appendChild(wrapper.firstChild); - template.removeChild(wrapper); - } - parent.insertBefore(template, anchor); - } - return [before ? before.nextSibling : parent.firstChild, anchor ? anchor.previousSibling : parent.lastChild]; - } -}; -var vtcKey = /* @__PURE__ */ Symbol("_vtc"); -function patchClass(el, value, isSVG) { - const transitionClasses = el[vtcKey]; - if (transitionClasses) value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" "); - if (value == null) el.removeAttribute("class"); - else if (isSVG) el.setAttribute("class", value); - else el.className = value; -} -var vShowOriginalDisplay = /* @__PURE__ */ Symbol("_vod"); -var vShowHidden = /* @__PURE__ */ Symbol("_vsh"); -var CSS_VAR_TEXT = /* @__PURE__ */ Symbol(""); -var displayRE = /(?:^|;)\s*display\s*:/; -function patchStyle(el, prev, next) { - const style = el.style; - const isCssString = isString$1(next); - let hasControlledDisplay = false; - if (next && !isCssString) { - if (prev) if (!isString$1(prev)) { - for (const key in prev) if (next[key] == null) setStyle(style, key, ""); - } else for (const prevStyle of prev.split(";")) { - const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim(); - if (next[key] == null) setStyle(style, key, ""); - } - for (const key in next) { - if (key === "display") hasControlledDisplay = true; - const value = next[key]; - if (value != null) { - if (!shouldPreserveTextareaResizeStyle(el, key, !isString$1(prev) && prev ? prev[key] : void 0, value)) setStyle(style, key, value); - } else setStyle(style, key, ""); - } - } else if (isCssString) { - if (prev !== next) { - const cssVarText = style[CSS_VAR_TEXT]; - if (cssVarText) next += ";" + cssVarText; - style.cssText = next; - hasControlledDisplay = displayRE.test(next); - } - } else if (prev) el.removeAttribute("style"); - if (vShowOriginalDisplay in el) { - if (!isCssString || prev !== next) el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : ""; - if (el[vShowHidden]) style.display = "none"; - } -} -var importantRE = /\s*!important$/; -function setStyle(style, name, val) { - if (isArray$2(val)) val.forEach((v) => setStyle(style, name, v)); - else { - if (val == null) val = ""; - if (name.startsWith("--")) if (importantRE.test(val)) style.setProperty(name, val.replace(importantRE, ""), "important"); - else style.setProperty(name, val); - else { - const prefixed = autoPrefix(style, name); - if (importantRE.test(val)) style.setProperty(hyphenate(prefixed), val.replace(importantRE, ""), "important"); - else style[prefixed] = val; - } - } -} -var prefixes = [ - "Webkit", - "Moz", - "ms" -]; -var prefixCache = {}; -function autoPrefix(style, rawName) { - const cached = prefixCache[rawName]; - if (cached) return cached; - let name = camelize(rawName); - if (name !== "filter" && name in style) return prefixCache[rawName] = name; - name = capitalize(name); - for (let i = 0; i < prefixes.length; i++) { - const prefixed = prefixes[i] + name; - if (prefixed in style) return prefixCache[rawName] = prefixed; - } - return rawName; -} -function shouldPreserveTextareaResizeStyle(el, key, prev, next) { - return el.tagName === "TEXTAREA" && (key === "width" || key === "height") && isString$1(next) && prev === next; -} -var xlinkNS = "http://www.w3.org/1999/xlink"; -function patchAttr(el, key, value, isSVG, instance, isBoolean = isSpecialBooleanAttr(key)) { - if (isSVG && key.startsWith("xlink:")) if (value == null) el.removeAttributeNS(xlinkNS, key.slice(6, key.length)); - else el.setAttributeNS(xlinkNS, key, value); - else if (value == null || isBoolean && !includeBooleanAttr(value)) el.removeAttribute(key); - else el.setAttribute(key, isBoolean ? "" : isSymbol(value) ? String(value) : value); -} -function patchDOMProp(el, key, value, parentComponent, attrName) { - if (key === "innerHTML" || key === "textContent") { - if (value != null) el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value; - return; - } - const tag = el.tagName; - if (key === "value" && tag !== "PROGRESS" && !tag.includes("-")) { - const oldValue = tag === "OPTION" ? el.getAttribute("value") || "" : el.value; - const newValue = value == null ? el.type === "checkbox" ? "on" : "" : String(value); - if (oldValue !== newValue || !("_value" in el)) el.value = newValue; - if (value == null) el.removeAttribute(key); - el._value = value; - return; - } - let needRemove = false; - if (value === "" || value == null) { - const type = typeof el[key]; - if (type === "boolean") value = includeBooleanAttr(value); - else if (value == null && type === "string") { - value = ""; - needRemove = true; - } else if (type === "number") { - value = 0; - needRemove = true; - } - } - try { - el[key] = value; - } catch (e) {} - needRemove && el.removeAttribute(attrName || key); -} -function addEventListener(el, event, handler, options) { - el.addEventListener(event, handler, options); -} -function removeEventListener(el, event, handler, options) { - el.removeEventListener(event, handler, options); -} -var veiKey = /* @__PURE__ */ Symbol("_vei"); -function patchEvent(el, rawName, prevValue, nextValue, instance = null) { - const invokers = el[veiKey] || (el[veiKey] = {}); - const existingInvoker = invokers[rawName]; - if (nextValue && existingInvoker) existingInvoker.value = nextValue; - else { - const [name, options] = parseName(rawName); - if (nextValue) addEventListener(el, name, invokers[rawName] = createInvoker(nextValue, instance), options); - else if (existingInvoker) { - removeEventListener(el, name, existingInvoker, options); - invokers[rawName] = void 0; - } - } -} -var optionsModifierRE = /(Once|Passive|Capture)$/; -var optionsModifierEventRE = /^on:?(?:Once|Passive|Capture)$/; -function parseName(name) { - let options; - let m; - while ((m = name.match(optionsModifierRE)) && !optionsModifierEventRE.test(name)) { - if (!options) options = {}; - name = name.slice(0, name.length - m[1].length); - options[m[1].toLowerCase()] = true; - } - return [name[2] === ":" ? name.slice(3) : hyphenate(name.slice(2)), options]; -} -var cachedNow = 0; -var p = /* @__PURE__ */ Promise.resolve(); -var getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now()); -function createInvoker(initialValue, instance) { - const invoker = (e) => { - if (!e._vts) e._vts = Date.now(); - else if (e._vts <= invoker.attached) return; - const value = invoker.value; - if (isArray$2(value)) { - const originalStop = e.stopImmediatePropagation; - e.stopImmediatePropagation = () => { - originalStop.call(e); - e._stopped = true; - }; - const handlers = value.slice(); - const args = [e]; - for (let i = 0; i < handlers.length; i++) { - if (e._stopped) break; - const handler = handlers[i]; - if (handler) callWithAsyncErrorHandling(handler, instance, 5, args); - } - } else callWithAsyncErrorHandling(value, instance, 5, [e]); - }; - invoker.value = initialValue; - invoker.attached = getNow(); - return invoker; -} -var isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123; -var patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => { - const isSVG = namespace === "svg"; - if (key === "class") patchClass(el, nextValue, isSVG); - else if (key === "style") patchStyle(el, prevValue, nextValue); - else if (isOn(key)) { - if (!isModelListener(key)) patchEvent(el, key, prevValue, nextValue, parentComponent); - } else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) { - patchDOMProp(el, key, nextValue); - if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value"); - } else if (el._isVueCE && (shouldSetAsPropForVueCE(el, key) || el._def.__asyncLoader && (/[A-Z]/.test(key) || !isString$1(nextValue)))) patchDOMProp(el, camelize(key), nextValue, parentComponent, key); - else { - if (key === "true-value") el._trueValue = nextValue; - else if (key === "false-value") el._falseValue = nextValue; - patchAttr(el, key, nextValue, isSVG); - } -}; -function shouldSetAsProp(el, key, value, isSVG) { - if (isSVG) { - if (key === "innerHTML" || key === "textContent") return true; - if (key in el && isNativeOn(key) && isFunction$2(value)) return true; - return false; - } - if (key === "spellcheck" || key === "draggable" || key === "translate" || key === "autocorrect") return false; - if (key === "sandbox" && el.tagName === "IFRAME") return false; - if (key === "form") return false; - if (key === "list" && el.tagName === "INPUT") return false; - if (key === "type" && el.tagName === "TEXTAREA") return false; - if (key === "width" || key === "height") { - const tag = el.tagName; - if (tag === "IMG" || tag === "VIDEO" || tag === "CANVAS" || tag === "SOURCE") return false; - } - if (isNativeOn(key) && isString$1(value)) return false; - return key in el; -} -function shouldSetAsPropForVueCE(el, key) { - const props = el._def.props; - if (!props) return false; - const camelKey = camelize(key); - return Array.isArray(props) ? props.some((prop) => camelize(prop) === camelKey) : Object.keys(props).some((prop) => camelize(prop) === camelKey); -} -var getModelAssigner = (vnode) => { - const fn = vnode.props["onUpdate:modelValue"] || false; - return isArray$2(fn) ? (value) => invokeArrayFns(fn, value) : fn; -}; -function onCompositionStart(e) { - e.target.composing = true; -} -function onCompositionEnd(e) { - const target = e.target; - if (target.composing) { - target.composing = false; - target.dispatchEvent(new Event("input")); - } -} -var assignKey = /* @__PURE__ */ Symbol("_assign"); -var initialValueKey = /* @__PURE__ */ Symbol("_initialValue"); -function castValue(value, trim, number) { - if (trim) value = value.trim(); - if (number) value = looseToNumber(value); - return value; -} -var vModelText = { - created(el, { modifiers: { lazy, trim, number } }, vnode) { - if (el.parentNode) { - if (el.type === "text") el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, ""); - else if (el.type === "textarea") el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, "\n"); - } - el[assignKey] = getModelAssigner(vnode); - const castToNumber = number || vnode.props && vnode.props.type === "number"; - addEventListener(el, lazy ? "change" : "input", (e) => { - if (e.target.composing) return; - el[assignKey](castValue(el.value, trim, castToNumber)); - }); - if (trim || castToNumber) addEventListener(el, "change", () => { - el.value = castValue(el.value, trim, castToNumber); - }); - if (!lazy) { - addEventListener(el, "compositionstart", onCompositionStart); - addEventListener(el, "compositionend", onCompositionEnd); - addEventListener(el, "change", onCompositionEnd); - } - }, - mounted(el, { value, modifiers: { trim, number } }) { - const newValue = value == null ? "" : value; - const initialValue = el[initialValueKey]; - delete el[initialValueKey]; - if (initialValue !== void 0 && (el.type === "text" || el.type === "textarea") && el.value !== initialValue) el[assignKey](castValue(el.value, trim, number)); - else el.value = newValue; - }, - beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim, number } }, vnode) { - el[assignKey] = getModelAssigner(vnode); - if (el.composing) return; - const elValue = (number || el.type === "number") && !/^0\d/.test(el.value) ? looseToNumber(el.value) : el.value; - const newValue = value == null ? "" : value; - if (elValue === newValue) return; - const rootNode = el.getRootNode(); - if ((rootNode instanceof Document || rootNode instanceof ShadowRoot) && rootNode.activeElement === el && el.type !== "range") { - if (lazy && value === oldValue) return; - if (trim && el.value.trim() === newValue) return; - } - el.value = newValue; - } -}; -var systemModifiers = [ - "ctrl", - "shift", - "alt", - "meta" -]; -var modifierGuards = { - stop: (e) => e.stopPropagation(), - prevent: (e) => e.preventDefault(), - self: (e) => e.target !== e.currentTarget, - ctrl: (e) => !e.ctrlKey, - shift: (e) => !e.shiftKey, - alt: (e) => !e.altKey, - meta: (e) => !e.metaKey, - left: (e) => "button" in e && e.button !== 0, - middle: (e) => "button" in e && e.button !== 1, - right: (e) => "button" in e && e.button !== 2, - exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m)) -}; -var withModifiers = (fn, modifiers) => { - if (!fn) return fn; - const cache = fn._withMods || (fn._withMods = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = ((event, ...args) => { - for (let i = 0; i < modifiers.length; i++) { - const guard = modifierGuards[modifiers[i]]; - if (guard && guard(event, modifiers)) return; - } - return fn(event, ...args); - })); -}; -var keyNames = { - esc: "escape", - space: " ", - up: "arrow-up", - left: "arrow-left", - right: "arrow-right", - down: "arrow-down", - delete: "backspace" -}; -var withKeys = (fn, modifiers) => { - const cache = fn._withKeys || (fn._withKeys = {}); - const cacheKey = modifiers.join("."); - return cache[cacheKey] || (cache[cacheKey] = ((event) => { - if (!("key" in event)) return; - const eventKey = hyphenate(event.key); - if (modifiers.some((k) => k === eventKey || keyNames[k] === eventKey)) return fn(event); - })); -}; -var rendererOptions = /* @__PURE__ */ extend$1({ patchProp }, nodeOps); -var renderer; -function ensureRenderer() { - return renderer || (renderer = createRenderer(rendererOptions)); -} -var createApp = ((...args) => { - const app = ensureRenderer().createApp(...args); - const { mount } = app; - app.mount = (containerOrSelector) => { - const container = normalizeContainer(containerOrSelector); - if (!container) return; - const component = app._component; - if (!isFunction$2(component) && !component.render && !component.template) component.template = container.innerHTML; - if (container.nodeType === 1) container.textContent = ""; - const proxy = mount(container, false, resolveRootNamespace(container)); - if (container instanceof Element) { - container.removeAttribute("v-cloak"); - container.setAttribute("data-v-app", ""); - } - return proxy; - }; - return app; -}); -function resolveRootNamespace(container) { - if (container instanceof SVGElement) return "svg"; - if (typeof MathMLElement === "function" && container instanceof MathMLElement) return "mathml"; -} -function normalizeContainer(container) { - if (isString$1(container)) return document.querySelector(container); - return container; -} -//#endregion -//#region node_modules/vue-router/dist/useApi-DtucMc-S.js -/*! -* vue-router v5.0.6 -* (c) 2026 Eduardo San Martin Morote -* @license MIT -*/ -var isBrowser = typeof document !== "undefined"; -/** -* Allows differentiating lazy components from functional components and vue-class-component -* @internal -* -* @param component -*/ -function isRouteComponent(component) { - return typeof component === "object" || "displayName" in component || "props" in component || "__vccOpts" in component; -} -function isESModule(obj) { - return obj.__esModule || obj[Symbol.toStringTag] === "Module" || obj.default && isRouteComponent(obj.default); -} -var assign = Object.assign; -function applyToParams(fn, params) { - const newParams = {}; - for (const key in params) { - const value = params[key]; - newParams[key] = isArray$1(value) ? value.map(fn) : fn(value); - } - return newParams; -} -var noop$1 = () => {}; -/** -* Typesafe alternative to Array.isArray -* https://github.com/microsoft/TypeScript/pull/48228 -* -* @internal -*/ -var isArray$1 = Array.isArray; -function mergeOptions(defaults, partialOptions) { - const options = {}; - for (const key in defaults) options[key] = key in partialOptions ? partialOptions[key] : defaults[key]; - return options; -} -/** -* Flags so we can combine them when checking for multiple errors. This is the internal version of -* {@link NavigationFailureType}. -* -* @internal -*/ -var ErrorTypes = /* @__PURE__ */ function(ErrorTypes) { - ErrorTypes[ErrorTypes["MATCHER_NOT_FOUND"] = 1] = "MATCHER_NOT_FOUND"; - ErrorTypes[ErrorTypes["NAVIGATION_GUARD_REDIRECT"] = 2] = "NAVIGATION_GUARD_REDIRECT"; - ErrorTypes[ErrorTypes["NAVIGATION_ABORTED"] = 4] = "NAVIGATION_ABORTED"; - ErrorTypes[ErrorTypes["NAVIGATION_CANCELLED"] = 8] = "NAVIGATION_CANCELLED"; - ErrorTypes[ErrorTypes["NAVIGATION_DUPLICATED"] = 16] = "NAVIGATION_DUPLICATED"; - return ErrorTypes; -}({}); -var NavigationFailureSymbol = Symbol(""); -ErrorTypes.MATCHER_NOT_FOUND, ErrorTypes.NAVIGATION_GUARD_REDIRECT, ErrorTypes.NAVIGATION_ABORTED, ErrorTypes.NAVIGATION_CANCELLED, ErrorTypes.NAVIGATION_DUPLICATED; -/** -* Creates a typed NavigationFailure object. -* @internal -* @param type - NavigationFailureType -* @param params - { from, to } -*/ -function createRouterError(type, params) { - return assign(/* @__PURE__ */ new Error(), { - type, - [NavigationFailureSymbol]: true - }, params); -} -function isNavigationFailure(error, type) { - return error instanceof Error && NavigationFailureSymbol in error && (type == null || !!(error.type & type)); -} -/** -* RouteRecord being rendered by the closest ancestor Router View. Used for -* `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View -* Location Matched -* -* @internal -*/ -var matchedRouteKey = Symbol(""); -/** -* Allows overriding the router view depth to control which component in -* `matched` is rendered. rvd stands for Router View Depth -* -* @internal -*/ -var viewDepthKey = Symbol(""); -/** -* Allows overriding the router instance returned by `useRouter` in tests. r -* stands for router -* -* @internal -*/ -var routerKey = Symbol(""); -/** -* Allows overriding the current route returned by `useRoute` in tests. rl -* stands for route location -* -* @internal -*/ -var routeLocationKey = Symbol(""); -/** -* Allows overriding the current route used by router-view. Internally this is -* used when the `route` prop is passed. -* -* @internal -*/ -var routerViewLocationKey = Symbol(""); -/** -* Returns the current route location. Equivalent to using `$route` inside -* templates. -*/ -function useRoute(_name) { - return inject(routeLocationKey); -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js -function _typeof(o) { - "@babel/helpers - typeof"; - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) { - return typeof o; - } : function(o) { - return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; - }, _typeof(o); -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPrimitive.js -function toPrimitive(t, r) { - if ("object" != _typeof(t) || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r || "default"); - if ("object" != _typeof(i)) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPropertyKey.js -function toPropertyKey(t) { - var i = toPrimitive(t, "string"); - return "symbol" == _typeof(i) ? i : i + ""; -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/defineProperty.js -function _defineProperty(e, r, t) { - return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { - value: t, - enumerable: !0, - configurable: !0, - writable: !0 - }) : e[r] = t, e; -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/objectSpread2.js -function ownKeys(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function(r) { - return Object.getOwnPropertyDescriptor(e, r).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread2(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys(Object(t), !0).forEach(function(r) { - _defineProperty(e, r, t[r]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) { - Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); - }); - } - return e; -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/asyncToGenerator.js -function asyncGeneratorStep(n, t, e, r, o, a, c) { - try { - var i = n[a](c), u = i.value; - } catch (n) { - e(n); - return; - } - i.done ? t(u) : Promise.resolve(u).then(r, o); -} -function _asyncToGenerator(n) { - return function() { - var t = this, e = arguments; - return new Promise(function(r, o) { - var a = n.apply(t, e); - function _next(n) { - asyncGeneratorStep(a, r, o, _next, _throw, "next", n); - } - function _throw(n) { - asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); - } - _next(void 0); - }); - }; -} -//#endregion -//#region node_modules/vue-router/dist/devtools-BPov6AZY.js -/*! -* vue-router v5.0.6 -* (c) 2026 Eduardo San Martin Morote -* @license MIT -*/ -/** -* Encoding Rules (␣ = Space) -* - Path: ␣ " < > # ? { } -* - Query: ␣ " < > # & = -* - Hash: ␣ " < > ` -* -* On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) -* defines some extra characters to be encoded. Most browsers do not encode them -* in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to -* also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`) -* plus `-._~`. This extra safety should be applied to query by patching the -* string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` -* should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` -* into a `/` if directly typed in. The _backtick_ (`````) should also be -* encoded everywhere because some browsers like FF encode it when directly -* written while others don't. Safari and IE don't encode ``"<>{}``` in hash. -*/ -var HASH_RE = /#/g; -var AMPERSAND_RE = /&/g; -var SLASH_RE = /\//g; -var EQUAL_RE = /=/g; -var IM_RE = /\?/g; -var PLUS_RE = /\+/g; -/** -* NOTE: It's not clear to me if we should encode the + symbol in queries, it -* seems to be less flexible than not doing so and I can't find out the legacy -* systems requiring this for regular requests like text/html. In the standard, -* the encoding of the plus character is only mentioned for -* application/x-www-form-urlencoded -* (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo -* leave the plus character as is in queries. To be more flexible, we allow the -* plus character on the query, but it can also be manually encoded by the user. -* -* Resources: -* - https://url.spec.whatwg.org/#urlencoded-parsing -* - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 -*/ -var ENC_BRACKET_OPEN_RE = /%5B/g; -var ENC_BRACKET_CLOSE_RE = /%5D/g; -var ENC_CARET_RE = /%5E/g; -var ENC_BACKTICK_RE = /%60/g; -var ENC_CURLY_OPEN_RE = /%7B/g; -var ENC_PIPE_RE = /%7C/g; -var ENC_CURLY_CLOSE_RE = /%7D/g; -var ENC_SPACE_RE = /%20/g; -/** -* Encode characters that need to be encoded on the path, search and hash -* sections of the URL. -* -* @internal -* @param text - string to encode -* @returns encoded string -*/ -function commonEncode(text) { - return text == null ? "" : encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]"); -} -/** -* Encode characters that need to be encoded on the hash section of the URL. -* -* @param text - string to encode -* @returns encoded string -*/ -function encodeHash(text) { - return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); -} -/** -* Encode characters that need to be encoded query values on the query -* section of the URL. -* -* @param text - string to encode -* @returns encoded string -*/ -function encodeQueryValue(text) { - return commonEncode(text).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^"); -} -/** -* Like `encodeQueryValue` but also encodes the `=` character. -* -* @param text - string to encode -*/ -function encodeQueryKey(text) { - return encodeQueryValue(text).replace(EQUAL_RE, "%3D"); -} -/** -* Encode characters that need to be encoded on the path section of the URL. -* -* @param text - string to encode -* @returns encoded string -*/ -function encodePath(text) { - return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F"); -} -/** -* Encode characters that need to be encoded on the path section of the URL as a -* param. This function encodes everything {@link encodePath} does plus the -* slash (`/`) character. If `text` is `null` or `undefined`, returns an empty -* string instead. -* -* @param text - string to encode -* @returns encoded string -*/ -function encodeParam(text) { - return encodePath(text).replace(SLASH_RE, "%2F"); -} -function decode(text) { - if (text == null) return null; - try { - return decodeURIComponent("" + text); - } catch (_unused) {} - return "" + text; -} -var TRAILING_SLASH_RE = /\/$/; -var removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ""); -/** -* Transforms a URI into a normalized history location -* -* @param parseQuery -* @param location - URI to normalize -* @param currentLocation - current absolute location. Allows resolving relative -* paths. Must start with `/`. Defaults to `/` -* @returns a normalized history location -*/ -function parseURL(parseQuery, location, currentLocation = "/") { - let path, query = {}, searchString = "", hash = ""; - const hashPos = location.indexOf("#"); - let searchPos = location.indexOf("?"); - searchPos = hashPos >= 0 && searchPos > hashPos ? -1 : searchPos; - if (searchPos >= 0) { - path = location.slice(0, searchPos); - searchString = location.slice(searchPos, hashPos > 0 ? hashPos : location.length); - query = parseQuery(searchString.slice(1)); - } - if (hashPos >= 0) { - path = path || location.slice(0, hashPos); - hash = location.slice(hashPos, location.length); - } - path = resolveRelativePath(path != null ? path : location, currentLocation); - return { - fullPath: path + searchString + hash, - path, - query, - hash: decode(hash) - }; -} -/** -* Stringifies a URL object -* -* @param stringifyQuery -* @param location -*/ -function stringifyURL(stringifyQuery, location) { - const query = location.query ? stringifyQuery(location.query) : ""; - return location.path + (query && "?") + query + (location.hash || ""); -} -/** -* Strips off the base from the beginning of a location.pathname in a non-case-sensitive way. -* -* @param pathname - location.pathname -* @param base - base to strip off -*/ -function stripBase(pathname, base) { - if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) return pathname; - return pathname.slice(base.length) || "/"; -} -/** -* Checks if two RouteLocation are equal. This means that both locations are -* pointing towards the same {@link RouteRecord} and that all `params`, `query` -* parameters and `hash` are the same -* -* @param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it. -* @param a - first {@link RouteLocation} -* @param b - second {@link RouteLocation} -*/ -function isSameRouteLocation(stringifyQuery, a, b) { - const aLastIndex = a.matched.length - 1; - const bLastIndex = b.matched.length - 1; - return aLastIndex > -1 && aLastIndex === bLastIndex && isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && isSameRouteLocationParams(a.params, b.params) && stringifyQuery(a.query) === stringifyQuery(b.query) && a.hash === b.hash; -} -/** -* Check if two `RouteRecords` are equal. Takes into account aliases: they are -* considered equal to the `RouteRecord` they are aliasing. -* -* @param a - first {@link RouteRecord} -* @param b - second {@link RouteRecord} -*/ -function isSameRouteRecord(a, b) { - return (a.aliasOf || a) === (b.aliasOf || b); -} -function isSameRouteLocationParams(a, b) { - if (Object.keys(a).length !== Object.keys(b).length) return false; - for (var key in a) if (!isSameRouteLocationParamsValue(a[key], b[key])) return false; - return true; -} -function isSameRouteLocationParamsValue(a, b) { - return isArray$1(a) ? isEquivalentArray(a, b) : isArray$1(b) ? isEquivalentArray(b, a) : (a && a.valueOf()) === (b && b.valueOf()); -} -/** -* Check if two arrays are the same or if an array with one single entry is the -* same as another primitive value. Used to check query and parameters -* -* @param a - array of values -* @param b - array of values or a single value -*/ -function isEquivalentArray(a, b) { - return isArray$1(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b; -} -/** -* Resolves a relative path that starts with `.`. -* -* @param to - path location we are resolving -* @param from - currentLocation.path, should start with `/` -*/ -function resolveRelativePath(to, from) { - if (to.startsWith("/")) return to; - if (!to) return from; - const fromSegments = from.split("/"); - const toSegments = to.split("/"); - const lastToSegment = toSegments[toSegments.length - 1]; - if (lastToSegment === ".." || lastToSegment === ".") toSegments.push(""); - let position = fromSegments.length - 1; - let toPosition; - let segment; - for (toPosition = 0; toPosition < toSegments.length; toPosition++) { - segment = toSegments[toPosition]; - if (segment === ".") continue; - if (segment === "..") { - if (position > 1) position--; - } else break; - } - return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition).join("/"); -} -/** -* Initial route location where the router is. Can be used in navigation guards -* to differentiate the initial navigation. -* -* @example -* ```js -* import { START_LOCATION } from 'vue-router' -* -* router.beforeEach((to, from) => { -* if (from === START_LOCATION) { -* // initial navigation -* } -* }) -* ``` -*/ -var START_LOCATION_NORMALIZED = { - path: "/", - name: void 0, - params: {}, - query: {}, - hash: "", - fullPath: "/", - matched: [], - meta: {}, - redirectedFrom: void 0 -}; -var NavigationType = /* @__PURE__ */ function(NavigationType) { - NavigationType["pop"] = "pop"; - NavigationType["push"] = "push"; - return NavigationType; -}({}); -var NavigationDirection = /* @__PURE__ */ function(NavigationDirection) { - NavigationDirection["back"] = "back"; - NavigationDirection["forward"] = "forward"; - NavigationDirection["unknown"] = ""; - return NavigationDirection; -}({}); -/** -* Normalizes a base by removing any trailing slash and reading the base tag if -* present. -* -* @param base - base to normalize -*/ -function normalizeBase(base) { - if (!base) if (isBrowser) { - const baseEl = document.querySelector("base"); - base = baseEl && baseEl.getAttribute("href") || "/"; - base = base.replace(/^\w+:\/\/[^/]+/, ""); - } else base = "/"; - if (base[0] !== "/" && base[0] !== "#") base = "/" + base; - return removeTrailingSlash(base); -} -var BEFORE_HASH_RE = /^[^#]+#/; -function createHref(base, location) { - return base.replace(BEFORE_HASH_RE, "#") + location; -} -function getElementPosition(el, offset) { - const docRect = document.documentElement.getBoundingClientRect(); - const elRect = el.getBoundingClientRect(); - return { - behavior: offset.behavior, - left: elRect.left - docRect.left - (offset.left || 0), - top: elRect.top - docRect.top - (offset.top || 0) - }; -} -var computeScrollPosition = () => ({ - left: window.scrollX, - top: window.scrollY -}); -function scrollToPosition(position) { - let scrollToOptions; - if ("el" in position) { - const positionEl = position.el; - const isIdSelector = typeof positionEl === "string" && positionEl.startsWith("#"); - const el = typeof positionEl === "string" ? isIdSelector ? document.getElementById(positionEl.slice(1)) : document.querySelector(positionEl) : positionEl; - if (!el) return; - scrollToOptions = getElementPosition(el, position); - } else scrollToOptions = position; - if ("scrollBehavior" in document.documentElement.style) window.scrollTo(scrollToOptions); - else window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.scrollX, scrollToOptions.top != null ? scrollToOptions.top : window.scrollY); -} -function getScrollKey(path, delta) { - return (history.state ? history.state.position - delta : -1) + path; -} -var scrollPositions = /* @__PURE__ */ new Map(); -function saveScrollPosition(key, scrollPosition) { - scrollPositions.set(key, scrollPosition); -} -function getSavedScrollPosition(key) { - const scroll = scrollPositions.get(key); - scrollPositions.delete(key); - return scroll; -} -/** -* ScrollBehavior instance used by the router to compute and restore the scroll -* position when navigating. -*/ -function isRouteLocation(route) { - return typeof route === "string" || route && typeof route === "object"; -} -function isRouteName(name) { - return typeof name === "string" || typeof name === "symbol"; -} -/** -* Transforms a queryString into a {@link LocationQuery} object. Accept both, a -* version with the leading `?` and without Should work as URLSearchParams - -* @internal -* -* @param search - search string to parse -* @returns a query object -*/ -function parseQuery(search) { - const query = {}; - if (search === "" || search === "?") return query; - const searchParams = (search[0] === "?" ? search.slice(1) : search).split("&"); - for (let i = 0; i < searchParams.length; ++i) { - const searchParam = searchParams[i].replace(PLUS_RE, " "); - const eqPos = searchParam.indexOf("="); - const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos)); - const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1)); - if (key in query) { - let currentValue = query[key]; - if (!isArray$1(currentValue)) currentValue = query[key] = [currentValue]; - currentValue.push(value); - } else query[key] = value; - } - return query; -} -/** -* Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it -* doesn't prepend a `?` -* -* @internal -* -* @param query - query object to stringify -* @returns string version of the query without the leading `?` -*/ -function stringifyQuery(query) { - let search = ""; - for (let key in query) { - const value = query[key]; - key = encodeQueryKey(key); - if (value == null) { - if (value !== void 0) search += (search.length ? "&" : "") + key; - continue; - } - (isArray$1(value) ? value.map((v) => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)]).forEach((value) => { - if (value !== void 0) { - search += (search.length ? "&" : "") + key; - if (value != null) search += "=" + value; - } - }); - } - return search; -} -/** -* Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting -* numbers into strings, removing keys with an undefined value and replacing -* undefined with null in arrays -* -* @param query - query object to normalize -* @returns a normalized query object -*/ -function normalizeQuery(query) { - const normalizedQuery = {}; - for (const key in query) { - const value = query[key]; - if (value !== void 0) normalizedQuery[key] = isArray$1(value) ? value.map((v) => v == null ? null : "" + v) : value == null ? value : "" + value; - } - return normalizedQuery; -} -/** -* Create a list of callbacks that can be reset. Used to create before and after navigation guards list -*/ -function useCallbacks() { - let handlers = []; - function add(handler) { - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) handlers.splice(i, 1); - }; - } - function reset() { - handlers = []; - } - return { - add, - list: () => handlers.slice(), - reset - }; -} -function guardToPromiseFn(guard, to, from, record, name, runWithContext = (fn) => fn()) { - const enterCallbackArray = record && (record.enterCallbacks[name] = record.enterCallbacks[name] || []); - return () => new Promise((resolve, reject) => { - const next = (valid) => { - if (valid === false) reject(createRouterError(ErrorTypes.NAVIGATION_ABORTED, { - from, - to - })); - else if (valid instanceof Error) reject(valid); - else if (isRouteLocation(valid)) reject(createRouterError(ErrorTypes.NAVIGATION_GUARD_REDIRECT, { - from: to, - to: valid - })); - else { - if (enterCallbackArray && record.enterCallbacks[name] === enterCallbackArray && typeof valid === "function") enterCallbackArray.push(valid); - resolve(); - } - }; - const guardReturn = runWithContext(() => guard.call(record && record.instances[name], to, from, next)); - let guardCall = Promise.resolve(guardReturn); - if (guard.length < 3) guardCall = guardCall.then(next); - guardCall.catch((err) => reject(err)); - }); -} -function extractComponentsGuards(matched, guardType, to, from, runWithContext = (fn) => fn()) { - const guards = []; - for (const record of matched) for (const name in record.components) { - let rawComponent = record.components[name]; - if (guardType !== "beforeRouteEnter" && !record.instances[name]) continue; - if (isRouteComponent(rawComponent)) { - const guard = (rawComponent.__vccOpts || rawComponent)[guardType]; - guard && guards.push(guardToPromiseFn(guard, to, from, record, name, runWithContext)); - } else { - let componentPromise = rawComponent(); - guards.push(() => componentPromise.then((resolved) => { - if (!resolved) throw new Error(`Couldn't resolve component "${name}" at "${record.path}"`); - const resolvedComponent = isESModule(resolved) ? resolved.default : resolved; - record.mods[name] = resolved; - record.components[name] = resolvedComponent; - const guard = (resolvedComponent.__vccOpts || resolvedComponent)[guardType]; - return guard && guardToPromiseFn(guard, to, from, record, name, runWithContext)(); - })); - } - } - return guards; -} -/** -* Split the leaving, updating, and entering records. -* @internal -* -* @param to - Location we are navigating to -* @param from - Location we are navigating from -*/ -function extractChangingRecords(to, from) { - const leavingRecords = []; - const updatingRecords = []; - const enteringRecords = []; - const len = Math.max(from.matched.length, to.matched.length); - for (let i = 0; i < len; i++) { - const recordFrom = from.matched[i]; - if (recordFrom) if (to.matched.find((record) => isSameRouteRecord(record, recordFrom))) updatingRecords.push(recordFrom); - else leavingRecords.push(recordFrom); - const recordTo = to.matched[i]; - if (recordTo) { - if (!from.matched.find((record) => isSameRouteRecord(record, recordTo))) enteringRecords.push(recordTo); - } - } - return [ - leavingRecords, - updatingRecords, - enteringRecords - ]; -} -//#endregion -//#region node_modules/vue-router/dist/vue-router.js -/*! -* vue-router v5.0.6 -* (c) 2026 Eduardo San Martin Morote -* @license MIT -*/ -var createBaseLocation = () => location.protocol + "//" + location.host; -/** -* Creates a normalized history location from a window.location object -* @param base - The base path -* @param location - The window.location object -*/ -function createCurrentLocation(base, location) { - const { pathname, search, hash } = location; - const hashPos = base.indexOf("#"); - if (hashPos > -1) { - let slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1; - let pathFromHash = hash.slice(slicePos); - if (pathFromHash[0] !== "/") pathFromHash = "/" + pathFromHash; - return stripBase(pathFromHash, ""); - } - return stripBase(pathname, base) + search + hash; -} -function useHistoryListeners(base, historyState, currentLocation, replace) { - let listeners = []; - let teardowns = []; - let pauseState = null; - const popStateHandler = ({ state }) => { - const to = createCurrentLocation(base, location); - const from = currentLocation.value; - const fromState = historyState.value; - let delta = 0; - if (state) { - currentLocation.value = to; - historyState.value = state; - if (pauseState && pauseState === from) { - pauseState = null; - return; - } - delta = fromState ? state.position - fromState.position : 0; - } else replace(to); - listeners.forEach((listener) => { - listener(currentLocation.value, from, { - delta, - type: NavigationType.pop, - direction: delta ? delta > 0 ? NavigationDirection.forward : NavigationDirection.back : NavigationDirection.unknown - }); - }); - }; - function pauseListeners() { - pauseState = currentLocation.value; - } - function listen(callback) { - listeners.push(callback); - const teardown = () => { - const index = listeners.indexOf(callback); - if (index > -1) listeners.splice(index, 1); - }; - teardowns.push(teardown); - return teardown; - } - function beforeUnloadListener() { - if (document.visibilityState === "hidden") { - const { history } = window; - if (!history.state) return; - history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), ""); - } - } - function destroy() { - for (const teardown of teardowns) teardown(); - teardowns = []; - window.removeEventListener("popstate", popStateHandler); - window.removeEventListener("pagehide", beforeUnloadListener); - document.removeEventListener("visibilitychange", beforeUnloadListener); - } - window.addEventListener("popstate", popStateHandler); - window.addEventListener("pagehide", beforeUnloadListener); - document.addEventListener("visibilitychange", beforeUnloadListener); - return { - pauseListeners, - listen, - destroy - }; -} -/** -* Creates a state object -*/ -function buildState(back, current, forward, replaced = false, computeScroll = false) { - return { - back, - current, - forward, - replaced, - position: window.history.length, - scroll: computeScroll ? computeScrollPosition() : null - }; -} -function useHistoryStateNavigation(base) { - const { history, location } = window; - const currentLocation = { value: createCurrentLocation(base, location) }; - const historyState = { value: history.state }; - if (!historyState.value) changeLocation(currentLocation.value, { - back: null, - current: currentLocation.value, - forward: null, - position: history.length - 1, - replaced: true, - scroll: null - }, true); - function changeLocation(to, state, replace) { - /** - * if a base tag is provided, and we are on a normal domain, we have to - * respect the provided `base` attribute because pushState() will use it and - * potentially erase anything before the `#` like at - * https://github.com/vuejs/router/issues/685 where a base of - * `/folder/#` but a base of `/` would erase the `/folder/` section. If - * there is no host, the `` tag makes no sense and if there isn't a - * base tag we can just use everything after the `#`. - */ - const hashIndex = base.indexOf("#"); - const url = hashIndex > -1 ? (location.host && document.querySelector("base") ? base : base.slice(hashIndex)) + to : createBaseLocation() + base + to; - try { - history[replace ? "replaceState" : "pushState"](state, "", url); - historyState.value = state; - } catch (err) { - console.error(err); - location[replace ? "replace" : "assign"](url); - } - } - function replace(to, data) { - changeLocation(to, assign({}, history.state, buildState(historyState.value.back, to, historyState.value.forward, true), data, { position: historyState.value.position }), true); - currentLocation.value = to; - } - function push(to, data) { - const currentState = assign({}, historyState.value, history.state, { - forward: to, - scroll: computeScrollPosition() - }); - changeLocation(currentState.current, currentState, true); - changeLocation(to, assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data), false); - currentLocation.value = to; - } - return { - location: currentLocation, - state: historyState, - push, - replace - }; -} -/** -* Creates an HTML5 history. Most common history for single page applications. -* -* @param base - -*/ -function createWebHistory(base) { - base = normalizeBase(base); - const historyNavigation = useHistoryStateNavigation(base); - const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace); - function go(delta, triggerListeners = true) { - if (!triggerListeners) historyListeners.pauseListeners(); - history.go(delta); - } - const routerHistory = assign({ - location: "", - base, - go, - createHref: createHref.bind(null, base) - }, historyNavigation, historyListeners); - Object.defineProperty(routerHistory, "location", { - enumerable: true, - get: () => historyNavigation.location.value - }); - Object.defineProperty(routerHistory, "state", { - enumerable: true, - get: () => historyNavigation.state.value - }); - return routerHistory; -} -var TokenType = /* @__PURE__ */ function(TokenType) { - TokenType[TokenType["Static"] = 0] = "Static"; - TokenType[TokenType["Param"] = 1] = "Param"; - TokenType[TokenType["Group"] = 2] = "Group"; - return TokenType; -}({}); -var TokenizerState = /* @__PURE__ */ function(TokenizerState) { - TokenizerState[TokenizerState["Static"] = 0] = "Static"; - TokenizerState[TokenizerState["Param"] = 1] = "Param"; - TokenizerState[TokenizerState["ParamRegExp"] = 2] = "ParamRegExp"; - TokenizerState[TokenizerState["ParamRegExpEnd"] = 3] = "ParamRegExpEnd"; - TokenizerState[TokenizerState["EscapeNext"] = 4] = "EscapeNext"; - return TokenizerState; -}(TokenizerState || {}); -var ROOT_TOKEN = { - type: TokenType.Static, - value: "" -}; -var VALID_PARAM_RE = /[a-zA-Z0-9_]/; -function tokenizePath(path) { - if (!path) return [[]]; - if (path === "/") return [[ROOT_TOKEN]]; - if (!path.startsWith("/")) throw new Error(`Invalid path "${path}"`); - function crash(message) { - throw new Error(`ERR (${state})/"${buffer}": ${message}`); - } - let state = TokenizerState.Static; - let previousState = state; - const tokens = []; - let segment; - function finalizeSegment() { - if (segment) tokens.push(segment); - segment = []; - } - let i = 0; - let char; - let buffer = ""; - let customRe = ""; - function consumeBuffer() { - if (!buffer) return; - if (state === TokenizerState.Static) segment.push({ - type: TokenType.Static, - value: buffer - }); - else if (state === TokenizerState.Param || state === TokenizerState.ParamRegExp || state === TokenizerState.ParamRegExpEnd) { - if (segment.length > 1 && (char === "*" || char === "+")) crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); - segment.push({ - type: TokenType.Param, - value: buffer, - regexp: customRe, - repeatable: char === "*" || char === "+", - optional: char === "*" || char === "?" - }); - } else crash("Invalid state to consume buffer"); - buffer = ""; - } - function addCharToBuffer() { - buffer += char; - } - while (i < path.length) { - char = path[i++]; - if (char === "\\" && state !== TokenizerState.ParamRegExp) { - previousState = state; - state = TokenizerState.EscapeNext; - continue; - } - switch (state) { - case TokenizerState.Static: - if (char === "/") { - if (buffer) consumeBuffer(); - finalizeSegment(); - } else if (char === ":") { - consumeBuffer(); - state = TokenizerState.Param; - } else addCharToBuffer(); - break; - case TokenizerState.EscapeNext: - addCharToBuffer(); - state = previousState; - break; - case TokenizerState.Param: - if (char === "(") state = TokenizerState.ParamRegExp; - else if (VALID_PARAM_RE.test(char)) addCharToBuffer(); - else { - consumeBuffer(); - state = TokenizerState.Static; - if (char !== "*" && char !== "?" && char !== "+") i--; - } - break; - case TokenizerState.ParamRegExp: - if (char === ")") if (customRe[customRe.length - 1] == "\\") customRe = customRe.slice(0, -1) + char; - else state = TokenizerState.ParamRegExpEnd; - else customRe += char; - break; - case TokenizerState.ParamRegExpEnd: - consumeBuffer(); - state = TokenizerState.Static; - if (char !== "*" && char !== "?" && char !== "+") i--; - customRe = ""; - break; - default: - crash("Unknown state"); - break; - } - } - if (state === TokenizerState.ParamRegExp) crash(`Unfinished custom RegExp for param "${buffer}"`); - consumeBuffer(); - finalizeSegment(); - return tokens; -} -var BASE_PARAM_PATTERN = "[^/]+?"; -var BASE_PATH_PARSER_OPTIONS = { - sensitive: false, - strict: false, - start: true, - end: true -}; -var PathScore = /* @__PURE__ */ function(PathScore) { - PathScore[PathScore["_multiplier"] = 10] = "_multiplier"; - PathScore[PathScore["Root"] = 90] = "Root"; - PathScore[PathScore["Segment"] = 40] = "Segment"; - PathScore[PathScore["SubSegment"] = 30] = "SubSegment"; - PathScore[PathScore["Static"] = 40] = "Static"; - PathScore[PathScore["Dynamic"] = 20] = "Dynamic"; - PathScore[PathScore["BonusCustomRegExp"] = 10] = "BonusCustomRegExp"; - PathScore[PathScore["BonusWildcard"] = -50] = "BonusWildcard"; - PathScore[PathScore["BonusRepeatable"] = -20] = "BonusRepeatable"; - PathScore[PathScore["BonusOptional"] = -8] = "BonusOptional"; - PathScore[PathScore["BonusStrict"] = .7000000000000001] = "BonusStrict"; - PathScore[PathScore["BonusCaseSensitive"] = .25] = "BonusCaseSensitive"; - return PathScore; -}(PathScore || {}); -var REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g; -/** -* Creates a path parser from an array of Segments (a segment is an array of Tokens) -* -* @param segments - array of segments returned by tokenizePath -* @param extraOptions - optional options for the regexp -* @returns a PathParser -*/ -function tokensToParser(segments, extraOptions) { - const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions); - const score = []; - let pattern = options.start ? "^" : ""; - const keys = []; - for (const segment of segments) { - const segmentScores = segment.length ? [] : [PathScore.Root]; - if (options.strict && !segment.length) pattern += "/"; - for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { - const token = segment[tokenIndex]; - let subSegmentScore = PathScore.Segment + (options.sensitive ? PathScore.BonusCaseSensitive : 0); - if (token.type === TokenType.Static) { - if (!tokenIndex) pattern += "/"; - pattern += token.value.replace(REGEX_CHARS_RE, "\\$&"); - subSegmentScore += PathScore.Static; - } else if (token.type === TokenType.Param) { - const { value, repeatable, optional, regexp } = token; - keys.push({ - name: value, - repeatable, - optional - }); - const re = regexp ? regexp : BASE_PARAM_PATTERN; - if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += PathScore.BonusCustomRegExp; - try { - new RegExp(`(${re})`); - } catch (err) { - throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` + err.message); - } - } - let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`; - if (!tokenIndex) subPattern = optional && segment.length < 2 ? `(?:/${subPattern})` : "/" + subPattern; - if (optional) subPattern += "?"; - pattern += subPattern; - subSegmentScore += PathScore.Dynamic; - if (optional) subSegmentScore += PathScore.BonusOptional; - if (repeatable) subSegmentScore += PathScore.BonusRepeatable; - if (re === ".*") subSegmentScore += PathScore.BonusWildcard; - } - segmentScores.push(subSegmentScore); - } - score.push(segmentScores); - } - if (options.strict && options.end) { - const i = score.length - 1; - score[i][score[i].length - 1] += PathScore.BonusStrict; - } - if (!options.strict) pattern += "/?"; - if (options.end) pattern += "$"; - else if (options.strict && !pattern.endsWith("/")) pattern += "(?:/|$)"; - const re = new RegExp(pattern, options.sensitive ? "" : "i"); - function parse(path) { - const match = path.match(re); - const params = {}; - if (!match) return null; - for (let i = 1; i < match.length; i++) { - const value = match[i] || ""; - const key = keys[i - 1]; - params[key.name] = value && key.repeatable ? value.split("/") : value; - } - return params; - } - function stringify(params) { - let path = ""; - let avoidDuplicatedSlash = false; - for (const segment of segments) { - if (!avoidDuplicatedSlash || !path.endsWith("/")) path += "/"; - avoidDuplicatedSlash = false; - for (const token of segment) if (token.type === TokenType.Static) path += token.value; - else if (token.type === TokenType.Param) { - const { value, repeatable, optional } = token; - const param = value in params ? params[value] : ""; - if (isArray$1(param) && !repeatable) throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = isArray$1(param) ? param.join("/") : param; - if (!text) if (optional) { - if (segment.length < 2) if (path.endsWith("/")) path = path.slice(0, -1); - else avoidDuplicatedSlash = true; - } else throw new Error(`Missing required param "${value}"`); - path += text; - } - } - return path || "/"; - } - return { - re, - score, - keys, - parse, - stringify - }; -} -/** -* Compares an array of numbers as used in PathParser.score and returns a -* number. This function can be used to `sort` an array -* -* @param a - first array of numbers -* @param b - second array of numbers -* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b -* should be sorted first -*/ -function compareScoreArray(a, b) { - let i = 0; - while (i < a.length && i < b.length) { - const diff = b[i] - a[i]; - if (diff) return diff; - i++; - } - if (a.length < b.length) return a.length === 1 && a[0] === PathScore.Static + PathScore.Segment ? -1 : 1; - else if (a.length > b.length) return b.length === 1 && b[0] === PathScore.Static + PathScore.Segment ? 1 : -1; - return 0; -} -/** -* Compare function that can be used with `sort` to sort an array of PathParser -* -* @param a - first PathParser -* @param b - second PathParser -* @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b -*/ -function comparePathParserScore(a, b) { - let i = 0; - const aScore = a.score; - const bScore = b.score; - while (i < aScore.length && i < bScore.length) { - const comp = compareScoreArray(aScore[i], bScore[i]); - if (comp) return comp; - i++; - } - if (Math.abs(bScore.length - aScore.length) === 1) { - if (isLastScoreNegative(aScore)) return 1; - if (isLastScoreNegative(bScore)) return -1; - } - return bScore.length - aScore.length; -} -/** -* This allows detecting splats at the end of a path: /home/:id(.*)* -* -* @param score - score to check -* @returns true if the last entry is negative -*/ -function isLastScoreNegative(score) { - const last = score[score.length - 1]; - return score.length > 0 && last[last.length - 1] < 0; -} -var PATH_PARSER_OPTIONS_DEFAULTS = { - strict: false, - end: true, - sensitive: false -}; -function createRouteRecordMatcher(record, parent, options) { - const matcher = assign(tokensToParser(tokenizePath(record.path), options), { - record, - parent, - children: [], - alias: [] - }); - if (parent) { - if (!matcher.record.aliasOf === !parent.record.aliasOf) parent.children.push(matcher); - } - return matcher; -} -/** -* Creates a Router Matcher. -* -* @internal -* @param routes - array of initial routes -* @param globalOptions - global route options -*/ -function createRouterMatcher(routes, globalOptions) { - const matchers = []; - const matcherMap = /* @__PURE__ */ new Map(); - globalOptions = mergeOptions(PATH_PARSER_OPTIONS_DEFAULTS, globalOptions); - function getRecordMatcher(name) { - return matcherMap.get(name); - } - function addRoute(record, parent, originalRecord) { - const isRootAdd = !originalRecord; - const mainNormalizedRecord = normalizeRouteRecord(record); - mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; - const options = mergeOptions(globalOptions, record); - const normalizedRecords = [mainNormalizedRecord]; - if ("alias" in record) { - const aliases = typeof record.alias === "string" ? [record.alias] : record.alias; - for (const alias of aliases) normalizedRecords.push(normalizeRouteRecord(assign({}, mainNormalizedRecord, { - components: originalRecord ? originalRecord.record.components : mainNormalizedRecord.components, - path: alias, - aliasOf: originalRecord ? originalRecord.record : mainNormalizedRecord - }))); - } - let matcher; - let originalMatcher; - for (const normalizedRecord of normalizedRecords) { - const { path } = normalizedRecord; - if (parent && path[0] !== "/") { - const parentPath = parent.record.path; - const connectingSlash = parentPath[parentPath.length - 1] === "/" ? "" : "/"; - normalizedRecord.path = parent.record.path + (path && connectingSlash + path); - } - matcher = createRouteRecordMatcher(normalizedRecord, parent, options); - if (originalRecord) originalRecord.alias.push(matcher); - else { - originalMatcher = originalMatcher || matcher; - if (originalMatcher !== matcher) originalMatcher.alias.push(matcher); - if (isRootAdd && record.name && !isAliasRecord(matcher)) removeRoute(record.name); - } - if (isMatchable(matcher)) insertMatcher(matcher); - if (mainNormalizedRecord.children) { - const children = mainNormalizedRecord.children; - for (let i = 0; i < children.length; i++) addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); - } - originalRecord = originalRecord || matcher; - } - return originalMatcher ? () => { - removeRoute(originalMatcher); - } : noop$1; - } - function removeRoute(matcherRef) { - if (isRouteName(matcherRef)) { - const matcher = matcherMap.get(matcherRef); - if (matcher) { - matcherMap.delete(matcherRef); - matchers.splice(matchers.indexOf(matcher), 1); - matcher.children.forEach(removeRoute); - matcher.alias.forEach(removeRoute); - } - } else { - const index = matchers.indexOf(matcherRef); - if (index > -1) { - matchers.splice(index, 1); - if (matcherRef.record.name) matcherMap.delete(matcherRef.record.name); - matcherRef.children.forEach(removeRoute); - matcherRef.alias.forEach(removeRoute); - } - } - } - function getRoutes() { - return matchers; - } - function insertMatcher(matcher) { - const index = findInsertionIndex(matcher, matchers); - matchers.splice(index, 0, matcher); - if (matcher.record.name && !isAliasRecord(matcher)) matcherMap.set(matcher.record.name, matcher); - } - function resolve(location, currentLocation) { - let matcher; - let params = {}; - let path; - let name; - if ("name" in location && location.name) { - matcher = matcherMap.get(location.name); - if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, { location }); - name = matcher.record.name; - params = assign(pickParams(currentLocation.params, matcher.keys.filter((k) => !k.optional).concat(matcher.parent ? matcher.parent.keys.filter((k) => k.optional) : []).map((k) => k.name)), location.params && pickParams(location.params, matcher.keys.map((k) => k.name))); - path = matcher.stringify(params); - } else if (location.path != null) { - path = location.path; - matcher = matchers.find((m) => m.re.test(path)); - if (matcher) { - params = matcher.parse(path); - name = matcher.record.name; - } - } else { - matcher = currentLocation.name ? matcherMap.get(currentLocation.name) : matchers.find((m) => m.re.test(currentLocation.path)); - if (!matcher) throw createRouterError(ErrorTypes.MATCHER_NOT_FOUND, { - location, - currentLocation - }); - name = matcher.record.name; - params = assign({}, currentLocation.params, location.params); - path = matcher.stringify(params); - } - const matched = []; - let parentMatcher = matcher; - while (parentMatcher) { - matched.unshift(parentMatcher.record); - parentMatcher = parentMatcher.parent; - } - return { - name, - path, - params, - matched, - meta: mergeMetaFields(matched) - }; - } - routes.forEach((route) => addRoute(route)); - function clearRoutes() { - matchers.length = 0; - matcherMap.clear(); - } - return { - addRoute, - resolve, - removeRoute, - clearRoutes, - getRoutes, - getRecordMatcher - }; -} -/** -* Picks an object param to contain only specified keys. -* -* @param params - params object to pick from -* @param keys - keys to pick -*/ -function pickParams(params, keys) { - const newParams = {}; - for (const key of keys) if (key in params) newParams[key] = params[key]; - return newParams; -} -/** -* Normalizes a RouteRecordRaw. Creates a copy -* -* @param record -* @returns the normalized version -*/ -function normalizeRouteRecord(record) { - const normalized = { - path: record.path, - redirect: record.redirect, - name: record.name, - meta: record.meta || {}, - aliasOf: record.aliasOf, - beforeEnter: record.beforeEnter, - props: normalizeRecordProps(record), - children: record.children || [], - instances: {}, - leaveGuards: /* @__PURE__ */ new Set(), - updateGuards: /* @__PURE__ */ new Set(), - enterCallbacks: {}, - components: "components" in record ? record.components || null : record.component && { default: record.component } - }; - Object.defineProperty(normalized, "mods", { value: {} }); - return normalized; -} -/** -* Normalize the optional `props` in a record to always be an object similar to -* components. Also accept a boolean for components. -* @param record -*/ -function normalizeRecordProps(record) { - const propsObject = {}; - const props = record.props || false; - if ("component" in record) propsObject.default = props; - else for (const name in record.components) propsObject[name] = typeof props === "object" ? props[name] : props; - return propsObject; -} -/** -* Checks if a record or any of its parent is an alias -* @param record -*/ -function isAliasRecord(record) { - while (record) { - if (record.record.aliasOf) return true; - record = record.parent; - } - return false; -} -/** -* Merge meta fields of an array of records -* -* @param matched - array of matched records -*/ -function mergeMetaFields(matched) { - return matched.reduce((meta, record) => assign(meta, record.meta), {}); -} -/** -* Performs a binary search to find the correct insertion index for a new matcher. -* -* Matchers are primarily sorted by their score. If scores are tied then we also consider parent/child relationships, -* with descendants coming before ancestors. If there's still a tie, new routes are inserted after existing routes. -* -* @param matcher - new matcher to be inserted -* @param matchers - existing matchers -*/ -function findInsertionIndex(matcher, matchers) { - let lower = 0; - let upper = matchers.length; - while (lower !== upper) { - const mid = lower + upper >> 1; - if (comparePathParserScore(matcher, matchers[mid]) < 0) upper = mid; - else lower = mid + 1; - } - const insertionAncestor = getInsertionAncestor(matcher); - if (insertionAncestor) upper = matchers.lastIndexOf(insertionAncestor, upper - 1); - return upper; -} -function getInsertionAncestor(matcher) { - let ancestor = matcher; - while (ancestor = ancestor.parent) if (isMatchable(ancestor) && comparePathParserScore(matcher, ancestor) === 0) return ancestor; -} -/** -* Checks if a matcher can be reachable. This means if it's possible to reach it as a route. For example, routes without -* a component, or name, or redirect, are just used to group other routes. -* @param matcher -* @param matcher.record record of the matcher -* @returns -*/ -function isMatchable({ record }) { - return !!(record.name || record.components && Object.keys(record.components).length || record.redirect); -} -/** -* Returns the internal behavior of a {@link RouterLink} without the rendering part. -* -* @param props - a `to` location and an optional `replace` flag -*/ -function useLink(props) { - const router = inject(routerKey); - const currentRoute = inject(routeLocationKey); - const route = computed(() => { - const to = unref(props.to); - return router.resolve(to); - }); - const activeRecordIndex = computed(() => { - const { matched } = route.value; - const { length } = matched; - const routeMatched = matched[length - 1]; - const currentMatched = currentRoute.matched; - if (!routeMatched || !currentMatched.length) return -1; - const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); - if (index > -1) return index; - const parentRecordPath = getOriginalPath(matched[length - 2]); - return length > 1 && getOriginalPath(routeMatched) === parentRecordPath && currentMatched[currentMatched.length - 1].path !== parentRecordPath ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) : index; - }); - const isActive = computed(() => activeRecordIndex.value > -1 && includesParams(currentRoute.params, route.value.params)); - const isExactActive = computed(() => activeRecordIndex.value > -1 && activeRecordIndex.value === currentRoute.matched.length - 1 && isSameRouteLocationParams(currentRoute.params, route.value.params)); - function navigate(e = {}) { - if (guardEvent(e)) { - const p = router[unref(props.replace) ? "replace" : "push"](unref(props.to)).catch(noop$1); - if (props.viewTransition && typeof document !== "undefined" && "startViewTransition" in document) document.startViewTransition(() => p); - return p; - } - return Promise.resolve(); - } - /** - * NOTE: update {@link _RouterLinkI}'s `$slots` type when updating this - */ - return { - route, - href: computed(() => route.value.href), - isActive, - isExactActive, - navigate - }; -} -function preferSingleVNode(vnodes) { - return vnodes.length === 1 ? vnodes[0] : vnodes; -} -/** -* Component to render a link that triggers a navigation on click. -*/ -var RouterLink = /* @__PURE__ */ defineComponent({ - name: "RouterLink", - compatConfig: { MODE: 3 }, - props: { - to: { - type: [String, Object], - required: true - }, - replace: Boolean, - activeClass: String, - exactActiveClass: String, - custom: Boolean, - ariaCurrentValue: { - type: String, - default: "page" - }, - viewTransition: Boolean - }, - useLink, - setup(props, { slots }) { - const link = /* @__PURE__ */ reactive(useLink(props)); - const { options } = inject(routerKey); - const elClass = computed(() => ({ - [getLinkClass(props.activeClass, options.linkActiveClass, "router-link-active")]: link.isActive, - [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, "router-link-exact-active")]: link.isExactActive - })); - return () => { - const children = slots.default && preferSingleVNode(slots.default(link)); - return props.custom ? children : h("a", { - "aria-current": link.isExactActive ? props.ariaCurrentValue : null, - href: link.href, - onClick: link.navigate, - class: elClass.value - }, children); - }; - } -}); -function guardEvent(e) { - if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return; - if (e.defaultPrevented) return; - if (e.button !== void 0 && e.button !== 0) return; - if (e.currentTarget && e.currentTarget.getAttribute) { - const target = e.currentTarget.getAttribute("target"); - if (/\b_blank\b/i.test(target)) return; - } - if (e.preventDefault) e.preventDefault(); - return true; -} -function includesParams(outer, inner) { - for (const key in inner) { - const innerValue = inner[key]; - const outerValue = outer[key]; - if (typeof innerValue === "string") { - if (innerValue !== outerValue) return false; - } else if (!isArray$1(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value.valueOf() !== outerValue[i].valueOf())) return false; - } - return true; -} -/** -* Get the original path value of a record by following its aliasOf -* @param record -*/ -function getOriginalPath(record) { - return record ? record.aliasOf ? record.aliasOf.path : record.path : ""; -} -/** -* Utility class to get the active class based on defaults. -* @param propClass -* @param globalClass -* @param defaultClass -*/ -var getLinkClass = (propClass, globalClass, defaultClass) => propClass != null ? propClass : globalClass != null ? globalClass : defaultClass; -var RouterViewImpl = /* @__PURE__ */ defineComponent({ - name: "RouterView", - inheritAttrs: false, - props: { - name: { - type: String, - default: "default" - }, - route: Object - }, - compatConfig: { MODE: 3 }, - setup(props, { attrs, slots }) { - const injectedRoute = inject(routerViewLocationKey); - const routeToDisplay = computed(() => props.route || injectedRoute.value); - const injectedDepth = inject(viewDepthKey, 0); - const depth = computed(() => { - let initialDepth = unref(injectedDepth); - const { matched } = routeToDisplay.value; - let matchedRoute; - while ((matchedRoute = matched[initialDepth]) && !matchedRoute.components) initialDepth++; - return initialDepth; - }); - const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]); - provide(viewDepthKey, computed(() => depth.value + 1)); - provide(matchedRouteKey, matchedRouteRef); - provide(routerViewLocationKey, routeToDisplay); - const viewRef = /* @__PURE__ */ ref(); - watch(() => [ - viewRef.value, - matchedRouteRef.value, - props.name - ], ([instance, to, name], [oldInstance, from, _oldName]) => { - if (to) { - to.instances[name] = instance; - if (from && from !== to && instance && instance === oldInstance) { - if (!to.leaveGuards.size) to.leaveGuards = from.leaveGuards; - if (!to.updateGuards.size) to.updateGuards = from.updateGuards; - } - } - if (instance && to && (!from || !isSameRouteRecord(to, from) || !oldInstance)) (to.enterCallbacks[name] || []).forEach((callback) => callback(instance)); - }, { flush: "post" }); - return () => { - const route = routeToDisplay.value; - const currentName = props.name; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[currentName]; - if (!ViewComponent) return normalizeSlot(slots.default, { - Component: ViewComponent, - route - }); - const routePropsOption = matchedRoute.props[currentName]; - const routeProps = routePropsOption ? routePropsOption === true ? route.params : typeof routePropsOption === "function" ? routePropsOption(route) : routePropsOption : null; - const onVnodeUnmounted = (vnode) => { - if (vnode.component.isUnmounted) matchedRoute.instances[currentName] = null; - }; - const component = h(ViewComponent, assign({}, routeProps, attrs, { - onVnodeUnmounted, - ref: viewRef - })); - return normalizeSlot(slots.default, { - Component: component, - route - }) || component; - }; - } -}); -function normalizeSlot(slot, data) { - if (!slot) return null; - const slotContent = slot(data); - return slotContent.length === 1 ? slotContent[0] : slotContent; -} -/** -* Component to display the current route the user is at. -*/ -var RouterView = RouterViewImpl; -/** -* Creates a Router instance that can be used by a Vue app. -* -* @param options - {@link RouterOptions} -*/ -function createRouter(options) { - const matcher = createRouterMatcher(options.routes, options); - const parseQuery$1 = options.parseQuery || parseQuery; - const stringifyQuery$1 = options.stringifyQuery || stringifyQuery; - const routerHistory = options.history; - const beforeGuards = useCallbacks(); - const beforeResolveGuards = useCallbacks(); - const afterGuards = useCallbacks(); - const currentRoute = /* @__PURE__ */ shallowRef(START_LOCATION_NORMALIZED); - let pendingLocation = START_LOCATION_NORMALIZED; - if (isBrowser && options.scrollBehavior && "scrollRestoration" in history) history.scrollRestoration = "manual"; - const normalizeParams = applyToParams.bind(null, (paramValue) => "" + paramValue); - const encodeParams = applyToParams.bind(null, encodeParam); - const decodeParams = applyToParams.bind(null, decode); - function addRoute(parentOrRoute, route) { - let parent; - let record; - if (isRouteName(parentOrRoute)) { - parent = matcher.getRecordMatcher(parentOrRoute); - record = route; - } else record = parentOrRoute; - return matcher.addRoute(record, parent); - } - function removeRoute(name) { - const recordMatcher = matcher.getRecordMatcher(name); - if (recordMatcher) matcher.removeRoute(recordMatcher); - } - function getRoutes() { - return matcher.getRoutes().map((routeMatcher) => routeMatcher.record); - } - function hasRoute(name) { - return !!matcher.getRecordMatcher(name); - } - function resolve(rawLocation, currentLocation) { - currentLocation = assign({}, currentLocation || currentRoute.value); - if (typeof rawLocation === "string") { - const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path); - const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation); - const href = routerHistory.createHref(locationNormalized.fullPath); - return assign(locationNormalized, matchedRoute, { - params: decodeParams(matchedRoute.params), - redirectedFrom: void 0, - href - }); - } - let matcherLocation; - if (rawLocation.path != null) matcherLocation = assign({}, rawLocation, { path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path }); - else { - const targetParams = assign({}, rawLocation.params); - for (const key in targetParams) if (targetParams[key] == null) delete targetParams[key]; - matcherLocation = assign({}, rawLocation, { params: encodeParams(targetParams) }); - currentLocation.params = encodeParams(currentLocation.params); - } - const matchedRoute = matcher.resolve(matcherLocation, currentLocation); - const hash = rawLocation.hash || ""; - matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); - const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { - hash: encodeHash(hash), - path: matchedRoute.path - })); - const href = routerHistory.createHref(fullPath); - return assign({ - fullPath, - hash, - query: stringifyQuery$1 === stringifyQuery ? normalizeQuery(rawLocation.query) : rawLocation.query || {} - }, matchedRoute, { - redirectedFrom: void 0, - href - }); - } - function locationAsObject(to) { - return typeof to === "string" ? parseURL(parseQuery$1, to, currentRoute.value.path) : assign({}, to); - } - function checkCanceledNavigation(to, from) { - if (pendingLocation !== to) return createRouterError(ErrorTypes.NAVIGATION_CANCELLED, { - from, - to - }); - } - function push(to) { - return pushWithRedirect(to); - } - function replace(to) { - return push(assign(locationAsObject(to), { replace: true })); - } - function handleRedirectRecord(to, from) { - const lastMatched = to.matched[to.matched.length - 1]; - if (lastMatched && lastMatched.redirect) { - const { redirect } = lastMatched; - let newTargetLocation = typeof redirect === "function" ? redirect(to, from) : redirect; - if (typeof newTargetLocation === "string") { - newTargetLocation = newTargetLocation.includes("?") || newTargetLocation.includes("#") ? newTargetLocation = locationAsObject(newTargetLocation) : { path: newTargetLocation }; - newTargetLocation.params = {}; - } - return assign({ - query: to.query, - hash: to.hash, - params: newTargetLocation.path != null ? {} : to.params - }, newTargetLocation); - } - } - function pushWithRedirect(to, redirectedFrom) { - const targetLocation = pendingLocation = resolve(to); - const from = currentRoute.value; - const data = to.state; - const force = to.force; - const replace = to.replace === true; - const shouldRedirect = handleRedirectRecord(targetLocation, from); - if (shouldRedirect) return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: typeof shouldRedirect === "object" ? assign({}, data, shouldRedirect.state) : data, - force, - replace - }), redirectedFrom || targetLocation); - const toLocation = targetLocation; - toLocation.redirectedFrom = redirectedFrom; - let failure; - if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(ErrorTypes.NAVIGATION_DUPLICATED, { - to: toLocation, - from - }); - handleScroll(from, from, true, false); - } - return (failure ? Promise.resolve(failure) : navigate(toLocation, from)).catch((error) => isNavigationFailure(error) ? isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT) ? error : markAsReady(error) : triggerError(error, toLocation, from)).then((failure) => { - if (failure) { - if (isNavigationFailure(failure, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) return pushWithRedirect(assign({ replace }, locationAsObject(failure.to), { - state: typeof failure.to === "object" ? assign({}, data, failure.to.state) : data, - force - }), redirectedFrom || toLocation); - } else failure = finalizeNavigation(toLocation, from, true, replace, data); - triggerAfterEach(toLocation, from, failure); - return failure; - }); - } - /** - * Helper to reject and skip all navigation guards if a new navigation happened - * @param to - * @param from - */ - function checkCanceledNavigationAndReject(to, from) { - const error = checkCanceledNavigation(to, from); - return error ? Promise.reject(error) : Promise.resolve(); - } - function runWithContext(fn) { - const app = installedApps.values().next().value; - return app && typeof app.runWithContext === "function" ? app.runWithContext(fn) : fn(); - } - function navigate(to, from) { - let guards; - const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from); - guards = extractComponentsGuards(leavingRecords.reverse(), "beforeRouteLeave", to, from); - for (const record of leavingRecords) record.leaveGuards.forEach((guard) => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards).then(() => { - guards = []; - for (const guard of beforeGuards.list()) guards.push(guardToPromiseFn(guard, to, from)); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }).then(() => { - guards = extractComponentsGuards(updatingRecords, "beforeRouteUpdate", to, from); - for (const record of updatingRecords) record.updateGuards.forEach((guard) => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }).then(() => { - guards = []; - for (const record of enteringRecords) if (record.beforeEnter) if (isArray$1(record.beforeEnter)) for (const beforeEnter of record.beforeEnter) guards.push(guardToPromiseFn(beforeEnter, to, from)); - else guards.push(guardToPromiseFn(record.beforeEnter, to, from)); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }).then(() => { - to.matched.forEach((record) => record.enterCallbacks = {}); - guards = extractComponentsGuards(enteringRecords, "beforeRouteEnter", to, from, runWithContext); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }).then(() => { - guards = []; - for (const guard of beforeResolveGuards.list()) guards.push(guardToPromiseFn(guard, to, from)); - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }).catch((err) => isNavigationFailure(err, ErrorTypes.NAVIGATION_CANCELLED) ? err : Promise.reject(err)); - } - function triggerAfterEach(to, from, failure) { - afterGuards.list().forEach((guard) => runWithContext(() => guard(to, from, failure))); - } - /** - * - Cleans up any navigation guards - * - Changes the url if necessary - * - Calls the scrollBehavior - */ - function finalizeNavigation(toLocation, from, isPush, replace, data) { - const error = checkCanceledNavigation(toLocation, from); - if (error) return error; - const isFirstNavigation = from === START_LOCATION_NORMALIZED; - const state = !isBrowser ? {} : history.state; - if (isPush) if (replace || isFirstNavigation) routerHistory.replace(toLocation.fullPath, assign({ scroll: isFirstNavigation && state && state.scroll }, data)); - else routerHistory.push(toLocation.fullPath, data); - currentRoute.value = toLocation; - handleScroll(toLocation, from, isPush, isFirstNavigation); - markAsReady(); - } - let removeHistoryListener; - function setupListeners() { - if (removeHistoryListener) return; - removeHistoryListener = routerHistory.listen((to, _from, info) => { - if (!router.listening) return; - const toLocation = resolve(to); - const shouldRedirect = handleRedirectRecord(toLocation, router.currentRoute.value); - if (shouldRedirect) { - pushWithRedirect(assign(shouldRedirect, { - replace: true, - force: true - }), toLocation).catch(noop$1); - return; - } - pendingLocation = toLocation; - const from = currentRoute.value; - if (isBrowser) saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition()); - navigate(toLocation, from).catch((error) => { - if (isNavigationFailure(error, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_CANCELLED)) return error; - if (isNavigationFailure(error, ErrorTypes.NAVIGATION_GUARD_REDIRECT)) { - pushWithRedirect(assign(locationAsObject(error.to), { force: true }), toLocation).then((failure) => { - if (isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED) && !info.delta && info.type === NavigationType.pop) routerHistory.go(-1, false); - }).catch(noop$1); - return Promise.reject(); - } - if (info.delta) routerHistory.go(-info.delta, false); - return triggerError(error, toLocation, from); - }).then((failure) => { - failure = failure || finalizeNavigation(toLocation, from, false); - if (failure) { - if (info.delta && !isNavigationFailure(failure, ErrorTypes.NAVIGATION_CANCELLED)) routerHistory.go(-info.delta, false); - else if (info.type === NavigationType.pop && isNavigationFailure(failure, ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED)) routerHistory.go(-1, false); - } - triggerAfterEach(toLocation, from, failure); - }).catch(noop$1); - }); - } - let readyHandlers = useCallbacks(); - let errorListeners = useCallbacks(); - let ready; - /** - * Trigger errorListeners added via onError and throws the error as well - * - * @param error - error to throw - * @param to - location we were navigating to when the error happened - * @param from - location we were navigating from when the error happened - * @returns the error as a rejected promise - */ - function triggerError(error, to, from) { - markAsReady(error); - const list = errorListeners.list(); - if (list.length) list.forEach((handler) => handler(error, to, from)); - else console.error(error); - return Promise.reject(error); - } - function isReady() { - if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) return Promise.resolve(); - return new Promise((resolve, reject) => { - readyHandlers.add([resolve, reject]); - }); - } - function markAsReady(err) { - if (!ready) { - ready = !err; - setupListeners(); - readyHandlers.list().forEach(([resolve, reject]) => err ? reject(err) : resolve()); - readyHandlers.reset(); - } - return err; - } - function handleScroll(to, from, isPush, isFirstNavigation) { - const { scrollBehavior } = options; - if (!isBrowser || !scrollBehavior) return Promise.resolve(); - const scrollPosition = !isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0)) || (isFirstNavigation || !isPush) && history.state && history.state.scroll || null; - return nextTick().then(() => scrollBehavior(to, from, scrollPosition)).then((position) => position && scrollToPosition(position)).catch((err) => triggerError(err, to, from)); - } - const go = (delta) => routerHistory.go(delta); - let started; - const installedApps = /* @__PURE__ */ new Set(); - const router = { - currentRoute, - listening: true, - addRoute, - removeRoute, - clearRoutes: matcher.clearRoutes, - hasRoute, - getRoutes, - resolve, - options, - push, - replace, - go, - back: () => go(-1), - forward: () => go(1), - beforeEach: beforeGuards.add, - beforeResolve: beforeResolveGuards.add, - afterEach: afterGuards.add, - onError: errorListeners.add, - isReady, - install(app) { - app.component("RouterLink", RouterLink); - app.component("RouterView", RouterView); - app.config.globalProperties.$router = router; - Object.defineProperty(app.config.globalProperties, "$route", { - enumerable: true, - get: () => unref(currentRoute) - }); - if (isBrowser && !started && currentRoute.value === START_LOCATION_NORMALIZED) { - started = true; - push(routerHistory.location).catch((err) => {}); - } - const reactiveRoute = {}; - for (const key in START_LOCATION_NORMALIZED) Object.defineProperty(reactiveRoute, key, { - get: () => currentRoute.value[key], - enumerable: true - }); - app.provide(routerKey, router); - app.provide(routeLocationKey, /* @__PURE__ */ shallowReactive(reactiveRoute)); - app.provide(routerViewLocationKey, currentRoute); - const unmountApp = app.unmount; - installedApps.add(app); - app.unmount = function() { - installedApps.delete(app); - if (installedApps.size < 1) { - pendingLocation = START_LOCATION_NORMALIZED; - removeHistoryListener && removeHistoryListener(); - removeHistoryListener = null; - currentRoute.value = START_LOCATION_NORMALIZED; - started = false; - ready = false; - } - unmountApp(); - }; - } - }; - function runGuardQueue(guards) { - return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve()); - } - return router; -} -"" + new URL("logo.C_e3UAcl.png", import.meta.url).href; -//#endregion -//#region node_modules/axios/lib/helpers/bind.js -/** -* Create a bound version of a function with a specified `this` context -* -* @param {Function} fn - The function to bind -* @param {*} thisArg - The value to be passed as the `this` parameter -* @returns {Function} A new function that will call the original function with the specified `this` context -*/ -function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; -} -//#endregion -//#region node_modules/axios/lib/utils.js -var { toString } = Object.prototype; -var { getPrototypeOf } = Object; -var { iterator, toStringTag } = Symbol; -var hasOwnProperty = (({ hasOwnProperty }) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); -var isUnsafeObjectKey = (prop) => typeof prop === "string" && (prop === "__proto__" || prop === "constructor" || prop === "prototype"); -/** -* Determine whether an inherited object must be treated as a shared-prototype -* boundary. Cross-realm Object.prototype objects cannot be distinguished -* reliably from application-created null-prototype objects because their -* properties are mutable, so all inherited terminal prototypes are excluded -* as a fail-closed boundary. A null-prototype source still keeps its own -* properties, as produced by mergeConfig and other safe materialization paths. -* -* @param {*} obj The object to inspect -* @param {*} prototype The object's prototype -* @param {boolean} source Whether obj is the original traversal source -* -* @returns {boolean} True when obj is a safe prototype traversal boundary -*/ -var isPrototypeBoundary = (obj, prototype, source) => obj === Object.prototype || !source && prototype === null; -/** -* Determine whether an object can retain its identity through code paths that -* add, replace, and remove config properties without bypassing unsafe-key -* filtering. Immutable objects, unsafe-key-bearing objects, and objects with -* accessor or restricted data properties must be materialized instead. -* -* @param {*} obj The object to inspect -* -* @returns {boolean} True when every own property is safe and fully mutable -*/ -var isSafeAndFullyMutable = (obj) => { - if (!Object.isExtensible(obj)) return false; - const props = Object.getOwnPropertyNames(obj); - if (Object.getOwnPropertySymbols) props.push(...Object.getOwnPropertySymbols(obj)); - return props.every((prop) => { - if (isUnsafeObjectKey(prop)) return false; - const descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!descriptor && descriptor.configurable && descriptor.writable === true; - }); -}; -/** -* Walk the prototype chain (excluding the source realm's Object.prototype) -* looking for an own `prop`. This distinguishes genuine own/inherited members -* — including class accessors and template prototypes — from members injected -* via Object.prototype pollution (e.g. `Object.prototype.username = '...'`), -* which live on Object.prototype itself and are therefore never matched. -* -* @param {*} thing The value whose chain to inspect -* @param {string|symbol} prop The property key to look for -* -* @returns {boolean} True when `prop` is owned below Object.prototype -*/ -var hasOwnInPrototypeChain = (thing, prop) => { - let obj = thing; - const seen = []; - while (obj != null) { - if (seen.indexOf(obj) !== -1) return false; - seen.push(obj); - const prototype = getPrototypeOf(obj); - if (isPrototypeBoundary(obj, prototype, obj === thing)) return false; - if (hasOwnProperty(obj, prop)) return true; - obj = prototype; - } - return false; -}; -/** -* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own -* properties and members inherited from a non-Object.prototype source (a class -* instance or template object) are honored; a value reachable only through a -* polluted Object.prototype is ignored and `undefined` is returned. -* -* @param {*} obj The source object -* @param {string|symbol} prop The property key to read -* -* @returns {*} The resolved value, or undefined when unsafe/absent -*/ -var getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : void 0; -/** -* Flatten an object and its application-defined prototype chain into a -* null-prototype object. Members inherited only from the source realm's -* Object.prototype are deliberately excluded, while class/template members -* below that boundary are preserved. -* -* @param {*} thing The value to flatten -* -* @returns {*} A null-prototype copy, or the original value when it is already -* structurally safe or is not an object -*/ -var toSafeFlatObject = (thing) => { - if (thing == null || typeof thing !== "object" && typeof thing !== "function") return thing; - const sourcePrototype = getPrototypeOf(thing); - if (sourcePrototype === null && isSafeAndFullyMutable(thing)) return thing; - const result = Object.create(null); - const merged = Object.create(null); - const seen = []; - let current = thing; - while (current != null) { - if (seen.indexOf(current) !== -1) break; - seen.push(current); - const prototype = current === thing ? sourcePrototype : getPrototypeOf(current); - if (isPrototypeBoundary(current, prototype, current === thing)) break; - const props = Object.getOwnPropertyNames(current); - if (Object.getOwnPropertySymbols) props.push(...Object.getOwnPropertySymbols(current)); - for (const prop of props) { - if (isUnsafeObjectKey(prop)) continue; - if (!hasOwnProperty(merged, prop)) { - result[prop] = thing[prop]; - merged[prop] = true; - } - } - current = prototype; - } - return result; -}; -var kindOf = ((cache) => (thing) => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); -})(Object.create(null)); -var kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type; -}; -var typeOfTest = (type) => (thing) => typeof thing === type; -/** -* Determine if a value is a non-null object -* -* @param {Object} val The value to test -* -* @returns {boolean} True if value is an Array, otherwise false -*/ -var { isArray } = Array; -/** -* Determine if a value is undefined -* -* @param {*} val The value to test -* -* @returns {boolean} True if the value is undefined, otherwise false -*/ -var isUndefined = typeOfTest("undefined"); -/** -* Determine if a value is a Buffer -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a Buffer, otherwise false -*/ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val); -} -/** -* Determine if a value is an ArrayBuffer -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is an ArrayBuffer, otherwise false -*/ -var isArrayBuffer = kindOfTest("ArrayBuffer"); -/** -* Determine if a value is a view on an ArrayBuffer -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false -*/ -function isArrayBufferView(val) { - let result; - if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) result = ArrayBuffer.isView(val); - else result = val && val.buffer && isArrayBuffer(val.buffer); - return result; -} -/** -* Determine if a value is a String -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a String, otherwise false -*/ -var isString = typeOfTest("string"); -/** -* Determine if a value is a Function -* -* @param {*} val The value to test -* @returns {boolean} True if value is a Function, otherwise false -*/ -var isFunction$1 = typeOfTest("function"); -/** -* Determine if a value is a Number -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a Number, otherwise false -*/ -var isNumber = typeOfTest("number"); -/** -* Determine if a value is an Object -* -* @param {*} thing The value to test -* -* @returns {boolean} True if value is an Object, otherwise false -*/ -var isObject = (thing) => thing !== null && typeof thing === "object"; -/** -* Determine if a value is a Boolean -* -* @param {*} thing The value to test -* @returns {boolean} True if value is a Boolean, otherwise false -*/ -var isBoolean = (thing) => thing === true || thing === false; -/** -* Determine if a value is a plain Object -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a plain Object, otherwise false -*/ -var isPlainObject = (val) => { - if (!isObject(val)) return false; - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) && !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator); -}; -/** -* Determine if a value is an empty object (safely handles Buffers) -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is an empty object, otherwise false -*/ -var isEmptyObject = (val) => { - if (!isObject(val) || isBuffer(val)) return false; - try { - return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; - } catch (e) { - return false; - } -}; -/** -* Determine if a value is a Date -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a Date, otherwise false -*/ -var isDate = kindOfTest("Date"); -/** -* Determine if a value is a File -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a File, otherwise false -*/ -var isFile = kindOfTest("File"); -/** -* Determine if a value is a React Native Blob -* React Native "blob": an object with a `uri` attribute. Optionally, it can -* also have a `name` and `type` attribute to specify filename and content type -* -* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71 -* -* @param {*} value The value to test -* -* @returns {boolean} True if value is a React Native Blob, otherwise false -*/ -var isReactNativeBlob = (value) => { - return !!(value && typeof value.uri !== "undefined"); -}; -/** -* Determine if environment is React Native -* ReactNative `FormData` has a non-standard `getParts()` method -* -* @param {*} formData The formData to test -* -* @returns {boolean} True if environment is React Native, otherwise false -*/ -var isReactNative = (formData) => formData && typeof formData.getParts !== "undefined"; -/** -* Determine if a value is a Blob -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a Blob, otherwise false -*/ -var isBlob = kindOfTest("Blob"); -/** -* Determine if a value is a FileList -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a FileList, otherwise false -*/ -var isFileList = kindOfTest("FileList"); -var isSet = kindOfTest("Set"); -/** -* Determine if a value is a Stream -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a Stream, otherwise false -*/ -var isStream = (val) => isObject(val) && isFunction$1(val.pipe); -/** -* Determine if a value is a FormData -* -* @param {*} thing The value to test -* -* @returns {boolean} True if value is an FormData, otherwise false -*/ -function getGlobal() { - if (typeof globalThis !== "undefined") return globalThis; - if (typeof self !== "undefined") return self; - if (typeof window !== "undefined") return window; - if (typeof global !== "undefined") return global; - return {}; -} -var G = getGlobal(); -var FormDataCtor = typeof G.FormData !== "undefined" ? G.FormData : void 0; -var isFormData = (thing) => { - if (!thing) return false; - if (FormDataCtor && thing instanceof FormDataCtor) return true; - const proto = getPrototypeOf(thing); - if (!proto || proto === Object.prototype) return false; - if (!isFunction$1(thing.append)) return false; - const kind = kindOf(thing); - return kind === "formdata" || kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]"; -}; -/** -* Determine if a value is a URLSearchParams object -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a URLSearchParams object, otherwise false -*/ -var isURLSearchParams = kindOfTest("URLSearchParams"); -var [isReadableStream, isRequest, isResponse, isHeaders] = [ - "ReadableStream", - "Request", - "Response", - "Headers" -].map(kindOfTest); -/** -* Trim excess whitespace off the beginning and end of a string -* -* @param {String} str The String to trim -* -* @returns {String} The String freed of excess whitespace -*/ -var trim = (str) => { - return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); -}; -/** -* Iterate over an Array or an Object invoking a function for each item. -* -* If `obj` is an Array callback will be called passing -* the value, index, and complete array for each item. -* -* If 'obj' is an Object callback will be called passing -* the value, key, and complete object for each property. -* -* @param {Object|Array} obj The object to iterate -* @param {Function} fn The callback to invoke for each item -* -* @param {Object} [options] -* @param {Boolean} [options.allOwnKeys = false] -* @returns {any} -*/ -function forEach(obj, fn, { allOwnKeys = false } = {}) { - if (obj === null || typeof obj === "undefined") return; - let i; - let l; - if (typeof obj !== "object") obj = [obj]; - if (isArray(obj)) for (i = 0, l = obj.length; i < l; i++) fn.call(null, obj[i], i, obj); - else { - if (isBuffer(obj)) return; - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); - } - } -} -/** -* Finds a key in an object, case-insensitive, returning the actual key name. -* Returns null if the object is a Buffer or if no match is found. -* -* @param {Object} obj - The object to search. -* @param {string} key - The key to find (case-insensitive). -* @returns {?string} The actual key name if found, otherwise null. -*/ -function findKey(obj, key) { - if (isBuffer(obj)) return null; - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) return _key; - } - return null; -} -var _global = (() => { - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; -})(); -var isContextDefined = (context) => !isUndefined(context) && context !== _global; -/** -* Accepts varargs expecting each argument to be an object, then -* immutably merges the properties of each object and returns result. -* -* When multiple objects contain the same key the later object in -* the arguments list will take precedence. -* -* Example: -* -* ```js -* const result = merge({foo: 123}, {foo: 456}); -* console.log(result.foo); // outputs 456 -* ``` -* -* @param {Object} obj1 Object to merge -* -* @returns {Object} Result of all merge properties -*/ -function merge(...objs) { - const { caseless, skipUndefined } = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - if (key === "__proto__" || key === "constructor" || key === "prototype") return; - const targetKey = caseless && typeof key === "string" && findKey(result, key) || key; - const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : void 0; - if (isPlainObject(existing) && isPlainObject(val)) result[targetKey] = merge(existing, val); - else if (isPlainObject(val)) result[targetKey] = merge({}, val); - else if (isArray(val)) result[targetKey] = val.slice(); - else if (!skipUndefined || !isUndefined(val)) result[targetKey] = val; - }; - for (let i = 0, l = objs.length; i < l; i++) { - const source = objs[i]; - if (!source || isBuffer(source)) continue; - forEach(source, assignValue); - if (typeof source !== "object" || isArray(source)) continue; - const symbols = Object.getOwnPropertySymbols(source); - for (let j = 0; j < symbols.length; j++) { - const symbol = symbols[j]; - if (propertyIsEnumerable.call(source, symbol)) assignValue(source[symbol], symbol); - } - } - return result; -} -/** -* Extends object a by mutably adding to it the properties of object b. -* -* @param {Object} a The object to be extended -* @param {Object} b The object to copy properties from -* @param {Object} thisArg The object to bind function to -* -* @param {Object} [options] -* @param {Boolean} [options.allOwnKeys] -* @returns {Object} The resulting value of object a -*/ -var extend = (a, b, thisArg, { allOwnKeys } = {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction$1(val)) Object.defineProperty(a, key, { - __proto__: null, - value: bind(val, thisArg), - writable: true, - enumerable: true, - configurable: true - }); - else Object.defineProperty(a, key, { - __proto__: null, - value: val, - writable: true, - enumerable: true, - configurable: true - }); - }, { allOwnKeys }); - return a; -}; -/** -* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) -* -* @param {string} content with BOM -* -* @returns {string} content value without BOM -*/ -var stripBOM = (content) => { - if (content.charCodeAt(0) === 65279) content = content.slice(1); - return content; -}; -/** -* Inherit the prototype methods from one constructor into another -* @param {function} constructor -* @param {function} superConstructor -* @param {object} [props] -* @param {object} [descriptors] -* -* @returns {void} -*/ -var inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - Object.defineProperty(constructor.prototype, "constructor", { - __proto__: null, - value: constructor, - writable: true, - enumerable: false, - configurable: true - }); - Object.defineProperty(constructor, "super", { - __proto__: null, - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); -}; -/** -* Resolve object with deep prototype chain to a flat object -* @param {Object} sourceObj source object -* @param {Object} [destObj] -* @param {Function|Boolean} [filter] -* @param {Function} [propFilter] -* -* @returns {Object} -*/ -var toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - destObj = destObj || {}; - if (sourceObj == null) return destObj; - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - return destObj; -}; -/** -* Determines whether a string ends with the characters of a specified string -* -* @param {String} str -* @param {String} searchString -* @param {Number} [position= 0] -* -* @returns {boolean} -*/ -var endsWith = (str, searchString, position) => { - str = String(str); - if (position === void 0 || position > str.length) position = str.length; - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -}; -/** -* Returns new array from array like object or null if failed -* -* @param {*} [thing] -* -* @returns {?Array} -*/ -var toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) arr[i] = thing[i]; - return arr; -}; -/** -* Checking if the Uint8Array exists and if it does, it returns a function that checks if the -* thing passed in is an instance of Uint8Array -* -* @param {TypedArray} -* -* @returns {Array} -*/ -var isTypedArray = ((TypedArray) => { - return (thing) => { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); -/** -* For each entry in the object, call the function with the key and value. -* -* @param {Object} obj - The object to iterate over. -* @param {Function} fn - The function to call for each entry. -* -* @returns {void} -*/ -var forEachEntry = (obj, fn) => { - const _iterator = (obj && obj[iterator]).call(obj); - let result; - while ((result = _iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } -}; -/** -* It takes a regular expression and a string, and returns an array of all the matches -* -* @param {string} regExp - The regular expression to match against. -* @param {string} str - The string to search. -* -* @returns {Array} -*/ -var matchAll = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) arr.push(matches); - return arr; -}; -var isHTMLForm = kindOfTest("HTMLFormElement"); -var toCamelCase = (str) => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - }); -}; -var { propertyIsEnumerable } = Object.prototype; -/** -* Determine if a value is a RegExp object -* -* @param {*} val The value to test -* -* @returns {boolean} True if value is a RegExp object, otherwise false -*/ -var isRegExp = kindOfTest("RegExp"); -var reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) reducedDescriptors[name] = ret || descriptor; - }); - Object.defineProperties(obj, reducedDescriptors); -}; -/** -* Makes all methods read-only -* @param {Object} obj -*/ -var freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - if (isFunction$1(obj) && [ - "arguments", - "caller", - "callee" - ].includes(name)) return false; - const value = obj[name]; - if (!isFunction$1(value)) return; - descriptor.enumerable = false; - if ("writable" in descriptor) { - descriptor.writable = false; - return; - } - if (!descriptor.set) descriptor.set = () => { - throw Error("Can not rewrite read-only method '" + name + "'"); - }; - }); -}; -/** -* Converts an array or a delimited string into an object set with values as keys and true as values. -* Useful for fast membership checks. -* -* @param {Array|string} arrayOrString - The array or string to convert. -* @param {string} delimiter - The delimiter to use if input is a string. -* @returns {Object} An object with keys from the array or string, values set to true. -*/ -var toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - const define = (arr) => { - arr.forEach((value) => { - obj[value] = true; - }); - }; - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - return obj; -}; -var noop = () => {}; -var toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; -}; -/** -* If the thing is a FormData object, return true, otherwise return false. -* -* @param {unknown} thing - The thing to check. -* -* @returns {boolean} -*/ -function isSpecCompliantForm(thing) { - return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]); -} -/** -* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers. -* -* @param {Object} obj - The object to convert. -* @returns {Object} The JSON-compatible object. -*/ -var toJSONObject = (obj) => { - const visited = /* @__PURE__ */ new WeakSet(); - const visit = (source) => { - if (isObject(source)) { - if (visited.has(source)) return; - if (isBuffer(source)) return source; - if (!("toJSON" in source)) { - visited.add(source); - let target; - if (isSet(source)) { - target = []; - for (const value of source) { - const reducedValue = visit(value); - !isUndefined(reducedValue) && target.push(reducedValue); - } - } else { - target = isArray(source) ? [] : {}; - forEach(source, (value, key) => { - const reducedValue = visit(value); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - } - visited.delete(source); - return target; - } - } - return source; - }; - return visit(obj); -}; -/** -* Determines if a value is an async function. -* -* @param {*} thing - The value to test. -* @returns {boolean} True if value is an async function, otherwise false. -*/ -var isAsyncFn = kindOfTest("AsyncFunction"); -/** -* Determines if a value is thenable (has then and catch methods). -* -* @param {*} thing - The value to test. -* @returns {boolean} True if value is thenable, otherwise false. -*/ -var isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch); -/** -* Provides a cross-platform setImmediate implementation. -* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout. -* -* @param {boolean} setImmediateSupported - Whether setImmediate is supported. -* @param {boolean} postMessageSupported - Whether postMessage is supported. -* @returns {Function} A function to schedule a callback asynchronously. -*/ -var _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) return setImmediate; - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({ source, data }) => { - if (source === _global && data === token) callbacks.length && callbacks.shift()(); - }, false); - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); - }; - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})(typeof setImmediate === "function", isFunction$1(_global.postMessage)); -/** -* Schedules a microtask or asynchronous callback as soon as possible. -* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate. -* -* @type {Function} -*/ -var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate; -var isIterable = (thing) => thing != null && isFunction$1(thing[iterator]); -/** -* Determine if a value is iterable via an iterator that is NOT sourced solely -* from a polluted Object.prototype. Use this instead of `isIterable` whenever -* the iterable comes from untrusted input (e.g. user-supplied header sources), -* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object -* into an attacker-controlled entries iterator. -* -* @param {*} thing The value to test -* -* @returns {boolean} True if value has a non-polluted iterator -*/ -var isSafeIterable = (thing) => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing); -var utils_default = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isEmptyObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, - isUndefined, - isDate, - isFile, - isReactNativeBlob, - isReactNative, - isBlob, - isRegExp, - isFunction: isFunction$1, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, - hasOwnInPrototypeChain, - getSafeProp, - toSafeFlatObject, - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap, - isIterable, - isSafeIterable -}; -//#endregion -//#region node_modules/axios/lib/helpers/parseHeaders.js -var ignoreDuplicateOf = utils_default.toObjectSet([ - "age", - "authorization", - "content-length", - "content-type", - "etag", - "expires", - "from", - "host", - "if-modified-since", - "if-unmodified-since", - "last-modified", - "location", - "max-forwards", - "proxy-authorization", - "referer", - "retry-after", - "user-agent" -]); -/** -* Parse headers into an object -* -* ``` -* Date: Wed, 27 Aug 2014 08:58:49 GMT -* Content-Type: application/json -* Connection: keep-alive -* Transfer-Encoding: chunked -* ``` -* -* @param {String} rawHeaders Headers needing to be parsed -* -* @returns {Object} Headers parsed into an object -*/ -var parseHeaders_default = (rawHeaders) => { - const parsed = {}; - let key; - let val; - let i; - rawHeaders && rawHeaders.split("\n").forEach(function parser(line) { - i = line.indexOf(":"); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - const hasKey = utils_default.hasOwnProp(parsed, key); - if (!key || hasKey && utils_default.hasOwnProp(ignoreDuplicateOf, key)) return; - if (key === "set-cookie") if (hasKey) parsed[key].push(val); - else parsed[key] = [val]; - else parsed[key] = hasKey ? parsed[key] + ", " + val : val; - }); - return parsed; -}; -//#endregion -//#region node_modules/axios/lib/helpers/sanitizeHeaderValue.js -function trimSPorHTAB(str) { - let start = 0; - let end = str.length; - while (start < end) { - const code = str.charCodeAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - while (end > start) { - const code = str.charCodeAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === str.length ? str : str.slice(start, end); -} -var INVALID_UNICODE_HEADER_VALUE_CHARS = /* @__PURE__ */ new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+", "g"); -var INVALID_BYTE_STRING_HEADER_VALUE_CHARS = /* @__PURE__ */ new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+", "g"); -function sanitizeValue(value, invalidChars) { - if (utils_default.isArray(value)) return value.map((item) => sanitizeValue(item, invalidChars)); - return trimSPorHTAB(String(value).replace(invalidChars, "")); -} -var sanitizeHeaderValue = (value) => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS); -var sanitizeByteStringHeaderValue = (value) => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS); -function toByteStringHeaderObject(headers) { - const byteStringHeaders = Object.create(null); - utils_default.forEach(headers.toJSON(), (value, header) => { - byteStringHeaders[header] = sanitizeByteStringHeaderValue(value); - }); - return byteStringHeaders; -} -//#endregion -//#region node_modules/axios/lib/core/AxiosHeaders.js -var $internals$1 = Symbol("internals"); -function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); -} -function normalizeValue(value) { - if (value === false || value == null) return value; - return utils_default.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value)); -} -function parseTokens(str) { - const tokens = Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - while (match = tokensRE.exec(str)) tokens[match[1]] = match[2]; - return tokens; -} -var parameterNameRE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -function trimOWS(value) { - let start = 0; - let end = value.length; - while (start < end) { - const code = value.charCodeAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - while (end > start) { - const code = value.charCodeAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -function decodeQuotedString(value) { - const last = value.length - 1; - if (last < 1 || value.charCodeAt(0) !== 34 || value.charCodeAt(last) !== 34) return value; - let decoded = ""; - for (let i = 1; i < last; i++) { - const code = value.charCodeAt(i); - if (code === 34) return value; - if (code === 92) { - i += 1; - if (i >= last) return value; - } - decoded += value[i]; - } - return decoded; -} -function parseParameters(value) { - const parameters = Object.create(null); - const str = String(value); - let start = 0; - let quoted = false; - let escaped = false; - function parseParameter(end) { - const part = trimOWS(str.slice(start, end)); - const equals = part.indexOf("="); - if (equals < 1) return; - const name = trimOWS(part.slice(0, equals)); - if (!parameterNameRE.test(name)) return; - const normalizedName = name.toLowerCase(); - if (normalizedName === "__proto__" || normalizedName === "constructor" || normalizedName === "prototype") return; - parameters[normalizedName] = decodeQuotedString(trimOWS(part.slice(equals + 1))); - } - for (let i = 0; i < str.length; i++) { - const code = str.charCodeAt(i); - if (quoted) { - if (escaped) escaped = false; - else if (code === 92) escaped = true; - else if (code === 34) quoted = false; - } else if (code === 34) quoted = true; - else if (code === 44 || code === 59) { - parseParameter(i); - start = i + 1; - } - } - parseParameter(str.length); - return parameters; -} -var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); -function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils_default.isFunction(filter)) return filter.call(this, value, header); - if (isHeaderNameFilter) value = header; - if (!utils_default.isString(value)) return; - if (utils_default.isString(filter)) return value.indexOf(filter) !== -1; - if (utils_default.isRegExp(filter)) return filter.test(value); -} -function formatHeader(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { - return char.toUpperCase() + str; - }); -} -function buildAccessors(obj, header) { - const accessorName = utils_default.toCamelCase(" " + header); - [ - "get", - "set", - "has" - ].forEach((methodName) => { - Object.defineProperty(obj, methodName + accessorName, { - __proto__: null, - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); -} -var AxiosHeaders = class { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self = this; - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); - if (!lHeader) return; - const key = utils_default.findKey(self, lHeader); - if (!key || self[key] === void 0 || _rewrite === true || _rewrite === void 0 && self[key] !== false) self[key || _header] = normalizeValue(_value); - } - const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils_default.isPlainObject(header) || header instanceof this.constructor) setHeaders(header, valueOrRewrite); - else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) setHeaders(parseHeaders_default(header), valueOrRewrite); - else if (utils_default.isObject(header) && utils_default.isSafeIterable(header)) { - let obj = Object.create(null), dest, key; - for (const entry of header) { - if (!utils_default.isArray(entry)) throw new TypeError("Object iterator must return a key-value pair"); - key = entry[0]; - if (utils_default.hasOwnProp(obj, key)) { - dest = obj[key]; - obj[key] = utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]; - } else obj[key] = entry[1]; - } - setHeaders(obj, valueOrRewrite); - } else header != null && setHeader(valueOrRewrite, header, rewrite); - return this; - } - get(header, parser) { - header = normalizeHeader(header); - if (header) { - const key = utils_default.findKey(this, header); - if (key) { - const value = this[key]; - if (!parser) return value; - if (parser === true) return parseTokens(value); - if (utils_default.isFunction(parser)) return parser.call(this, value, key); - if (utils_default.isRegExp(parser)) return parser.exec(value); - throw new TypeError("parser must be boolean|regexp|function"); - } - } - } - has(header, matcher) { - header = normalizeHeader(header); - if (header) { - const key = utils_default.findKey(this, header); - return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } - return false; - } - delete(header, matcher) { - const self = this; - let deleted = false; - function deleteHeader(_header) { - _header = normalizeHeader(_header); - if (_header) { - const key = utils_default.findKey(self, _header); - if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { - delete self[key]; - deleted = true; - } - } - } - if (utils_default.isArray(header)) header.forEach(deleteHeader); - else deleteHeader(header); - return deleted; - } - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - while (i--) { - const key = keys[i]; - if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } - return deleted; - } - normalize(format) { - const self = this; - const headers = {}; - utils_default.forEach(this, (value, header) => { - const key = utils_default.findKey(headers, header); - if (key) { - self[key] = normalizeValue(value); - delete self[header]; - return; - } - const normalized = format ? formatHeader(header) : String(header).trim(); - if (normalized !== header) delete self[header]; - self[normalized] = normalizeValue(value); - headers[normalized] = true; - }); - return this; - } - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - toJSON(asStrings) { - const obj = Object.create(null); - utils_default.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); - }); - return obj; - } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); - } - getSetCookie() { - const value = this.get("set-cookie"); - return utils_default.isArray(value) ? value : value == null || value === false ? [] : [value]; - } - get [Symbol.toStringTag]() { - return "AxiosHeaders"; - } - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - static parseParameters(value) { - return parseParameters(value); - } - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); - return computed; - } - static accessor(header) { - const accessors = (this[$internals$1] = this[$internals$1] = { accessors: {} }).accessors; - const prototype = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype, _header); - accessors[lHeader] = true; - } - } - utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - return this; - } -}; -AxiosHeaders.accessor([ - "Content-Type", - "Content-Length", - "Accept", - "Accept-Encoding", - "User-Agent", - "Authorization" -]); -utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } - }; -}); -utils_default.freezeMethods(AxiosHeaders); -//#endregion -//#region node_modules/axios/lib/core/AxiosError.js -var REDACTED = "[REDACTED ****]"; -function hasOwnOrPrototypeToJSON(source) { - if (utils_default.hasOwnProp(source, "toJSON")) return true; - let prototype = Object.getPrototypeOf(source); - while (prototype && prototype !== Object.prototype) { - if (utils_default.hasOwnProp(prototype, "toJSON")) return true; - prototype = Object.getPrototypeOf(prototype); - } - return false; -} -function redactConfig(config, redactKeys) { - const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase())); - const seen = []; - const visit = (source) => { - if (source === null || typeof source !== "object") return source; - if (utils_default.isBuffer(source)) return source; - if (seen.indexOf(source) !== -1) return void 0; - if (source instanceof AxiosHeaders) source = source.toJSON(); - seen.push(source); - let result; - if (utils_default.isArray(source)) { - result = []; - source.forEach((v, i) => { - const reducedValue = visit(v); - if (!utils_default.isUndefined(reducedValue)) result[i] = reducedValue; - }); - } else { - if (!utils_default.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) { - seen.pop(); - return source; - } - result = Object.create(null); - for (const [key, value] of Object.entries(source)) { - const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value); - if (!utils_default.isUndefined(reducedValue)) result[key] = reducedValue; - } - } - seen.pop(); - return result; - }; - return visit(config); -} -function stringifySafely$1(value) { - try { - return String(value); - } catch (err) { - return ""; - } -} -function aggregateErrorMessage(error) { - return error.errors.map((entry) => { - try { - return entry && entry.message ? stringifySafely$1(entry.message) : stringifySafely$1(entry); - } catch (err) { - return ""; - } - }).filter(Boolean).join("; ") || error.name || "AggregateError"; -} -var AxiosError = class AxiosError extends Error { - static from(error, code, config, request, response, customProps) { - let message = error.message; - if (!message && utils_default.isArray(error.errors) && error.errors.length) message = aggregateErrorMessage(error); - const axiosError = new AxiosError(message, code || error.code, config, request, response); - Object.defineProperty(axiosError, "cause", { - __proto__: null, - value: error, - writable: true, - enumerable: false, - configurable: true - }); - axiosError.name = error.name; - if (error.status != null && axiosError.status == null) axiosError.status = error.status; - customProps && Object.assign(axiosError, customProps); - return axiosError; - } - /** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * - * @returns {Error} The created error. - */ - constructor(message, code, config, request, response) { - super(message); - Object.defineProperty(this, "message", { - __proto__: null, - value: message, - enumerable: true, - writable: true, - configurable: true - }); - this.name = "AxiosError"; - this.isAxiosError = true; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status; - } - } - toJSON() { - const config = this.config; - const redactKeys = config && utils_default.hasOwnProp(config, "redact") ? config.redact : void 0; - const serializedConfig = utils_default.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils_default.toJSONObject(config); - return { - message: this.message, - name: this.name, - description: this.description, - number: this.number, - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - config: serializedConfig, - code: this.code, - status: this.status - }; - } -}; -AxiosError.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE"; -AxiosError.ERR_BAD_OPTION = "ERR_BAD_OPTION"; -AxiosError.ECONNABORTED = "ECONNABORTED"; -AxiosError.ETIMEDOUT = "ETIMEDOUT"; -AxiosError.ECONNREFUSED = "ECONNREFUSED"; -AxiosError.ERR_NETWORK = "ERR_NETWORK"; -AxiosError.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS"; -AxiosError.ERR_DEPRECATED = "ERR_DEPRECATED"; -AxiosError.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE"; -AxiosError.ERR_BAD_REQUEST = "ERR_BAD_REQUEST"; -AxiosError.ERR_CANCELED = "ERR_CANCELED"; -AxiosError.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT"; -AxiosError.ERR_INVALID_URL = "ERR_INVALID_URL"; -AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = "ERR_FORM_DATA_DEPTH_EXCEEDED"; -/** -* Determines if the given thing is a array or js object. -* -* @param {string} thing - The object or array to be visited. -* -* @returns {boolean} -*/ -function isVisitable(thing) { - return utils_default.isPlainObject(thing) || utils_default.isArray(thing); -} -/** -* It removes the brackets from the end of a string -* -* @param {string} key - The key of the parameter. -* -* @returns {string} the key without the brackets. -*/ -function removeBrackets(key) { - return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; -} -/** -* It takes a path, a key, and a boolean, and returns a string -* -* @param {string} path - The path to the current key. -* @param {string} key - The key of the current object being iterated over. -* @param {string} dots - If true, the key will be rendered with dots instead of brackets. -* -* @returns {string} The path to the current key. -*/ -function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - token = removeBrackets(token); - return !dots && i ? "[" + token + "]" : token; - }).join(dots ? "." : ""); -} -/** -* If the array is an array and none of its elements are visitable, then it's a flat array. -* -* @param {Array} arr - The array to check -* -* @returns {boolean} -*/ -function isFlatArray(arr) { - return utils_default.isArray(arr) && !arr.some(isVisitable); -} -var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); -}); -/** -* Convert a data object to FormData -* -* @param {Object} obj -* @param {?Object} [formData] -* @param {?Object} [options] -* @param {Function} [options.visitor] -* @param {Boolean} [options.metaTokens = true] -* @param {Boolean} [options.dots = false] -* @param {?Boolean} [options.indexes = false] -* -* @returns {Object} -**/ -/** -* It converts an object into a FormData object -* -* @param {Object} obj - The object to convert to form data. -* @param {string} formData - The FormData object to append to. -* @param {Object} options -* -* @returns -*/ -function toFormData(obj, formData, options) { - if (!utils_default.isObject(obj)) throw new TypeError("target must be an object"); - formData = formData || new FormData(); - const option = (name, fallback) => { - const value = utils_default.getSafeProp(options, name); - return utils_default.isUndefined(value) ? fallback : value; - }; - const metaTokens = option("metaTokens", true); - const visitor = option("visitor") || defaultVisitor; - const dots = option("dots", false); - const indexes = option("indexes", false); - const _Blob = option("Blob") || typeof Blob !== "undefined" && Blob; - const maxDepth = option("maxDepth", 100); - const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); - const stack = []; - if (!utils_default.isFunction(visitor)) throw new TypeError("visitor must be a function"); - function convertValue(value) { - if (value === null) return ""; - if (utils_default.isDate(value)) return value.toISOString(); - if (utils_default.isBoolean(value)) return value.toString(); - if (!useBlob && utils_default.isBlob(value)) throw new AxiosError("Blob is not supported. Use a Buffer instead."); - if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { - if (useBlob && typeof _Blob === "function") return new _Blob([value]); - throw new AxiosError("Blob is not supported. Use a Buffer instead.", AxiosError.ERR_NOT_SUPPORT); - } - return value; - } - function throwIfMaxDepthExceeded(depth) { - if (depth > maxDepth) throw new AxiosError("Object is too deeply nested (" + depth + " levels). Max depth: " + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED); - } - function stringifyWithDepthLimit(value, depth) { - if (maxDepth === Infinity) return JSON.stringify(value); - const ancestors = []; - return JSON.stringify(value, function limitDepth(_key, currentValue) { - if (!utils_default.isObject(currentValue)) return currentValue; - while (ancestors.length && ancestors[ancestors.length - 1] !== this) ancestors.pop(); - ancestors.push(currentValue); - throwIfMaxDepthExceeded(depth + ancestors.length - 1); - return currentValue; - }); - } - /** - * Default visitor. - * - * @param {*} value - * @param {String|Number} key - * @param {Array} path - * @this {FormData} - * - * @returns {boolean} return true to visit the each prop of the value recursively - */ - function defaultVisitor(value, key, path) { - let arr = value; - if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) { - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } - if (value && !path && typeof value === "object") { - if (utils_default.endsWith(key, "{}")) { - key = metaTokens ? key : key.slice(0, -2); - value = stringifyWithDepthLimit(value, 1); - } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { - key = removeBrackets(key); - arr.forEach(function each(el, index) { - !(utils_default.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el)); - }); - return false; - } - } - if (isVisitable(value)) return true; - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - function build(value, path, depth = 0) { - if (utils_default.isUndefined(value)) return; - throwIfMaxDepthExceeded(depth); - if (stack.indexOf(value) !== -1) throw new Error("Circular reference detected in " + path.join(".")); - stack.push(value); - utils_default.forEach(value, function each(el, key) { - if ((!(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path, exposedHelpers)) === true) build(el, path ? path.concat(key) : [key], depth + 1); - }); - stack.pop(); - } - if (!utils_default.isObject(obj)) throw new TypeError("data must be an object"); - build(obj); - return formData; -} -//#endregion -//#region node_modules/axios/lib/helpers/AxiosURLSearchParams.js -/** -* It encodes a string by replacing all characters that are not in the unreserved set with -* their percent-encoded equivalents -* -* @param {string} str - The string to encode. -* -* @returns {string} The encoded string. -*/ -function encode$1(str) { - const charMap = { - "!": "%21", - "'": "%27", - "(": "%28", - ")": "%29", - "~": "%7E", - "%20": "+" - }; - return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) { - return charMap[match]; - }); -} -/** -* It takes a params object and converts it to a FormData object -* -* @param {Object} params - The parameters to be converted to a FormData object. -* @param {Object} options - The options object passed to the Axios constructor. -* -* @returns {void} -*/ -function AxiosURLSearchParams(params, options) { - this._pairs = []; - params && toFormData(params, this, options); -} -var prototype = AxiosURLSearchParams.prototype; -prototype.append = function append(name, value) { - this._pairs.push([name, value]); -}; -prototype.toString = function toString(encoder) { - const _encode = encoder ? (value) => encoder.call(this, value, encode$1) : encode$1; - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + "=" + _encode(pair[1]); - }, "").join("&"); -}; -//#endregion -//#region node_modules/axios/lib/helpers/buildURL.js -/** -* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with -* their plain counterparts (`:`, `$`, `,`, `+`). -* -* @param {string} val The value to be encoded. -* -* @returns {string} The encoded value. -*/ -function encode(val) { - return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+"); -} -/** -* Build a URL by appending params to the end -* -* @param {string} url The base of the url (e.g., http://www.google.com) -* @param {object} [params] The params to be appended -* @param {?(object|Function)} options -* -* @returns {string} The formatted url -*/ -function buildURL(url, params, options) { - if (!params) return url; - url = url || ""; - const _options = utils_default.isFunction(options) ? { serialize: options } : options; - const _encode = utils_default.getSafeProp(_options, "encode") || encode; - const serializeFn = utils_default.getSafeProp(_options, "serialize"); - let serializedParams; - if (serializeFn) serializedParams = serializeFn(params, _options); - else serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode); - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); - if (hashmarkIndex !== -1) url = url.slice(0, hashmarkIndex); - url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; - } - return url; -} -//#endregion -//#region node_modules/axios/lib/core/InterceptorManager.js -var $internals = Symbol("internals"); -function countHandlers(handlers) { - return handlers ? handlers.length : 0; -} -function trimHandlers(handlers) { - if (!handlers) return; - while (handlers.length && handlers[handlers.length - 1] === null) handlers.pop(); -} -function syncHandlerEntries(manager, internals) { - const handlers = manager.handlers; - const length = countHandlers(handlers); - if (handlers !== internals.handlersRef) { - internals.handlersRef = handlers; - internals.handlerEntries.clear(); - } else if (length !== internals.handlersLength) if (!length) internals.handlerEntries.clear(); - else internals.handlerEntries.forEach(function removeStaleEntry(entry, id) { - if (handlers[entry.index] !== entry.handler) internals.handlerEntries.delete(id); - }); - internals.handlersLength = length; -} -var InterceptorManager = class { - constructor() { - this.handlers = []; - this[$internals] = { - handlersRef: this.handlers, - handlersLength: this.handlers.length, - handlerEntries: /* @__PURE__ */ new Map(), - iterationDepth: 0, - nextId: 0 - }; - } - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * @param {Object} options The options for the interceptor, synchronous and runWhen - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - const handler = { - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }; - const internals = this[$internals]; - if (this.handlers == null) this.handlers = []; - syncHandlerEntries(this, internals); - const id = internals.nextId++; - this.handlers.push(handler); - internals.handlerEntries.set(id, { - handler, - index: this.handlers.length - 1 - }); - internals.handlersLength = this.handlers.length; - return id; - } - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {void} - */ - eject(id) { - const internals = this[$internals]; - syncHandlerEntries(this, internals); - const entry = internals.handlerEntries.get(id); - if (entry) { - internals.handlerEntries.delete(id); - if (this.handlers[entry.index] !== entry.handler) return; - this.handlers[entry.index] = null; - if (!internals.iterationDepth) { - trimHandlers(this.handlers); - internals.handlersLength = this.handlers.length; - } - } - } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; - syncHandlerEntries(this, this[$internals]); - } - } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - const internals = this[$internals]; - syncHandlerEntries(this, internals); - internals.iterationDepth++; - try { - utils_default.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) fn(h); - }); - } finally { - if (!--internals.iterationDepth) { - syncHandlerEntries(this, internals); - trimHandlers(this.handlers); - internals.handlersLength = countHandlers(this.handlers); - } - } - } -}; -//#endregion -//#region node_modules/axios/lib/defaults/transitional.js -var transitional_default = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false, - legacyInterceptorReqResOrdering: true, - advertiseZstdAcceptEncoding: false, - validateStatusUndefinedResolves: true -}; -//#endregion -//#region node_modules/axios/lib/platform/browser/index.js -var browser_default = { - isBrowser: true, - classes: { - URLSearchParams: typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams, - FormData: typeof FormData !== "undefined" ? FormData : null, - Blob: typeof Blob !== "undefined" ? Blob : null - }, - protocols: [ - "http", - "https", - "file", - "blob", - "url", - "data" - ] -}; -//#endregion -//#region node_modules/axios/lib/platform/common/utils.js -var utils_exports = /* @__PURE__ */ __exportAll({ - hasBrowserEnv: () => hasBrowserEnv, - hasStandardBrowserEnv: () => hasStandardBrowserEnv, - hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv, - navigator: () => _navigator, - origin: () => origin -}); -var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined"; -var _navigator = typeof navigator === "object" && navigator || void 0; -/** -* Determine if we're running in a standard browser environment -* -* This allows axios to run in a web worker, and react-native. -* Both environments support XMLHttpRequest, but not fully standard globals. -* -* web workers: -* typeof window -> undefined -* typeof document -> undefined -* -* react-native: -* navigator.product -> 'ReactNative' -* nativescript -* navigator.product -> 'NativeScript' or 'NS' -* -* @returns {boolean} -*/ -var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || [ - "ReactNative", - "NativeScript", - "NS" -].indexOf(_navigator.product) < 0); -/** -* Determine if we're running in a standard browser webWorker environment -* -* Although the `isStandardBrowserEnv` method indicates that -* `allows axios to run in a web worker`, the WebWorker will still be -* filtered out due to its judgment standard -* `typeof window !== 'undefined' && typeof document !== 'undefined'`. -* This leads to a problem when axios post `FormData` in webWorker -*/ -var hasStandardBrowserWebWorkerEnv = (() => { - return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; -})(); -var origin = hasBrowserEnv && window.location.href || "http://localhost"; -//#endregion -//#region node_modules/axios/lib/platform/index.js -var platform_default = _objectSpread2(_objectSpread2({}, utils_exports), browser_default); -//#endregion -//#region node_modules/axios/lib/helpers/toURLEncodedForm.js -function toURLEncodedForm(data, options) { - return toFormData(data, new platform_default.classes.URLSearchParams(), _objectSpread2({ visitor: function(value, key, path, helpers) { - if (platform_default.isNode && utils_default.isBuffer(value)) { - this.append(key, value.toString("base64")); - return false; - } - return helpers.defaultVisitor.apply(this, arguments); - } }, options)); -} -//#endregion -//#region node_modules/axios/lib/helpers/formDataToJSON.js -var MAX_DEPTH = 100; -function throwIfDepthExceeded(index) { - if (index > MAX_DEPTH) throw new AxiosError("FormData field is too deeply nested (" + index + " levels). Max depth: " + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED); -} -/** -* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] -* -* @param {string} name - The name of the property to get. -* -* @returns An array of strings. -*/ -function parsePropPath(name) { - const path = []; - const pattern = /[^.[\]]+|\[([^.[\]]*)]/g; - let match; - while ((match = pattern.exec(name)) !== null) { - throwIfDepthExceeded(path.length); - path.push(match[0] === "[]" ? "" : match[1] || match[0]); - } - return path; -} -/** -* Convert an array to an object. -* -* @param {Array} arr - The array to convert to an object. -* -* @returns An object with the same keys and values as the array. -*/ -function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; -} -/** -* It takes a FormData object and returns a JavaScript object -* -* @param {string} formData The FormData object to convert to JSON. -* -* @returns {Object | null} The converted object. -*/ -function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - throwIfDepthExceeded(index); - let name = path[index++]; - if (name === "__proto__") return true; - const isNumericKey = Number.isFinite(+name); - const isLast = index >= path.length; - name = !name && utils_default.isArray(target) ? target.length : name; - if (isLast) { - if (utils_default.hasOwnProp(target, name)) target[name] = utils_default.isArray(target[name]) ? target[name].concat(value) : [target[name], value]; - else target[name] = value; - return !isNumericKey; - } - if (!utils_default.hasOwnProp(target, name) || !utils_default.isObject(target[name])) target[name] = []; - if (buildPath(path, value, target[name], index) && utils_default.isArray(target[name])) target[name] = arrayToObject(target[name]); - return !isNumericKey; - } - if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { - const obj = {}; - utils_default.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); - return obj; - } - return null; -} -//#endregion -//#region node_modules/axios/lib/core/methodList.js -var methodList = Object.freeze([ - "get", - "delete", - "head", - "options", - "post", - "put", - "patch", - "purge", - "link", - "unlink", - "query" -]); -//#endregion -//#region node_modules/axios/lib/defaults/index.js -var own = (obj, key) => obj != null && utils_default.hasOwnProp(obj, key) ? obj[key] : void 0; -/** -* It takes a string, tries to parse it, and if it fails, it returns the stringified version -* of the input -* -* @param {any} rawValue - The value to be stringified. -* @param {Function} parser - A function that parses a string into a JavaScript object. -* @param {Function} encoder - A function that takes a value and returns a string. -* -* @returns {string} A stringified version of the rawValue. -*/ -function stringifySafely(rawValue, parser, encoder) { - if (utils_default.isString(rawValue)) try { - (parser || JSON.parse)(rawValue); - return utils_default.trim(rawValue); - } catch (e) { - if (e.name !== "SyntaxError") throw e; - } - return (encoder || JSON.stringify)(rawValue); -} -var defaults = { - transitional: transitional_default, - adapter: [ - "xhr", - "http", - "fetch" - ], - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ""; - const hasJSONContentType = contentType.indexOf("application/json") > -1; - const isObjectPayload = utils_default.isObject(data); - if (isObjectPayload && utils_default.isHTMLForm(data)) data = new FormData(data); - if (utils_default.isFormData(data)) return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) return data; - if (utils_default.isArrayBufferView(data)) return data.buffer; - if (utils_default.isURLSearchParams(data)) { - headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); - return data.toString(); - } - let isFileList; - if (isObjectPayload) { - const formSerializer = own(this, "formSerializer"); - if (contentType.indexOf("application/x-www-form-urlencoded") > -1) return toURLEncodedForm(data, formSerializer).toString(); - if ((isFileList = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { - const env = own(this, "env"); - const _FormData = env && env.FormData; - return toFormData(isFileList ? { "files[]": data } : data, _FormData && new _FormData(), formSerializer); - } - } - if (isObjectPayload || hasJSONContentType) { - headers.setContentType("application/json", false); - return stringifySafely(data); - } - return data; - }], - transformResponse: [function transformResponse(data) { - const transitional = own(this, "transitional") || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const responseType = own(this, "responseType"); - const JSONRequested = responseType === "json"; - if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) return data; - if (data && utils_default.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) { - const strictJSONParsing = !(transitional && transitional.silentJSONParsing) && JSONRequested; - try { - return JSON.parse(data, own(this, "parseReviver")); - } catch (e) { - if (strictJSONParsing) { - if (e.name === "SyntaxError") throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, "response")); - throw e; - } - } - } - return data; - }], - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - xsrfCookieName: "XSRF-TOKEN", - xsrfHeaderName: "X-XSRF-TOKEN", - maxContentLength: -1, - maxBodyLength: -1, - env: { - FormData: platform_default.classes.FormData, - Blob: platform_default.classes.Blob - }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - headers: { common: { - Accept: "application/json, text/plain, */*", - "Content-Type": void 0 - } } -}; -utils_default.forEach(methodList, (method) => { - defaults.headers[method] = {}; -}); -//#endregion -//#region node_modules/axios/lib/core/transformData.js -/** -* Transform the data for a request or a response -* -* @param {Array|Function} fns A single function or Array of functions -* @param {?Object} response The response object -* -* @returns {*} The resulting transformed data -*/ -function transformData(fns, response) { - const config = this || defaults; - const context = response || config; - const headers = AxiosHeaders.from(context.headers); - let data = context.data; - utils_default.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); - }); - headers.normalize(); - return data; -} -//#endregion -//#region node_modules/axios/lib/cancel/isCancel.js -function isCancel(value) { - return !!(value && value.__CANCEL__); -} -//#endregion -//#region node_modules/axios/lib/cancel/CanceledError.js -var CanceledError = class extends AxiosError { - /** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. - */ - constructor(message, config, request) { - super(message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request); - this.name = "CanceledError"; - this.__CANCEL__ = true; - } -}; -//#endregion -//#region node_modules/axios/lib/core/settle.js -/** -* Resolve or reject a Promise based on response status. -* -* @param {Function} resolve A function that resolves the promise. -* @param {Function} reject A function that rejects the promise. -* @param {object} response The response. -* -* @returns {object} The response. -*/ -function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) resolve(response); - else reject(new AxiosError("Request failed with status code " + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response)); -} -//#endregion -//#region node_modules/axios/lib/helpers/normalizeURLForProtocolCheck.js -var urlParserControlCharacters = /[\t\n\r]/g; -/** -* Match WHATWG URL preprocessing before checking a URL's protocol. -* -* @param {string} url -* -* @returns {string} -*/ -function normalizeURLForProtocolCheck(url) { - if (typeof url !== "string") return url; - let start = 0; - while (start < url.length && url.charCodeAt(start) <= 32) start++; - return url.slice(start).replace(urlParserControlCharacters, ""); -} -//#endregion -//#region node_modules/axios/lib/helpers/parseProtocol.js -function parseProtocol(url) { - const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url); - return match && match[1] || ""; -} -//#endregion -//#region node_modules/axios/lib/helpers/speedometer.js -/** -* Calculate data maxRate -* @param {Number} [samplesCount= 10] -* @param {Number} [min= 1000] -* @returns {Function} -*/ -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== void 0 ? min : 1e3; - return function push(chunkLength) { - const now = Date.now(); - const startedAt = timestamps[tail]; - if (!firstSampleTS) firstSampleTS = now; - bytes[head] = chunkLength; - timestamps[head] = now; - let i = tail; - let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } - head = (head + 1) % samplesCount; - if (head === tail) tail = (tail + 1) % samplesCount; - if (now - firstSampleTS < min) return; - const passed = startedAt && now - startedAt; - return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; - }; -} -//#endregion -//#region node_modules/axios/lib/helpers/throttle.js -/** -* Throttle decorator -* @param {Function} fn -* @param {Number} freq -* @return {Array} -*/ -function throttle(fn, freq) { - let timestamp = 0; - let threshold = 1e3 / freq; - let lastArgs; - let timer; - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; - } - fn(...args); - }; - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if (passed >= threshold) invoke(args, now); - else { - lastArgs = args; - if (!timer) timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); - } - }; - const flush = () => lastArgs && invoke(lastArgs); - const flushWith = (...args) => invoke(args); - return [ - throttled, - flush, - flushWith - ]; -} -//#endregion -//#region node_modules/axios/lib/helpers/progressEventReducer.js -var progressEventReducer = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - return throttle((e) => { - if (!e || !utils_default.isNumber(e.loaded)) return; - const rawLoaded = e.loaded; - const total = e.lengthComputable ? e.total : void 0; - const loaded = Math.max(0, total != null ? Math.min(rawLoaded, total) : rawLoaded); - const progressBytes = Math.max(0, loaded - bytesNotified); - const rate = _speedometer(progressBytes); - bytesNotified = Math.max(bytesNotified, loaded); - listener({ - loaded, - total, - progress: total ? loaded / total : void 0, - bytes: progressBytes, - rate: rate ? rate : void 0, - estimated: rate && total ? (total - loaded) / rate : void 0, - event: e, - lengthComputable: total != null, - [isDownloadStream ? "download" : "upload"]: true - }); - }, freq); -}; -var progressEventDecorator = (total, throttled) => { - const lengthComputable = total != null; - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; -}; -var asyncDecorator = (fn, scheduler = utils_default.asap) => (...args) => scheduler(() => fn(...args)); -//#endregion -//#region node_modules/axios/lib/helpers/isURLSameOrigin.js -var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { - url = new URL(url, platform_default.origin); - return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port); -})(new URL(platform_default.origin), platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)) : () => true; -//#endregion -//#region node_modules/axios/lib/helpers/cookies.js -var cookies_default = platform_default.hasStandardBrowserEnv ? { - write(name, value, expires, path, domain, secure, sameSite) { - if (typeof document === "undefined") return; - const cookie = [`${name}=${encodeURIComponent(value)}`]; - if (utils_default.isNumber(expires)) cookie.push(`expires=${new Date(expires).toUTCString()}`); - if (utils_default.isString(path)) cookie.push(`path=${path}`); - if (utils_default.isString(domain)) cookie.push(`domain=${domain}`); - if (secure === true) cookie.push("secure"); - if (utils_default.isString(sameSite)) cookie.push(`SameSite=${sameSite}`); - document.cookie = cookie.join("; "); - }, - read(name) { - if (typeof document === "undefined") return null; - const cookies = document.cookie.split(";"); - for (let i = 0; i < cookies.length; i++) { - const cookie = cookies[i].replace(/^\s+/, ""); - const eq = cookie.indexOf("="); - if (eq !== -1 && cookie.slice(0, eq) === name) try { - return decodeURIComponent(cookie.slice(eq + 1)); - } catch (e) { - return cookie.slice(eq + 1); - } - } - return null; - }, - remove(name) { - this.write(name, "", Date.now() - 864e5, "/"); - } -} : { - write() {}, - read() { - return null; - }, - remove() {} -}; -//#endregion -//#region node_modules/axios/lib/helpers/isAbsoluteURL.js -/** -* Determines whether the specified URL is absolute -* -* @param {string} url The URL to test -* -* @returns {boolean} True if the specified URL is absolute, otherwise false -*/ -function isAbsoluteURL(url) { - if (typeof url !== "string") return false; - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -} -//#endregion -//#region node_modules/axios/lib/helpers/combineURLs.js -/** -* Creates a new URL by combining the specified URLs -* -* @param {string} baseURL The base URL -* @param {string} relativeURL The relative URL -* -* @returns {string} The combined URL -*/ -function combineURLs(baseURL, relativeURL) { - if (!relativeURL) return baseURL; - let end = baseURL.length; - while (end > 0 && baseURL.charCodeAt(end - 1) === 47) end--; - return baseURL.slice(0, end) + "/" + relativeURL.replace(/^\/+/, ""); -} -//#endregion -//#region node_modules/axios/lib/core/buildFullPath.js -var malformedHttpProtocol = /^https?:(?!\/\/)/i; -function redactFragment(fragment) { - if (!fragment) return fragment; - return fragment.replace(/(^|&)([^=&]*=)?[^&]+/g, (match, separator, parameterName = "") => { - return `${separator}${parameterName}${REDACTED}`; - }); -} -function redactSensitiveURLParts(url) { - const redactedURL = url.replace(/^(https?:\/{0,2})[^/?#]*@/i, `$1${REDACTED}@`); - const fragmentIndex = redactedURL.indexOf("#"); - const redactedURLWithoutFragment = (fragmentIndex === -1 ? redactedURL : redactedURL.slice(0, fragmentIndex)).replace(/([?&][^=&#]*=)[^&#]*/g, `$1${REDACTED}`); - if (fragmentIndex === -1) return redactedURLWithoutFragment; - return `${redactedURLWithoutFragment}#${redactFragment(redactedURL.slice(fragmentIndex + 1))}`; -} -function assertValidHttpProtocolURL(url, config) { - if (typeof url === "string") { - const normalizedURL = normalizeURLForProtocolCheck(url); - if (malformedHttpProtocol.test(normalizedURL)) throw new AxiosError(`Invalid URL ${JSON.stringify(redactSensitiveURLParts(normalizedURL))}: missing "//" after protocol`, AxiosError.ERR_INVALID_URL, config); - } -} -/** -* Creates a new URL by combining the baseURL with the requestedURL, -* only when the requestedURL is not already an absolute URL. -* If the requestURL is absolute, this function returns the requestedURL untouched. -* -* @param {string} baseURL The base URL -* @param {string} requestedURL Absolute or relative URL to combine -* -* @returns {string} The combined full path -*/ -function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) { - assertValidHttpProtocolURL(requestedURL, config); - let isRelativeUrl = !isAbsoluteURL(requestedURL); - if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) { - assertValidHttpProtocolURL(baseURL, config); - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -} -//#endregion -//#region node_modules/axios/lib/core/mergeConfig.js -var headersToObject = (thing) => thing instanceof AxiosHeaders ? _objectSpread2({}, thing) : thing; -var ownEnumerableKeys = (thing) => { - if (Object.getOwnPropertySymbols && Object.getOwnPropertyDescriptor) return Object.keys(thing).concat(Object.getOwnPropertySymbols(thing).filter((symbol) => Object.getOwnPropertyDescriptor(thing, symbol).enumerable)); - return Object.keys(thing); -}; -/** -* Config-specific merge-function which creates a new config-object -* by merging two configuration objects together. -* -* @param {Object} config1 -* @param {Object} config2 -* -* @returns {Object} New object resulting from merging config2 to config1 -*/ -function mergeConfig(config1, config2) { - config1 = config1 || {}; - config2 = config2 || {}; - const config = Object.create(null); - Object.defineProperty(config, "hasOwnProperty", { - __proto__: null, - value: Object.prototype.hasOwnProperty, - enumerable: false, - writable: true, - configurable: true - }); - function getMergedValue(target, source, prop, caseless) { - if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) return utils_default.merge.call({ caseless }, target, source); - else if (utils_default.isPlainObject(source)) return utils_default.merge({}, source); - else if (utils_default.isArray(source)) return source.slice(); - return source; - } - function mergeDeepProperties(a, b, prop, caseless) { - if (!utils_default.isUndefined(b)) return getMergedValue(a, b, prop, caseless); - else if (!utils_default.isUndefined(a)) return getMergedValue(void 0, a, prop, caseless); - } - function valueFromConfig2(a, b) { - if (!utils_default.isUndefined(b)) return getMergedValue(void 0, b); - } - function defaultToConfig2(a, b) { - if (!utils_default.isUndefined(b)) return getMergedValue(void 0, b); - else if (!utils_default.isUndefined(a)) return getMergedValue(void 0, a); - } - function getMergedTransitionalOption(prop) { - const transitional2 = utils_default.hasOwnProp(config2, "transitional") ? config2.transitional : void 0; - if (!utils_default.isUndefined(transitional2)) if (utils_default.isPlainObject(transitional2)) { - if (utils_default.hasOwnProp(transitional2, prop)) return transitional2[prop]; - } else return; - const transitional1 = utils_default.hasOwnProp(config1, "transitional") ? config1.transitional : void 0; - if (utils_default.isPlainObject(transitional1) && utils_default.hasOwnProp(transitional1, prop)) return transitional1[prop]; - } - function mergeDirectKeys(a, b, prop) { - if (utils_default.hasOwnProp(config2, prop)) return getMergedValue(a, b); - else if (utils_default.hasOwnProp(config1, prop)) return getMergedValue(void 0, a); - } - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutErrorMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - allowedSocketPaths: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true) - }; - utils_default.forEach(ownEnumerableKeys(_objectSpread2(_objectSpread2({}, config1), config2)), function computeConfigValue(prop) { - if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return; - const merge = utils_default.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties; - const configValue = merge(utils_default.hasOwnProp(config1, prop) ? config1[prop] : void 0, utils_default.hasOwnProp(config2, prop) ? config2[prop] : void 0, prop); - utils_default.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue); - }); - if (utils_default.hasOwnProp(config2, "validateStatus") && utils_default.isUndefined(config2.validateStatus) && getMergedTransitionalOption("validateStatusUndefinedResolves") === false) if (utils_default.hasOwnProp(config1, "validateStatus")) config.validateStatus = getMergedValue(void 0, config1.validateStatus); - else delete config.validateStatus; - return config; -} -//#endregion -//#region node_modules/axios/lib/core/setFormDataHeaders.js -var FORM_DATA_CONTENT_HEADERS = ["content-type", "content-length"]; -/** -* Apply the headers generated by a FormData implementation to the request headers, -* honoring the `formDataHeaderPolicy` option: with 'content-only', copy only the -* content-* headers; otherwise merge all of them. -* -* @param {AxiosHeaders} headers - the request headers to mutate -* @param {Object | null | undefined} formHeaders - headers produced by the FormData implementation -* @param {String} [policy] - the resolved `formDataHeaderPolicy` config value -* -* @returns {void} -*/ -function setFormDataHeaders(headers, formHeaders, policy) { - if (policy !== "content-only") { - headers.set(formHeaders); - return; - } - Object.entries(formHeaders || {}).forEach(([key, val]) => { - if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) headers.set(key, val); - }); -} -//#endregion -//#region node_modules/axios/lib/helpers/resolveConfig.js -/** -* Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). -* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern. -* -* @param {string} str The string to encode -* -* @returns {string} UTF-8 bytes as a Latin-1 string -*/ -var encodeUTF8$1 = (str) => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))); -function resolveConfig(config) { - const newConfig = mergeConfig({}, config); - const own = (key) => utils_default.hasOwnProp(newConfig, key) ? newConfig[key] : void 0; - const data = own("data"); - let withXSRFToken = own("withXSRFToken"); - const xsrfHeaderName = own("xsrfHeaderName"); - const xsrfCookieName = own("xsrfCookieName"); - let headers = own("headers"); - const auth = own("auth"); - const baseURL = own("baseURL"); - const allowAbsoluteUrls = own("allowAbsoluteUrls"); - const url = own("url"); - newConfig.headers = headers = AxiosHeaders.from(headers); - newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own("params"), own("paramsSerializer")); - if (auth) { - const username = utils_default.getSafeProp(auth, "username") || ""; - const password = utils_default.getSafeProp(auth, "password") || ""; - try { - headers.set("Authorization", "Basic " + btoa(username + ":" + (password ? encodeUTF8$1(password) : ""))); - } catch (e) { - throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config); - } - } - if (utils_default.isFormData(data)) { - const getHeaders = utils_default.getSafeProp(data, "getHeaders"); - if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv || utils_default.isReactNative(data)) headers.setContentType(void 0); - else if (utils_default.isFunction(getHeaders)) setFormDataHeaders(headers, getHeaders.call(data), own("formDataHeaderPolicy")); - } - if (platform_default.hasStandardBrowserEnv) { - if (utils_default.isFunction(withXSRFToken)) withXSRFToken = withXSRFToken(newConfig); - if (withXSRFToken === true || withXSRFToken == null && isURLSameOrigin_default(newConfig.url)) { - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName); - if (xsrfValue) headers.set(xsrfHeaderName, xsrfValue); - } - } - return newConfig; -} -var xhr_default = typeof XMLHttpRequest !== "undefined" && function(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config); - let requestData = _config.data; - const requestHeaders = AxiosHeaders.from(_config.headers).normalize(); - let { responseType, onUploadProgress, onDownloadProgress } = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload, flushDownloadWithEvent; - function done() { - flushUpload && flushUpload(); - flushDownload && flushDownload(); - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); - _config.signal && _config.signal.removeEventListener("abort", onCanceled); - } - let request = new XMLHttpRequest(); - request.open(_config.method.toUpperCase(), _config.url, true); - request.timeout = _config.timeout; - function onloadend(event) { - if (!request) return; - if (request.status === 0 && (parseProtocol(normalizeURLForProtocolCheck(_config.url)) || parseProtocol(platform_default.origin)) !== "file" && !(request.responseURL && request.responseURL.startsWith("file:"))) { - reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); - done(); - request = null; - return; - } - try { - if (event) flushDownloadWithEvent && flushDownloadWithEvent(event); - else flushDownload && flushDownload(); - } catch (err) { - setTimeout(() => { - throw err; - }); - } - if (!request) return; - const responseHeaders = AxiosHeaders.from("getAllResponseHeaders" in request && request.getAllResponseHeaders()); - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, { - data: !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }); - request = null; - } - if ("onloadend" in request) request.onloadend = onloadend; - else request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) return; - if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith("file:"))) return; - setTimeout(onloadend); - }; - request.onabort = function handleAbort() { - if (!request) return; - reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request)); - done(); - request = null; - }; - request.onerror = function handleError(event) { - const err = new AxiosError(event && event.message ? event.message : "Network Error", AxiosError.ERR_NETWORK, config, request); - err.event = event || null; - reject(err); - done(); - request = null; - }; - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded"; - const transitional = _config.transitional || transitional_default; - if (_config.timeoutErrorMessage) timeoutErrorMessage = _config.timeoutErrorMessage; - reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request)); - done(); - request = null; - }; - requestData === void 0 && requestHeaders.setContentType(null); - if ("setRequestHeader" in request) utils_default.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - if (!utils_default.isUndefined(_config.withCredentials)) request.withCredentials = !!_config.withCredentials; - if (responseType && responseType !== "json") request.responseType = _config.responseType; - if (onDownloadProgress) { - [downloadThrottled, flushDownload, flushDownloadWithEvent] = progressEventReducer(onDownloadProgress, true); - request.addEventListener("progress", downloadThrottled); - } - if (onUploadProgress && request.upload) { - [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress); - request.upload.addEventListener("progress", uploadThrottled); - request.upload.addEventListener("loadend", flushUpload); - } - if (_config.cancelToken || _config.signal) { - onCanceled = (cancel) => { - if (!request) return; - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - done(); - request = null; - }; - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled); - } - const protocol = parseProtocol(_config.url); - if (protocol && !platform_default.protocols.includes(protocol)) { - reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config)); - done(); - return; - } - request.send(requestData || null); - }); -}; -//#endregion -//#region node_modules/axios/lib/helpers/composeSignals.js -var composeSignals = (signals, timeout) => { - signals = signals ? signals.filter(Boolean) : []; - if (!timeout && !signals.length) return; - const controller = new AbortController(); - let aborted = false; - const onabort = function(reason) { - if (!aborted) { - aborted = true; - unsubscribe(); - const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); - } - }; - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT)); - }, timeout); - const unsubscribe = () => { - if (!signals) return; - timer && clearTimeout(timer); - timer = null; - signals.forEach((signal) => { - signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener("abort", onabort); - }); - signals = null; - }; - signals.forEach((signal) => { - if (aborted) return; - if (signal.aborted) { - onabort.call(signal); - return; - } - signal.addEventListener("abort", onabort, { once: true }); - }); - const { signal } = controller; - signal.unsubscribe = () => utils_default.asap(unsubscribe); - return signal; -}; -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/asyncIterator.js -function _asyncIterator(r) { - var n, t, o, e = 2; - for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { - if (t && null != (n = r[t])) return n.call(r); - if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); - t = "@@asyncIterator", o = "@@iterator"; - } - throw new TypeError("Object is not async iterable"); -} -function AsyncFromSyncIterator(r) { - function AsyncFromSyncIteratorContinuation(r) { - if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object.")); - var n = r.done; - return Promise.resolve(r.value).then(function(r) { - return { - value: r, - done: n - }; - }); - } - return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) { - this.s = r, this.n = r.next; - }, AsyncFromSyncIterator.prototype = { - s: null, - n: null, - next: function next() { - return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); - }, - "return": function _return(r) { - var n = this.s["return"]; - return void 0 === n ? Promise.resolve({ - value: r, - done: !0 - }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); - }, - "throw": function _throw(r) { - var n = this.s["return"]; - return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); - } - }, new AsyncFromSyncIterator(r); -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/OverloadYield.js -function _OverloadYield(e, d) { - this.v = e, this.k = d; -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/awaitAsyncGenerator.js -function _awaitAsyncGenerator(e) { - return new _OverloadYield(e, 0); -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/asyncGeneratorDelegate.js -function _asyncGeneratorDelegate(t) { - var e = {}, n = !1; - function pump(e, r) { - return n = !0, r = new Promise(function(n) { - n(t[e](r)); - }), { - done: !1, - value: new _OverloadYield(r, 1) - }; - } - return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function() { - return this; - }, e.next = function(t) { - return n ? (n = !1, t) : pump("next", t); - }, "function" == typeof t["throw"] && (e["throw"] = function(t) { - if (n) throw n = !1, t; - return pump("throw", t); - }), "function" == typeof t["return"] && (e["return"] = function(t) { - return n ? (n = !1, t) : pump("return", t); - }), e; -} -//#endregion -//#region \0@oxc-project+runtime@0.133.0/helpers/esm/wrapAsyncGenerator.js -function _wrapAsyncGenerator(e) { - return function() { - return new AsyncGenerator(e.apply(this, arguments)); - }; -} -function AsyncGenerator(e) { - var r, t; - function resume(r, t) { - try { - var n = e[r](t), o = n.value, u = o instanceof _OverloadYield; - Promise.resolve(u ? o.v : o).then(function(t) { - if (u) { - var i = "return" === r ? "return" : "next"; - if (!o.k || t.done) return resume(i, t); - t = e[i](t).value; - } - settle(n.done ? "return" : "normal", t); - }, function(e) { - resume("throw", e); - }); - } catch (e) { - settle("throw", e); - } - } - function settle(e, n) { - switch (e) { - case "return": - r.resolve({ - value: n, - done: !0 - }); - break; - case "throw": - r.reject(n); - break; - default: r.resolve({ - value: n, - done: !1 - }); - } - (r = r.next) ? resume(r.key, r.arg) : t = null; - } - this._invoke = function(e, n) { - return new Promise(function(o, u) { - var i = { - key: e, - arg: n, - resolve: o, - reject: u, - next: null - }; - t ? t = t.next = i : (r = t = i, resume(e, n)); - }); - }, "function" != typeof e["return"] && (this["return"] = void 0); -} -AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() { - return this; -}, AsyncGenerator.prototype.next = function(e) { - return this._invoke("next", e); -}, AsyncGenerator.prototype["throw"] = function(e) { - return this._invoke("throw", e); -}, AsyncGenerator.prototype["return"] = function(e) { - return this._invoke("return", e); -}; -//#endregion -//#region node_modules/axios/lib/helpers/trackStream.js -var streamChunk = function* (chunk, chunkSize) { - let len = chunk.byteLength; - if (!chunkSize || len < chunkSize) { - yield chunk; - return; - } - let pos = 0; - let end; - while (pos < len) { - end = pos + chunkSize; - yield chunk.slice(pos, end); - pos = end; - } -}; -var readBytes = /* @__PURE__ */ function() { - var _ref = _wrapAsyncGenerator(function* (iterable, chunkSize) { - var _iteratorAbruptCompletion = false; - var _didIteratorError = false; - var _iteratorError; - try { - for (var _iterator = _asyncIterator(readStream(iterable)), _step; _iteratorAbruptCompletion = !(_step = yield _awaitAsyncGenerator(_iterator.next())).done; _iteratorAbruptCompletion = false) { - const chunk = _step.value; - yield* _asyncGeneratorDelegate(_asyncIterator(streamChunk(chunk, chunkSize))); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (_iteratorAbruptCompletion && _iterator.return != null) yield _awaitAsyncGenerator(_iterator.return()); - } finally { - if (_didIteratorError) throw _iteratorError; - } - } - }); - return function readBytes(_x, _x2) { - return _ref.apply(this, arguments); - }; -}(); -var readStream = /* @__PURE__ */ function() { - var _ref2 = _wrapAsyncGenerator(function* (stream) { - if (stream[Symbol.asyncIterator]) { - yield* _asyncGeneratorDelegate(_asyncIterator(stream)); - return; - } - const reader = stream.getReader(); - try { - for (;;) { - const { done, value } = yield _awaitAsyncGenerator(reader.read()); - if (done) break; - yield value; - } - } finally { - yield _awaitAsyncGenerator(reader.cancel()); - } - }); - return function readStream(_x3) { - return _ref2.apply(this, arguments); - }; -}(); -var trackStream = (stream, chunkSize, onProgress, onFinish) => { - const iterator = readBytes(stream, chunkSize); - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); - } - }; - return new ReadableStream({ - pull(controller) { - return _asyncToGenerator(function* () { - try { - const { done, value } = yield iterator.next(); - if (done) { - _onFinish(); - controller.close(); - return; - } - let len = value.byteLength; - if (onProgress) onProgress(bytes += len); - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; - } - })(); - }, - cancel(reason) { - _onFinish(reason); - return iterator.return(); - } - }, { highWaterMark: 2 }); -}; -//#endregion -//#region node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js -/** -* Estimate data: URL byte lengths *without* allocating large buffers. -* - Fetch percent-decodes a base64 body before decoding it. -* - Node's Buffer.from(body, 'base64') sizes its backing allocation from the -* raw body, including ignored characters and content after padding. -* - Non-base64 data is percent-decoded and then encoded as UTF-8. -*/ -var isHexDigit = (charCode) => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102; -var isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2)); -var hexValue = (charCode) => charCode <= 57 ? charCode - 48 : (charCode & 223) - 55; -var isBase64Char = (charCode) => charCode >= 65 && charCode <= 90 || charCode >= 97 && charCode <= 122 || charCode >= 48 && charCode <= 57 || charCode === 43 || charCode === 47 || charCode === 45 || charCode === 95; -var isBase64Whitespace = (charCode) => charCode === 9 || charCode === 10 || charCode === 12 || charCode === 13 || charCode === 32; -var base64Bytes = (significant) => { - const groups = Math.floor(significant / 4); - const remainder = significant % 4; - return groups * 3 + (remainder === 2 ? 1 : remainder === 3 ? 2 : 0); -}; -var estimateBase64BufferAllocation = (body) => { - const len = body.length; - let padding = 0; - if (len > 0 && body.charCodeAt(len - 1) === 61) { - padding++; - if (len > 1 && body.charCodeAt(len - 2) === 61) padding++; - } - return Math.floor((len - padding) * 3 / 4); -}; -var estimatePercentDecodedBase64Bytes = (body) => { - const len = body.length; - let significant = 0; - let padding = 0; - let invalid = false; - for (let i = 0; i < len; i++) { - let code = body.charCodeAt(i); - if (code === 37 && isPercentEncodedByte(body, i, len)) { - code = hexValue(body.charCodeAt(i + 1)) * 16 + hexValue(body.charCodeAt(i + 2)); - i += 2; - } - if (isBase64Whitespace(code)) continue; - if (code === 61) { - padding++; - continue; - } - if (!isBase64Char(code) || padding > 0) { - invalid = true; - continue; - } - significant++; - } - if (invalid || padding > 2 || padding > 0 && (significant + padding) % 4 !== 0 || significant % 4 === 1) return estimateBase64BufferAllocation(body); - return base64Bytes(significant); -}; -var estimateDataURLBytes = (url, estimateBase64) => { - if (!url || typeof url !== "string") return 0; - if (!url.startsWith("data:")) return 0; - const comma = url.indexOf(","); - if (comma < 0) return 0; - const meta = url.slice(5, comma); - const body = url.slice(comma + 1); - if (/;base64/i.test(meta)) return estimateBase64(body); - let bytes = 0; - for (let i = 0, len = body.length; i < len; i++) { - const c = body.charCodeAt(i); - if (c === 37 && isPercentEncodedByte(body, i, len)) { - bytes += 1; - i += 2; - } else if (c < 128) bytes += 1; - else if (c < 2048) bytes += 2; - else if (c >= 55296 && c <= 56319 && i + 1 < len) { - const next = body.charCodeAt(i + 1); - if (next >= 56320 && next <= 57343) { - bytes += 4; - i++; - } else bytes += 3; - } else bytes += 3; - } - return bytes; -}; -/** -* Estimate the percent-decoded payload size used by Fetch data: URLs. -* -* @param {string} url -* @returns {number} -*/ -function estimateDataURLDecodedBytes(url) { - const fragmentIndex = typeof url === "string" ? url.indexOf("#") : -1; - return estimateDataURLBytes(fragmentIndex === -1 ? url : url.slice(0, fragmentIndex), estimatePercentDecodedBase64Bytes); -} -//#endregion -//#region node_modules/axios/lib/env/data.js -var VERSION = "1.20.0"; -//#endregion -//#region node_modules/axios/lib/adapters/fetch.js -var DEFAULT_CHUNK_SIZE = 64 * 1024; -var DEFAULT_REQUEST_OPTIONS = { - cache: "default", - redirect: "follow", - referrer: "about:client", - referrerPolicy: "", - mode: "cors", - integrity: "", - keepalive: false, - priority: "auto", - window: null -}; -var { isFunction } = utils_default; -/** -* Encode a UTF-8 string to a Latin-1 byte string for use with btoa(). -* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern. -* -* @param {string} str The string to encode -* -* @returns {string} UTF-8 bytes as a Latin-1 string -*/ -var encodeUTF8 = (str) => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))); -var decodeURIComponentSafe = (value) => { - if (!utils_default.isString(value)) return value; - try { - return decodeURIComponent(value); - } catch (error) { - return value; - } -}; -var test = (fn, ...args) => { - try { - return !!fn(...args); - } catch (e) { - return false; - } -}; -var maybeWithAuthCredentials = (url) => { - const protocolIndex = url.indexOf("://"); - let urlToCheck = url; - if (protocolIndex !== -1) urlToCheck = urlToCheck.slice(protocolIndex + 3); - return urlToCheck.includes("@") || urlToCheck.includes(":"); -}; -var factory = (env) => { - const globalObject = utils_default.global !== void 0 && utils_default.global !== null ? utils_default.global : globalThis; - const { ReadableStream, TextEncoder } = globalObject; - env = utils_default.merge.call({ skipUndefined: true }, { - Request: globalObject.Request, - Response: globalObject.Response - }, env); - const { fetch: envFetch, Request, Response } = env; - const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function"; - const isRequestSupported = isFunction(Request); - const isResponseSupported = isFunction(Response); - if (!isFetchSupported) return false; - const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream); - const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : function() { - var _ref = _asyncToGenerator(function* (str) { - return new Uint8Array(yield new Request(str).arrayBuffer()); - }); - return function(_x) { - return _ref.apply(this, arguments); - }; - }()); - const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { - let duplexAccessed = false; - const request = new Request(platform_default.origin, { - body: new ReadableStream(), - method: "POST", - get duplex() { - duplexAccessed = true; - return "half"; - } - }); - const hasContentType = request.headers.has("Content-Type"); - if (request.body != null) request.body.cancel(); - return duplexAccessed && !hasContentType; - }); - const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body)); - const resolvers = { stream: supportsResponseStream && ((res) => res.body) }; - isFetchSupported && (() => { - [ - "text", - "arrayBuffer", - "blob", - "formData", - "stream" - ].forEach((type) => { - !resolvers[type] && (resolvers[type] = (res, config) => { - let method = res && res[type]; - if (method) return method.call(res); - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }); - }); - })(); - const getBodyLength = function() { - var _ref2 = _asyncToGenerator(function* (body) { - if (body == null) return 0; - if (utils_default.isBlob(body)) return body.size; - if (utils_default.isSpecCompliantForm(body)) return (yield new Request(platform_default.origin, { - method: "POST", - body - }).arrayBuffer()).byteLength; - if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) return body.byteLength; - if (utils_default.isURLSearchParams(body)) body = body + ""; - if (utils_default.isString(body)) return (yield encodeText(body)).byteLength; - }); - return function getBodyLength(_x2) { - return _ref2.apply(this, arguments); - }; - }(); - const resolveBodyLength = function() { - var _ref3 = _asyncToGenerator(function* (headers, body) { - const length = utils_default.toFiniteNumber(headers.getContentLength()); - return length == null ? getBodyLength(body) : length; - }); - return function resolveBodyLength(_x3, _x4) { - return _ref3.apply(this, arguments); - }; - }(); - return function() { - var _ref4 = _asyncToGenerator(function* (config) { - let { url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, withCredentials = "same-origin", fetchOptions, maxContentLength, maxBodyLength, maxRedirects } = resolveConfig(config); - const hasMaxContentLength = utils_default.isNumber(maxContentLength) && maxContentLength > -1; - const hasMaxBodyLength = utils_default.isNumber(maxBodyLength) && maxBodyLength > -1; - const own = (key) => utils_default.hasOwnProp(config, key) ? config[key] : void 0; - let _fetch = envFetch || fetch; - responseType = responseType ? (responseType + "").toLowerCase() : "text"; - let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout); - let request = null; - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); - let requestContentLength; - let pendingBodyError = null; - const maxBodyLengthError = () => new AxiosError("Request body larger than maxBodyLength limit", AxiosError.ERR_BAD_REQUEST, config, request); - try { - let auth = void 0; - const configAuth = own("auth"); - if (configAuth) auth = { - username: utils_default.getSafeProp(configAuth, "username") || "", - password: utils_default.getSafeProp(configAuth, "password") || "" - }; - if (maybeWithAuthCredentials(url)) { - const parsedURL = new URL(url, platform_default.origin); - if (!auth && (parsedURL.username || parsedURL.password)) auth = { - username: decodeURIComponentSafe(parsedURL.username), - password: decodeURIComponentSafe(parsedURL.password) - }; - if (parsedURL.username || parsedURL.password) { - parsedURL.username = ""; - parsedURL.password = ""; - url = parsedURL.href; - } - } - if (auth) { - headers.delete("authorization"); - headers.set("Authorization", "Basic " + btoa(encodeUTF8((auth.username || "") + ":" + (auth.password || "")))); - } - if (hasMaxContentLength && typeof url === "string" && url.startsWith("data:")) { - if (estimateDataURLDecodedBytes(url) > maxContentLength) throw new AxiosError("maxContentLength size of " + maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config, request); - } - if (hasMaxBodyLength && method !== "get" && method !== "head") { - const outboundLength = yield getBodyLength(data); - if (typeof outboundLength === "number" && isFinite(outboundLength)) { - requestContentLength = outboundLength; - if (outboundLength > maxBodyLength) throw maxBodyLengthError(); - } - } - const mustEnforceStreamBody = hasMaxBodyLength && (utils_default.isReadableStream(data) || utils_default.isStream(data)); - const trackRequestStream = (stream, onProgress, flush) => trackStream(stream, DEFAULT_CHUNK_SIZE, (loadedBytes) => { - if (hasMaxBodyLength && loadedBytes > maxBodyLength) throw pendingBodyError = maxBodyLengthError(); - onProgress && onProgress(loadedBytes); - }, flush); - if (supportsRequestStream && method !== "get" && method !== "head" && (onUploadProgress || mustEnforceStreamBody)) { - requestContentLength = requestContentLength == null ? yield resolveBodyLength(headers, data) : requestContentLength; - if (requestContentLength !== 0 || mustEnforceStreamBody) { - let _request = new Request(url, { - method: "POST", - body: data, - duplex: "half" - }); - let contentTypeHeader; - if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) headers.setContentType(contentTypeHeader); - if (_request.body) { - const [onProgress, flush] = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || []; - data = trackRequestStream(_request.body, onProgress, flush); - } - } - } else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== "get" && method !== "head") data = trackRequestStream(data); - else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== "get" && method !== "head") throw new AxiosError("Stream request bodies are not supported by the current fetch implementation", AxiosError.ERR_NOT_SUPPORT, config, request); - if (!utils_default.isString(withCredentials)) withCredentials = withCredentials ? "include" : "omit"; - const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; - if (utils_default.isFormData(data)) { - const contentType = headers.getContentType(); - if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) headers.delete("content-type"); - } - headers.set("User-Agent", "axios/" + VERSION, false); - const safeFetchOptions = fetchOptions == null ? fetchOptions : Object.assign(Object.create(null), fetchOptions); - if (safeFetchOptions) { - delete safeFetchOptions.body; - delete safeFetchOptions.headers; - delete safeFetchOptions.method; - delete safeFetchOptions.signal; - delete safeFetchOptions.duplex; - delete safeFetchOptions.credentials; - } - const resolvedOptions = Object.assign(Object.create(null), safeFetchOptions, { - signal: composedSignal, - method: method.toUpperCase(), - headers: toByteStringHeaderObject(headers.normalize()), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : void 0 - }); - if (isRequestSupported) { - utils_default.forEach(DEFAULT_REQUEST_OPTIONS, (value, key) => { - if (resolvedOptions[key] === void 0) resolvedOptions[key] = value; - }); - if (resolvedOptions.signal === void 0) resolvedOptions.signal = null; - if (resolvedOptions.body === void 0) resolvedOptions.body = null; - } - if (maxRedirects === 0) { - resolvedOptions.redirect = "manual"; - if (safeFetchOptions) safeFetchOptions.redirect = "manual"; - } - request = isRequestSupported && new Request(url, resolvedOptions); - let response = yield isRequestSupported ? _fetch(request, safeFetchOptions) : _fetch(url, resolvedOptions); - const responseHeaders = AxiosHeaders.from(response.headers); - if (hasMaxContentLength) { - const declaredLength = utils_default.toFiniteNumber(responseHeaders.getContentLength()); - if (declaredLength != null && declaredLength > maxContentLength) throw new AxiosError("maxContentLength size of " + maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config, request); - } - const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response"); - if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) { - const options = {}; - [ - "status", - "statusText", - "headers" - ].forEach((prop) => { - options[prop] = response[prop]; - }); - const responseContentLength = utils_default.toFiniteNumber(responseHeaders.getContentLength()); - const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || []; - let bytesRead = 0; - const onChunkProgress = (loadedBytes) => { - if (hasMaxContentLength) { - bytesRead = loadedBytes; - if (bytesRead > maxContentLength) throw new AxiosError("maxContentLength size of " + maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config, request); - } - onProgress && onProgress(loadedBytes); - }; - response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), options); - } - responseType = responseType || "text"; - let responseData = yield resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config); - if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) { - let materializedSize; - if (responseData != null) { - if (typeof responseData.byteLength === "number") materializedSize = responseData.byteLength; - else if (typeof responseData.size === "number") materializedSize = responseData.size; - else if (typeof responseData === "string") materializedSize = typeof TextEncoder === "function" ? new TextEncoder().encode(responseData).byteLength : responseData.length; - } - if (typeof materializedSize === "number" && materializedSize > maxContentLength) throw new AxiosError("maxContentLength size of " + maxContentLength + " exceeded", AxiosError.ERR_BAD_RESPONSE, config, request); - } - !isStreamResponse && unsubscribe && unsubscribe(); - return yield new Promise((resolve, reject) => { - settle(resolve, reject, { - data: responseData, - headers: AxiosHeaders.from(response.headers), - status: response.status, - statusText: response.statusText, - config, - request - }); - }); - } catch (err) { - unsubscribe && unsubscribe(); - if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) { - const canceledError = composedSignal.reason; - canceledError.config = config; - request && (canceledError.request = request); - if (err !== canceledError) Object.defineProperty(canceledError, "cause", { - __proto__: null, - value: err, - writable: true, - enumerable: false, - configurable: true - }); - throw canceledError; - } - if (pendingBodyError) { - request && !pendingBodyError.request && (pendingBodyError.request = request); - throw pendingBodyError; - } - if (err instanceof AxiosError) { - request && !err.request && (err.request = request); - throw err; - } - if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) { - const networkError = new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request, err && err.response); - Object.defineProperty(networkError, "cause", { - __proto__: null, - value: err.cause || err, - writable: true, - enumerable: false, - configurable: true - }); - throw networkError; - } - throw AxiosError.from(err, err && err.code, config, request, err && err.response); - } - }); - return function(_x5) { - return _ref4.apply(this, arguments); - }; - }(); -}; -var seedCache = /* @__PURE__ */ new Map(); -var getFetch = (config) => { - let env = config && config.env || {}; - const { fetch, Request, Response } = env; - const seeds = [ - Request, - Response, - fetch - ]; - let i = seeds.length, seed, target, map = seedCache; - while (i--) { - seed = seeds[i]; - target = map.get(seed); - target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env)); - map = target; - } - return target; -}; -getFetch(); -//#endregion -//#region node_modules/axios/lib/adapters/adapters.js -/** -* Known adapters mapping. -* Provides environment-specific adapters for Axios: -* - `http` for Node.js -* - `xhr` for browsers -* - `fetch` for fetch API-based requests -* -* @type {Object} -*/ -var knownAdapters = { - http: null, - xhr: xhr_default, - fetch: { get: getFetch } -}; -utils_default.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, "name", { - __proto__: null, - value - }); - } catch (e) {} - Object.defineProperty(fn, "adapterName", { - __proto__: null, - value - }); - } -}); -/** -* Render a rejection reason string for unknown or unsupported adapters -* -* @param {string} reason -* @returns {string} -*/ -var renderReason = (reason) => `- ${reason}`; -/** -* Check if the adapter is resolved (function, null, or false) -* -* @param {Function|null|false} adapter -* @returns {boolean} -*/ -var isResolvedHandle = (adapter) => utils_default.isFunction(adapter) || adapter === null || adapter === false; -/** -* Get the first suitable adapter from the provided list. -* Tries each adapter in order until a supported one is found. -* Throws an AxiosError if no adapter is suitable. -* -* @param {Array|string|Function} adapters - Adapter(s) by name or function. -* @param {Object} config - Axios request configuration -* @throws {AxiosError} If no suitable adapter is available -* @returns {Function} The resolved adapter function -*/ -function getAdapter(adapters, config) { - adapters = utils_default.isArray(adapters) ? adapters : [adapters]; - const { length } = adapters; - let nameOrAdapter; - let adapter; - const rejectedReasons = {}; - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; - adapter = nameOrAdapter; - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - if (adapter === void 0) throw new AxiosError(`Unknown adapter '${id}'`); - } - if (adapter && (utils_default.isFunction(adapter) || (adapter = adapter.get(config)))) break; - rejectedReasons[id || "#" + i] = adapter; - } - if (!adapter) { - const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")); - throw new AxiosError(`There is no suitable adapter to dispatch the request ` + (length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified"), AxiosError.ERR_NOT_SUPPORT); - } - return adapter; -} -/** -* Exports Axios adapters and utility to resolve an adapter -*/ -var adapters_default = { - /** - * Resolve an adapter from a list of adapter names or functions. - * @type {Function} - */ - getAdapter, - /** - * Exposes all known adapters - * @type {Object} - */ - adapters: knownAdapters -}; -//#endregion -//#region node_modules/axios/lib/core/dispatchRequest.js -/** -* Throws a `CanceledError` if cancellation has been requested. -* -* @param {Object} config The config that is to be used for the request -* -* @returns {void} -*/ -function throwIfCancellationRequested(config) { - if (config.cancelToken) config.cancelToken.throwIfRequested(); - if (config.signal && config.signal.aborted) throw new CanceledError(null, config); -} -/** -* Dispatch a request to the server using the configured adapter. -* -* @param {object} config The config that is to be used for the request -* -* @returns {Promise} The Promise to be fulfilled -*/ -function dispatchRequest(_config) { - const config = utils_default.toSafeFlatObject(_config); - throwIfCancellationRequested(config); - config.headers = AxiosHeaders.from(utils_default.getSafeProp(config, "headers")); - config.data = transformData.call(config, config.transformRequest); - if ([ - "post", - "put", - "patch" - ].indexOf(config.method) !== -1) config.headers.setContentType("application/x-www-form-urlencoded", false); - return adapters_default.getAdapter(config.adapter || defaults.adapter, config)(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - config.response = response; - try { - response.data = transformData.call(config, config.transformResponse, response); - } finally { - delete config.response; - } - response.headers = AxiosHeaders.from(response.headers); - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - if (reason && reason.response) { - config.response = reason.response; - try { - reason.response.data = transformData.call(config, config.transformResponse, reason.response); - } finally { - delete config.response; - } - reason.response.headers = AxiosHeaders.from(reason.response.headers); - } - } - return Promise.reject(reason); - }); -} -//#endregion -//#region node_modules/axios/lib/helpers/validator.js -var validators$1 = {}; -[ - "object", - "boolean", - "number", - "function", - "string", - "symbol" -].forEach((type, i) => { - validators$1[type] = function validator(thing) { - return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type; - }; -}); -var deprecatedWarnings = {}; -/** -* Transitional option validator -* -* @param {function|boolean?} validator - set to false if the transitional option has been removed -* @param {string?} version - deprecated version / removed since version -* @param {string?} message - some message with additional info -* -* @returns {function} -*/ -validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); - } - return (value, opt, opts) => { - if (validator === false) throw new AxiosError(formatMessage(opt, " has been removed" + (version ? " in " + version : "")), AxiosError.ERR_DEPRECATED); - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - console.warn(formatMessage(opt, " has been deprecated since v" + version + " and will be removed in the near future")); - } - return validator ? validator(value, opt, opts) : true; - }; -}; -validators$1.spelling = function spelling(correctSpelling) { - return (value, opt) => { - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - }; -}; -/** -* Assert object's properties type -* -* @param {object} options -* @param {object} schema -* @param {boolean?} allowUnknown -* -* @returns {object} -*/ -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== "object" || options === null) throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE); - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : void 0; - if (validator) { - const value = options[opt]; - const result = value === void 0 || validator(value, opt, options); - if (result !== true) throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE); - continue; - } - if (allowUnknown !== true) throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION); - } -} -var validator_default = { - assertOptions, - validators: validators$1 -}; -//#endregion -//#region node_modules/axios/lib/core/Axios.js -var validators = validator_default.validators; -/** -* Create a new instance of Axios -* -* @param {Object} instanceConfig The default config for the instance -* -* @return {Axios} A new instance of Axios -*/ -var Axios = class { - constructor(instanceConfig) { - this.defaults = instanceConfig || {}; - this.interceptors = { - request: new InterceptorManager(), - response: new InterceptorManager() - }; - } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - request(configOrUrl, config) { - var _this = this; - return _asyncToGenerator(function* () { - try { - return yield _this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) try { - let dummy = {}; - Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = /* @__PURE__ */ new Error(); - const dummyStack = dummy.stack; - let stack = ""; - if (typeof dummyStack === "string") { - const firstNewlineIndex = dummyStack.indexOf("\n"); - stack = firstNewlineIndex === -1 ? "" : dummyStack.slice(firstNewlineIndex + 1); - } - if (!err.stack) err.stack = stack; - else if (stack) { - const firstNewlineIndex = stack.indexOf("\n"); - const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf("\n", firstNewlineIndex + 1); - const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? "" : stack.slice(secondNewlineIndex + 1); - if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) err.stack += "\n" + stack; - } - } catch (e) {} - throw err; - } - })(); - } - _request(configOrUrl, config) { - if (typeof configOrUrl === "string") { - config = config || {}; - config.url = configOrUrl; - } else config = configOrUrl || {}; - config = mergeConfig(this.defaults, config); - const { transitional, paramsSerializer, headers } = config; - if (transitional !== void 0) validator_default.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean), - legacyInterceptorReqResOrdering: validators.transitional(validators.boolean), - advertiseZstdAcceptEncoding: validators.transitional(validators.boolean), - validateStatusUndefinedResolves: validators.transitional(validators.boolean) - }, false); - if (paramsSerializer != null) if (utils_default.isFunction(paramsSerializer)) config.paramsSerializer = { serialize: paramsSerializer }; - else validator_default.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); - if (config.allowAbsoluteUrls !== void 0) {} else if (this.defaults.allowAbsoluteUrls !== void 0) config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; - else config.allowAbsoluteUrls = true; - validator_default.assertOptions(config, { - baseUrl: validators.spelling("baseURL"), - withXsrfToken: validators.spelling("withXSRFToken") - }, true); - config.method = (utils_default.getSafeProp(config, "method") || utils_default.getSafeProp(this.defaults, "method") || "get").toLowerCase(); - let contextHeaders = headers && utils_default.merge(headers.common, headers[config.method]); - headers && utils_default.forEach(methodList.concat("common"), (method) => { - delete headers[method]; - }); - config.headers = AxiosHeaders.concat(contextHeaders, headers); - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) return; - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - const transitional = config.transitional || transitional_default; - if (transitional && transitional.legacyInterceptorReqResOrdering) requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - else requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - let promise; - let i = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), void 0]; - chain.unshift(...requestInterceptorChain); - chain.push(...responseInterceptorChain); - len = chain.length; - promise = Promise.resolve(config); - while (i < len) promise = promise.then(chain[i++], chain[i++]); - return promise; - } - len = requestInterceptorChain.length; - let newConfig = config; - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled ? onFulfilled(newConfig) : newConfig; - } catch (error) { - if (!onRejected) { - promise = Promise.reject(error); - break; - } - try { - const rejectedResult = onRejected.call(this, error); - if (utils_default.isThenable(rejectedResult)) promise = Promise.resolve(rejectedResult).then(() => dispatchRequest.call(this, newConfig)); - } catch (rejectedError) { - promise = Promise.reject(rejectedError); - } - break; - } - } - if (!promise) try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - promise = Promise.reject(error); - } - i = 0; - len = responseInterceptorChain.length; - while (i < len) promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); - return promise; - } - getUri(config) { - config = mergeConfig(this.defaults, config); - return buildURL(buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config), config.params, config.paramsSerializer); - } -}; -utils_default.forEach([ - "delete", - "get", - "head", - "options" -], function forEachMethodNoData(method) { - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: config && utils_default.hasOwnProp(config, "data") ? config.data : void 0 - })); - }; -}); -utils_default.forEach([ - "post", - "put", - "patch", - "query" -], function forEachMethodWithData(method) { - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { "Content-Type": "multipart/form-data" } : {}, - url, - data - })); - }; - } - Axios.prototype[method] = generateHTTPMethod(); - if (method !== "query") Axios.prototype[method + "Form"] = generateHTTPMethod(true); -}); -//#endregion -//#region node_modules/axios/lib/cancel/CancelToken.js -/** -* A `CancelToken` is an object that can be used to request cancellation of an operation. -* -* @param {Function} executor The executor function. -* -* @returns {CancelToken} -*/ -var CancelToken = class CancelToken { - constructor(executor) { - if (typeof executor !== "function") throw new TypeError("executor must be a function."); - let resolvePromise; - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - const token = this; - this.promise.then((cancel) => { - if (!token._listeners) return; - let i = token._listeners.length; - while (i-- > 0) token._listeners[i](cancel); - token._listeners = null; - }); - this.promise.then = (onfulfilled) => { - let _resolve; - const promise = new Promise((resolve) => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; - executor(function cancel(message, config, request) { - if (token.reason) return; - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) throw this.reason; - } - /** - * Subscribe to the cancel signal - */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - if (this._listeners) this._listeners.push(listener); - else this._listeners = [listener]; - } - /** - * Unsubscribe from the cancel signal - */ - unsubscribe(listener) { - if (!this._listeners) return; - const index = this._listeners.indexOf(listener); - if (index !== -1) this._listeners.splice(index, 1); - } - toAbortSignal() { - const controller = new AbortController(); - const abort = (err) => { - controller.abort(err); - }; - this.subscribe(abort); - controller.signal.unsubscribe = () => this.unsubscribe(abort); - return controller.signal; - } - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - return { - token: new CancelToken(function executor(c) { - cancel = c; - }), - cancel - }; - } -}; -//#endregion -//#region node_modules/axios/lib/helpers/spread.js -/** -* Syntactic sugar for invoking a function and expanding an array for arguments. -* -* Common use case would be to use `Function.prototype.apply`. -* -* ```js -* function f(x, y, z) {} -* const args = [1, 2, 3]; -* f.apply(null, args); -* ``` -* -* With `spread` this example can be re-written. -* -* ```js -* spread(function(x, y, z) {})([1, 2, 3]); -* ``` -* -* @param {Function} callback -* -* @returns {Function} -*/ -function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -} -//#endregion -//#region node_modules/axios/lib/helpers/isAxiosError.js -/** -* Determines whether the payload is an error thrown by Axios -* -* @param {*} payload The value to test -* -* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false -*/ -function isAxiosError(payload) { - return utils_default.isObject(payload) && payload.isAxiosError === true; -} -//#endregion -//#region node_modules/axios/lib/helpers/HttpStatusCode.js -var HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - /** - * @deprecated Use `ContentTooLarge` instead. - */ - PayloadTooLarge: 413, - ContentTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - /** - * @deprecated Use `UnprocessableContent` instead. - */ - UnprocessableEntity: 422, - UnprocessableContent: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, - WebServerReturnsAnUnknownError: 520, - WebServerIsDown: 521, - ConnectionTimedOut: 522, - OriginIsUnreachable: 523, - TimeoutOccurred: 524, - SslHandshakeFailed: 525, - InvalidSslCertificate: 526 -}; -Object.entries(HttpStatusCode).forEach(([key, value]) => { - if (HttpStatusCode[value] === void 0) HttpStatusCode[value] = key; -}); -//#endregion -//#region node_modules/axios/lib/axios.js -/** -* Create an instance of Axios -* -* @param {Object} defaultConfig The default config for the instance -* -* @returns {Axios} A new instance of Axios -*/ -function createInstance(defaultConfig) { - const context = new Axios(defaultConfig); - const instance = bind(Axios.prototype.request, context); - utils_default.extend(instance, Axios.prototype, context, { allOwnKeys: true }); - utils_default.extend(instance, context, null, { allOwnKeys: true }); - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - return instance; -} -var axios = createInstance(defaults); -axios.Axios = Axios; -axios.CanceledError = CanceledError; -axios.CancelToken = CancelToken; -axios.isCancel = isCancel; -axios.VERSION = VERSION; -axios.toFormData = toFormData; -axios.AxiosError = AxiosError; -axios.Cancel = axios.CanceledError; -axios.all = function all(promises) { - return Promise.all(promises); -}; -axios.spread = spread; -axios.isAxiosError = isAxiosError; -axios.mergeConfig = mergeConfig; -axios.AxiosHeaders = AxiosHeaders; -axios.formToJSON = (thing) => formDataToJSON(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); -axios.getAdapter = adapters_default.getAdapter; -axios.HttpStatusCode = HttpStatusCode; -axios.default = axios; -//#endregion -//#region src/types/binding.ts -var ErrorCodes = { - AUTHENTICATION_FAILED: "AUTHENTICATION_FAILED", - AUTHORIZATION_FAILED: "AUTHORIZATION_FAILED", - RESOURCE_NOT_FOUND: "RESOURCE_NOT_FOUND", - INTERNAL_ERROR: "INTERNAL_ERROR", - BAD_REQUEST: "BAD_REQUEST", - CLUSTER_CONNECTION_FAILED: "CLUSTER_CONNECTION_FAILED" -}; -function isKubeBindError(error) { - return error && typeof error === "object" && error.kind === "Error" && error.apiVersion && error.message && error.code; -} -//#endregion -//#region src/services/http.ts -var StructuredError = class extends Error { - constructor(kubeBindError, httpStatus) { - super(kubeBindError.message); - _defineProperty(this, "kubeBindError", void 0); - _defineProperty(this, "httpStatus", void 0); - this.kubeBindError = kubeBindError; - this.httpStatus = httpStatus; - this.name = "StructuredError"; - } -}; -var HttpClient = class { - constructor() { - _defineProperty(this, "client", void 0); - this.client = axios.create({ - baseURL: "/api", - timeout: 3e4, - withCredentials: true, - headers: { "Content-Type": "application/json" } - }); - this.setupInterceptors(); - } - setupInterceptors() { - this.client.interceptors.request.use((config) => { - return config; - }, (error) => { - return Promise.reject(error); - }); - this.client.interceptors.response.use((response) => response, (error) => { - var _error$response, _error$response2; - const status = (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status; - const responseData = (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.data; - if (responseData && isKubeBindError(responseData)) { - if (responseData.code === ErrorCodes.AUTHENTICATION_FAILED) { - console.warn("Authentication expired, need to re-authenticate"); - window.dispatchEvent(new CustomEvent("auth-expired")); - } - return Promise.reject(new StructuredError(responseData, status)); - } - return Promise.reject(error); - }); - } - get(url, config) { - var _this = this; - return _asyncToGenerator(function* () { - return _this.client.get(url, config); - })(); - } - post(url, data, config) { - var _this2 = this; - return _asyncToGenerator(function* () { - return _this2.client.post(url, data, config); - })(); - } - put(url, data, config) { - var _this3 = this; - return _asyncToGenerator(function* () { - return _this3.client.put(url, data, config); - })(); - } - delete(url, config) { - var _this4 = this; - return _asyncToGenerator(function* () { - return _this4.client.delete(url, config); - })(); - } - getPublic(url, config) { - return _asyncToGenerator(function* () { - return axios.get(`/api${url}`, config); - })(); - } -}; -var httpClient = new HttpClient(); -//#endregion -//#region src/services/auth.ts -var PRESERVED_PARAMS_STORAGE_KEY = "kube-bind-preserved-params"; -var AuthService = class { - isAuthenticated() { - var _this = this; - return _asyncToGenerator(function* () { - return (yield _this.checkAuthentication()).isAuthenticated; - })(); - } - checkAuthentication() { - return _asyncToGenerator(function* () { - try { - const clusterId = new URLSearchParams(window.location.search).get("cluster_id") || ""; - const authCheckUrl = clusterId ? `/ping?cluster_id=${clusterId}` : "/ping"; - const response = yield httpClient.get(authCheckUrl); - const isAuth = response.status === 200; - console.log("Auth check:", { - clusterId, - status: response.status, - isAuth - }); - return { isAuthenticated: isAuth }; - } catch (error) { - var _error$response, _error$response2; - if (error instanceof StructuredError) { - const kubeError = error.kubeBindError; - if (kubeError.code === ErrorCodes.AUTHENTICATION_FAILED || kubeError.code === ErrorCodes.AUTHORIZATION_FAILED) return { - isAuthenticated: false, - error: kubeError.message - }; - } - if ((error === null || error === void 0 || (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401 || (error === null || error === void 0 || (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.status) === 403) { - console.log("Auth check failed with authentication error but no structured response"); - return { - isAuthenticated: false, - error: "Authentication required" - }; - } - console.error("Auth check error:", error); - return { - isAuthenticated: false, - error: "Authentication check failed" - }; - } - })(); - } - initiateAuth(sessionId, clusterId, consumerId) { - return _asyncToGenerator(function* () { - const authUrl = `/api/authorize`; - const redirect_url = window.location.origin + window.location.pathname; - const currentParams = new URLSearchParams(window.location.search); - const paramsToPreserve = {}; - if (currentParams.has("consumer_id")) paramsToPreserve.consumer_id = currentParams.get("consumer_id"); - if (currentParams.has("session_id")) paramsToPreserve.session_id = currentParams.get("session_id"); - if (currentParams.has("redirect_url")) paramsToPreserve.redirect_url = currentParams.get("redirect_url"); - if (currentParams.has("cluster_id")) paramsToPreserve.cluster_id = currentParams.get("cluster_id"); - sessionStorage.setItem(PRESERVED_PARAMS_STORAGE_KEY, JSON.stringify(paramsToPreserve)); - const params = new URLSearchParams({ - session_id: sessionId, - redirect_url, - cluster_id: clusterId, - client_type: "ui" - }); - if (consumerId) params.set("consumer_id", consumerId); - window.location.href = `${authUrl}?${params}`; - })(); - } - logout() { - return _asyncToGenerator(function* () { - try { - const clusterId = new URLSearchParams(window.location.search).get("cluster_id") || ""; - const logoutUrl = clusterId ? `/api/logout?cluster_id=${encodeURIComponent(clusterId)}` : "/api/logout"; - const response = yield httpClient.post(logoutUrl); - console.log("Logout response:", { - status: response.status, - clusterId - }); - window.location.href = window.location.origin + window.location.pathname; - } catch (error) { - console.error("Logout error:", error); - window.location.reload(); - } - })(); - } - getSessionCookieName() { - const clusterId = new URLSearchParams(window.location.search).get("cluster_id") || ""; - return clusterId ? `kube-bind-${clusterId}` : "kube-bind"; - } - isCliFlow() { - if (new URLSearchParams(window.location.search).has("redirect_url")) return true; - const preservedParams = sessionStorage.getItem(PRESERVED_PARAMS_STORAGE_KEY); - if (preservedParams) try { - return !!JSON.parse(preservedParams).redirect_url; - } catch (e) { - return false; - } - return false; - } - redirectToCliCallback(bindingResponseData) { - const urlParams = new URLSearchParams(window.location.search); - let redirectUrl = urlParams.get("redirect_url"); - let sessionId = urlParams.get("session_id"); - let consumerId = urlParams.get("consumer_id"); - if (!redirectUrl) { - const preservedParams = sessionStorage.getItem(PRESERVED_PARAMS_STORAGE_KEY); - if (preservedParams) try { - const params = JSON.parse(preservedParams); - redirectUrl = params.redirect_url || null; - sessionId = sessionId || params.session_id || null; - consumerId = consumerId || params.consumer_id || null; - } catch (e) { - console.error("Failed to parse preserved params:", e); - } - } - if (redirectUrl) { - const callbackUrl = new URL(redirectUrl); - if (sessionId) callbackUrl.searchParams.append("session_id", sessionId); - if (consumerId) callbackUrl.searchParams.append("consumer_id", consumerId); - const base64Response = btoa(JSON.stringify(bindingResponseData)); - callbackUrl.searchParams.append("binding_response", base64Response); - window.location.href = callbackUrl.toString(); - } else console.error("No redirect URL found for CLI callback"); - } - restorePreservedParams() { - const preservedParamsJson = sessionStorage.getItem(PRESERVED_PARAMS_STORAGE_KEY); - if (!preservedParamsJson) return false; - try { - const preservedParams = JSON.parse(preservedParamsJson); - const currentParams = new URLSearchParams(window.location.search); - let needsUpdate = false; - for (const [key, value] of Object.entries(preservedParams)) if (!currentParams.has(key)) { - currentParams.set(key, value); - needsUpdate = true; - } - if (needsUpdate) { - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - const newUrl = `${window.location.pathname}?${currentParams.toString()}`; - window.location.replace(newUrl); - return true; - } else { - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - return false; - } - } catch (error) { - console.error("Failed to restore preserved params:", error); - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - return false; - } - } -}; -var authService = new AuthService(); -//#endregion -//#region src/App.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1$5 = { id: "app" }; -var _hoisted_2$5 = { class: "header" }; -var _hoisted_3$5 = { class: "header-content" }; -var _hoisted_4$5 = { - key: 0, - class: "user-section" -}; -var _hoisted_5$5 = { class: "main" }; -var _hoisted_6$5 = { - key: 0, - class: "auth-placeholder" -}; -var _hoisted_7$5 = { - key: 0, - class: "auth-error" -}; -var _hoisted_8$4 = { class: "error-content" }; -var _hoisted_9$4 = { key: 1 }; -var _hoisted_10$4 = ["disabled"]; -var _hoisted_11$4 = { key: 0 }; -var _hoisted_12$4 = { key: 1 }; -var App_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({ - __name: "App", - setup(__props) { - const route = useRoute(); - const authStatus = /* @__PURE__ */ ref({ - isAuthenticated: false, - loading: true, - error: null - }); - const hasAttemptedAuth = /* @__PURE__ */ ref(false); - const checkAuthStatus = function() { - var _ref = _asyncToGenerator(function* () { - try { - const result = yield authService.checkAuthentication(); - authStatus.value.isAuthenticated = result.isAuthenticated; - authStatus.value.error = result.error || null; - } catch (error) { - console.error("Auth check failed:", error); - authStatus.value.error = "Authentication check failed"; - } finally { - authStatus.value.loading = false; - } - }); - return function checkAuthStatus() { - return _ref.apply(this, arguments); - }; - }(); - const authenticate = function() { - var _ref2 = _asyncToGenerator(function* () { - try { - hasAttemptedAuth.value = true; - const cluster = route.query.cluster_id || ""; - const sessionId = route.query.session_id || generateSessionId(); - const consumerId = route.query.consumer_id || ""; - yield authService.initiateAuth(sessionId, cluster, consumerId); - } catch (error) { - console.error("Authentication failed:", error); - authStatus.value.error = "Authentication failed"; - } - }); - return function authenticate() { - return _ref2.apply(this, arguments); - }; - }(); - const logout = function() { - var _ref3 = _asyncToGenerator(function* () { - try { - yield authService.logout(); - authStatus.value.isAuthenticated = false; - } catch (error) { - console.error("Logout failed:", error); - } - }); - return function logout() { - return _ref3.apply(this, arguments); - }; - }(); - const generateSessionId = () => { - return Math.random().toString(36).substring(2) + Date.now().toString(36); - }; - onMounted(() => { - if (authService.restorePreservedParams()) return; - checkAuthStatus(); - window.addEventListener("auth-expired", () => { - console.log("Received auth-expired event, updating authentication status"); - authStatus.value.isAuthenticated = false; - authStatus.value.error = "Session expired. Please re-authenticate."; - const hasRequiredParams = route.query.cluster_id || route.query.session_id; - if (hasRequiredParams && !hasAttemptedAuth.value) { - console.log("Auto-redirecting to authentication due to auth-expired event"); - authenticate(); - } else if (!hasRequiredParams) console.log("No cluster_id or session_id parameters found, requiring manual authentication"); - else console.log("Authentication already attempted, preventing hot loop"); - }); - }); - return (_ctx, _cache) => { - const _component_router_view = resolveComponent("router-view"); - return openBlock(), createElementBlock("div", _hoisted_1$5, [createBaseVNode("header", _hoisted_2$5, [createBaseVNode("div", _hoisted_3$5, [_cache[2] || (_cache[2] = createBaseVNode("div", { class: "brand" }, [createBaseVNode("div", { class: "logo" }, [createBaseVNode("img", { - src: "" + new URL("logo.C_e3UAcl.png", import.meta.url).href, - alt: "Kube Bind" - })]), createBaseVNode("h1", null, "Kube Bind")], -1)), authStatus.value.isAuthenticated ? (openBlock(), createElementBlock("div", _hoisted_4$5, [_cache[1] || (_cache[1] = createBaseVNode("div", { class: "user-info" }, [createBaseVNode("div", { class: "status-indicator" }), createBaseVNode("span", { class: "welcome-text" }, "Connected")], -1)), createBaseVNode("button", { - onClick: logout, - class: "logout-btn" - }, [..._cache[0] || (_cache[0] = [createBaseVNode("svg", { - width: "16", - height: "16", - viewBox: "0 0 24 24", - fill: "none", - xmlns: "http://www.w3.org/2000/svg" - }, [ - createBaseVNode("path", { - d: "M9 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H9", - stroke: "currentColor", - "stroke-width": "2", - "stroke-linecap": "round", - "stroke-linejoin": "round" - }), - createBaseVNode("path", { - d: "M16 17L21 12L16 7", - stroke: "currentColor", - "stroke-width": "2", - "stroke-linecap": "round", - "stroke-linejoin": "round" - }), - createBaseVNode("path", { - d: "M21 12H9", - stroke: "currentColor", - "stroke-width": "2", - "stroke-linecap": "round", - "stroke-linejoin": "round" - }) - ], -1), createTextVNode(" Sign out ", -1)])])])) : createCommentVNode("", true)])]), createBaseVNode("main", _hoisted_5$5, [!authStatus.value.isAuthenticated ? (openBlock(), createElementBlock("div", _hoisted_6$5, [ - _cache[5] || (_cache[5] = createBaseVNode("h2", null, "Authentication Required", -1)), - authStatus.value.error ? (openBlock(), createElementBlock("div", _hoisted_7$5, [_cache[4] || (_cache[4] = createBaseVNode("div", { class: "error-icon" }, "⚠️", -1)), createBaseVNode("div", _hoisted_8$4, [_cache[3] || (_cache[3] = createBaseVNode("h3", null, "Authentication Error", -1)), createBaseVNode("p", null, toDisplayString(authStatus.value.error), 1)])])) : (openBlock(), createElementBlock("p", _hoisted_9$4, "Please authenticate to access resources.")), - createBaseVNode("button", { - onClick: authenticate, - class: "auth-btn", - disabled: authStatus.value.loading - }, [authStatus.value.loading ? (openBlock(), createElementBlock("span", _hoisted_11$4, "Authenticating...")) : (openBlock(), createElementBlock("span", _hoisted_12$4, toDisplayString(authStatus.value.error ? "Try Again" : "Authenticate"), 1))], 8, _hoisted_10$4) - ])) : (openBlock(), createBlock(_component_router_view, { - key: 1, - "auth-status": authStatus.value - }, null, 8, ["auth-status"]))])]); - }; - } -}); -//#endregion -//#region \0plugin-vue:export-helper -var _plugin_vue_export_helper_default = (sfc, props) => { - const target = sfc.__vccOpts || sfc; - for (const [key, val] of props) target[key] = val; - return target; -}; -//#endregion -//#region src/App.vue -var App_default = /*#__PURE__*/ _plugin_vue_export_helper_default(App_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-eb0cbf2e"]]); -//#endregion -//#region src/components/BindingResult.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1$4 = { class: "binding-header" }; -var _hoisted_2$4 = { class: "binding-content" }; -var _hoisted_3$4 = { class: "method-tabs" }; -var _hoisted_4$4 = { - key: 0, - class: "instructions-section" -}; -var _hoisted_5$4 = { class: "step-group" }; -var _hoisted_6$4 = { class: "upload-block" }; -var _hoisted_7$4 = ["disabled"]; -var _hoisted_8$3 = { - key: 0, - class: "file-info" -}; -var _hoisted_9$3 = { class: "step-group" }; -var _hoisted_10$3 = ["disabled"]; -var _hoisted_11$3 = { class: "step-group" }; -var _hoisted_12$3 = ["disabled"]; -var _hoisted_13$3 = { - key: 0, - class: "spinner" -}; -var _hoisted_14$3 = { - key: 0, - class: "status-message success" -}; -var _hoisted_15$3 = { - key: 1, - class: "status-message error" -}; -var _hoisted_16$3 = { - key: 1, - class: "instructions-section" -}; -var _hoisted_17$3 = { class: "step-group" }; -var _hoisted_18$2 = { class: "command-block" }; -var _hoisted_19$2 = { class: "step-group" }; -var _hoisted_20$2 = { class: "command-block" }; -var _hoisted_21$2 = { class: "step-group" }; -var _hoisted_22$2 = { class: "command-block" }; -var _hoisted_23$2 = { - key: 2, - class: "instructions-section" -}; -var _hoisted_24$2 = { class: "step-group" }; -var _hoisted_25$2 = { class: "command-block" }; -var _hoisted_26$2 = { class: "step-group" }; -var _hoisted_27$2 = { class: "command-block" }; -var _hoisted_28$2 = { class: "step-group" }; -var _hoisted_29$2 = { class: "command-block" }; -//#endregion -//#region src/components/BindingResult.vue -var BindingResult_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ - __name: "BindingResult", - props: { - show: { type: Boolean }, - templateName: {}, - bindingResponse: {} - }, - emits: ["close"], - setup(__props, { emit: __emit }) { - const props = __props; - const emit = __emit; - const activeMethod = /* @__PURE__ */ ref("oneclick"); - const kubeconfigData = /* @__PURE__ */ ref(null); - const kubeconfigFileName = /* @__PURE__ */ ref(""); - const applyStatus = /* @__PURE__ */ ref("idle"); - const applyMessage = /* @__PURE__ */ ref(""); - const kubeconfigFileInput = /* @__PURE__ */ ref(null); - const hostAliasInput = /* @__PURE__ */ ref(""); - const bindingName = computed(() => { - return props.bindingResponse.bindingName || props.templateName; - }); - const kubeconfigSecretName = computed(() => { - return `kubeconfig-${bindingName.value.toLowerCase().replace(/[^a-z0-9-]/g, "-")}`; - }); - const createSecretCommand = computed(() => { - return `kubectl create secret generic ${kubeconfigSecretName.value} --from-file=kubeconfig=./kubeconfig.yaml -n kube-bind`; - }); - const bindCommand = computed(() => { - return `kubectl bind apiservice --remote-kubeconfig-namespace kube-bind --remote-kubeconfig-name ${kubeconfigSecretName.value} -f apiservice-export.yaml`; - }); - const handleKubeconfigUpload = (event) => { - var _target$files; - const file = (_target$files = event.target.files) === null || _target$files === void 0 ? void 0 : _target$files[0]; - if (!file) return; - kubeconfigFileName.value = file.name; - applyStatus.value = "idle"; - applyMessage.value = ""; - const reader = new FileReader(); - reader.onload = (e) => { - var _e$target; - const content = (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.result; - kubeconfigData.value = btoa(content); - }; - reader.readAsText(file); - }; - const applyToConsumer = function() { - var _ref = _asyncToGenerator(function* () { - if (!kubeconfigData.value) return; - applyStatus.value = "loading"; - applyMessage.value = ""; - try { - const response = yield fetch("/api/apply-binding", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - consumerKubeconfig: kubeconfigData.value, - bindingName: bindingName.value, - hostAliases: hostAliasInput.value.trim() ? [hostAliasInput.value.trim()] : void 0 - }) - }); - if (!response.ok) { - const errorData = yield response.json().catch(() => null); - throw new Error((errorData === null || errorData === void 0 ? void 0 : errorData.message) || `HTTP ${response.status}`); - } - const result = yield response.json(); - applyStatus.value = "success"; - applyMessage.value = result.message; - if (result.konnectorDeployed) applyMessage.value += " (konnector was newly deployed)"; - } catch (error) { - applyStatus.value = "error"; - applyMessage.value = error.message || "Failed to apply binding"; - } - }); - return function applyToConsumer() { - return _ref.apply(this, arguments); - }; - }(); - const closeModal = () => { - emit("close"); - }; - const copyCommand = function() { - var _ref2 = _asyncToGenerator(function* (command) { - try { - yield navigator.clipboard.writeText(command); - } catch (err) { - console.error("Failed to copy command:", err); - const textarea = document.createElement("textarea"); - textarea.value = command; - document.body.appendChild(textarea); - textarea.select(); - document.execCommand("copy"); - document.body.removeChild(textarea); - } - }); - return function copyCommand(_x) { - return _ref2.apply(this, arguments); - }; - }(); - const triggerDownload = (content, filename, type = "text/yaml") => { - const blob = new Blob([content], { type }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - }; - const decodedKubeconfig = computed(() => { - try { - return atob(props.bindingResponse.kubeconfig); - } catch (_unused) { - return props.bindingResponse.kubeconfig; - } - }); - const bindingBundleYaml = computed(() => { - const kubeconfigBase64 = props.bindingResponse.kubeconfig; - const secretName = kubeconfigSecretName.value; - return `apiVersion: v1 -kind: Namespace -metadata: - name: kube-bind ---- -apiVersion: v1 -kind: Secret -metadata: - name: ${secretName} - namespace: kube-bind -type: Opaque -data: - kubeconfig: ${kubeconfigBase64} ---- -apiVersion: kube-bind.io/v1alpha2 -kind: APIServiceBindingBundle -metadata: - name: ${bindingName.value} -spec: - kubeconfigSecretRef: - name: ${secretName} - namespace: kube-bind - key: kubeconfig -`; - }); - const downloadBindingBundle = () => { - triggerDownload(bindingBundleYaml.value, "binding-bundle.yaml"); - }; - const downloadKonnectorManifests = function() { - var _ref3 = _asyncToGenerator(function* () { - try { - const response = yield fetch("/api/konnector-manifests"); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - triggerDownload(yield response.text(), "konnector.yaml"); - } catch (error) { - console.error("Failed to fetch konnector manifests:", error); - } - }); - return function downloadKonnectorManifests() { - return _ref3.apply(this, arguments); - }; - }(); - const downloadKubeconfig = () => { - triggerDownload(decodedKubeconfig.value, "kubeconfig.yaml"); - }; - const downloadAPIRequests = () => { - try { - triggerDownload(props.bindingResponse.requests.map((req) => { - if (typeof req === "string") return req.trim(); - else return JSON.stringify(req, null, 2); - }).join("\n---\n"), "apiservice-export.yaml"); - } catch (error) { - console.error("Failed to format API requests:", error); - triggerDownload(JSON.stringify(props.bindingResponse.requests, null, 2), "apiservice-export.json", "application/json"); - } - }; - return (_ctx, _cache) => { - return __props.show ? (openBlock(), createElementBlock("div", { - key: 0, - class: "binding-modal-overlay", - onClick: closeModal - }, [createBaseVNode("div", { - class: "binding-modal", - onClick: _cache[10] || (_cache[10] = withModifiers(() => {}, ["stop"])) - }, [ - createBaseVNode("div", _hoisted_1$4, [createBaseVNode("h3", null, "Setup Binding: " + toDisplayString(__props.templateName), 1), createBaseVNode("button", { - onClick: closeModal, - class: "close-btn" - }, "×")]), - createBaseVNode("div", _hoisted_2$4, [ - createBaseVNode("div", _hoisted_3$4, [ - createBaseVNode("button", { - class: normalizeClass(["method-tab", { active: activeMethod.value === "oneclick" }]), - onClick: _cache[0] || (_cache[0] = ($event) => activeMethod.value = "oneclick") - }, " Provide Kubeconfig ", 2), - createBaseVNode("button", { - class: normalizeClass(["method-tab", { active: activeMethod.value === "bundle" }]), - onClick: _cache[1] || (_cache[1] = ($event) => activeMethod.value = "bundle") - }, " APIServiceBindingBundle ", 2), - createBaseVNode("button", { - class: normalizeClass(["method-tab", { active: activeMethod.value === "manual" }]), - onClick: _cache[2] || (_cache[2] = ($event) => activeMethod.value = "manual") - }, " Manual (CLI) ", 2) - ]), - activeMethod.value === "oneclick" ? (openBlock(), createElementBlock("div", _hoisted_4$4, [ - _cache[16] || (_cache[16] = createBaseVNode("p", { class: "instructions-text" }, " Upload your consumer cluster kubeconfig and we'll automatically deploy the konnector agent and configure the binding bundle for you. No CLI required. ", -1)), - _cache[17] || (_cache[17] = createBaseVNode("div", { class: "security-warning" }, [ - createBaseVNode("strong", null, "⚠️ Security Note:"), - createTextVNode(" Your kubeconfig will be used transiently to apply resources to your consumer cluster and will "), - createBaseVNode("strong", null, "not"), - createTextVNode(" be stored. The provider backend needs cluster-admin level access to deploy the konnector and create binding resources. ") - ], -1)), - createBaseVNode("div", _hoisted_5$4, [ - _cache[11] || (_cache[11] = createBaseVNode("h5", null, "Upload Consumer Kubeconfig", -1)), - _cache[12] || (_cache[12] = createBaseVNode("p", { class: "step-description" }, "Select the kubeconfig file for your consumer cluster.", -1)), - createBaseVNode("div", _hoisted_6$4, [createBaseVNode("input", { - type: "file", - ref_key: "kubeconfigFileInput", - ref: kubeconfigFileInput, - accept: ".yaml,.yml,.conf,.kubeconfig", - onChange: handleKubeconfigUpload, - class: "file-input", - disabled: applyStatus.value === "loading" - }, null, 40, _hoisted_7$4), kubeconfigFileName.value ? (openBlock(), createElementBlock("div", _hoisted_8$3, " 📄 " + toDisplayString(kubeconfigFileName.value), 1)) : createCommentVNode("", true)]) - ]), - createBaseVNode("div", _hoisted_9$3, [ - _cache[13] || (_cache[13] = createBaseVNode("h5", null, [createTextVNode("Host Aliases "), createBaseVNode("span", { class: "optional-label" }, "(optional)")], -1)), - _cache[14] || (_cache[14] = createBaseVNode("p", { class: "step-description" }, " Add host alias entries for the konnector pods if the provider hostname doesn't resolve correctly from the consumer cluster (e.g., in Kind/Docker environments). ", -1)), - withDirectives(createBaseVNode("input", { - "onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => hostAliasInput.value = $event), - type: "text", - class: "text-input", - placeholder: "e.g. 172.19.0.2:kube-bind.dev.local", - disabled: applyStatus.value === "loading" - }, null, 8, _hoisted_10$3), [[vModelText, hostAliasInput.value]]), - _cache[15] || (_cache[15] = createBaseVNode("p", { class: "step-hint" }, "Format: IP:hostname1,hostname2", -1)) - ]), - createBaseVNode("div", _hoisted_11$3, [createBaseVNode("button", { - onClick: applyToConsumer, - class: "apply-btn", - disabled: !kubeconfigData.value || applyStatus.value === "loading" - }, [applyStatus.value === "loading" ? (openBlock(), createElementBlock("span", _hoisted_13$3)) : createCommentVNode("", true), createTextVNode(" " + toDisplayString(applyStatus.value === "loading" ? "Applying..." : "Apply to Consumer Cluster"), 1)], 8, _hoisted_12$3)]), - applyStatus.value === "success" ? (openBlock(), createElementBlock("div", _hoisted_14$3, " ✅ " + toDisplayString(applyMessage.value), 1)) : createCommentVNode("", true), - applyStatus.value === "error" ? (openBlock(), createElementBlock("div", _hoisted_15$3, " ❌ " + toDisplayString(applyMessage.value), 1)) : createCommentVNode("", true) - ])) : createCommentVNode("", true), - activeMethod.value === "bundle" ? (openBlock(), createElementBlock("div", _hoisted_16$3, [ - _cache[26] || (_cache[26] = createBaseVNode("p", { class: "instructions-text" }, " Download and apply these files to your consumer cluster. The APIServiceBindingBundle will automatically discover and bind services from the provider. ", -1)), - createBaseVNode("div", _hoisted_17$3, [ - _cache[19] || (_cache[19] = createBaseVNode("h5", null, "1. Deploy the konnector agent (one-time)", -1)), - _cache[20] || (_cache[20] = createBaseVNode("p", { class: "step-description" }, "Skip this step if the konnector is already deployed on your consumer cluster.", -1)), - createBaseVNode("div", { class: "download-block" }, [createBaseVNode("div", { class: "download-actions" }, [createBaseVNode("button", { - onClick: downloadKonnectorManifests, - class: "download-btn primary" - }, "Download konnector.yaml")])]), - createBaseVNode("div", _hoisted_18$2, [_cache[18] || (_cache[18] = createBaseVNode("code", null, "kubectl apply -f konnector.yaml", -1)), createBaseVNode("button", { - onClick: _cache[4] || (_cache[4] = ($event) => copyCommand("kubectl apply -f konnector.yaml")), - class: "copy-cmd-btn" - }, "Copy")]) - ]), - createBaseVNode("div", _hoisted_19$2, [ - _cache[22] || (_cache[22] = createBaseVNode("h5", null, "2. Apply the binding bundle", -1)), - _cache[23] || (_cache[23] = createBaseVNode("p", { class: "step-description" }, "Creates the kubeconfig secret and an APIServiceBindingBundle that auto-discovers and binds all services.", -1)), - createBaseVNode("div", { class: "download-block" }, [createBaseVNode("div", { class: "download-actions" }, [createBaseVNode("button", { - onClick: downloadBindingBundle, - class: "download-btn primary" - }, "Download binding-bundle.yaml")])]), - createBaseVNode("div", _hoisted_20$2, [_cache[21] || (_cache[21] = createBaseVNode("code", null, "kubectl apply -f binding-bundle.yaml", -1)), createBaseVNode("button", { - onClick: _cache[5] || (_cache[5] = ($event) => copyCommand("kubectl apply -f binding-bundle.yaml")), - class: "copy-cmd-btn" - }, "Copy")]) - ]), - createBaseVNode("div", _hoisted_21$2, [_cache[25] || (_cache[25] = createBaseVNode("h5", null, "3. Verify", -1)), createBaseVNode("div", _hoisted_22$2, [_cache[24] || (_cache[24] = createBaseVNode("code", null, "kubectl get apiservicebindingbundles,apiservicebindings", -1)), createBaseVNode("button", { - onClick: _cache[6] || (_cache[6] = ($event) => copyCommand("kubectl get apiservicebindingbundles,apiservicebindings")), - class: "copy-cmd-btn" - }, "Copy")])]) - ])) : createCommentVNode("", true), - activeMethod.value === "manual" ? (openBlock(), createElementBlock("div", _hoisted_23$2, [ - _cache[32] || (_cache[32] = createBaseVNode("p", { class: "instructions-text" }, " Download the required files and run the following commands on your consumer cluster. ", -1)), - createBaseVNode("div", { class: "step-group" }, [_cache[27] || (_cache[27] = createBaseVNode("h5", null, "1. Download required files", -1)), createBaseVNode("div", { class: "download-block" }, [createBaseVNode("div", { class: "download-actions" }, [createBaseVNode("button", { - onClick: downloadKubeconfig, - class: "download-btn primary" - }, "Download kubeconfig.yaml"), createBaseVNode("button", { - onClick: downloadAPIRequests, - class: "download-btn primary" - }, "Download apiservice-export.yaml")])])]), - createBaseVNode("div", _hoisted_24$2, [_cache[29] || (_cache[29] = createBaseVNode("h5", null, "2. Create kube-bind namespace", -1)), createBaseVNode("div", _hoisted_25$2, [_cache[28] || (_cache[28] = createBaseVNode("code", null, "kubectl create namespace kube-bind --dry-run=client -o yaml | kubectl apply -f -", -1)), createBaseVNode("button", { - onClick: _cache[7] || (_cache[7] = ($event) => copyCommand("kubectl create namespace kube-bind --dry-run=client -o yaml | kubectl apply -f -")), - class: "copy-cmd-btn" - }, "Copy")])]), - createBaseVNode("div", _hoisted_26$2, [_cache[30] || (_cache[30] = createBaseVNode("h5", null, "3. Create kubeconfig secret", -1)), createBaseVNode("div", _hoisted_27$2, [createBaseVNode("code", null, toDisplayString(createSecretCommand.value), 1), createBaseVNode("button", { - onClick: _cache[8] || (_cache[8] = ($event) => copyCommand(createSecretCommand.value)), - class: "copy-cmd-btn" - }, "Copy")])]), - createBaseVNode("div", _hoisted_28$2, [_cache[31] || (_cache[31] = createBaseVNode("h5", null, "4. Bind the API service", -1)), createBaseVNode("div", _hoisted_29$2, [createBaseVNode("code", null, toDisplayString(bindCommand.value), 1), createBaseVNode("button", { - onClick: _cache[9] || (_cache[9] = ($event) => copyCommand(bindCommand.value)), - class: "copy-cmd-btn" - }, "Copy")])]) - ])) : createCommentVNode("", true) - ]), - createBaseVNode("div", { class: "binding-footer" }, [createBaseVNode("button", { - onClick: closeModal, - class: "ok-btn" - }, "Close")]) - ])])) : createCommentVNode("", true); - }; - } -}), [["__scopeId", "data-v-6ba48543"]]); -//#endregion -//#region src/components/TemplateBindingModal.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1$3 = { class: "modal-header" }; -var _hoisted_2$3 = { class: "modal-content" }; -var _hoisted_3$3 = { class: "binding-name-section" }; -var _hoisted_4$3 = { - key: 0, - class: "form-help" -}; -var _hoisted_5$3 = { - key: 1, - class: "form-error" -}; -var _hoisted_6$3 = { class: "template-details" }; -var _hoisted_7$3 = { - key: 0, - class: "detail-section" -}; -var _hoisted_8$2 = { class: "description" }; -var _hoisted_9$2 = { - key: 1, - class: "detail-section" -}; -var _hoisted_10$2 = { class: "resource-list" }; -var _hoisted_11$2 = { class: "resource-name" }; -var _hoisted_12$2 = { class: "resource-group" }; -var _hoisted_13$2 = { - key: 0, - class: "resource-versions" -}; -var _hoisted_14$2 = { - key: 2, - class: "detail-section" -}; -var _hoisted_15$2 = { class: "permission-list" }; -var _hoisted_16$2 = { class: "permission-name" }; -var _hoisted_17$2 = { class: "permission-group" }; -var _hoisted_18$1 = { - key: 0, - class: "permission-selector" -}; -var _hoisted_19$1 = { - key: 0, - class: "selector-section" -}; -var _hoisted_20$1 = { class: "selector-content" }; -var _hoisted_21$1 = { class: "label-key" }; -var _hoisted_22$1 = { class: "label-value" }; -var _hoisted_23$1 = { - key: 1, - class: "selector-section" -}; -var _hoisted_24$1 = { class: "selector-content" }; -var _hoisted_25$1 = { class: "resource-name" }; -var _hoisted_26$1 = { - key: 0, - class: "resource-namespace" -}; -var _hoisted_27$1 = { - key: 2, - class: "selector-section" -}; -var _hoisted_28$1 = { class: "selector-content" }; -var _hoisted_29$1 = { class: "reference-header" }; -var _hoisted_30$1 = { class: "reference-resource" }; -var _hoisted_31$1 = { class: "reference-group" }; -var _hoisted_32$1 = { - key: 0, - class: "reference-paths" -}; -var _hoisted_33$1 = { - key: 0, - class: "json-path" -}; -var _hoisted_34$1 = { class: "path-value" }; -var _hoisted_35$1 = { - key: 1, - class: "json-path" -}; -var _hoisted_36$1 = { class: "path-value" }; -var _hoisted_37 = { - key: 3, - class: "detail-section" -}; -var _hoisted_38 = { class: "namespace-list" }; -var _hoisted_39 = { class: "namespace-name" }; -var _hoisted_40 = { - key: 0, - class: "namespace-desc" -}; -var _hoisted_41 = { class: "modal-footer" }; -var _hoisted_42 = ["disabled"]; -var _hoisted_43 = { key: 0 }; -var _hoisted_44 = { key: 1 }; -//#endregion -//#region src/components/TemplateBindingModal.vue -var TemplateBindingModal_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ - __name: "TemplateBindingModal", - props: { - show: { type: Boolean }, - template: {}, - isCliFlow: { type: Boolean } - }, - emits: ["close", "bind"], - setup(__props, { emit: __emit }) { - const props = __props; - const emit = __emit; - const binding = /* @__PURE__ */ ref(false); - const bindingName = /* @__PURE__ */ ref(""); - const isValidBindingName = computed(() => { - const name = bindingName.value.trim(); - if (!name) return false; - return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/.test(name); - }); - watch(() => props.template, (newTemplate) => { - var _newTemplate$metadata; - if (newTemplate === null || newTemplate === void 0 || (_newTemplate$metadata = newTemplate.metadata) === null || _newTemplate$metadata === void 0 ? void 0 : _newTemplate$metadata.name) bindingName.value = newTemplate.metadata.name.toLowerCase().replace(/[^a-z0-9-]/g, "-"); - }, { immediate: true }); - const closeModal = () => { - if (!binding.value) emit("close"); - }; - const handleBind = function() { - var _ref = _asyncToGenerator(function* () { - const name = bindingName.value.trim(); - if (!name || binding.value || !isValidBindingName.value) return; - binding.value = true; - try { - emit("bind", props.template.metadata.name, name); - } finally { - binding.value = false; - } - }); - return function handleBind() { - return _ref.apply(this, arguments); - }; - }(); - const getLabelSelectorLabels = (selector) => { - if (!selector) return {}; - if (selector.matchLabels) return selector.matchLabels; - return {}; - }; - const getNamedResourceKey = (resource) => { - if (typeof resource === "string") return resource; - if (typeof resource === "object" && resource.name) return resource.namespace ? `${resource.namespace}/${resource.name}` : resource.name; - return JSON.stringify(resource); - }; - const getNamedResourceName = (resource) => { - if (typeof resource === "string") return resource; - if (typeof resource === "object" && resource.name) return resource.name; - return JSON.stringify(resource); - }; - const getNamedResourceNamespace = (resource) => { - if (typeof resource === "object" && resource.namespace) return resource.namespace; - return ""; - }; - const getReferenceKey = (ref) => { - if (typeof ref === "object") return `${ref.group || "core"}/${ref.resource || "unknown"}`; - return JSON.stringify(ref); - }; - return (_ctx, _cache) => { - return __props.show ? (openBlock(), createElementBlock("div", { - key: 0, - class: "modal-overlay", - onClick: closeModal - }, [createBaseVNode("div", { - class: "modal", - onClick: _cache[1] || (_cache[1] = withModifiers(() => {}, ["stop"])) - }, [ - createBaseVNode("div", _hoisted_1$3, [createBaseVNode("h3", null, "Bind Template: " + toDisplayString(__props.template.metadata.name), 1), createBaseVNode("button", { - onClick: closeModal, - class: "close-btn" - }, "×")]), - createBaseVNode("div", _hoisted_2$3, [createBaseVNode("div", _hoisted_3$3, [ - _cache[2] || (_cache[2] = createBaseVNode("label", { - for: "bindingName", - class: "form-label" - }, "Binding Name", -1)), - withDirectives(createBaseVNode("input", { - id: "bindingName", - "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => bindingName.value = $event), - type: "text", - class: normalizeClass(["form-input", { "invalid": !isValidBindingName.value }]), - placeholder: "Enter a unique name for this binding", - onKeyup: withKeys(handleBind, ["enter"]) - }, null, 34), [[vModelText, bindingName.value]]), - isValidBindingName.value ? (openBlock(), createElementBlock("p", _hoisted_4$3, "This name will be used to identify your binding in the CLI.")) : (openBlock(), createElementBlock("p", _hoisted_5$3, "Name must be lowercase letters, numbers, and hyphens only. Must start and end with alphanumeric characters.")) - ]), createBaseVNode("div", _hoisted_6$3, [ - _cache[10] || (_cache[10] = createBaseVNode("h4", null, "Template Details", -1)), - __props.template.spec.description ? (openBlock(), createElementBlock("div", _hoisted_7$3, [_cache[3] || (_cache[3] = createBaseVNode("h5", null, "Description", -1)), createBaseVNode("p", _hoisted_8$2, toDisplayString(__props.template.spec.description), 1)])) : createCommentVNode("", true), - __props.template.spec.resources && __props.template.spec.resources.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_9$2, [createBaseVNode("h5", null, "Resources (" + toDisplayString(__props.template.spec.resources.length) + ")", 1), createBaseVNode("div", _hoisted_10$2, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.template.spec.resources, (resource) => { - return openBlock(), createElementBlock("div", { - key: `${resource.group}/${resource.resource}`, - class: "resource-item" - }, [ - createBaseVNode("span", _hoisted_11$2, toDisplayString(resource.resource), 1), - createBaseVNode("span", _hoisted_12$2, toDisplayString(resource.group || "core"), 1), - resource.versions ? (openBlock(), createElementBlock("span", _hoisted_13$2, toDisplayString(resource.versions.join(", v")), 1)) : createCommentVNode("", true) - ]); - }), 128))])])) : createCommentVNode("", true), - __props.template.spec.permissionClaims && __props.template.spec.permissionClaims.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_14$2, [createBaseVNode("h5", null, "Permission Claims (" + toDisplayString(__props.template.spec.permissionClaims.length) + ")", 1), createBaseVNode("div", _hoisted_15$2, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.template.spec.permissionClaims, (claim) => { - return openBlock(), createElementBlock("div", { - key: `${claim.group}/${claim.resource}`, - class: "permission-item" - }, [ - createBaseVNode("span", _hoisted_16$2, toDisplayString(claim.resource), 1), - createBaseVNode("span", _hoisted_17$2, toDisplayString(claim.group || "core"), 1), - claim.selector ? (openBlock(), createElementBlock("div", _hoisted_18$1, [ - claim.selector.labelSelector ? (openBlock(), createElementBlock("div", _hoisted_19$1, [_cache[5] || (_cache[5] = createBaseVNode("strong", { class: "selector-title" }, "Label Selector:", -1)), createBaseVNode("div", _hoisted_20$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(getLabelSelectorLabels(claim.selector.labelSelector), (value, key) => { - return openBlock(), createElementBlock("div", { - key, - class: "label-item" - }, [ - createBaseVNode("span", _hoisted_21$1, toDisplayString(key), 1), - _cache[4] || (_cache[4] = createBaseVNode("span", { class: "label-separator" }, "=", -1)), - createBaseVNode("span", _hoisted_22$1, toDisplayString(value), 1) - ]); - }), 128))])])) : createCommentVNode("", true), - claim.selector.namedResources && claim.selector.namedResources.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_23$1, [_cache[6] || (_cache[6] = createBaseVNode("strong", { class: "selector-title" }, "Named Resources:", -1)), createBaseVNode("div", _hoisted_24$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(claim.selector.namedResources, (resource) => { - return openBlock(), createElementBlock("div", { - key: getNamedResourceKey(resource), - class: "named-resource-item" - }, [createBaseVNode("span", _hoisted_25$1, toDisplayString(getNamedResourceName(resource)), 1), getNamedResourceNamespace(resource) ? (openBlock(), createElementBlock("span", _hoisted_26$1, " in " + toDisplayString(getNamedResourceNamespace(resource)), 1)) : createCommentVNode("", true)]); - }), 128))])])) : createCommentVNode("", true), - claim.selector.references && claim.selector.references.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_27$1, [_cache[9] || (_cache[9] = createBaseVNode("strong", { class: "selector-title" }, "References:", -1)), createBaseVNode("div", _hoisted_28$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(claim.selector.references, (ref) => { - return openBlock(), createElementBlock("div", { - key: getReferenceKey(ref), - class: "reference-item" - }, [createBaseVNode("div", _hoisted_29$1, [createBaseVNode("span", _hoisted_30$1, toDisplayString(ref.resource), 1), createBaseVNode("span", _hoisted_31$1, "(" + toDisplayString(ref.group || "core") + ")", 1)]), ref.jsonPath ? (openBlock(), createElementBlock("div", _hoisted_32$1, [ref.jsonPath.name ? (openBlock(), createElementBlock("div", _hoisted_33$1, [_cache[7] || (_cache[7] = createBaseVNode("span", { class: "path-label" }, "Name:", -1)), createBaseVNode("code", _hoisted_34$1, toDisplayString(ref.jsonPath.name), 1)])) : createCommentVNode("", true), ref.jsonPath.namespace ? (openBlock(), createElementBlock("div", _hoisted_35$1, [_cache[8] || (_cache[8] = createBaseVNode("span", { class: "path-label" }, "Namespace:", -1)), createBaseVNode("code", _hoisted_36$1, toDisplayString(ref.jsonPath.namespace), 1)])) : createCommentVNode("", true)])) : createCommentVNode("", true)]); - }), 128))])])) : createCommentVNode("", true) - ])) : createCommentVNode("", true) - ]); - }), 128))])])) : createCommentVNode("", true), - __props.template.spec.namespaces && __props.template.spec.namespaces.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_37, [createBaseVNode("h5", null, "Namespaces (" + toDisplayString(__props.template.spec.namespaces.length) + ")", 1), createBaseVNode("div", _hoisted_38, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.template.spec.namespaces, (ns) => { - return openBlock(), createElementBlock("div", { - key: ns.name, - class: "namespace-item" - }, [createBaseVNode("span", _hoisted_39, toDisplayString(ns.name), 1), ns.description ? (openBlock(), createElementBlock("span", _hoisted_40, toDisplayString(ns.description), 1)) : createCommentVNode("", true)]); - }), 128))])])) : createCommentVNode("", true) - ])]), - createBaseVNode("div", _hoisted_41, [createBaseVNode("button", { - onClick: closeModal, - class: "cancel-btn" - }, "Cancel"), createBaseVNode("button", { - onClick: handleBind, - disabled: !bindingName.value.trim() || binding.value || !isValidBindingName.value, - class: "bind-btn" - }, [binding.value ? (openBlock(), createElementBlock("span", _hoisted_43, "Binding...")) : (openBlock(), createElementBlock("span", _hoisted_44, toDisplayString(__props.isCliFlow ? "Bind for CLI" : "Bind Template"), 1))], 8, _hoisted_42)]) - ])])) : createCommentVNode("", true); - }; - } -}), [["__scopeId", "data-v-4218c1a0"]]); -//#endregion -//#region src/components/TemplateDetails.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1$2 = { class: "modal-container" }; -var _hoisted_2$2 = { class: "modal-header" }; -var _hoisted_3$2 = { class: "modal-body" }; -var _hoisted_4$2 = { class: "detail-section" }; -var _hoisted_5$2 = { - key: 0, - class: "tag-list" -}; -var _hoisted_6$2 = { - key: 1, - class: "empty-note" -}; -var _hoisted_7$2 = { - key: 0, - class: "detail-section" -}; -var _hoisted_8$1 = { class: "tag-list" }; -var _hoisted_9$1 = { - key: 1, - class: "detail-section" -}; -var _hoisted_10$1 = { class: "detail-section exports-section" }; -var _hoisted_11$1 = { - key: 0, - class: "status-loading" -}; -var _hoisted_12$1 = { - key: 1, - class: "exports-list" -}; -var _hoisted_13$1 = { class: "connection-info" }; -var _hoisted_14$1 = { class: "ns-label" }; -var _hoisted_15$1 = { class: "tag-list" }; -var _hoisted_16$1 = { - key: 2, - class: "empty-note" -}; -var _hoisted_17$1 = { class: "modal-footer" }; -//#endregion -//#region src/components/TemplateDetails.vue -var TemplateDetails_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ - __name: "TemplateDetails", - props: { - show: { type: Boolean }, - template: {} - }, - emits: ["close", "bind"], - setup(__props) { - const props = __props; - const status = /* @__PURE__ */ ref(null); - const statusLoading = /* @__PURE__ */ ref(false); - const fetchStatus = function() { - var _ref = _asyncToGenerator(function* () { - statusLoading.value = true; - try { - const response = yield fetch("/api/consumer-status"); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - status.value = yield response.json(); - } catch (err) { - console.error("Failed to check consumer status:", err); - status.value = null; - } finally { - statusLoading.value = false; - } - }); - return function fetchStatus() { - return _ref.apply(this, arguments); - }; - }(); - watch(() => props.show, (visible) => { - if (visible) { - status.value = null; - fetchStatus(); - } - }); - return (_ctx, _cache) => { - var _props$template$spec$, _props$template$spec$2, _status$value; - return __props.show ? (openBlock(), createElementBlock("div", { - key: 0, - class: "modal-overlay", - onClick: _cache[3] || (_cache[3] = withModifiers(($event) => _ctx.$emit("close"), ["self"])) - }, [createBaseVNode("div", _hoisted_1$2, [ - createBaseVNode("div", _hoisted_2$2, [createBaseVNode("h3", null, toDisplayString(__props.template.metadata.name), 1), createBaseVNode("button", { - class: "close-btn", - onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("close")) - }, "×")]), - createBaseVNode("div", _hoisted_3$2, [ - createBaseVNode("section", _hoisted_4$2, [_cache[4] || (_cache[4] = createBaseVNode("h4", null, "Resources", -1)), ((_props$template$spec$ = __props.template.spec.resources) === null || _props$template$spec$ === void 0 ? void 0 : _props$template$spec$.length) ? (openBlock(), createElementBlock("div", _hoisted_5$2, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.template.spec.resources, (r) => { - return openBlock(), createElementBlock("span", { - key: r.resource, - class: "tag" - }, toDisplayString(r.group ? `${r.resource}.${r.group}` : r.resource), 1); - }), 128))])) : (openBlock(), createElementBlock("p", _hoisted_6$2, "No resources defined."))]), - ((_props$template$spec$2 = __props.template.spec.permissionClaims) === null || _props$template$spec$2 === void 0 ? void 0 : _props$template$spec$2.length) ? (openBlock(), createElementBlock("section", _hoisted_7$2, [_cache[5] || (_cache[5] = createBaseVNode("h4", null, "Permission Claims", -1)), createBaseVNode("div", _hoisted_8$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.template.spec.permissionClaims, (claim, i) => { - return openBlock(), createElementBlock("span", { - key: i, - class: "tag permission-tag" - }, toDisplayString(claim.group ? `${claim.resource}.${claim.group}` : claim.resource), 1); - }), 128))])])) : createCommentVNode("", true), - __props.template.spec.description ? (openBlock(), createElementBlock("section", _hoisted_9$1, [_cache[6] || (_cache[6] = createBaseVNode("h4", null, "Description", -1)), createBaseVNode("p", null, toDisplayString(__props.template.spec.description), 1)])) : createCommentVNode("", true), - createBaseVNode("section", _hoisted_10$1, [_cache[10] || (_cache[10] = createBaseVNode("h4", null, "Active Service Exports", -1)), statusLoading.value ? (openBlock(), createElementBlock("div", _hoisted_11$1, [..._cache[7] || (_cache[7] = [createBaseVNode("span", { class: "spinner" }, null, -1), createTextVNode(" Checking connection… ", -1)])])) : ((_status$value = status.value) === null || _status$value === void 0 ? void 0 : _status$value.connected) && status.value.exports.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_12$1, [createBaseVNode("div", _hoisted_13$1, [_cache[9] || (_cache[9] = createBaseVNode("span", { class: "connected-badge" }, "Connected", -1)), createBaseVNode("span", _hoisted_14$1, [_cache[8] || (_cache[8] = createTextVNode("Namespace: ", -1)), createBaseVNode("strong", null, toDisplayString(status.value.namespace), 1)])]), createBaseVNode("div", _hoisted_15$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(status.value.exports, (name) => { - return openBlock(), createElementBlock("span", { - key: name, - class: "tag export-tag" - }, toDisplayString(name), 1); - }), 128))])])) : (openBlock(), createElementBlock("div", _hoisted_16$1, " No active exports. Bind this template to create service exports on the provider. "))]) - ]), - createBaseVNode("div", _hoisted_17$1, [createBaseVNode("button", { - class: "secondary-btn", - onClick: _cache[1] || (_cache[1] = ($event) => _ctx.$emit("close")) - }, "Close"), createBaseVNode("button", { - class: "primary-btn", - onClick: _cache[2] || (_cache[2] = ($event) => _ctx.$emit("bind", __props.template)) - }, "Bind")]) - ])])) : createCommentVNode("", true); - }; - } -}), [["__scopeId", "data-v-4c7f1934"]]); -//#endregion -//#region src/components/AlertModal.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1$1 = { class: "modal-content" }; -var _hoisted_2$1 = { class: "message-content" }; -var _hoisted_3$1 = { class: "icon" }; -var _hoisted_4$1 = { class: "message-text" }; -var _hoisted_5$1 = { key: 0 }; -var _hoisted_6$1 = { key: 1 }; -var _hoisted_7$1 = { class: "modal-footer" }; -//#endregion -//#region src/components/AlertModal.vue -var AlertModal_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ - __name: "AlertModal", - props: { - show: { type: Boolean }, - title: { default: "Alert" }, - message: {}, - type: { default: "error" }, - preserveWhitespace: { - type: Boolean, - default: false - } - }, - emits: ["close"], - setup(__props, { emit: __emit }) { - const props = __props; - const emit = __emit; - const headerClass = computed(() => { - switch (props.type) { - case "error": return "header-error"; - case "warning": return "header-warning"; - case "info": return "header-info"; - case "success": return "header-success"; - default: return "header-error"; - } - }); - const iconClass = computed(() => { - switch (props.type) { - case "error": return "icon-error"; - case "warning": return "icon-warning"; - case "info": return "icon-info"; - case "success": return "icon-success"; - default: return "icon-error"; - } - }); - const buttonClass = computed(() => { - switch (props.type) { - case "error": return "btn-error"; - case "warning": return "btn-warning"; - case "info": return "btn-info"; - case "success": return "btn-success"; - default: return "btn-error"; - } - }); - const icon = computed(() => { - switch (props.type) { - case "error": return "⚠️"; - case "warning": return "⚠️"; - case "info": return "ℹ️"; - case "success": return "✅"; - default: return "⚠️"; - } - }); - const closeModal = () => { - emit("close"); - }; - return (_ctx, _cache) => { - return __props.show ? (openBlock(), createElementBlock("div", { - key: 0, - class: "modal-overlay", - onClick: closeModal - }, [createBaseVNode("div", { - class: "modal", - onClick: _cache[0] || (_cache[0] = withModifiers(() => {}, ["stop"])) - }, [ - createBaseVNode("div", { class: normalizeClass(["modal-header", headerClass.value]) }, [createBaseVNode("h3", null, toDisplayString(__props.title), 1), createBaseVNode("button", { - onClick: closeModal, - class: "close-btn" - }, "×")], 2), - createBaseVNode("div", _hoisted_1$1, [createBaseVNode("div", _hoisted_2$1, [icon.value ? (openBlock(), createElementBlock("div", { - key: 0, - class: normalizeClass(["icon-container", iconClass.value]) - }, [createBaseVNode("span", _hoisted_3$1, toDisplayString(icon.value), 1)], 2)) : createCommentVNode("", true), createBaseVNode("div", _hoisted_4$1, [__props.preserveWhitespace ? (openBlock(), createElementBlock("pre", _hoisted_5$1, toDisplayString(__props.message), 1)) : (openBlock(), createElementBlock("p", _hoisted_6$1, toDisplayString(__props.message), 1))])])]), - createBaseVNode("div", _hoisted_7$1, [createBaseVNode("button", { - onClick: closeModal, - class: normalizeClass(["ok-btn", buttonClass.value]) - }, " OK ", 2)]) - ])])) : createCommentVNode("", true); - }; - } -}), [["__scopeId", "data-v-5efb8bd4"]]); -//#endregion -//#region src/views/Resources.vue?vue&type=script&setup=true&lang.ts -var _hoisted_1 = { class: "resources" }; -var _hoisted_2 = { class: "header-section" }; -var _hoisted_3 = { - key: 0, - class: "cli-indicator" -}; -var _hoisted_4 = { - key: 0, - class: "loading" -}; -var _hoisted_5 = { - key: 1, - class: "error" -}; -var _hoisted_6 = { - key: 2, - class: "resources-container" -}; -var _hoisted_7 = { class: "templates-section" }; -var _hoisted_8 = { class: "section-header" }; -var _hoisted_9 = { class: "item-count" }; -var _hoisted_10 = { - key: 0, - class: "no-resources" -}; -var _hoisted_11 = { - key: 1, - class: "resource-grid" -}; -var _hoisted_12 = { class: "card-header" }; -var _hoisted_13 = { class: "card-title" }; -var _hoisted_14 = { class: "card-badges" }; -var _hoisted_15 = { - key: 0, - class: "badge resources-badge" -}; -var _hoisted_16 = { - key: 1, - class: "badge permissions-badge" -}; -var _hoisted_17 = { - key: 2, - class: "badge namespaces-badge" -}; -var _hoisted_18 = { class: "card-content" }; -var _hoisted_19 = { - key: 0, - class: "card-description" -}; -var _hoisted_20 = { - key: 1, - class: "card-preview" -}; -var _hoisted_21 = { class: "resource-preview" }; -var _hoisted_22 = { - key: 0, - class: "more-indicator" -}; -var _hoisted_23 = { class: "card-actions" }; -var _hoisted_24 = ["onClick"]; -var _hoisted_25 = ["onClick"]; -var _hoisted_26 = { - key: 0, - class: "collections-section" -}; -var _hoisted_27 = { class: "section-header" }; -var _hoisted_28 = { class: "item-count" }; -var _hoisted_29 = { class: "resource-grid" }; -var _hoisted_30 = { class: "card-header" }; -var _hoisted_31 = { class: "card-title" }; -var _hoisted_32 = { class: "card-content" }; -var _hoisted_33 = { - key: 0, - class: "card-description" -}; -var _hoisted_34 = { - key: 1, - class: "collection-templates" -}; -var _hoisted_35 = { class: "template-list" }; -var _hoisted_36 = { - key: 0, - class: "more-indicator" -}; -//#endregion -//#region src/views/Resources.vue -var Resources_default = /*#__PURE__*/ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({ - __name: "Resources", - setup(__props) { - const route = useRoute(); - const loading = /* @__PURE__ */ ref(true); - const error = /* @__PURE__ */ ref(null); - const templates = /* @__PURE__ */ ref([]); - const collections = /* @__PURE__ */ ref([]); - const showBindingResult = /* @__PURE__ */ ref(false); - const selectedTemplateName = /* @__PURE__ */ ref(""); - const bindingResponse = /* @__PURE__ */ ref(null); - const showAlert = /* @__PURE__ */ ref(false); - const alertTitle = /* @__PURE__ */ ref("Alert"); - const alertMessage = /* @__PURE__ */ ref(""); - const alertType = /* @__PURE__ */ ref("error"); - const alertPreserveWhitespace = /* @__PURE__ */ ref(false); - const isCliFlow = computed(() => authService.isCliFlow()); - const showDetails = /* @__PURE__ */ ref(false); - const detailsTemplate = /* @__PURE__ */ ref(null); - const showBindingModal = /* @__PURE__ */ ref(false); - const selectedTemplate = /* @__PURE__ */ ref(null); - const cluster = computed(() => route.query.cluster_id || ""); - const consumerId = computed(() => route.query.consumer_id || ""); - const buildApiUrl = (endpoint) => { - const params = new URLSearchParams(); - if (cluster.value) params.set("cluster_id", cluster.value); - if (consumerId.value) params.set("consumer_id", consumerId.value); - return params.toString() ? `${endpoint}?${params.toString()}` : endpoint; - }; - const loadResources = function() { - var _ref = _asyncToGenerator(function* () { - loading.value = true; - error.value = null; - try { - const templatesUrl = buildApiUrl("/templates"); - const collectionsUrl = buildApiUrl("/collections"); - const [templatesResponse, collectionsResponse] = yield Promise.all([httpClient.get(templatesUrl), httpClient.get(collectionsUrl)]); - templates.value = templatesResponse.data.items || []; - collections.value = collectionsResponse.data.items || []; - } catch (err) { - console.error("Failed to load resources:", err); - if (err instanceof StructuredError) { - const kubeError = err.kubeBindError; - if (kubeError.code === "AUTHENTICATION_FAILED") return; - switch (kubeError.code) { - case "AUTHORIZATION_FAILED": - error.value = `Authorization failed: ${kubeError.details || kubeError.message}`; - break; - case "CLUSTER_CONNECTION_FAILED": - error.value = `Could not connect to cluster: ${kubeError.details || kubeError.message}`; - break; - case "RESOURCE_NOT_FOUND": - error.value = `Resources not found: ${kubeError.details || kubeError.message}`; - break; - default: error.value = `Error: ${kubeError.message}`; - } - } else { - var _err$response; - if (((_err$response = err.response) === null || _err$response === void 0 ? void 0 : _err$response.status) === 401) return; - error.value = "Failed to load resources. Please try again."; - } - } finally { - loading.value = false; - } - }); - return function loadResources() { - return _ref.apply(this, arguments); - }; - }(); - const openBindingModal = (template) => { - selectedTemplate.value = template; - showBindingModal.value = true; - }; - const closeBindingModal = () => { - showBindingModal.value = false; - selectedTemplate.value = null; - }; - const showTemplateDetails = (template) => { - detailsTemplate.value = template; - showDetails.value = true; - }; - const closeDetails = () => { - showDetails.value = false; - detailsTemplate.value = null; - }; - const onDetailsBind = (template) => { - closeDetails(); - openBindingModal(template); - }; - const handleBind = function() { - var _ref2 = _asyncToGenerator(function* (templateName, bindingName) { - try { - const bindUrl = buildApiUrl("/bind"); - const clusterIdentity = consumerId.value || "ui-identity"; - const bindingRequest = { - metadata: { name: bindingName }, - spec: { - templateRef: { name: templateName }, - clusterIdentity: { identity: clusterIdentity }, - author: "web-ui" - } - }; - const response = yield httpClient.post(bindUrl, bindingRequest); - if (response.status === 200) { - closeBindingModal(); - if (authService.isCliFlow()) { - console.log(response.data); - authService.redirectToCliCallback(response.data); - } else { - bindingResponse.value = response.data; - selectedTemplateName.value = templateName; - showBindingResult.value = true; - } - } else showAlertModal(`Failed to bind template: ${templateName}`, "Binding Failed", "error"); - } catch (err) { - console.error("Failed to bind template:", err); - if (err instanceof StructuredError) { - const kubeError = err.kubeBindError; - if (kubeError.code === "AUTHENTICATION_FAILED") return; - let errorMessage; - switch (kubeError.code) { - case "AUTHORIZATION_FAILED": - errorMessage = `Authorization failed: You don't have permission to bind resources in this cluster.\n\nDetails: ${kubeError.details || kubeError.message}`; - break; - case "CLUSTER_CONNECTION_FAILED": - errorMessage = `Cluster connection failed: Unable to connect to the target cluster.\n\nDetails: ${kubeError.details || kubeError.message}`; - break; - case "RESOURCE_NOT_FOUND": - errorMessage = `Template not found: The requested template could not be found.\n\nDetails: ${kubeError.details || kubeError.message}`; - break; - default: errorMessage = `Failed to bind template: ${kubeError.message}\n\nDetails: ${kubeError.details || "No additional details available"}`; - } - showAlertModal(errorMessage, "Binding Failed", "error", true); - } else { - var _err$response2; - if (((_err$response2 = err.response) === null || _err$response2 === void 0 ? void 0 : _err$response2.status) === 401) return; - showAlertModal(`Failed to bind template: ${templateName}. Check console for details.`, "Binding Failed", "error"); - } - } - }); - return function handleBind(_x, _x2) { - return _ref2.apply(this, arguments); - }; - }(); - const closeBindingResult = () => { - showBindingResult.value = false; - bindingResponse.value = null; - selectedTemplateName.value = ""; - }; - const showAlertModal = (message, title = "Error", type = "error", preserveWhitespace = false) => { - alertMessage.value = message; - alertTitle.value = title; - alertType.value = type; - alertPreserveWhitespace.value = preserveWhitespace; - showAlert.value = true; - }; - const closeAlert = () => { - showAlert.value = false; - }; - onMounted(() => { - loadResources(); - }); - return (_ctx, _cache) => { - return openBlock(), createElementBlock("div", _hoisted_1, [ - createBaseVNode("div", _hoisted_2, [_cache[0] || (_cache[0] = createBaseVNode("h2", null, "Available Resources", -1)), isCliFlow.value ? (openBlock(), createElementBlock("div", _hoisted_3, " CLI Mode: Select a template to bind for CLI ")) : createCommentVNode("", true)]), - loading.value ? (openBlock(), createElementBlock("div", _hoisted_4, " Loading resources... ")) : error.value ? (openBlock(), createElementBlock("div", _hoisted_5, [ - _cache[1] || (_cache[1] = createBaseVNode("h3", null, "Error Loading Resources", -1)), - createBaseVNode("p", null, toDisplayString(error.value), 1), - createBaseVNode("button", { - onClick: loadResources, - class: "retry-btn" - }, "Retry") - ])) : (openBlock(), createElementBlock("div", _hoisted_6, [createBaseVNode("div", _hoisted_7, [createBaseVNode("div", _hoisted_8, [_cache[2] || (_cache[2] = createBaseVNode("h3", null, "Templates", -1)), createBaseVNode("span", _hoisted_9, toDisplayString(templates.value.length) + " available", 1)]), templates.value.length === 0 ? (openBlock(), createElementBlock("div", _hoisted_10, [..._cache[3] || (_cache[3] = [ - createBaseVNode("div", { class: "no-resources-icon" }, [createBaseVNode("svg", { - width: "48", - height: "48", - fill: "none", - stroke: "currentColor", - viewBox: "0 0 24 24" - }, [createBaseVNode("path", { - "stroke-linecap": "round", - "stroke-linejoin": "round", - "stroke-width": "1.5", - d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" - })])], -1), - createBaseVNode("h4", null, "No templates available", -1), - createBaseVNode("p", null, "There are no API service export templates available in this cluster.", -1) - ])])) : (openBlock(), createElementBlock("div", _hoisted_11, [(openBlock(true), createElementBlock(Fragment, null, renderList(templates.value, (template) => { - var _template$spec$resour, _template$spec$permis, _template$spec$namesp, _template$spec$resour2; - return openBlock(), createElementBlock("div", { - key: template.metadata.name, - class: "template-card" - }, [ - createBaseVNode("div", _hoisted_12, [createBaseVNode("h4", _hoisted_13, toDisplayString(template.metadata.name), 1), createBaseVNode("div", _hoisted_14, [ - ((_template$spec$resour = template.spec.resources) === null || _template$spec$resour === void 0 ? void 0 : _template$spec$resour.length) ? (openBlock(), createElementBlock("span", _hoisted_15, toDisplayString(template.spec.resources.length) + " resources ", 1)) : createCommentVNode("", true), - ((_template$spec$permis = template.spec.permissionClaims) === null || _template$spec$permis === void 0 ? void 0 : _template$spec$permis.length) ? (openBlock(), createElementBlock("span", _hoisted_16, toDisplayString(template.spec.permissionClaims.length) + " permissions ", 1)) : createCommentVNode("", true), - ((_template$spec$namesp = template.spec.namespaces) === null || _template$spec$namesp === void 0 ? void 0 : _template$spec$namesp.length) ? (openBlock(), createElementBlock("span", _hoisted_17, toDisplayString(template.spec.namespaces.length) + " namespaces ", 1)) : createCommentVNode("", true) - ])]), - createBaseVNode("div", _hoisted_18, [template.spec.description ? (openBlock(), createElementBlock("p", _hoisted_19, toDisplayString(template.spec.description), 1)) : createCommentVNode("", true), ((_template$spec$resour2 = template.spec.resources) === null || _template$spec$resour2 === void 0 ? void 0 : _template$spec$resour2.length) ? (openBlock(), createElementBlock("div", _hoisted_20, [_cache[4] || (_cache[4] = createBaseVNode("strong", null, "Key Resources:", -1)), createBaseVNode("div", _hoisted_21, [(openBlock(true), createElementBlock(Fragment, null, renderList(template.spec.resources.slice(0, 3), (resource) => { - return openBlock(), createElementBlock("span", { - key: resource.resource, - class: "resource-tag" - }, toDisplayString(resource.resource), 1); - }), 128)), template.spec.resources.length > 3 ? (openBlock(), createElementBlock("span", _hoisted_22, " +" + toDisplayString(template.spec.resources.length - 3) + " more ", 1)) : createCommentVNode("", true)])])) : createCommentVNode("", true)]), - createBaseVNode("div", _hoisted_23, [createBaseVNode("button", { - onClick: ($event) => showTemplateDetails(template), - class: "details-btn" - }, " View Details ", 8, _hoisted_24), createBaseVNode("button", { - onClick: ($event) => openBindingModal(template), - class: "bind-btn" - }, toDisplayString(isCliFlow.value ? "Bind for CLI" : "Bind"), 9, _hoisted_25)]) - ]); - }), 128))]))]), collections.value.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_26, [createBaseVNode("div", _hoisted_27, [_cache[5] || (_cache[5] = createBaseVNode("h3", null, "Collections", -1)), createBaseVNode("span", _hoisted_28, toDisplayString(collections.value.length) + " available", 1)]), createBaseVNode("div", _hoisted_29, [(openBlock(true), createElementBlock(Fragment, null, renderList(collections.value, (collection) => { - var _collection$spec$temp; - return openBlock(), createElementBlock("div", { - key: collection.metadata.name, - class: "collection-card" - }, [createBaseVNode("div", _hoisted_30, [createBaseVNode("h4", _hoisted_31, toDisplayString(collection.metadata.name), 1)]), createBaseVNode("div", _hoisted_32, [collection.spec.description ? (openBlock(), createElementBlock("p", _hoisted_33, toDisplayString(collection.spec.description), 1)) : createCommentVNode("", true), ((_collection$spec$temp = collection.spec.templates) === null || _collection$spec$temp === void 0 ? void 0 : _collection$spec$temp.length) ? (openBlock(), createElementBlock("div", _hoisted_34, [_cache[6] || (_cache[6] = createBaseVNode("strong", null, "Templates in this collection:", -1)), createBaseVNode("div", _hoisted_35, [(openBlock(true), createElementBlock(Fragment, null, renderList(collection.spec.templates.slice(0, 4), (templateName) => { - return openBlock(), createElementBlock("span", { - key: templateName, - class: "template-tag" - }, toDisplayString(templateName), 1); - }), 128)), collection.spec.templates.length > 4 ? (openBlock(), createElementBlock("span", _hoisted_36, " +" + toDisplayString(collection.spec.templates.length - 4) + " more ", 1)) : createCommentVNode("", true)])])) : createCommentVNode("", true)])]); - }), 128))])])) : createCommentVNode("", true)])), - detailsTemplate.value ? (openBlock(), createBlock(TemplateDetails_default, { - key: 3, - show: showDetails.value, - template: detailsTemplate.value, - onClose: closeDetails, - onBind: onDetailsBind - }, null, 8, ["show", "template"])) : createCommentVNode("", true), - selectedTemplate.value ? (openBlock(), createBlock(TemplateBindingModal_default, { - key: 4, - show: showBindingModal.value, - template: selectedTemplate.value, - "is-cli-flow": isCliFlow.value, - onClose: closeBindingModal, - onBind: handleBind - }, null, 8, [ - "show", - "template", - "is-cli-flow" - ])) : createCommentVNode("", true), - bindingResponse.value ? (openBlock(), createBlock(BindingResult_default, { - key: 5, - show: showBindingResult.value, - "template-name": selectedTemplateName.value, - "binding-response": bindingResponse.value, - onClose: closeBindingResult - }, null, 8, [ - "show", - "template-name", - "binding-response" - ])) : createCommentVNode("", true), - createVNode(AlertModal_default, { - show: showAlert.value, - title: alertTitle.value, - message: alertMessage.value, - type: alertType.value, - "preserve-whitespace": alertPreserveWhitespace.value, - onClose: closeAlert - }, null, 8, [ - "show", - "title", - "message", - "type", - "preserve-whitespace" - ]) - ]); - }; - } -}), [["__scopeId", "data-v-1cd8a497"]]); -//#endregion -//#region src/main.ts -var routes = [{ - path: "/", - component: Resources_default -}, { - path: "/resources", - component: Resources_default -}]; -var router = createRouter({ - history: createWebHistory(), - routes -}); -createApp(App_default).use(router).mount("#app"); -//#endregion diff --git a/web/dist/assets/index.BhVI6qbi.css b/web/dist/assets/index.BhVI6qbi.css deleted file mode 100644 index 0397a4501..000000000 --- a/web/dist/assets/index.BhVI6qbi.css +++ /dev/null @@ -1,1471 +0,0 @@ - -#app[data-v-eb0cbf2e] { - font-family: - -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", - "Cantarell", sans-serif; -} -.header[data-v-eb0cbf2e] { - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - border-bottom: 1px solid rgba(255, 255, 255, 0.1); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); - position: sticky; - top: 0; - z-index: 100; -} -.header-content[data-v-eb0cbf2e] { - max-width: 1200px; - margin: 0 auto; - display: flex; - justify-content: space-between; - align-items: center; - padding: 1rem 2rem; -} -.brand[data-v-eb0cbf2e] { - display: flex; - align-items: center; - gap: 0.75rem; -} -.logo[data-v-eb0cbf2e] { - display: flex; - align-items: center; - justify-content: center; -} -.logo img[data-v-eb0cbf2e] { - width: 32px; - height: 32px; - display: block; -} -.header h1[data-v-eb0cbf2e] { - margin: 0; - color: white; - font-size: 1.5rem; - font-weight: 600; - letter-spacing: -0.025em; -} -.user-section[data-v-eb0cbf2e] { - display: flex; - align-items: center; - gap: 1.5rem; -} -.user-info[data-v-eb0cbf2e] { - display: flex; - align-items: center; - gap: 0.5rem; - color: rgba(255, 255, 255, 0.9); - font-size: 0.875rem; - font-weight: 500; -} -.status-indicator[data-v-eb0cbf2e] { - width: 8px; - height: 8px; - background: #10b981; - border-radius: 50%; - box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.3); - animation: pulse-eb0cbf2e 2s infinite; -} -@keyframes pulse-eb0cbf2e { -0%, - 100% { - opacity: 1; -} -50% { - opacity: 0.5; -} -} -.welcome-text[data-v-eb0cbf2e] { - color: rgba(255, 255, 255, 0.8); -} -.logout-btn[data-v-eb0cbf2e] { - display: flex; - align-items: center; - gap: 0.5rem; - padding: 0.5rem 1rem; - background: rgba(255, 255, 255, 0.1); - color: rgba(255, 255, 255, 0.9); - border: 1px solid rgba(255, 255, 255, 0.2); - border-radius: 8px; - cursor: pointer; - font-size: 0.875rem; - font-weight: 500; - transition: all 0.2s ease; - backdrop-filter: blur(10px); -} -.logout-btn[data-v-eb0cbf2e]:hover { - background: rgba(255, 255, 255, 0.2); - color: white; - border-color: rgba(255, 255, 255, 0.3); - transform: translateY(-1px); -} -.main[data-v-eb0cbf2e] { - min-height: calc(100vh - 80px); - background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); - padding: 0; -} -.auth-placeholder[data-v-eb0cbf2e] { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - text-align: center; - padding: 4rem 2rem; - min-height: calc(100vh - 200px); -} -.auth-placeholder h2[data-v-eb0cbf2e] { - color: #1f2937; - margin-bottom: 1rem; - font-size: 2rem; - font-weight: 600; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - -webkit-background-clip: text; - -webkit-text-fill-color: transparent; - background-clip: text; -} -.auth-placeholder p[data-v-eb0cbf2e] { - color: #6b7280; - margin-bottom: 2rem; - font-size: 1.125rem; - max-width: 500px; - line-height: 1.6; -} -.auth-btn[data-v-eb0cbf2e] { - display: inline-flex; - align-items: center; - gap: 0.5rem; - padding: 1rem 2rem; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; - border: none; - border-radius: 12px; - cursor: pointer; - font-size: 1rem; - font-weight: 600; - transition: all 0.2s ease; - box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3); -} -.auth-btn[data-v-eb0cbf2e]:hover { - background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%); - transform: translateY(-2px); - box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4); -} -.auth-error[data-v-eb0cbf2e] { - display: flex; - align-items: flex-start; - gap: 1rem; - padding: 1rem 1.5rem; - margin: 1.5rem 0; - background: #fef2f2; - border: 1px solid #fecaca; - border-radius: 12px; - max-width: 500px; - text-align: left; - box-shadow: 0 2px 8px rgba(239, 68, 68, 0.1); -} -.error-icon[data-v-eb0cbf2e] { - font-size: 1.5rem; - line-height: 1; - margin-top: 0.125rem; -} -.error-content h3[data-v-eb0cbf2e] { - margin: 0 0 0.5rem 0; - color: #dc2626; - font-size: 1rem; - font-weight: 600; -} -.error-content p[data-v-eb0cbf2e] { - margin: 0; - color: #991b1b; - font-size: 0.875rem; - line-height: 1.5; -} - -.binding-modal-overlay[data-v-6ba48543] { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.6); - display: flex; - align-items: center; - justify-content: center; - z-index: 1000; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; -} -.binding-modal[data-v-6ba48543] { - background: white; - border-radius: 12px; - width: 90%; - max-width: 900px; - max-height: 85vh; - overflow: hidden; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2); -} -.binding-header[data-v-6ba48543] { - display: flex; - justify-content: space-between; - align-items: center; - padding: 1.5rem 2rem; - border-bottom: 1px solid #e5e7eb; - background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); - color: white; -} -.binding-header h3[data-v-6ba48543] { - margin: 0; - font-size: 1.25rem; - font-weight: 600; -} -.close-btn[data-v-6ba48543] { - background: none; - border: none; - font-size: 1.5rem; - cursor: pointer; - color: rgba(255, 255, 255, 0.8); - width: 32px; - height: 32px; - display: flex; - align-items: center; - justify-content: center; - border-radius: 50%; - transition: all 0.2s; -} -.close-btn[data-v-6ba48543]:hover { - background: rgba(255, 255, 255, 0.1); - color: white; -} -.binding-content[data-v-6ba48543] { - padding: 2rem; - max-height: 70vh; - overflow-y: auto; -} -.binding-info[data-v-6ba48543] { - margin-bottom: 1.5rem; - padding-bottom: 1.5rem; - border-bottom: 1px solid #e5e7eb; -} -.binding-info h4[data-v-6ba48543] { - margin-bottom: 1rem; - color: #111827; - font-size: 1.125rem; - font-weight: 600; -} -.binding-info p[data-v-6ba48543] { - margin: 0.5rem 0; - color: #6b7280; - font-size: 0.9rem; -} -.method-tabs[data-v-6ba48543] { - display: flex; - gap: 0; - margin-bottom: 1.5rem; - border-bottom: 2px solid #e5e7eb; - flex-wrap: wrap; -} -.method-tab[data-v-6ba48543] { - padding: 0.75rem 1.25rem; - background: none; - border: none; - border-bottom: 2px solid transparent; - margin-bottom: -2px; - cursor: pointer; - font-size: 0.85rem; - font-weight: 500; - color: #6b7280; - transition: all 0.2s; - white-space: nowrap; -} -.method-tab[data-v-6ba48543]:hover { - color: #374151; -} -.method-tab.active[data-v-6ba48543] { - color: #3b82f6; - border-bottom-color: #3b82f6; -} -.instructions-section[data-v-6ba48543] { - margin-bottom: 1rem; -} -.instructions-text[data-v-6ba48543] { - margin-bottom: 1.5rem; - color: #6b7280; - line-height: 1.6; -} -.step-group[data-v-6ba48543] { - margin-bottom: 2rem; -} -.step-group h5[data-v-6ba48543] { - margin-bottom: 0.5rem; - color: #374151; - font-size: 1rem; - font-weight: 600; -} -.step-description[data-v-6ba48543] { - margin-bottom: 0.75rem; - color: #6b7280; - font-size: 0.875rem; -} -.download-block[data-v-6ba48543] { - background: #f0f9ff; - border: 1px solid #bfdbfe; - border-radius: 8px; - padding: 1rem; - margin-bottom: 0.75rem; -} -.download-actions[data-v-6ba48543] { - display: flex; - gap: 1rem; -} -.download-btn[data-v-6ba48543] { - padding: 0.75rem 1.5rem; - background: #6b7280; - color: white; - border: none; - border-radius: 8px; - cursor: pointer; - font-size: 0.875rem; - font-weight: 500; - transition: background-color 0.2s; -} -.download-btn[data-v-6ba48543]:hover { - background: #4b5563; -} -.download-btn.primary[data-v-6ba48543] { - background: #3b82f6; -} -.download-btn.primary[data-v-6ba48543]:hover { - background: #2563eb; -} -.command-block[data-v-6ba48543] { - display: flex; - align-items: center; - background: #f8fafc; - border: 1px solid #e2e8f0; - border-radius: 8px; - padding: 1rem; - gap: 1rem; -} -.command-block code[data-v-6ba48543] { - flex: 1; - font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', 'Consolas', monospace; - font-size: 0.875rem; - color: #1f2937; - background: none; - word-break: break-all; -} -.copy-cmd-btn[data-v-6ba48543] { - padding: 0.5rem 1rem; - background: #3b82f6; - color: white; - border: none; - border-radius: 6px; - cursor: pointer; - font-size: 0.875rem; - font-weight: 500; - transition: background-color 0.2s; - flex-shrink: 0; -} -.copy-cmd-btn[data-v-6ba48543]:hover { - background: #2563eb; -} - -/* One-Click tab styles */ -.security-warning[data-v-6ba48543] { - background: #fffbeb; - border: 1px solid #fcd34d; - border-radius: 8px; - padding: 1rem; - margin-bottom: 1.5rem; - color: #92400e; - font-size: 0.875rem; - line-height: 1.5; -} -.upload-block[data-v-6ba48543] { - background: #f9fafb; - border: 2px dashed #d1d5db; - border-radius: 8px; - padding: 1.5rem; - text-align: center; -} -.file-input[data-v-6ba48543] { - margin-bottom: 0.5rem; -} -.file-info[data-v-6ba48543] { - margin-top: 0.5rem; - color: #059669; - font-size: 0.875rem; - font-weight: 500; -} -.text-input[data-v-6ba48543] { - width: 100%; - padding: 0.5rem 0.75rem; - border: 1px solid #d1d5db; - border-radius: 6px; - font-size: 0.875rem; - font-family: 'SF Mono', Monaco, monospace; - box-sizing: border-box; -} -.text-input[data-v-6ba48543]:focus { - outline: none; - border-color: #3b82f6; - box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.15); -} -.optional-label[data-v-6ba48543] { - font-weight: 400; - font-size: 0.8rem; - color: #9ca3af; -} -.step-hint[data-v-6ba48543] { - margin: 0.25rem 0 0; - font-size: 0.78rem; - color: #9ca3af; -} -.apply-btn[data-v-6ba48543] { - padding: 0.875rem 2rem; - background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); - color: white; - border: none; - border-radius: 8px; - cursor: pointer; - font-size: 1rem; - font-weight: 600; - transition: all 0.2s; - display: flex; - align-items: center; - gap: 0.5rem; -} -.apply-btn[data-v-6ba48543]:hover:not(:disabled) { - background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); - transform: translateY(-1px); -} -.apply-btn[data-v-6ba48543]:disabled { - opacity: 0.5; - cursor: not-allowed; -} -.spinner[data-v-6ba48543] { - display: inline-block; - width: 16px; - height: 16px; - border: 2px solid rgba(255, 255, 255, 0.3); - border-radius: 50%; - border-top-color: white; - animation: spin-6ba48543 0.8s linear infinite; -} -@keyframes spin-6ba48543 { -to { transform: rotate(360deg); -} -} -.status-message[data-v-6ba48543] { - padding: 1rem; - border-radius: 8px; - font-size: 0.9rem; - margin-top: 1rem; -} -.status-message.success[data-v-6ba48543] { - background: #ecfdf5; - border: 1px solid #a7f3d0; - color: #065f46; -} -.status-message.error[data-v-6ba48543] { - background: #fef2f2; - border: 1px solid #fecaca; - color: #991b1b; -} - -/* Already Connected tab styles */ -.status-check[data-v-6ba48543] { - display: flex; - align-items: center; - gap: 0.75rem; - padding: 2rem; - justify-content: center; - color: #6b7280; -} -.status-check .spinner[data-v-6ba48543] { - border-color: rgba(59, 130, 246, 0.3); - border-top-color: #3b82f6; -} -.connected-badge[data-v-6ba48543] { - background: #ecfdf5; - border: 1px solid #a7f3d0; - color: #065f46; - padding: 0.75rem 1rem; - border-radius: 8px; - font-weight: 600; - font-size: 1rem; - margin-bottom: 1rem; -} -.not-connected-badge[data-v-6ba48543] { - background: #f0f9ff; - border: 1px solid #bfdbfe; - color: #1e40af; - padding: 0.75rem 1rem; - border-radius: 8px; - font-weight: 600; - font-size: 1rem; - margin-bottom: 1rem; -} -.exports-list[data-v-6ba48543] { - background: #f9fafb; - border: 1px solid #e5e7eb; - border-radius: 8px; - padding: 1rem; - margin-bottom: 1.5rem; -} -.exports-list h5[data-v-6ba48543] { - margin: 0 0 0.5rem 0; - color: #374151; - font-size: 0.9rem; -} -.exports-list ul[data-v-6ba48543] { - margin: 0; - padding-left: 1.5rem; -} -.exports-list li[data-v-6ba48543] { - color: #6b7280; - font-size: 0.875rem; - font-family: 'SF Mono', 'Monaco', monospace; - padding: 0.25rem 0; -} -.method-suggestions[data-v-6ba48543] { - padding-left: 1.5rem; - color: #6b7280; - line-height: 2; -} -.binding-footer[data-v-6ba48543] { - padding: 1.5rem 2rem; - border-top: 1px solid #e5e7eb; - background: #f9fafb; - text-align: right; -} -.ok-btn[data-v-6ba48543] { - padding: 0.75rem 1.5rem; - background: linear-gradient(135deg, #10b981 0%, #059669 100%); - color: white; - border: none; - border-radius: 8px; - cursor: pointer; - font-weight: 600; - transition: all 0.2s; -} -.ok-btn[data-v-6ba48543]:hover { - background: linear-gradient(135deg, #059669 0%, #047857 100%); - transform: translateY(-1px); -} - -.modal-overlay[data-v-4218c1a0] { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.6); - display: flex; - align-items: center; - justify-content: center; - z-index: 1000; - animation: fadeIn-4218c1a0 0.2s ease; -} -.modal[data-v-4218c1a0] { - background: white; - border-radius: 12px; - width: 90%; - max-width: 700px; - max-height: 85vh; - overflow: hidden; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2); - animation: slideIn-4218c1a0 0.3s ease; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; -} -@keyframes fadeIn-4218c1a0 { -from { opacity: 0; -} -to { opacity: 1; -} -} -@keyframes slideIn-4218c1a0 { -from { transform: translateY(-20px) scale(0.95); opacity: 0; -} -to { transform: translateY(0) scale(1); opacity: 1; -} -} -.modal-header[data-v-4218c1a0] { - display: flex; - justify-content: space-between; - align-items: center; - padding: 1.5rem 2rem; - border-bottom: 1px solid #e5e7eb; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; -} -.modal-header h3[data-v-4218c1a0] { - margin: 0; - font-size: 1.25rem; - font-weight: 600; -} -.close-btn[data-v-4218c1a0] { - background: none; - border: none; - font-size: 1.5rem; - cursor: pointer; - color: rgba(255, 255, 255, 0.8); - width: 32px; - height: 32px; - display: flex; - align-items: center; - justify-content: center; - border-radius: 50%; - transition: all 0.2s; -} -.close-btn[data-v-4218c1a0]:hover { - background: rgba(255, 255, 255, 0.1); - color: white; -} -.modal-content[data-v-4218c1a0] { - padding: 2rem; - max-height: 60vh; - overflow-y: auto; -} -.binding-name-section[data-v-4218c1a0] { - margin-bottom: 2rem; - padding-bottom: 2rem; - border-bottom: 1px solid #e5e7eb; -} -.form-label[data-v-4218c1a0] { - display: block; - margin-bottom: 0.5rem; - font-weight: 600; - color: #374151; -} -.form-input[data-v-4218c1a0] { - width: 100%; - padding: 0.75rem 1rem; - border: 2px solid #d1d5db; - border-radius: 8px; - font-size: 1rem; - transition: border-color 0.2s, box-shadow 0.2s; -} -.form-input[data-v-4218c1a0]:focus { - outline: none; - border-color: #667eea; - box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); -} -.form-help[data-v-4218c1a0] { - margin-top: 0.5rem; - font-size: 0.875rem; - color: #6b7280; -} -.form-input.invalid[data-v-4218c1a0] { - border-color: #dc2626; - background-color: #fef2f2; -} -.form-input.invalid[data-v-4218c1a0]:focus { - border-color: #dc2626; - box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1); -} -.form-error[data-v-4218c1a0] { - margin-top: 0.5rem; - font-size: 0.875rem; - color: #dc2626; - font-weight: 500; -} -.template-details h4[data-v-4218c1a0] { - margin-bottom: 1.5rem; - color: #111827; - font-size: 1.125rem; - font-weight: 600; -} -.detail-section[data-v-4218c1a0] { - margin-bottom: 2rem; -} -.detail-section h5[data-v-4218c1a0] { - margin-bottom: 1rem; - color: #374151; - font-size: 1rem; - font-weight: 600; - display: flex; - align-items: center; - gap: 0.5rem; -} -.description[data-v-4218c1a0] { - color: #6b7280; - line-height: 1.6; - background: #f9fafb; - padding: 1rem; - border-radius: 8px; - border-left: 4px solid #667eea; -} -.resource-list[data-v-4218c1a0], .permission-list[data-v-4218c1a0], .namespace-list[data-v-4218c1a0] { - display: grid; - gap: 0.75rem; -} -.resource-item[data-v-4218c1a0], .permission-item[data-v-4218c1a0], .namespace-item[data-v-4218c1a0] { - background: #f8fafc; - border: 1px solid #e2e8f0; - border-radius: 8px; - padding: 1rem; - transition: border-color 0.2s; -} -.resource-item[data-v-4218c1a0]:hover, .permission-item[data-v-4218c1a0]:hover, .namespace-item[data-v-4218c1a0]:hover { - border-color: #cbd5e1; -} -.resource-name[data-v-4218c1a0], .permission-name[data-v-4218c1a0], .namespace-name[data-v-4218c1a0] { - font-weight: 600; - color: #1e293b; - display: block; - margin-bottom: 0.25rem; -} -.resource-group[data-v-4218c1a0], .permission-group[data-v-4218c1a0] { - font-size: 0.875rem; - color: #64748b; - background: #e2e8f0; - padding: 0.25rem 0.5rem; - border-radius: 4px; - display: inline-block; - margin-right: 0.5rem; -} -.resource-versions[data-v-4218c1a0] { - font-size: 0.875rem; - color: #059669; - background: #d1fae5; - padding: 0.25rem 0.5rem; - border-radius: 4px; - display: inline-block; -} -.permission-selector[data-v-4218c1a0] { - margin-top: 0.75rem; - font-size: 0.875rem; -} -.selector-section[data-v-4218c1a0] { - margin-bottom: 0.75rem; -} -.selector-section[data-v-4218c1a0]:last-child { - margin-bottom: 0; -} -.selector-title[data-v-4218c1a0] { - display: block; - color: #374151; - font-size: 0.8rem; - margin-bottom: 0.375rem; - text-transform: uppercase; - letter-spacing: 0.05em; -} -.selector-content[data-v-4218c1a0] { - margin-left: 0.5rem; -} - -/* Label selector styles */ -.label-item[data-v-4218c1a0] { - display: inline-flex; - align-items: center; - background: #f3f4f6; - border: 1px solid #e5e7eb; - border-radius: 6px; - padding: 0.25rem 0.5rem; - margin-right: 0.5rem; - margin-bottom: 0.25rem; - font-size: 0.75rem; -} -.label-key[data-v-4218c1a0] { - color: #1f2937; - font-weight: 600; -} -.label-separator[data-v-4218c1a0] { - color: #6b7280; - margin: 0 0.25rem; -} -.label-value[data-v-4218c1a0] { - color: #059669; - background: #d1fae5; - padding: 0.125rem 0.25rem; - border-radius: 3px; - font-family: monospace; -} - -/* Named resources styles */ -.named-resource-item[data-v-4218c1a0] { - background: #fef3c7; - border: 1px solid #fbbf24; - border-radius: 6px; - padding: 0.375rem 0.5rem; - margin-bottom: 0.25rem; - font-size: 0.75rem; -} -.resource-name[data-v-4218c1a0] { - color: #92400e; - font-weight: 600; -} -.resource-namespace[data-v-4218c1a0] { - color: #d97706; - font-style: italic; - margin-left: 0.25rem; -} - -/* References styles */ -.reference-item[data-v-4218c1a0] { - background: #dbeafe; - border: 1px solid #93c5fd; - border-radius: 6px; - padding: 0.5rem; - margin-bottom: 0.5rem; - font-size: 0.75rem; -} -.reference-item[data-v-4218c1a0]:last-child { - margin-bottom: 0; -} -.reference-header[data-v-4218c1a0] { - display: flex; - align-items: center; - margin-bottom: 0.375rem; -} -.reference-resource[data-v-4218c1a0] { - color: #1e40af; - font-weight: 600; - margin-right: 0.25rem; -} -.reference-group[data-v-4218c1a0] { - color: #3b82f6; - font-size: 0.7rem; - opacity: 0.8; -} -.reference-paths[data-v-4218c1a0] { - margin-top: 0.375rem; -} -.json-path[data-v-4218c1a0] { - display: flex; - align-items: center; - margin-bottom: 0.25rem; -} -.json-path[data-v-4218c1a0]:last-child { - margin-bottom: 0; -} -.path-label[data-v-4218c1a0] { - color: #374151; - font-weight: 500; - margin-right: 0.5rem; - min-width: 4rem; -} -.path-value[data-v-4218c1a0] { - background: #1f2937; - color: #f9fafb; - padding: 0.125rem 0.375rem; - border-radius: 4px; - font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; - font-size: 0.7rem; -} -.namespace-desc[data-v-4218c1a0] { - font-size: 0.875rem; - color: #6b7280; - display: block; - margin-top: 0.25rem; -} -.modal-footer[data-v-4218c1a0] { - padding: 1.5rem 2rem; - border-top: 1px solid #e5e7eb; - background: #f9fafb; - display: flex; - justify-content: flex-end; - gap: 1rem; -} -.cancel-btn[data-v-4218c1a0], .bind-btn[data-v-4218c1a0] { - padding: 0.75rem 1.5rem; - border: none; - border-radius: 8px; - cursor: pointer; - font-weight: 600; - transition: all 0.2s; -} -.cancel-btn[data-v-4218c1a0] { - background: #f3f4f6; - color: #374151; -} -.cancel-btn[data-v-4218c1a0]:hover { - background: #e5e7eb; -} -.bind-btn[data-v-4218c1a0] { - background: linear-gradient(135deg, #10b981 0%, #059669 100%); - color: white; -} -.bind-btn[data-v-4218c1a0]:hover:not(:disabled) { - background: linear-gradient(135deg, #059669 0%, #047857 100%); - transform: translateY(-1px); -} -.bind-btn[data-v-4218c1a0]:disabled { - background: #d1d5db; - color: #9ca3af; - cursor: not-allowed; - transform: none; -} - -.modal-overlay[data-v-4c7f1934] { - position: fixed; - inset: 0; - background: rgba(0, 0, 0, 0.5); - display: flex; - align-items: center; - justify-content: center; - z-index: 1000; -} -.modal-container[data-v-4c7f1934] { - background: white; - border-radius: 12px; - width: 560px; - max-width: 90vw; - max-height: 80vh; - display: flex; - flex-direction: column; - box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); -} -.modal-header[data-v-4c7f1934] { - display: flex; - align-items: center; - justify-content: space-between; - padding: 1.25rem 1.5rem; - border-bottom: 1px solid #e2e8f0; -} -.modal-header h3[data-v-4c7f1934] { - margin: 0; - font-size: 1.25rem; - color: #1e293b; -} -.close-btn[data-v-4c7f1934] { - background: none; - border: none; - font-size: 1.5rem; - color: #64748b; - cursor: pointer; - line-height: 1; -} -.modal-body[data-v-4c7f1934] { - padding: 1.5rem; - overflow-y: auto; - flex: 1; -} -.detail-section[data-v-4c7f1934] { - margin-bottom: 1.25rem; -} -.detail-section[data-v-4c7f1934]:last-child { - margin-bottom: 0; -} -.detail-section h4[data-v-4c7f1934] { - margin: 0 0 0.5rem; - font-size: 0.875rem; - color: #475569; - text-transform: uppercase; - letter-spacing: 0.05em; -} -.tag-list[data-v-4c7f1934] { - display: flex; - flex-wrap: wrap; - gap: 0.375rem; -} -.tag[data-v-4c7f1934] { - padding: 0.25rem 0.625rem; - border-radius: 4px; - font-size: 0.8rem; - font-family: 'SF Mono', Monaco, monospace; - background: #f1f5f9; - color: #334155; - border: 1px solid #e2e8f0; -} -.permission-tag[data-v-4c7f1934] { - background: #fef3c7; - border-color: #fbbf24; - color: #92400e; -} -.export-tag[data-v-4c7f1934] { - background: #ecfdf5; - border-color: #6ee7b7; - color: #065f46; -} -.empty-note[data-v-4c7f1934] { - color: #94a3b8; - font-size: 0.875rem; - font-style: italic; - margin: 0; -} -.exports-section[data-v-4c7f1934] { - border-top: 1px solid #e2e8f0; - padding-top: 1.25rem; -} -.connection-info[data-v-4c7f1934] { - display: flex; - align-items: center; - gap: 0.75rem; - margin-bottom: 0.625rem; -} -.connected-badge[data-v-4c7f1934] { - padding: 0.2rem 0.5rem; - border-radius: 4px; - font-weight: 600; - font-size: 0.7rem; - text-transform: uppercase; - background: #22c55e; - color: white; -} -.ns-label[data-v-4c7f1934] { - font-size: 0.8rem; - color: #475569; -} -.status-loading[data-v-4c7f1934] { - display: flex; - align-items: center; - gap: 0.5rem; - color: #64748b; - font-size: 0.875rem; -} -.spinner[data-v-4c7f1934] { - display: inline-block; - width: 14px; - height: 14px; - border: 2px solid #e2e8f0; - border-top-color: #3b82f6; - border-radius: 50%; - animation: spin-4c7f1934 0.6s linear infinite; -} -@keyframes spin-4c7f1934 { -to { transform: rotate(360deg); -} -} -.modal-footer[data-v-4c7f1934] { - display: flex; - justify-content: flex-end; - gap: 0.75rem; - padding: 1rem 1.5rem; - border-top: 1px solid #e2e8f0; -} -.secondary-btn[data-v-4c7f1934] { - padding: 0.5rem 1rem; - border-radius: 6px; - border: 1px solid #cbd5e1; - background: white; - color: #475569; - cursor: pointer; - font-size: 0.875rem; -} -.secondary-btn[data-v-4c7f1934]:hover { - background: #f8fafc; -} -.primary-btn[data-v-4c7f1934] { - padding: 0.5rem 1.25rem; - border-radius: 6px; - border: none; - background: #3b82f6; - color: white; - cursor: pointer; - font-size: 0.875rem; - font-weight: 500; -} -.primary-btn[data-v-4c7f1934]:hover { - background: #2563eb; -} - -.modal-overlay[data-v-5efb8bd4] { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(0, 0, 0, 0.6); - display: flex; - align-items: center; - justify-content: center; - z-index: 1000; - animation: fadeIn-5efb8bd4 0.2s ease; -} -.modal[data-v-5efb8bd4] { - background: white; - border-radius: 12px; - width: 90%; - max-width: 500px; - max-height: 85vh; - overflow: hidden; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2); - animation: slideIn-5efb8bd4 0.3s ease; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; -} -@keyframes fadeIn-5efb8bd4 { -from { opacity: 0; -} -to { opacity: 1; -} -} -@keyframes slideIn-5efb8bd4 { -from { transform: translateY(-20px) scale(0.95); opacity: 0; -} -to { transform: translateY(0) scale(1); opacity: 1; -} -} -.modal-header[data-v-5efb8bd4] { - display: flex; - justify-content: space-between; - align-items: center; - padding: 1.5rem 2rem; - border-bottom: 1px solid #e5e7eb; - color: white; -} -.header-error[data-v-5efb8bd4] { - background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%); -} -.header-warning[data-v-5efb8bd4] { - background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); -} -.header-info[data-v-5efb8bd4] { - background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); -} -.header-success[data-v-5efb8bd4] { - background: linear-gradient(135deg, #10b981 0%, #059669 100%); -} -.modal-header h3[data-v-5efb8bd4] { - margin: 0; - font-size: 1.25rem; - font-weight: 600; -} -.close-btn[data-v-5efb8bd4] { - background: none; - border: none; - font-size: 1.5rem; - cursor: pointer; - color: rgba(255, 255, 255, 0.8); - width: 32px; - height: 32px; - display: flex; - align-items: center; - justify-content: center; - border-radius: 50%; - transition: all 0.2s; -} -.close-btn[data-v-5efb8bd4]:hover { - background: rgba(255, 255, 255, 0.1); - color: white; -} -.modal-content[data-v-5efb8bd4] { - padding: 2rem; -} -.message-content[data-v-5efb8bd4] { - display: flex; - align-items: flex-start; - gap: 1rem; -} -.icon-container[data-v-5efb8bd4] { - flex-shrink: 0; - width: 3rem; - height: 3rem; - display: flex; - align-items: center; - justify-content: center; - border-radius: 50%; - font-size: 1.5rem; -} -.icon-error[data-v-5efb8bd4] { - background: #fee2e2; - color: #dc2626; -} -.icon-warning[data-v-5efb8bd4] { - background: #fef3c7; - color: #f59e0b; -} -.icon-info[data-v-5efb8bd4] { - background: #dbeafe; - color: #3b82f6; -} -.icon-success[data-v-5efb8bd4] { - background: #d1fae5; - color: #10b981; -} -.message-text[data-v-5efb8bd4] { - flex: 1; - min-width: 0; -} -.message-text p[data-v-5efb8bd4] { - margin: 0; - color: #374151; - line-height: 1.6; - word-wrap: break-word; -} -.message-text pre[data-v-5efb8bd4] { - margin: 0; - color: #374151; - line-height: 1.6; - white-space: pre-wrap; - word-wrap: break-word; - font-family: inherit; -} -.modal-footer[data-v-5efb8bd4] { - padding: 1.5rem 2rem; - border-top: 1px solid #e5e7eb; - background: #f9fafb; - display: flex; - justify-content: flex-end; -} -.ok-btn[data-v-5efb8bd4] { - padding: 0.75rem 2rem; - border: none; - border-radius: 8px; - cursor: pointer; - font-weight: 600; - transition: all 0.2s; - color: white; -} -.btn-error[data-v-5efb8bd4] { - background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%); -} -.btn-error[data-v-5efb8bd4]:hover { - background: linear-gradient(135deg, #b91c1c 0%, #991b1b 100%); - transform: translateY(-1px); -} -.btn-warning[data-v-5efb8bd4] { - background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); -} -.btn-warning[data-v-5efb8bd4]:hover { - background: linear-gradient(135deg, #d97706 0%, #b45309 100%); - transform: translateY(-1px); -} -.btn-info[data-v-5efb8bd4] { - background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); -} -.btn-info[data-v-5efb8bd4]:hover { - background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); - transform: translateY(-1px); -} -.btn-success[data-v-5efb8bd4] { - background: linear-gradient(135deg, #10b981 0%, #059669 100%); -} -.btn-success[data-v-5efb8bd4]:hover { - background: linear-gradient(135deg, #059669 0%, #047857 100%); - transform: translateY(-1px); -} - -.resources[data-v-1cd8a497] { - max-width: 1200px; - margin: 0 auto; - padding: 2rem; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; -} -.header-section[data-v-1cd8a497] { - margin-bottom: 2rem; -} -.resources h2[data-v-1cd8a497] { - color: #1e293b; - margin-bottom: 1rem; - font-size: 1.875rem; - font-weight: 600; - font-family: inherit; -} -.resources h3[data-v-1cd8a497] { - color: #334155; - font-size: 1.25rem; - font-weight: 600; - font-family: inherit; - margin: 0; -} -.cli-indicator[data-v-1cd8a497] { - background-color: #dbeafe; - border: 1px solid #3b82f6; - border-radius: 8px; - padding: 0.75rem 1rem; - color: #1e40af; - font-weight: 500; - font-size: 0.875rem; - display: flex; - align-items: center; - gap: 0.5rem; -} -.loading[data-v-1cd8a497] { - text-align: center; - padding: 2rem; - color: #666; -} -.error[data-v-1cd8a497] { - text-align: center; - padding: 2rem; - color: #dc3545; -} -.retry-btn[data-v-1cd8a497] { - padding: 0.5rem 1rem; - background-color: #007bff; - color: white; - border: none; - border-radius: 4px; - cursor: pointer; - margin-top: 1rem; -} -.retry-btn[data-v-1cd8a497]:hover { - background-color: #0056b3; -} -.resources-container[data-v-1cd8a497] { - display: grid; - gap: 3rem; -} -.templates-section[data-v-1cd8a497], -.collections-section[data-v-1cd8a497] { - background: #f8fafc; - padding: 1.5rem; - border-radius: 12px; - border: 1px solid #e2e8f0; -} -.no-resources[data-v-1cd8a497] { - text-align: center; - color: #666; - padding: 1rem; -} -.section-header[data-v-1cd8a497] { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 1.5rem; -} -.item-count[data-v-1cd8a497] { - font-size: 0.9rem; - color: #666; - background: #e9ecef; - padding: 0.25rem 0.75rem; - border-radius: 12px; - font-weight: 500; -} -.no-resources[data-v-1cd8a497] { - text-align: center; - padding: 3rem 2rem; - color: #6b7280; - background: white; - border-radius: 12px; - border: 2px dashed #d1d5db; -} -.no-resources-icon[data-v-1cd8a497] { - margin-bottom: 1rem; - opacity: 0.4; - color: #9ca3af; -} -.no-resources h4[data-v-1cd8a497] { - margin: 0 0 0.5rem 0; - color: #374151; - font-weight: 600; -} -.no-resources p[data-v-1cd8a497] { - margin: 0; - font-size: 0.9rem; -} -.resource-grid[data-v-1cd8a497] { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); - gap: 1.5rem; -} -.template-card[data-v-1cd8a497], .collection-card[data-v-1cd8a497] { - background: white; - border: 1px solid #e2e8f0; - border-radius: 12px; - padding: 0; - transition: all 0.2s ease; - overflow: hidden; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); -} -.template-card[data-v-1cd8a497]:hover, .collection-card[data-v-1cd8a497]:hover { - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); - transform: translateY(-2px); - border-color: #cbd5e1; -} -.card-header[data-v-1cd8a497] { - padding: 1.5rem 1.5rem 1rem 1.5rem; - border-bottom: 1px solid #f1f5f9; -} -.card-title[data-v-1cd8a497] { - margin: 0 0 0.75rem 0; - color: #1e293b; - font-size: 1.125rem; - font-weight: 600; -} -.card-badges[data-v-1cd8a497] { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; -} -.badge[data-v-1cd8a497] { - font-size: 0.75rem; - padding: 0.25rem 0.75rem; - border-radius: 12px; - font-weight: 500; - display: inline-flex; - align-items: center; -} -.resources-badge[data-v-1cd8a497] { - background: #dbeafe; - color: #1d4ed8; -} -.permissions-badge[data-v-1cd8a497] { - background: #fef3c7; - color: #d97706; -} -.namespaces-badge[data-v-1cd8a497] { - background: #d1fae5; - color: #047857; -} -.card-content[data-v-1cd8a497] { - padding: 1rem 1.5rem; -} -.card-description[data-v-1cd8a497] { - color: #64748b; - margin: 0 0 1rem 0; - line-height: 1.5; - font-size: 0.9rem; -} -.card-preview[data-v-1cd8a497], .collection-templates[data-v-1cd8a497] { - margin-top: 1rem; -} -.card-preview strong[data-v-1cd8a497], .collection-templates strong[data-v-1cd8a497] { - color: #374151; - font-size: 0.875rem; - display: block; - margin-bottom: 0.5rem; -} -.resource-preview[data-v-1cd8a497], .template-list[data-v-1cd8a497] { - display: flex; - flex-wrap: wrap; - gap: 0.5rem; -} -.resource-tag[data-v-1cd8a497], .template-tag[data-v-1cd8a497] { - font-size: 0.75rem; - background: #f1f5f9; - color: #475569; - padding: 0.25rem 0.5rem; - border-radius: 6px; - border: 1px solid #e2e8f0; -} -.more-indicator[data-v-1cd8a497] { - font-size: 0.75rem; - color: #6b7280; - font-style: italic; -} -.card-actions[data-v-1cd8a497] { - padding: 1rem 1.5rem; - background: #fafbfc; - border-top: 1px solid #f1f5f9; - display: flex; - gap: 0.75rem; - justify-content: flex-end; -} -.details-btn[data-v-1cd8a497], .bind-btn[data-v-1cd8a497] { - padding: 0.5rem 1rem; - border: none; - border-radius: 6px; - cursor: pointer; - font-weight: 500; - font-size: 0.875rem; - transition: all 0.2s ease; -} -.details-btn[data-v-1cd8a497] { - background: #f8fafc; - color: #475569; - border: 1px solid #e2e8f0; -} -.details-btn[data-v-1cd8a497]:hover { - background: #f1f5f9; - border-color: #cbd5e1; -} -.bind-btn[data-v-1cd8a497] { - background: linear-gradient(135deg, #10b981 0%, #059669 100%); - color: white; - border: 1px solid transparent; -} -.bind-btn[data-v-1cd8a497]:hover { - background: linear-gradient(135deg, #059669 0%, #047857 100%); - transform: translateY(-1px); - box-shadow: 0 2px 4px rgba(16, 185, 129, 0.2); -} - diff --git a/web/dist/assets/logo.C_e3UAcl.png b/web/dist/assets/logo.C_e3UAcl.png deleted file mode 100644 index 4d09fe4ff..000000000 Binary files a/web/dist/assets/logo.C_e3UAcl.png and /dev/null differ diff --git a/web/dist/index.html b/web/dist/index.html deleted file mode 100644 index 4a572e2ed..000000000 --- a/web/dist/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Kube Bind - - - - -
- - diff --git a/web/embed.go b/web/embed.go index 79371df39..f183ff4a7 100644 --- a/web/embed.go +++ b/web/embed.go @@ -1,5 +1,5 @@ /* -Copyright 2025 The Kube Bind Authors. +Copyright 2026 The kbind Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,25 +14,23 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package web embeds the gateway's UI: a dependency-free static SPA that is a +// pure gateway client — it holds no flow state the gateway doesn't have. package web import ( "embed" "io/fs" - "net/http" ) -// Static files embedded in the binary. -// -//go:embed dist/* -var StaticFiles embed.FS +//go:embed static +var static embed.FS -// GetFileSystem returns the embedded file system for serving static files. -func GetFileSystem() http.FileSystem { - // Create a sub-filesystem starting from dist - subFS, err := fs.Sub(StaticFiles, "dist") +// Static returns the UI filesystem rooted at the static directory. +func Static() fs.FS { + sub, err := fs.Sub(static, "static") if err != nil { - panic("failed to create sub filesystem: " + err.Error()) + panic(err) // embedded path is fixed at compile time } - return http.FS(subFS) + return sub } diff --git a/web/go.mod b/web/go.mod deleted file mode 100644 index 8347bb4c2..000000000 --- a/web/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/kube-bind/kube-bind/web - -go 1.26.9 diff --git a/web/index.html b/web/index.html deleted file mode 100644 index f09140361..000000000 --- a/web/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Kube Bind - - -
- - - diff --git a/web/package-lock.json b/web/package-lock.json deleted file mode 100644 index 6c2e8ed2f..000000000 --- a/web/package-lock.json +++ /dev/null @@ -1,3591 +0,0 @@ -{ - "name": "kube-bind-frontend", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "kube-bind-frontend", - "version": "1.0.0", - "dependencies": { - "axios": "^1.20.0", - "vue": "^3.5.32", - "vue-router": "^5.0.4" - }, - "devDependencies": { - "@types/node": "^25.5.2", - "@typescript-eslint/eslint-plugin": "^8.58.0", - "@typescript-eslint/parser": "^8.58.0", - "@vitejs/plugin-vue": "^6.0.5", - "@vue/eslint-config-typescript": "^14.7.0", - "eslint": "^10.2.0", - "eslint-plugin-vue": "^10.8.0", - "typescript": "^6.0.2", - "vite": "^8.0.16", - "vue-tsc": "^3.2.6" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", - "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.9", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", - "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.8" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.8", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", - "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", - "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/object-schema": "^3.0.5", - "debug": "^4.3.1", - "minimatch": "^10.2.4" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/config-helpers": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.5.5.tgz", - "integrity": "sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/core": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", - "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/object-schema": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", - "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.1.tgz", - "integrity": "sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1", - "levn": "^0.4.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@humanfs/core": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", - "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/types": "^0.15.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.8", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", - "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/core": "^0.19.2", - "@humanfs/types": "^0.15.0", - "@humanwhocodes/retry": "^0.4.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/types": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", - "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", - "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", - "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@oxc-project/types": { - "version": "0.133.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz", - "integrity": "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Boshen" - } - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz", - "integrity": "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.3.tgz", - "integrity": "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.3.tgz", - "integrity": "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.3.tgz", - "integrity": "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.3.tgz", - "integrity": "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.3.tgz", - "integrity": "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.3.tgz", - "integrity": "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.3.tgz", - "integrity": "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.3.tgz", - "integrity": "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.3.tgz", - "integrity": "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.3.tgz", - "integrity": "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.3.tgz", - "integrity": "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.3.tgz", - "integrity": "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.10.0", - "@emnapi/runtime": "1.10.0", - "@napi-rs/wasm-runtime": "^1.1.4" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.3.tgz", - "integrity": "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.3.tgz", - "integrity": "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.13", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.13.tgz", - "integrity": "sha512-3ngTAv6F/Py35BsYbeeLeecvhMKdsKm4AoOETVhAA+Qc8nrA2I0kF7oa93mE9qnIurngOSpMnQ0x2nQY2FPviA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", - "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@types/esrecurse": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", - "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "25.6.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz", - "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~7.19.0" - } - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz", - "integrity": "sha512-K72/pvT7qpm8q3k8G5u93NCSN1RcLxX5h7Gw0bQpbMXviBHeY6Nx1WEwmk9wP+eKTSQ8ecxvcgt/ZX/rB938xQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.71.2", - "@typescript-eslint/type-utils": "8.71.2", - "@typescript-eslint/utils": "8.71.2", - "@typescript-eslint/visitor-keys": "8.71.2", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.71.2", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.71.2.tgz", - "integrity": "sha512-aTtmZjp/x3gsGHkDs04/1I8kNogBJkpQaeGaN0PfiG43NzDEmW2n+OP5im9wfsvyX0yP1UZWBrAGtDBfH9jEVw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.71.2", - "@typescript-eslint/types": "8.71.2", - "@typescript-eslint/typescript-estree": "8.71.2", - "@typescript-eslint/visitor-keys": "8.71.2", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/project-service": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.71.2.tgz", - "integrity": "sha512-Pd68GsLVh5ZXlcEccFPdhSOvtHZ/2WU0XsA8zmXOS3F158lVlcTLhfQ6qvtL1RzbMie0Kp8xtbVwAg4nejKPHw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.71.2", - "@typescript-eslint/types": "^8.71.2", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.71.2.tgz", - "integrity": "sha512-YF4wgg5iUX5Obywoac27B56FhozMNFhdJSbh11H5GBAwmBtfyRhmgTQqW9tRNNmHDvsZ2CX6UGzoz+YfYn2Leg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.71.2", - "@typescript-eslint/visitor-keys": "8.71.2" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.71.2.tgz", - "integrity": "sha512-jz49TAWokm/7yWD9/o837nYax9DyALxIPOImdImvVzo6canBCZYzin8zJyqNR5k1j9K1DE0bVvr0XYB+99uAdg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.71.2.tgz", - "integrity": "sha512-cC8UaalCViJkb3rH/xLIvidEwoFRtMZMUqDjjJMGEKaTFwYRHYBcoczlEGHuvkHEO8svRDrgZ0yQgOArFmwang==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.71.2", - "@typescript-eslint/typescript-estree": "8.71.2", - "@typescript-eslint/utils": "8.71.2", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/types": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.71.2.tgz", - "integrity": "sha512-y5Ukl3oVp7e/VGxqIoEXoeb/Roj71PAJ4WG/N/RGj+eeDvKRLM15kGr9MijLbN0i03S52zxu31Z98E5gWChJKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.71.2.tgz", - "integrity": "sha512-DgNOEsl4pdYzwSL+N/Cl33tX1Hlw3FvId73LnKXfq7jnrF2viOEn7X+P7RBkkSWCVm92gnWd28GIC5vJuLREeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.71.2", - "@typescript-eslint/tsconfig-utils": "8.71.2", - "@typescript-eslint/types": "8.71.2", - "@typescript-eslint/visitor-keys": "8.71.2", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.71.2.tgz", - "integrity": "sha512-RyKa1G1M9rKHDhrk+HJtiF1MvLD5Ux2JW3TSkzw+02pRALdpJb+QzG1Y5em+LvCgzGwgg8H7mBRFKljNz7ImPw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.71.2", - "@typescript-eslint/types": "8.71.2", - "@typescript-eslint/typescript-estree": "8.71.2" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.71.2.tgz", - "integrity": "sha512-zozlN0UA32bSG2zkKAgQyRYSbEISVoyU6vvkKYo2aSny74D8Jh4e+POkJ6Lk0dlezZi5x7TtD+88Xb06IB8nhg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.71.2", - "eslint-visitor-keys": "^5.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@vitejs/plugin-vue": { - "version": "6.0.6", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.6.tgz", - "integrity": "sha512-u9HHgfrq3AjXlysn0eINFnWQOJQLO9WN6VprZ8FXl7A2bYisv3Hui9Ij+7QZ41F/WYWarHjwBbXtD7dKg3uxbg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rolldown/pluginutils": "1.0.0-rc.13" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", - "vue": "^3.2.25" - } - }, - "node_modules/@volar/language-core": { - "version": "2.4.28", - "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.28.tgz", - "integrity": "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@volar/source-map": "2.4.28" - } - }, - "node_modules/@volar/source-map": { - "version": "2.4.28", - "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.28.tgz", - "integrity": "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@volar/typescript": { - "version": "2.4.28", - "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.28.tgz", - "integrity": "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@volar/language-core": "2.4.28", - "path-browserify": "^1.0.1", - "vscode-uri": "^3.0.8" - } - }, - "node_modules/@vue-macros/common": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@vue-macros/common/-/common-3.1.2.tgz", - "integrity": "sha512-h9t4ArDdniO9ekYHAD95t9AZcAbb19lEGK+26iAjUODOIJKmObDNBSe4+6ELQAA3vtYiFPPBtHh7+cQCKi3Dng==", - "license": "MIT", - "dependencies": { - "@vue/compiler-sfc": "^3.5.22", - "ast-kit": "^2.1.2", - "local-pkg": "^1.1.2", - "magic-string-ast": "^1.0.2", - "unplugin-utils": "^0.3.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/sponsors/vue-macros" - }, - "peerDependencies": { - "vue": "^2.7.0 || ^3.2.25" - }, - "peerDependenciesMeta": { - "vue": { - "optional": true - } - } - }, - "node_modules/@vue/compiler-core": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.44.tgz", - "integrity": "sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ==", - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.9", - "@vue/shared": "3.5.44", - "entities": "^7.0.1", - "estree-walker": "^2.0.2", - "source-map-js": "^1.2.2" - } - }, - "node_modules/@vue/compiler-dom": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.44.tgz", - "integrity": "sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==", - "license": "MIT", - "dependencies": { - "@vue/compiler-core": "3.5.44", - "@vue/shared": "3.5.44" - } - }, - "node_modules/@vue/compiler-sfc": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.44.tgz", - "integrity": "sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw==", - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.9", - "@vue/compiler-core": "3.5.44", - "@vue/compiler-dom": "3.5.44", - "@vue/compiler-ssr": "3.5.44", - "@vue/shared": "3.5.44", - "estree-walker": "^2.0.2", - "magic-string": "^0.30.21", - "postcss": "^8.5.29", - "source-map-js": "^1.2.2" - } - }, - "node_modules/@vue/compiler-ssr": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.44.tgz", - "integrity": "sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA==", - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.44", - "@vue/shared": "3.5.44" - } - }, - "node_modules/@vue/devtools-api": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-8.1.1.tgz", - "integrity": "sha512-bsDMJ07b3GN1puVwJb/fyFnj/U2imyswK5UQVLZwVl7O05jDrt6BHxeG5XffmOOdasOj/bOmIjxJvGPxU7pcqw==", - "license": "MIT", - "dependencies": { - "@vue/devtools-kit": "^8.1.1" - } - }, - "node_modules/@vue/devtools-kit": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-8.1.1.tgz", - "integrity": "sha512-gVBaBv++i+adg4JpH71k9ppl4soyR7Y2McEqO5YNgv0BI1kMZ7BDX5gnwkZ5COYgiCyhejZG+yGNrBAjj6Coqg==", - "license": "MIT", - "dependencies": { - "@vue/devtools-shared": "^8.1.1", - "birpc": "^2.6.1", - "hookable": "^5.5.3", - "perfect-debounce": "^2.0.0" - } - }, - "node_modules/@vue/devtools-shared": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-8.1.1.tgz", - "integrity": "sha512-+h4ttmJYl/txpxHKaoZcaKpC+pvckgLzIDiSQlaQ7kKthKh8KuwoLW2D8hPJEnqKzXOvu15UHEoGyngAXCz0EQ==", - "license": "MIT" - }, - "node_modules/@vue/eslint-config-typescript": { - "version": "14.9.0", - "resolved": "https://registry.npmjs.org/@vue/eslint-config-typescript/-/eslint-config-typescript-14.9.0.tgz", - "integrity": "sha512-E3j9hDlfVf10F30MRcLTPY2IIhWIx1nsvkVukk14kTcuA+oBVot9zsP1hzsO+PAMDxV3Fd9FimBJtUBNBL5KFA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/utils": "^8.60.0", - "fast-glob": "^3.3.3", - "typescript-eslint": "^8.60.0", - "vue-eslint-parser": "^10.4.0" - }, - "bin": { - "vue-eslint-config-typescript": "dist/bin.js" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "peerDependencies": { - "eslint": "^9.10.0 || ^10.0.0", - "eslint-plugin-vue": "^9.28.0 || ^10.0.0", - "typescript": ">=4.8.4" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@vue/language-core": { - "version": "3.2.8", - "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.2.8.tgz", - "integrity": "sha512-9OiSPQFiAAWNVnXb0d2dcTmcKnFQamhuNES6ayyISrb/mwPWVgoGdAqSfCWqKhQpa3D5gDTcYD+w7ObiheZ81g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@volar/language-core": "2.4.28", - "@vue/compiler-dom": "^3.5.0", - "@vue/shared": "^3.5.0", - "alien-signals": "^3.1.2", - "muggle-string": "^0.4.1", - "path-browserify": "^1.0.1", - "picomatch": "^4.0.4" - } - }, - "node_modules/@vue/language-core/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/@vue/reactivity": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.44.tgz", - "integrity": "sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw==", - "license": "MIT", - "dependencies": { - "@vue/shared": "3.5.44" - } - }, - "node_modules/@vue/runtime-core": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.44.tgz", - "integrity": "sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ==", - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.44", - "@vue/shared": "3.5.44" - } - }, - "node_modules/@vue/runtime-dom": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.44.tgz", - "integrity": "sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg==", - "license": "MIT", - "dependencies": { - "@vue/reactivity": "3.5.44", - "@vue/runtime-core": "3.5.44", - "@vue/shared": "3.5.44", - "csstype": "^3.2.3" - } - }, - "node_modules/@vue/server-renderer": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.44.tgz", - "integrity": "sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ==", - "license": "MIT", - "dependencies": { - "@vue/compiler-ssr": "3.5.44", - "@vue/runtime-dom": "3.5.44", - "@vue/shared": "3.5.44" - } - }, - "node_modules/@vue/shared": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.44.tgz", - "integrity": "sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==", - "license": "MIT" - }, - "node_modules/acorn": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", - "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "license": "MIT", - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/alien-signals": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.1.2.tgz", - "integrity": "sha512-d9dYqZTS90WLiU0I5c6DHj/HcKkF8ZyGN3G5x8wSbslulz70KOxaqCT0hQCo9KOyhVqzqGojvNdJXoTumZOtcw==", - "dev": true, - "license": "MIT" - }, - "node_modules/ast-kit": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-2.2.0.tgz", - "integrity": "sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==", - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.5", - "pathe": "^2.0.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/sponsors/sxzz" - } - }, - "node_modules/ast-walker-scope": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/ast-walker-scope/-/ast-walker-scope-0.8.3.tgz", - "integrity": "sha512-cbdCP0PGOBq0ASG+sjnKIoYkWMKhhz+F/h9pRexUdX2Hd38+WOlBkRKlqkGOSm0YQpcFMQBJeK4WspUAkwsEdg==", - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.28.4", - "ast-kit": "^2.1.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/sponsors/sxzz" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "license": "MIT" - }, - "node_modules/axios": { - "version": "1.20.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", - "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", - "license": "MIT", - "dependencies": { - "follow-redirects": "^1.16.0", - "form-data": "^4.0.6", - "https-proxy-agent": "^5.0.1", - "proxy-from-env": "^2.1.0" - } - }, - "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/birpc": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz", - "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", - "dev": true, - "license": "ISC" - }, - "node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/chokidar": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", - "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "license": "MIT", - "dependencies": { - "readdirp": "^5.0.0" - }, - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/confbox": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", - "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "license": "MIT" - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.3.0.tgz", - "integrity": "sha512-XbEXaRva5cF0ZQB8w6MluHA0kZZfV2DuCMJ3ozyEOHLwDpZX2Lmm/7Pp0xdJmI0GL1W05VH5VwIFHEm1Vcw2gw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.8.0", - "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.5", - "@eslint/config-helpers": "^0.5.5", - "@eslint/core": "^1.2.1", - "@eslint/plugin-kit": "^0.7.1", - "@humanfs/node": "^0.16.6", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.2", - "@types/estree": "^1.0.6", - "ajv": "^6.14.0", - "cross-spawn": "^7.0.6", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^9.1.2", - "eslint-visitor-keys": "^5.0.1", - "espree": "^11.2.0", - "esquery": "^1.7.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.4", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-plugin-vue": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.9.1.tgz", - "integrity": "sha512-cHB0Tf4Duvzwecwd/AqWzZvF/QszE13BhjVUpVXWCy9AeMR5GjkAjP3i85vqgLgOuTmkHR1OJ5oMeqLHtuw8zg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "natural-compare": "^1.4.0", - "nth-check": "^2.1.1", - "postcss-selector-parser": "^7.1.0", - "semver": "^7.6.3", - "xml-name-validator": "^4.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "peerDependencies": { - "@stylistic/eslint-plugin": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", - "@typescript-eslint/parser": "^7.0.0 || ^8.0.0", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "vue-eslint-parser": "^10.3.0" - }, - "peerDependenciesMeta": { - "@stylistic/eslint-plugin": { - "optional": true - }, - "@typescript-eslint/parser": { - "optional": true - } - } - }, - "node_modules/eslint-scope": { - "version": "9.1.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", - "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@types/esrecurse": "^4.3.1", - "@types/estree": "^1.0.8", - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/espree": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", - "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.16.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^5.0.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/espree/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estree-walker": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", - "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "license": "MIT" - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/exsolve": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", - "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", - "license": "MIT" - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/flatted": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", - "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", - "dev": true, - "license": "ISC" - }, - "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/form-data": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", - "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.4", - "mime-types": "^2.1.35" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", - "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hookable": { - "version": "5.5.3", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", - "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", - "license": "MIT" - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "license": "MIT", - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/ignore": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", - "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/local-pkg": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.1.2.tgz", - "integrity": "sha512-arhlxbFRmoQHl33a0Zkle/YWlmNwoyt6QNZEIJcqNbdrsix5Lvc4HyyI3EnwxTYlZYc32EbYrQ8SzEZ7dqgg9A==", - "license": "MIT", - "dependencies": { - "mlly": "^1.7.4", - "pkg-types": "^2.3.0", - "quansync": "^0.2.11" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/magic-string-ast": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/magic-string-ast/-/magic-string-ast-1.0.3.tgz", - "integrity": "sha512-CvkkH1i81zl7mmb94DsRiFeG9V2fR2JeuK8yDgS8oiZSFa++wWLEgZ5ufEOyLHbvSbD1gTRKv9NdX69Rnvr9JA==", - "license": "MIT", - "dependencies": { - "magic-string": "^0.30.19" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/sponsors/sxzz" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/mlly": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", - "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", - "license": "MIT", - "dependencies": { - "acorn": "^8.16.0", - "pathe": "^2.0.3", - "pkg-types": "^1.3.1", - "ufo": "^1.6.3" - } - }, - "node_modules/mlly/node_modules/confbox": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", - "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", - "license": "MIT" - }, - "node_modules/mlly/node_modules/pkg-types": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", - "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", - "license": "MIT", - "dependencies": { - "confbox": "^0.1.8", - "mlly": "^1.7.4", - "pathe": "^2.0.1" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/muggle-string": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", - "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.20", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", - "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/nth-check": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0" - }, - "funding": { - "url": "https://github.com/fb55/nth-check?sponsor=1" - } - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/path-browserify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", - "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "license": "MIT" - }, - "node_modules/perfect-debounce": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", - "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pkg-types": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.1.tgz", - "integrity": "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg==", - "license": "MIT", - "dependencies": { - "confbox": "^0.2.4", - "exsolve": "^1.0.8", - "pathe": "^2.0.3" - } - }, - "node_modules/postcss": { - "version": "8.5.30", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz", - "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.20", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postcss-selector-parser": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", - "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/proxy-from-env": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", - "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/quansync": { - "version": "0.2.11", - "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", - "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/antfu" - }, - { - "type": "individual", - "url": "https://github.com/sponsors/sxzz" - } - ], - "license": "MIT" - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/readdirp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz", - "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", - "license": "MIT", - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rolldown": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", - "integrity": "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "=0.133.0", - "@rolldown/pluginutils": "^1.0.0" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.3", - "@rolldown/binding-darwin-arm64": "1.0.3", - "@rolldown/binding-darwin-x64": "1.0.3", - "@rolldown/binding-freebsd-x64": "1.0.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", - "@rolldown/binding-linux-arm64-gnu": "1.0.3", - "@rolldown/binding-linux-arm64-musl": "1.0.3", - "@rolldown/binding-linux-ppc64-gnu": "1.0.3", - "@rolldown/binding-linux-s390x-gnu": "1.0.3", - "@rolldown/binding-linux-x64-gnu": "1.0.3", - "@rolldown/binding-linux-x64-musl": "1.0.3", - "@rolldown/binding-openharmony-arm64": "1.0.3", - "@rolldown/binding-wasm32-wasi": "1.0.3", - "@rolldown/binding-win32-arm64-msvc": "1.0.3", - "@rolldown/binding-win32-x64-msvc": "1.0.3" - } - }, - "node_modules/rolldown/node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", - "dev": true, - "license": "MIT" - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/scule": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/scule/-/scule-1.3.0.tgz", - "integrity": "sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.17", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", - "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/tinyglobby/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/typescript": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", - "devOptional": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/typescript-eslint": { - "version": "8.71.2", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.71.2.tgz", - "integrity": "sha512-Rz4effbMy2g9wnvOJZG6SbVavX313Lap1vNEbk1RUochzickvzP8P4HB+bkNg5e50eVz1hQGjh9K1omI1xB4Bw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "8.71.2", - "@typescript-eslint/parser": "8.71.2", - "@typescript-eslint/typescript-estree": "8.71.2", - "@typescript-eslint/utils": "8.71.2" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/ufo": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", - "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", - "license": "MIT" - }, - "node_modules/undici-types": { - "version": "7.19.2", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz", - "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", - "dev": true, - "license": "MIT" - }, - "node_modules/unplugin": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-3.0.0.tgz", - "integrity": "sha512-0Mqk3AT2TZCXWKdcoaufeXNukv2mTrEZExeXlHIOZXdqYoHHr4n51pymnwV8x2BOVxwXbK2HLlI7usrqMpycdg==", - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.5", - "picomatch": "^4.0.3", - "webpack-virtual-modules": "^0.6.2" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/unplugin-utils": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/unplugin-utils/-/unplugin-utils-0.3.1.tgz", - "integrity": "sha512-5lWVjgi6vuHhJ526bI4nlCOmkCIF3nnfXkCMDeMJrtdvxTs6ZFCM8oNufGTsDbKv/tJ/xj8RpvXjRuPBZJuJog==", - "license": "MIT", - "dependencies": { - "pathe": "^2.0.3", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/sponsors/sxzz" - } - }, - "node_modules/unplugin-utils/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/unplugin/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, - "license": "MIT" - }, - "node_modules/vite": { - "version": "8.0.16", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", - "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "lightningcss": "^1.32.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.15", - "rolldown": "1.0.3", - "tinyglobby": "^0.2.17" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.18", - "esbuild": "^0.27.0 || ^0.28.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "@vitejs/devtools": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vite/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/vue": { - "version": "3.5.44", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.44.tgz", - "integrity": "sha512-dvvmaOCG7lAMkJTPqPwWeGMsPS6DIsFsfZDUgBp9V6mHf9b3+/wyVwYR4Es+WV6uJC0FKRxp81Obcq0ZwUcGFQ==", - "license": "MIT", - "dependencies": { - "@vue/compiler-dom": "3.5.44", - "@vue/compiler-sfc": "3.5.44", - "@vue/runtime-dom": "3.5.44", - "@vue/server-renderer": "3.5.44", - "@vue/shared": "3.5.44" - }, - "peerDependencies": { - "typescript": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/vue-eslint-parser": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.0.tgz", - "integrity": "sha512-Vxi9pJdbN3ZnVGLODVtZ7y4Y2kzAAE2Cm0CZ3ZDRvydVYxZ6VrnBhLikBsRS+dpwj4Jv4UCv21PTEwF5rQ9WXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "eslint-scope": "^8.2.0 || ^9.0.0", - "eslint-visitor-keys": "^4.2.0 || ^5.0.0", - "espree": "^10.3.0 || ^11.0.0", - "esquery": "^1.6.0", - "semver": "^7.6.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://github.com/sponsors/mysticatea" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" - } - }, - "node_modules/vue-eslint-parser/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/vue-router": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.0.6.tgz", - "integrity": "sha512-9+kmUTGbKMyW9Asoy98IXXYIzrTMT7JDAdpDDeEkorHvybpUvBI2wsrSM5jFOXrFydpzRFJ9vAh+80DN2PGu9w==", - "license": "MIT", - "dependencies": { - "@babel/generator": "^7.28.6", - "@vue-macros/common": "^3.1.1", - "@vue/devtools-api": "^8.0.6", - "ast-walker-scope": "^0.8.3", - "chokidar": "^5.0.0", - "json5": "^2.2.3", - "local-pkg": "^1.1.2", - "magic-string": "^0.30.21", - "mlly": "^1.8.0", - "muggle-string": "^0.4.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "scule": "^1.3.0", - "tinyglobby": "^0.2.15", - "unplugin": "^3.0.0", - "unplugin-utils": "^0.3.1", - "yaml": "^2.8.2" - }, - "funding": { - "url": "https://github.com/sponsors/posva" - }, - "peerDependencies": { - "@pinia/colada": ">=0.21.2", - "@vue/compiler-sfc": "^3.5.17", - "pinia": "^3.0.4", - "vue": "^3.5.0" - }, - "peerDependenciesMeta": { - "@pinia/colada": { - "optional": true - }, - "@vue/compiler-sfc": { - "optional": true - }, - "pinia": { - "optional": true - } - } - }, - "node_modules/vue-router/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/vue-tsc": { - "version": "3.2.8", - "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.2.8.tgz", - "integrity": "sha512-27vTLJ6Q2370obOd0PFYoYoKnmXJ521uUIedrs3Zhhhg/8YG10VOCMmwt+JQslatpAMTDbnWiitLnoD5VlIvog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@volar/typescript": "2.4.28", - "@vue/language-core": "3.2.8" - }, - "bin": { - "vue-tsc": "bin/vue-tsc.js" - }, - "peerDependencies": { - "typescript": ">=5.0.0" - } - }, - "node_modules/webpack-virtual-modules": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", - "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", - "license": "MIT" - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/xml-name-validator": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", - "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12" - } - }, - "node_modules/yaml": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.4.tgz", - "integrity": "sha512-ml/JPOj9fOQK8RNnWojA67GbZ0ApXAUlN2UQclwv2eVgTgn7O9gg9o7paZWKMp4g0H3nTLtS9LVzhkpOFIKzog==", - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - } -} diff --git a/web/package.json b/web/package.json deleted file mode 100644 index 4adc71d52..000000000 --- a/web/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "kube-bind-frontend", - "version": "1.0.0", - "private": true, - "type": "module", - "scripts": { - "dev": "vite", - "build": "vite build --config vite.config.docker.ts", - "build:local": "vite build", - "build:check": "vue-tsc --noEmit && vite build", - "preview": "vite preview", - "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore", - "type-check": "vue-tsc --noEmit" - }, - "dependencies": { - "vue": "^3.5.32", - "vue-router": "^5.0.4", - "axios": "^1.20.0" - }, - "devDependencies": { - "@types/node": "^25.5.2", - "@typescript-eslint/eslint-plugin": "^8.58.0", - "@typescript-eslint/parser": "^8.58.0", - "@vitejs/plugin-vue": "^6.0.5", - "@vue/eslint-config-typescript": "^14.7.0", - "eslint": "^10.2.0", - "eslint-plugin-vue": "^10.8.0", - "typescript": "^6.0.2", - "vite": "^8.0.16", - "vue-tsc": "^3.2.6" - } -} diff --git a/web/src/App.vue b/web/src/App.vue deleted file mode 100644 index 019b1c809..000000000 --- a/web/src/App.vue +++ /dev/null @@ -1,372 +0,0 @@ - - - - - diff --git a/web/src/assets/logo.png b/web/src/assets/logo.png deleted file mode 100644 index 4d09fe4ff..000000000 Binary files a/web/src/assets/logo.png and /dev/null differ diff --git a/web/src/components/AlertModal.vue b/web/src/components/AlertModal.vue deleted file mode 100644 index 5072a6c51..000000000 --- a/web/src/components/AlertModal.vue +++ /dev/null @@ -1,321 +0,0 @@ - - - - - \ No newline at end of file diff --git a/web/src/components/BindingResult.vue b/web/src/components/BindingResult.vue deleted file mode 100644 index 94df5c8be..000000000 --- a/web/src/components/BindingResult.vue +++ /dev/null @@ -1,831 +0,0 @@ - - - - - \ No newline at end of file diff --git a/web/src/components/TemplateBindingModal.vue b/web/src/components/TemplateBindingModal.vue deleted file mode 100644 index c6e9315bf..000000000 --- a/web/src/components/TemplateBindingModal.vue +++ /dev/null @@ -1,651 +0,0 @@ - - - - - \ No newline at end of file diff --git a/web/src/components/TemplateDetails.vue b/web/src/components/TemplateDetails.vue deleted file mode 100644 index f68c248ff..000000000 --- a/web/src/components/TemplateDetails.vue +++ /dev/null @@ -1,315 +0,0 @@ - - - - - diff --git a/web/src/main.ts b/web/src/main.ts deleted file mode 100644 index 120a943af..000000000 --- a/web/src/main.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createApp } from 'vue' -import { createRouter, createWebHistory } from 'vue-router' -import App from './App.vue' -import Resources from './views/Resources.vue' - -const routes = [ - { path: '/', component: Resources }, - { path: '/resources', component: Resources }, -] - -const router = createRouter({ - history: createWebHistory(), - routes -}) - -createApp(App).use(router).mount('#app') \ No newline at end of file diff --git a/web/src/services/auth.ts b/web/src/services/auth.ts deleted file mode 100644 index 4e985d5cf..000000000 --- a/web/src/services/auth.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { httpClient, StructuredError } from "./http"; -import { ErrorCodes } from "../types/binding"; - -export interface AuthStatus { - isAuthenticated: boolean; - sessionId?: string; - clusterId?: string; -} - -export interface AuthCheckResult { - isAuthenticated: boolean; - error?: string; -} - -const PRESERVED_PARAMS_STORAGE_KEY = "kube-bind-preserved-params"; - -class AuthService { - async isAuthenticated(): Promise { - const result = await this.checkAuthentication(); - return result.isAuthenticated; - } - - async checkAuthentication(): Promise { - try { - // Since cookies are HTTP-only, we need to check authentication by making an API call - const urlParams = new URLSearchParams(window.location.search); - const clusterId = urlParams.get("cluster_id") || ""; - // Make a simple API call to check if we're authenticated - const authCheckUrl = clusterId - ? `/ping?cluster_id=${clusterId}` - : "/ping"; - const response = await httpClient.get(authCheckUrl); - const isAuth = response.status === 200; - console.log("Auth check:", { - clusterId, - status: response.status, - isAuth, - }); - return { isAuthenticated: isAuth }; - } catch (error) { - // Handle structured errors - if (error instanceof StructuredError) { - const kubeError = error.kubeBindError; - - // Return structured error message for auth/authorization failures - if ( - kubeError.code === ErrorCodes.AUTHENTICATION_FAILED || - kubeError.code === ErrorCodes.AUTHORIZATION_FAILED - ) { - return { - isAuthenticated: false, - error: kubeError.message, - }; - } - } - - // Handle cases where we get 401/403 but don't have the expected structured error - if ( - (error as any)?.response?.status === 401 || - (error as any)?.response?.status === 403 - ) { - console.log( - "Auth check failed with authentication error but no structured response", - ); - return { - isAuthenticated: false, - error: "Authentication required", - }; - } - - console.error("Auth check error:", error); - return { - isAuthenticated: false, - error: "Authentication check failed", - }; - } - } - - async initiateAuth( - sessionId: string, - clusterId: string, - consumerId?: string, - ): Promise { - const authUrl = `/api/authorize`; - - const redirect_url = window.location.origin + window.location.pathname; - - // Store query parameters in sessionStorage to preserve them through OAuth flow - const currentParams = new URLSearchParams(window.location.search); - const paramsToPreserve: Record = {}; - - // Store all query params that we need to preserve - if (currentParams.has("consumer_id")) { - paramsToPreserve.consumer_id = currentParams.get("consumer_id")!; - } - if (currentParams.has("session_id")) { - paramsToPreserve.session_id = currentParams.get("session_id")!; - } - if (currentParams.has("redirect_url")) { - paramsToPreserve.redirect_url = currentParams.get("redirect_url")!; - } - if (currentParams.has("cluster_id")) { - paramsToPreserve.cluster_id = currentParams.get("cluster_id")!; - } - - sessionStorage.setItem( - PRESERVED_PARAMS_STORAGE_KEY, - JSON.stringify(paramsToPreserve), - ); - - const params = new URLSearchParams({ - session_id: sessionId, - redirect_url: redirect_url, - cluster_id: clusterId, - client_type: "ui", // Use UI type to get cookies - }); - - if (consumerId) { - params.set("consumer_id", consumerId); - } - - window.location.href = `${authUrl}?${params}`; - } - - async logout(): Promise { - try { - // Call backend logout endpoint to clear HttpOnly cookies - const urlParams = new URLSearchParams(window.location.search); - const clusterId = urlParams.get("cluster_id") || ""; - - // Build logout URL with cluster_id parameter if present - const logoutUrl = clusterId - ? `/api/logout?cluster_id=${encodeURIComponent(clusterId)}` - : "/api/logout"; - - // Make POST request to logout endpoint - const response = await httpClient.post(logoutUrl); - - console.log("Logout response:", { status: response.status, clusterId }); - - // Redirect to clear any cached state regardless of response - window.location.href = window.location.origin + window.location.pathname; - } catch (error) { - console.error("Logout error:", error); - - // Still try to reload even if there was an error - window.location.reload(); - } - } - - getSessionCookieName(): string | null { - // Since cookies are HTTP-only, we can't read them from JavaScript - // The session parameter will be added automatically by the HTTP interceptor - // based on the current cluster_id in the URL - const urlParams = new URLSearchParams(window.location.search); - const clusterId = urlParams.get("cluster_id") || ""; - - // Return the expected cookie name format for the HTTP interceptor to use - return clusterId ? `kube-bind-${clusterId}` : "kube-bind"; - } - - isCliFlow(): boolean { - const urlParams = new URLSearchParams(window.location.search); - // Check URL params first - if (urlParams.has("redirect_url")) { - return true; - } - - // Check sessionStorage in case params were lost during OAuth flow - const preservedParams = sessionStorage.getItem( - PRESERVED_PARAMS_STORAGE_KEY, - ); - if (preservedParams) { - try { - const params = JSON.parse(preservedParams); - return !!params.redirect_url; - } catch (e) { - return false; - } - } - - return false; - } - - redirectToCliCallback(bindingResponseData: any): void { - // Try to get parameters from URL first, then fall back to sessionStorage - const urlParams = new URLSearchParams(window.location.search); - let redirectUrl = urlParams.get("redirect_url"); - let sessionId = urlParams.get("session_id"); - let consumerId = urlParams.get("consumer_id"); - - // If not in URL, check sessionStorage (in case they were lost during OAuth flow) - if (!redirectUrl) { - const preservedParams = sessionStorage.getItem( - PRESERVED_PARAMS_STORAGE_KEY, - ); - if (preservedParams) { - try { - const params = JSON.parse(preservedParams); - redirectUrl = params.redirect_url || null; - sessionId = sessionId || params.session_id || null; - consumerId = consumerId || params.consumer_id || null; - } catch (e) { - console.error("Failed to parse preserved params:", e); - } - } - } - - if (redirectUrl) { - // Construct the callback URL entirely on the client side - const callbackUrl = new URL(redirectUrl); - - if (sessionId) { - callbackUrl.searchParams.append("session_id", sessionId); - } - if (consumerId) { - callbackUrl.searchParams.append("consumer_id", consumerId); - } - - // Add binding response data as base64 encoded query parameter - const base64Response = btoa(JSON.stringify(bindingResponseData)); - callbackUrl.searchParams.append("binding_response", base64Response); - - window.location.href = callbackUrl.toString(); - } else { - console.error("No redirect URL found for CLI callback"); - } - } - - restorePreservedParams(): boolean { - // Check if we have preserved params from before OAuth redirect - const preservedParamsJson = sessionStorage.getItem( - PRESERVED_PARAMS_STORAGE_KEY, - ); - - if (!preservedParamsJson) { - return false; - } - - try { - const preservedParams = JSON.parse(preservedParamsJson); - const currentParams = new URLSearchParams(window.location.search); - - // Only restore if the params are missing in current URL - let needsUpdate = false; - - for (const [key, value] of Object.entries(preservedParams)) { - if (!currentParams.has(key)) { - currentParams.set(key, value as string); - needsUpdate = true; - } - } - - if (needsUpdate) { - // Clear the stored params - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - - // Update URL with preserved params and reload to ensure Vue Router picks up the changes - const newUrl = `${window.location.pathname}?${currentParams.toString()}`; - window.location.replace(newUrl); - return true; - } else { - // Params are already in URL, just clean up storage - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - return false; - } - } catch (error) { - console.error("Failed to restore preserved params:", error); - sessionStorage.removeItem(PRESERVED_PARAMS_STORAGE_KEY); - return false; - } - } -} - -export const authService = new AuthService(); diff --git a/web/src/services/http.ts b/web/src/services/http.ts deleted file mode 100644 index f61db4b9d..000000000 --- a/web/src/services/http.ts +++ /dev/null @@ -1,94 +0,0 @@ -import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' -import { isKubeBindError, type KubeBindError, ErrorCodes } from '../types/binding' - -// Custom error class for structured errors -export class StructuredError extends Error { - public readonly kubeBindError: KubeBindError - public readonly httpStatus: number - - constructor(kubeBindError: KubeBindError, httpStatus: number) { - super(kubeBindError.message) - this.kubeBindError = kubeBindError - this.httpStatus = httpStatus - this.name = 'StructuredError' - } -} - -class HttpClient { - private client: AxiosInstance - - constructor() { - this.client = axios.create({ - baseURL: '/api', - timeout: 30000, - withCredentials: true, // Enable cookies - headers: { - 'Content-Type': 'application/json' - } - }) - - this.setupInterceptors() - } - - private setupInterceptors() { - // Request interceptor - cookies are handled automatically with withCredentials: true - // No need to manually add session parameters since HTTP-only cookies are sent automatically - this.client.interceptors.request.use( - (config) => { - // Cookies are automatically included due to withCredentials: true setting - return config - }, - (error) => { - return Promise.reject(error) - } - ) - - // Response interceptor to handle structured errors - this.client.interceptors.response.use( - (response) => response, - (error) => { - const status = error.response?.status - const responseData = error.response?.data - - // Check if we received a structured error from the backend - if (responseData && isKubeBindError(responseData)) { - // Handle specific error codes - if (responseData.code === ErrorCodes.AUTHENTICATION_FAILED) { - // Session expired or invalid - emit event for App.vue to handle - console.warn('Authentication expired, need to re-authenticate') - window.dispatchEvent(new CustomEvent('auth-expired')) - } - - // Throw our custom structured error - return Promise.reject(new StructuredError(responseData, status)) - } - - return Promise.reject(error) - } - ) - } - - // Generic HTTP methods - async get(url: string, config?: AxiosRequestConfig): Promise> { - return this.client.get(url, config) - } - - async post(url: string, data?: any, config?: AxiosRequestConfig): Promise> { - return this.client.post(url, data, config) - } - - async put(url: string, data?: any, config?: AxiosRequestConfig): Promise> { - return this.client.put(url, data, config) - } - - async delete(url: string, config?: AxiosRequestConfig): Promise> { - return this.client.delete(url, config) - } - - // Method to make requests without auth headers (for public endpoints) - async getPublic(url: string, config?: AxiosRequestConfig): Promise> { - return axios.get(`/api${url}`, config) - } -} - -export const httpClient = new HttpClient() \ No newline at end of file diff --git a/web/src/types/binding.ts b/web/src/types/binding.ts deleted file mode 100644 index e51bd251a..000000000 --- a/web/src/types/binding.ts +++ /dev/null @@ -1,82 +0,0 @@ -export interface BindingTemplate { - name: string -} - -export interface ClusterIdentity { - identity: string - name?: string -} - -export interface BindableResourcesRequest { - metadata: { - name: string - } - spec: { - templateRef: BindingTemplate - clusterIdentity: ClusterIdentity - author: string - } -} - -export interface APIServiceExportRequestResponse { - apiVersion: string - kind: string - metadata: { - name: string - } - spec: { - resources: any[] - permissionClaims: any[] - namespaces: any[] - } -} - -export interface BindingResponseAuthentication { - oauth2CodeGrant: { - sessionID: string - id: string - } -} - -export interface BindingResponse { - apiVersion: string - kind: string - authentication: BindingResponseAuthentication - kubeconfig: string - requests: any[] - providerNamespace?: string - bindingName?: string -} - -export interface BindingResult { - success: boolean - data?: BindingResponse - message?: string - error?: string -} - -// Structured error response from backend -export interface KubeBindError { - kind: 'Error' - apiVersion: string - message: string - code: string - details?: string -} - -// Common error codes from backend -export const ErrorCodes = { - AUTHENTICATION_FAILED: 'AUTHENTICATION_FAILED', - AUTHORIZATION_FAILED: 'AUTHORIZATION_FAILED', - RESOURCE_NOT_FOUND: 'RESOURCE_NOT_FOUND', - INTERNAL_ERROR: 'INTERNAL_ERROR', - BAD_REQUEST: 'BAD_REQUEST', - CLUSTER_CONNECTION_FAILED: 'CLUSTER_CONNECTION_FAILED' -} as const - -export type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes] - -// Helper function to check if an error response is a structured KubeBindError -export function isKubeBindError(error: any): error is KubeBindError { - return error && typeof error === 'object' && error.kind === 'Error' && error.apiVersion && error.message && error.code -} diff --git a/web/src/views/Resources.vue b/web/src/views/Resources.vue deleted file mode 100644 index d58aca2a7..000000000 --- a/web/src/views/Resources.vue +++ /dev/null @@ -1,727 +0,0 @@ - - - - - diff --git a/web/static/app.js b/web/static/app.js new file mode 100644 index 000000000..fd9b122bc --- /dev/null +++ b/web/static/app.js @@ -0,0 +1,513 @@ +// kbind gateway UI — a pure gateway client. All state lives in the gateway's +// API; this page only renders it. +"use strict"; + +const $ = (id) => document.getElementById(id); +let provider = null; +let countdownTimer = null; + +async function getJSON(url, opts) { + const res = await fetch(url, opts); + if (res.status === 401) throw { unauthenticated: true }; + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.error || res.statusText); + return body; +} + +function show(view) { + for (const v of ["loading", "catalog", "error"]) { + $("view-" + v).hidden = v !== view; + } +} + +// The login page is separate (/login); the app just sends you there. +function toLogin() { + window.location.href = "/login"; +} + +async function init() { + try { + provider = await getJSON("/api/provider"); + $("provider-name").textContent = provider.name; + $("provider-chip").hidden = false; + document.title = provider.name + " · kbind"; + } catch (e) { + $("error-text").textContent = "The gateway is not reachable: " + (e.message || e); + show("error"); + return; + } + await loadCatalog(); +} + +async function loadCatalog() { + try { + const catalog = await getJSON("/api/catalog"); + renderCatalog(catalog); + show("catalog"); + $("nav").hidden = false; + loadWhoami(); + } catch (e) { + if (e.unauthenticated) { + toLogin(); + return; + } + $("error-text").textContent = e.message || String(e); + show("error"); + } +} + +async function loadWhoami() { + try { + const me = await getJSON("/api/me"); + $("whoami").textContent = me.displayName || me.subject; + $("whoami").title = me.subject; + } catch { + $("whoami").textContent = ""; + } +} + +function renderCatalog(catalog) { + const root = $("catalog"); + root.textContent = ""; + const exports = catalog.exports || []; + $("catalog-count").textContent = + exports.length === 1 ? "1 service" : exports.length + " services"; + + if (exports.length === 0) { + const p = document.createElement("p"); + p.className = "muted"; + p.textContent = "Nothing is published yet. The provider curates offerings as Export objects (catalog.kbind.io)."; + root.appendChild(p); + return; + } + + const byName = new Map(exports.map((e) => [e.name, e])); + const grouped = new Set(); + for (const col of catalog.collections || []) { + const section = document.createElement("div"); + const title = document.createElement("div"); + title.className = "collection-title"; + title.textContent = col.title || col.name; + section.appendChild(title); + for (const name of col.exports) { + const exp = byName.get(name); + if (exp) { + section.appendChild(exportRow(exp)); + grouped.add(name); + } + } + root.appendChild(section); + } + + const rest = exports.filter((e) => !grouped.has(e.name)); + if (rest.length > 0) { + if (grouped.size > 0) { + const title = document.createElement("div"); + title.className = "collection-title"; + title.textContent = "More services"; + root.appendChild(title); + } + for (const exp of rest) root.appendChild(exportRow(exp)); + } +} + +function exportRow(exp) { + const row = document.createElement("div"); + row.className = "export"; + + const body = document.createElement("div"); + body.className = "export-body"; + + const title = document.createElement("div"); + title.className = "export-title"; + title.textContent = exp.title || exp.name; + body.appendChild(title); + + if (exp.description) { + const desc = document.createElement("div"); + desc.className = "export-desc"; + desc.textContent = exp.description; + body.appendChild(desc); + } + + const apis = document.createElement("div"); + apis.className = "export-apis"; + for (const api of exp.apis || []) { + const chip = document.createElement("span"); + chip.className = "api-name"; + chip.textContent = api; + apis.appendChild(chip); + } + // Related resources (a core concept): auxiliary secrets/configmaps that + // sync alongside the APIs. Shown up front so you know what flows. + for (const rr of exp.relatedResources || []) { + const chip = document.createElement("span"); + chip.className = "api-name related-chip"; + chip.textContent = (rr.direction === "FromConsumer" ? "⇧ " : "⇩ ") + rr.resource; + chip.title = (rr.direction === "FromConsumer" + ? "synced from your cluster to the provider" + : "synced from the provider into your cluster") + + (rr.selector ? " — " + rr.selector : ""); + apis.appendChild(chip); + } + body.appendChild(apis); + + if (exp.docs) { + const docs = document.createElement("a"); + docs.className = "export-docs"; + docs.href = exp.docs; + docs.target = "_blank"; + docs.rel = "noreferrer"; + docs.textContent = "Documentation"; + body.appendChild(docs); + } + + body.appendChild(instancesSection(exp)); + + const btn = document.createElement("button"); + btn.className = "btn primary"; + btn.textContent = "Bind"; + btn.addEventListener("click", () => bind(exp, btn)); + + row.appendChild(body); + row.appendChild(btn); + return row; +} + +// instancesSection is the per-catalog-item "what is actually running" panel: +// the provider objects consumers synced under this export, loaded on expand. +function instancesSection(exp) { + const details = document.createElement("details"); + details.className = "instances"; + const summary = document.createElement("summary"); + summary.textContent = "Synced instances"; + const list = document.createElement("div"); + list.className = "instances-list"; + details.append(summary, list); + + details.addEventListener("toggle", async () => { + if (!details.open) return; + list.textContent = "Loading…"; + try { + const res = await getJSON("/api/catalog/" + encodeURIComponent(exp.name) + "/instances"); + renderInstances(list, summary, res.instances || []); + } catch (e) { + list.textContent = e.unauthenticated ? "" : "Unavailable: " + (e.message || e); + if (e.unauthenticated) toLogin(); + } + }); + return details; +} + +function renderInstances(list, summary, instances) { + summary.textContent = instances.length === 1 + ? "1 synced instance" + : instances.length + " synced instances"; + list.textContent = ""; + if (instances.length === 0) { + const p = document.createElement("p"); + p.className = "muted small"; + p.textContent = "Nothing synced under this service yet."; + list.appendChild(p); + return; + } + for (const inst of instances) { + const row = document.createElement("div"); + row.className = "instance-row"; + + const obj = document.createElement("span"); + obj.className = "mono instance-name"; + obj.textContent = (inst.namespace ? inst.namespace + "/" : "") + inst.name; + + const apiChip = document.createElement("span"); + apiChip.className = "api-name" + (inst.related ? " related-chip" : ""); + apiChip.textContent = inst.related + ? (inst.direction === "FromConsumer" ? "⇧ " : "⇩ ") + inst.api + : inst.api; + + const who = document.createElement("span"); + who.className = "instance-who muted small"; + const cluster = inst.clusterUID ? "cluster " + inst.clusterUID.slice(0, 13) : ""; + const parts = [inst.identity, cluster]; + if (inst.related && inst.direction === "FromProvider") { + // The provider original: its copies live on the consumers, which this + // side cannot see — say what it is, not who wrote it. + parts.unshift("delivered to bound clusters"); + } + parts.push(ago(inst.createdAt)); + who.textContent = parts.filter(Boolean).join(" · "); + if (inst.clusterUID) who.title = inst.clusterUID; + + row.append(obj, apiChip, who); + list.appendChild(row); + } +} + +async function bind(exp, btn) { + btn.disabled = true; + btn.textContent = "Provisioning…"; + try { + const res = await getJSON("/api/bind", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ export: exp.name }), + }); + openTicket(exp, res); + } catch (e) { + if (e.unauthenticated) { + toLogin(); + } else { + alert("Bind failed: " + (e.message || e)); + } + } finally { + btn.disabled = false; + btn.textContent = "Bind"; + } +} + +function openTicket(exp, res) { + const url = new URL(res.pickupURL, location.origin).toString(); + $("ticket-title").textContent = exp.title || exp.name; + $("dl").href = url; + $("dl").setAttribute("download", res.grant + ".yaml"); + $("ticket-expired").hidden = true; + $("dl").removeAttribute("aria-disabled"); + + const curl = "curl -fsS " + url + " | kubectl apply -f -"; + const cli = "kubectl bind export " + exp.name + " --server " + location.origin; + $("cmd-preview").textContent = "# pick up once, apply, done\n" + curl; + $("copy-curl").onclick = () => copy(curl, $("copy-curl")); + $("copy-cli").onclick = () => copy(cli, $("copy-cli")); + + startCountdown(new Date(res.expiresAt)); + + const applySection = $("browser-apply"); + applySection.hidden = !provider.applyEnabled; + if (provider.applyEnabled) { + $("apply-result").hidden = true; + $("apply-btn").onclick = () => browserApply(exp); + } + + $("ticket").showModal(); +} + +function startCountdown(expiry) { + clearInterval(countdownTimer); + const tick = () => { + const left = Math.floor((expiry - Date.now()) / 1000); + if (left <= 0) { + clearInterval(countdownTimer); + $("countdown").textContent = "0:00"; + $("ticket-expired").hidden = false; + $("dl").setAttribute("aria-disabled", "true"); + return; + } + $("countdown").textContent = Math.floor(left / 60) + ":" + String(left % 60).padStart(2, "0"); + }; + tick(); + countdownTimer = setInterval(tick, 1000); +} + +async function browserApply(exp) { + const kubeconfig = $("apply-kubeconfig").value.trim(); + if (!kubeconfig) { + alert("Paste a consumer-cluster kubeconfig first."); + return; + } + const btn = $("apply-btn"); + btn.disabled = true; + btn.textContent = "Applying…"; + try { + const res = await getJSON("/api/apply", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + export: exp.name, + kubeconfig: btoa(kubeconfig), + installKonnector: $("apply-konnector").checked, + }), + }); + const out = $("apply-result"); + out.textContent = "applied:\n" + res.applied.map((a) => " " + a).join("\n"); + out.hidden = false; + } catch (e) { + alert("Apply failed: " + (e.message || e)); + } finally { + btn.disabled = false; + btn.textContent = "Apply to cluster"; + } +} + +// ---------------------------------------------------------------- clusters -- + +function switchView(name) { + $("nav-catalog").classList.toggle("active", name === "catalog"); + $("nav-clusters").classList.toggle("active", name === "clusters"); + $("pane-catalog").hidden = name !== "catalog"; + $("pane-clusters").hidden = name !== "clusters"; + if (name === "clusters") loadClusters(); +} + +async function loadClusters() { + try { + renderClusters(await getJSON("/api/clusters")); + } catch (e) { + if (e.unauthenticated) { + toLogin(); + return; + } + $("clusters-count").textContent = "unavailable: " + (e.message || e); + } +} + +function ago(iso) { + const seconds = Math.max(0, Math.floor((Date.now() - new Date(iso)) / 1000)); + if (seconds < 90) return seconds + "s ago"; + if (seconds < 5400) return Math.round(seconds / 60) + "m ago"; + return Math.round(seconds / 3600) + "h ago"; +} + +function renderClusters(data) { + const root = $("clusters"); + root.textContent = ""; + const clusters = data.clusters || []; + $("clusters-count").textContent = + clusters.length === 1 ? "1 cluster" : clusters.length + " clusters"; + + if (clusters.length === 0) { + const p = document.createElement("p"); + p.className = "muted"; + p.textContent = "No consumer cluster has connected yet. Bind a service and apply its bundle — the konnector's heartbeat shows up here."; + root.appendChild(p); + } + + for (const cluster of clusters) { + const card = document.createElement("div"); + card.className = "cluster"; + + const head = document.createElement("div"); + head.className = "cluster-head"; + const dot = document.createElement("span"); + dot.className = "live-dot" + (cluster.live ? "" : " stale"); + dot.title = cluster.live ? "heartbeat current" : "heartbeat stale"; + const uid = document.createElement("span"); + uid.className = "cluster-uid"; + uid.textContent = "cluster " + cluster.uid.slice(0, 13); + uid.title = cluster.uid; + const seen = document.createElement("span"); + seen.className = "cluster-seen"; + seen.textContent = (cluster.live ? "heartbeat " : "last seen ") + ago(cluster.lastHeartbeat); + head.append(dot, uid, seen); + card.appendChild(head); + + for (const b of cluster.bindings || []) { + const row = document.createElement("div"); + row.className = "cluster-grant"; + + const exp = document.createElement("span"); + exp.className = "cluster-grant-export"; + exp.textContent = b.export; + exp.title = "grant " + b.grant; + + const identity = document.createElement("span"); + identity.className = "cluster-grant-identity"; + identity.textContent = b.identity || b.subject || ""; + + const apis = document.createElement("span"); + apis.className = "cluster-grant-apis"; + for (const a of b.apis || []) { + const chip = document.createElement("span"); + chip.className = "api-name"; + chip.append(a.name + " · "); + const count = document.createElement("span"); + count.className = "synced-count"; + count.textContent = a.syncedCount + " synced"; + chip.appendChild(count); + apis.appendChild(chip); + } + row.append(exp, identity, apis); + card.appendChild(row); + } + root.appendChild(card); + } + + if ((data.pending || []).length > 0) { + const title = document.createElement("div"); + title.className = "pending-title"; + title.textContent = "bound, never connected"; + root.appendChild(title); + for (const p of data.pending) { + const row = document.createElement("div"); + row.className = "pending-row"; + row.textContent = p.export + " — " + (p.identity || p.grant) + " (bound " + ago(p.createdAt) + ", bundle never applied)"; + root.appendChild(row); + } + } +} + +$("nav-catalog").addEventListener("click", () => switchView("catalog")); +$("nav-clusters").addEventListener("click", () => switchView("clusters")); + +// ------------------------------------------------------- connect a cluster -- + +function openConnect() { + const cmd = "curl -fsS " + location.origin + "/api/konnector | kubectl apply -f -"; + $("connect-cmd").textContent = cmd; + $("connect-copy").onclick = () => copy(cmd, $("connect-copy")); + + const applySection = $("connect-apply"); + applySection.hidden = !provider.applyEnabled; + if (provider.applyEnabled) { + $("connect-apply-result").hidden = true; + $("connect-apply-btn").onclick = connectApply; + } + $("connect").showModal(); +} + +async function connectApply() { + const kubeconfig = $("connect-kubeconfig").value.trim(); + if (!kubeconfig) { + alert("Paste a consumer-cluster kubeconfig first."); + return; + } + const btn = $("connect-apply-btn"); + btn.disabled = true; + btn.textContent = "Installing…"; + try { + const res = await getJSON("/api/apply", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ kubeconfig: btoa(kubeconfig), installKonnector: true }), + }); + const out = $("connect-apply-result"); + out.textContent = "installed:\n" + res.applied.map((a) => " " + a).join("\n") + + "\n\nNow bind a service from the Catalog."; + out.hidden = false; + } catch (e) { + alert("Install failed: " + (e.message || e)); + } finally { + btn.disabled = false; + btn.textContent = "Install konnector"; + } +} + +$("connect-btn").addEventListener("click", openConnect); +$("connect-close").addEventListener("click", () => $("connect").close()); + +async function copy(text, btn) { + try { + await navigator.clipboard.writeText(text); + const prev = btn.textContent; + btn.textContent = "Copied"; + setTimeout(() => (btn.textContent = prev), 1200); + } catch { + prompt("Copy this:", text); + } +} + +$("ticket-close").addEventListener("click", () => { + clearInterval(countdownTimer); + $("ticket").close(); +}); + +init(); diff --git a/web/src/assets/favicon.png b/web/static/favicon.png similarity index 100% rename from web/src/assets/favicon.png rename to web/static/favicon.png diff --git a/web/static/index.html b/web/static/index.html new file mode 100644 index 000000000..547698026 --- /dev/null +++ b/web/static/index.html @@ -0,0 +1,129 @@ + + + + + + kbind + + + + + +
+ + +
+

Reaching the gateway…

+ + + + +
+
+ + + +
+
+ one-time bundle + +
+

+

This pickup link works once and expires in + . The credentials inside + keep working after pickup — commit the file to git if you do GitOps.

+
+ Download bundle + + +
+

+      
+
+      
+    
+
+ + + +
+
+ connect a cluster + +
+

Install the konnector

+

Run this against the cluster you want to connect. + It installs the konnector (CRDs, RBAC, Deployment) — the only thing + that ever runs on your side.

+

+      
+ + Download konnector.yaml +
+

Then pick a service in the Catalog and + apply its bundle — the cluster appears here once its heartbeat starts.

+ + +
+
+ + + + diff --git a/web/static/login.html b/web/static/login.html new file mode 100644 index 000000000..5e90fe4aa --- /dev/null +++ b/web/static/login.html @@ -0,0 +1,35 @@ + + + + + + Sign in · kbind + + + + + + + + + diff --git a/docs/images/logo.svg b/web/static/logo.svg similarity index 100% rename from docs/images/logo.svg rename to web/static/logo.svg diff --git a/web/static/style.css b/web/static/style.css new file mode 100644 index 000000000..5b5401ef8 --- /dev/null +++ b/web/static/style.css @@ -0,0 +1,281 @@ +/* kbind gateway UI. + Porcelain light, ink slate, one spruce accent for bind/ready semantics; + copper is reserved for single-use/expiry. Kubernetes identifiers are + always mono. No external assets — this ships inside the binary. */ + +:root { + --bg: #f6f7f5; + --surface: #ffffff; + --ink: #1d2a2e; + --muted: #5c6b6f; + --line: #dde3e0; + --accent: #2e6e52; + --accent-ink: #ffffff; + --copper: #a3572a; + --copper-soft: #f7ebe2; + --mono: ui-monospace, "SF Mono", "Cascadia Code", "JetBrains Mono", Menlo, monospace; + --sans: "Avenir Next", "Segoe UI Variable", "Segoe UI", system-ui, sans-serif; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #161c1a; + --surface: #1f2624; + --ink: #e6ebe8; + --muted: #93a29c; + --line: #33403b; + --accent: #58a37f; + --accent-ink: #0e1512; + --copper: #d98d5a; + --copper-soft: #33261c; + } +} + +* { box-sizing: border-box; } +html, body { margin: 0; } +body { + background: var(--bg); + color: var(--ink); + font-family: var(--sans); + font-size: 16px; + line-height: 1.55; + min-height: 100vh; +} +code, .mono { font-family: var(--mono); font-size: 0.92em; } +a { color: var(--accent); } + +/* Shell: fixed left sidebar, content on the right. */ +.shell { display: flex; min-height: 100vh; } +.side { + width: 218px; flex-shrink: 0; + display: flex; flex-direction: column; gap: 16px; + padding: 20px 14px; + background: var(--surface); + border-right: 1px solid var(--line); + position: sticky; top: 0; height: 100vh; +} +main { flex: 1; min-width: 0; } + +.brand { display: flex; align-items: center; gap: 10px; padding: 0 8px; } +.brand-mark { width: 26px; height: 26px; display: block; } +.brand-name { font-weight: 600; letter-spacing: 0.02em; font-size: 18px; } +.context-chip { + font-family: var(--mono); font-size: 11.5px; + border: 1px solid var(--line); border-radius: 999px; + padding: 3px 10px; margin: 0 8px; color: var(--muted); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.chip-key { color: var(--accent); } + +.nav { display: flex; flex-direction: column; gap: 2px; } +.nav-item { + font: inherit; font-size: 14.5px; font-weight: 500; text-align: left; + background: none; border: none; color: var(--muted); + border-left: 2px solid transparent; + border-radius: 0 8px 8px 0; + padding: 9px 12px; cursor: pointer; +} +.nav-item:hover { color: var(--ink); } +.nav-item.active { + color: var(--ink); font-weight: 600; + background: var(--bg); + border-left-color: var(--accent); +} +.nav-item:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +.side-foot { margin-top: auto; padding: 0 8px; } +.whoami { + font-family: var(--mono); font-size: 12px; color: var(--muted); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.signout { + display: inline-block; margin-top: 6px; + font-size: 13px; color: var(--muted); text-decoration: none; +} +.signout:hover { color: var(--copper); text-decoration: underline; } + +.stage { max-width: 860px; margin: 0 auto; padding: 48px 32px; } + +/* The login page (login.html) owns the whole viewport: centered card. */ +.login-page { + min-height: 100vh; + display: flex; align-items: center; justify-content: center; + padding: 32px 24px; +} +.login-card { + max-width: 460px; + display: flex; flex-direction: column; align-items: center; + text-align: center; gap: 6px; +} +.login-brand { flex-direction: column; gap: 12px; padding: 0; margin-bottom: 18px; } +.login-brand .brand-mark { width: 72px; height: 72px; } +.login-brand .brand-name { font-size: 22px; } +.login-card .lede { margin: 6px 0 22px; } +.login-provider { margin-top: 22px; } +h1 { font-size: 34px; line-height: 1.15; letter-spacing: -0.015em; margin: 0 0 14px; font-weight: 600; } +h2 { font-size: 20px; margin: 4px 0 8px; } +.lede { font-size: 17px; color: var(--muted); max-width: 46ch; } +.muted { color: var(--muted); } +.small { font-size: 13.5px; } + +.btn { + display: inline-block; + font: inherit; font-size: 14.5px; font-weight: 500; + color: var(--ink); + background: var(--surface); + border: 1px solid var(--line); + border-radius: 8px; + padding: 9px 16px; + cursor: pointer; + text-decoration: none; +} +.btn:hover { border-color: var(--accent); } +.btn.primary { + background: var(--accent); color: var(--accent-ink); border-color: var(--accent); +} +.btn.primary:hover { filter: brightness(1.08); } +.btn.ghost { border: none; background: none; color: var(--muted); font-size: 16px; } +.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.btn[disabled] { opacity: 0.5; cursor: default; } + +.catalog-head { display: flex; align-items: baseline; justify-content: space-between; } + +/* Clusters view: one card per consumer cluster, keyed by its UID. */ +.cluster { + background: var(--surface); + border: 1px solid var(--line); + border-radius: 10px; + padding: 16px 20px; + margin: 12px 0; +} +.cluster-head { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.live-dot { + width: 9px; height: 9px; border-radius: 50%; + background: var(--accent); flex-shrink: 0; +} +.live-dot.stale { background: var(--copper); } +.cluster-uid { font-family: var(--mono); font-size: 13.5px; font-weight: 600; } +.cluster-seen { font-size: 12.5px; color: var(--muted); margin-left: auto; } +.cluster-grant { + display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; + border-top: 1px dashed var(--line); + padding: 10px 0 2px; margin-top: 10px; +} +.cluster-grant-export { font-weight: 600; } +.cluster-grant-identity { font-size: 13px; color: var(--muted); } +.cluster-grant-apis { display: flex; flex-wrap: wrap; gap: 6px; } +.synced-count { color: var(--accent); font-weight: 600; } +.pending-title { + font-family: var(--mono); font-size: 12.5px; text-transform: uppercase; + letter-spacing: 0.08em; color: var(--copper); + margin: 26px 0 8px; +} +.pending-row { font-size: 14px; color: var(--muted); padding: 3px 0; } + +/* Exports render as manifest rows: a left rule, mono API names — the list + reads like the document you are about to receive. */ +.collection-title { + font-family: var(--mono); font-size: 12.5px; text-transform: uppercase; + letter-spacing: 0.08em; color: var(--muted); + margin: 30px 0 10px; padding-bottom: 6px; border-bottom: 1px solid var(--line); +} +.export { + display: flex; gap: 18px; align-items: flex-start; justify-content: space-between; + background: var(--surface); + border: 1px solid var(--line); + border-left: 3px solid var(--accent); + border-radius: 10px; + padding: 18px 20px; + margin: 12px 0; +} +.export-body { min-width: 0; } +.export-title { font-weight: 600; font-size: 17px; } +.export-desc { color: var(--muted); margin: 3px 0 8px; font-size: 14.5px; } +.export-apis { display: flex; flex-wrap: wrap; gap: 6px; } +.api-name { + font-family: var(--mono); font-size: 12px; + background: var(--bg); border: 1px solid var(--line); + border-radius: 5px; padding: 2px 7px; +} +/* Related-resource chips: same family as API chips, accent-tinted so the + auxiliary objects read as "comes with", not "is the API". */ +.related-chip { color: var(--accent); border-style: dashed; cursor: help; } +.export-docs { font-size: 13px; } +.export .btn { flex-shrink: 0; } + +/* Per-catalog-item synced instances, loaded on expand. */ +.instances { margin-top: 10px; border-top: 1px dashed var(--line); padding-top: 8px; } +.instances summary { + cursor: pointer; color: var(--muted); font-size: 13.5px; +} +.instances summary:hover { color: var(--ink); } +.instances-list { padding: 8px 0 2px; } +.instance-row { + display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; + padding: 4px 0; font-size: 13.5px; +} +.instance-name { font-weight: 600; } +.instance-who { margin-left: auto; } + +/* The bundle ticket. */ +dialog#ticket, dialog#connect { + border: 1px solid var(--line); border-radius: 14px; + background: var(--surface); color: var(--ink); + padding: 0; width: min(560px, calc(100vw - 40px)); +} +dialog#ticket::backdrop, dialog#connect::backdrop { background: rgba(20, 28, 26, 0.45); } +/* The connect flow installs software but hands out no one-time credential, + so its eyebrow is calm accent, not single-use copper. */ +.connect-eyebrow { color: var(--accent); background: var(--bg); } +#connect-apply { margin-top: 18px; border-top: 1px dashed var(--line); padding-top: 12px; } +#connect-apply summary { cursor: pointer; color: var(--muted); font-size: 14px; } +#connect-apply textarea { + width: 100%; font-family: var(--mono); font-size: 12px; + background: var(--bg); color: var(--ink); + border: 1px solid var(--line); border-radius: 8px; padding: 10px; margin: 10px 0; +} +.ticket-inner { padding: 22px 26px 26px; } +.ticket-head { display: flex; justify-content: space-between; align-items: center; } +.ticket-eyebrow { + font-family: var(--mono); font-size: 11.5px; text-transform: uppercase; + letter-spacing: 0.1em; color: var(--copper); + background: var(--copper-soft); border-radius: 999px; padding: 3px 10px; +} +.ticket-note { color: var(--muted); font-size: 14.5px; } +.countdown { font-family: var(--mono); color: var(--copper); font-weight: 600; } +.ticket-actions { display: flex; flex-wrap: wrap; gap: 10px; margin: 14px 0; } +.cmd { + font-family: var(--mono); font-size: 12.5px; line-height: 1.6; + background: var(--bg); border: 1px solid var(--line); border-radius: 8px; + padding: 12px 14px; overflow-x: auto; white-space: pre; +} +.ticket-expired { color: var(--copper); font-weight: 500; } + +#browser-apply { margin-top: 18px; border-top: 1px dashed var(--line); padding-top: 12px; } +#browser-apply summary { cursor: pointer; color: var(--muted); font-size: 14px; } +#browser-apply textarea { + width: 100%; font-family: var(--mono); font-size: 12px; + background: var(--bg); color: var(--ink); + border: 1px solid var(--line); border-radius: 8px; padding: 10px; margin: 10px 0; +} +.check { display: block; font-size: 14px; margin: 0 0 10px; } + +@media (max-width: 720px) { + /* Sidebar collapses into a top bar. */ + .shell { flex-direction: column; } + .side { + width: 100%; height: auto; position: static; + flex-direction: row; align-items: center; gap: 12px; + padding: 10px 16px; + border-right: none; border-bottom: 1px solid var(--line); + } + .nav { flex-direction: row; margin-left: auto; } + .nav-item, .nav-item.active { border-left: none; border-radius: 8px; } + .nav-item.active { box-shadow: inset 0 -2px 0 var(--accent); } + .context-chip, .side-foot { display: none; } + .stage { padding: 32px 18px; } + h1 { font-size: 27px; } + .export { flex-direction: column; } +} +@media (prefers-reduced-motion: no-preference) { + .export { transition: border-color 120ms ease; } +} diff --git a/web/tsconfig.json b/web/tsconfig.json deleted file mode 100644 index b68745b90..000000000 --- a/web/tsconfig.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "preserve", - - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - - /* Path mapping */ - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - } - }, - "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], - "references": [{ "path": "./tsconfig.node.json" }] -} \ No newline at end of file diff --git a/web/tsconfig.node.json b/web/tsconfig.node.json deleted file mode 100644 index 4eb43d054..000000000 --- a/web/tsconfig.node.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "composite": true, - "skipLibCheck": true, - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "strict": true - }, - "include": ["vite.config.ts"] -} \ No newline at end of file diff --git a/web/vite.config.docker.ts b/web/vite.config.docker.ts deleted file mode 100644 index 5e0ed179e..000000000 --- a/web/vite.config.docker.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import { fileURLToPath, URL } from 'node:url' - -// Docker-specific configuration that avoids native dependency issues -export default defineConfig({ - plugins: [vue()], - resolve: { - alias: { - '@': fileURLToPath(new URL('./src', import.meta.url)) - } - }, - build: { - outDir: 'dist', - assetsDir: 'assets', - emptyOutDir: true, - // Target ES2015 for broader compatibility - target: 'es2015', - // Disable minification to avoid potential native dep issues - minify: false, - // Use Rollup options that avoid native dependencies - rollupOptions: { - output: { - // Simplified output configuration - assetFileNames: 'assets/[name].[hash][extname]', - chunkFileNames: 'assets/[name].[hash].js', - entryFileNames: 'assets/[name].[hash].js', - // Avoid code splitting to reduce complexity - manualChunks: undefined - } - } - }, - // Ensure proper base URL for production - base: './', - // TypeScript configuration for better compatibility - esbuild: { - target: 'es2015' - }, - // Optimize dependencies to avoid potential issues - optimizeDeps: { - exclude: ['@rollup/rollup-linux-arm64-gnu', '@rollup/rollup-linux-x64-gnu'] - } -}) \ No newline at end of file diff --git a/web/vite.config.ts b/web/vite.config.ts deleted file mode 100644 index 7d8b4421f..000000000 --- a/web/vite.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import { fileURLToPath, URL } from 'node:url' - -export default defineConfig({ - plugins: [vue()], - resolve: { - alias: { - '@': fileURLToPath(new URL('./src', import.meta.url)) - } - }, - server: { - port: 3000, - host: true, // Allow external connections - allowedHosts: [ - 'localhost', - '127.0.0.1', - 'kube-bind.dev.local', - '.local' // Allow any .local domain - ], - proxy: { - '/api': { - target: 'http://localhost:8080', - changeOrigin: true - } - } - }, - build: { - outDir: 'dist', - assetsDir: 'assets', - emptyOutDir: true, - // Target ES2015 for broader compatibility - target: 'es2015', - // Generate manifest for proper asset handling - manifest: false, - // Ensure assets are properly hashed for caching - rollupOptions: { - output: { - assetFileNames: 'assets/[name]-[hash][extname]', - chunkFileNames: 'assets/[name]-[hash].js', - entryFileNames: 'assets/[name]-[hash].js' - } - } - }, - // Ensure proper base URL for production - base: './', - // TypeScript configuration for better compatibility - esbuild: { - target: 'es2015' - } -}) \ No newline at end of file